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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
04c25f9817491e997c125d29b14df58d2944b132 | 140 | java | Java | src/IO/data/Population.java | Uncrowned/Migration | de4f9eb22958ab23d1490296d5efa474b8fed2ef | [
"MIT"
] | null | null | null | src/IO/data/Population.java | Uncrowned/Migration | de4f9eb22958ab23d1490296d5efa474b8fed2ef | [
"MIT"
] | null | null | null | src/IO/data/Population.java | Uncrowned/Migration | de4f9eb22958ab23d1490296d5efa474b8fed2ef | [
"MIT"
] | null | null | null | package IO.data;
/**
* Created by sevenbits on 01.02.16.
*/
public class Population {
public String type;
public Integer size;
}
| 14 | 36 | 0.664286 |
fb43b6a73300ddd58621ee8421cb9036e0f76f9a | 79 | java | Java | Ejercicios/03 - Objetos y Clases en Java/08/src/dominio/Bono.java | Floating-Island/Java-Exercises-_2018__ES_ | d000e1f638377bede81c5fe11b44d298bbcc700a | [
"Unlicense"
] | null | null | null | Ejercicios/03 - Objetos y Clases en Java/08/src/dominio/Bono.java | Floating-Island/Java-Exercises-_2018__ES_ | d000e1f638377bede81c5fe11b44d298bbcc700a | [
"Unlicense"
] | null | null | null | Ejercicios/03 - Objetos y Clases en Java/08/src/dominio/Bono.java | Floating-Island/Java-Exercises-_2018__ES_ | d000e1f638377bede81c5fe11b44d298bbcc700a | [
"Unlicense"
] | null | null | null | package dominio;
public interface Bono {
public abstract double importe();
}
| 13.166667 | 34 | 0.759494 |
660422b991d10a1fe92f9cb6ba16d5abf445bba7 | 1,518 | swift | Swift | Sources/CFRDT/Timestamp/DisambiguousTimeInterval.swift | rkreutz/CFRDT | 83506466ffa58f6c1e536ea69cd4574b7d5c8e0c | [
"MIT"
] | null | null | null | Sources/CFRDT/Timestamp/DisambiguousTimeInterval.swift | rkreutz/CFRDT | 83506466ffa58f6c1e536ea69cd4574b7d5c8e0c | [
"MIT"
] | null | null | null | Sources/CFRDT/Timestamp/DisambiguousTimeInterval.swift | rkreutz/CFRDT | 83506466ffa58f6c1e536ea69cd4574b7d5c8e0c | [
"MIT"
] | null | null | null | import Foundation
public struct DisambiguousTimeInterval: Timestampable, Identifiable {
public static func tick() -> DisambiguousTimeInterval { DisambiguousTimeInterval() }
public var id = UUID()
public var timeInterval: TimeInterval = Date().timeIntervalSince1970
public mutating func tick() {
id = UUID()
timeInterval = Date().timeIntervalSince1970
}
}
extension DisambiguousTimeInterval: Codable {
public enum CodingKeys: CodingKey {
case id
case timeInterval
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(UUID.self, forKey: .id)
guard let timeInterval = TimeInterval(try container.decode(String.self, forKey: .timeInterval)) else {
throw DecodingError.dataCorruptedError(forKey: .timeInterval, in: container, debugDescription: "Failed to parse TimeInterval")
}
self.timeInterval = timeInterval
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode("\(timeInterval)", forKey: .timeInterval)
}
}
extension DisambiguousTimeInterval: Comparable {
public static func < (lhs: DisambiguousTimeInterval, rhs: DisambiguousTimeInterval) -> Bool {
(lhs.timeInterval, lhs.id.uuidString) < (rhs.timeInterval, rhs.id.uuidString)
}
}
| 29.764706 | 138 | 0.695652 |
eb77f786e73ace81603e1d51b6b7f7fd3abc5a52 | 591 | asm | Assembly | programs/oeis/186/A186352.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/186/A186352.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/186/A186352.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A186352: Adjusted joint rank sequence of (f(i)) and (g(j)) with f(i) after g(j) when f(i)=g(j), where f and g are the odd numbers and the triangular numbers. Complement of A186353.
; 2,4,5,7,8,10,11,13,14,15,17,18,19,20,22,23,24,25,27,28,29,30,32,33,34,35,36,38,39,40,41,42,43,45,46,47,48,49,50,52,53,54,55,56,57,59,60,61,62,63,64,65,67,68,69,70,71,72,73,74,76,77,78,79,80,81,82,83,85,86,87,88,89,90,91,92,94,95,96,97,98,99,100,101,102,104,105,106,107,108,109,110,111,112,113,115,116,117,118,119
mul $0,2
mov $1,$0
mov $2,1
lpb $1
add $0,2
add $2,1
sub $1,$2
lpe
div $0,2
add $0,2
| 42.214286 | 314 | 0.659898 |
9f6035efd255bc48bec330ffbe2db1a5d3e3940a | 319 | swift | Swift | Tisym/Ressources/Data.swift | hadrienbbt/Tisym | f91d9554600bee213eecee8d83d616f31f514eb5 | [
"MIT"
] | 1 | 2020-09-10T08:59:16.000Z | 2020-09-10T08:59:16.000Z | Tisym/Ressources/Data.swift | hadrienbbt/Tisym | f91d9554600bee213eecee8d83d616f31f514eb5 | [
"MIT"
] | null | null | null | Tisym/Ressources/Data.swift | hadrienbbt/Tisym | f91d9554600bee213eecee8d83d616f31f514eb5 | [
"MIT"
] | null | null | null | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Helpers for loading images and data.
*/
import UIKit
import SwiftUI
import CoreLocation
let lightData: [Light] = load("mockLights.json")
let colorRGBData: [ColorRGB] = load("mockColors.json")
let colorHexData: [ColorHex] = load("indigo.json")
| 21.266667 | 59 | 0.761755 |
2a1473471fdc1a05ab6a75802cb3969ae3953c38 | 2,142 | java | Java | JavaMyPublisher/src/javaclient/JavaClient.java | hasanalpzengin/MQTT-Implementation | 9d4efdfe5db27c931c4b32842a670843f5e796af | [
"Apache-2.0"
] | null | null | null | JavaMyPublisher/src/javaclient/JavaClient.java | hasanalpzengin/MQTT-Implementation | 9d4efdfe5db27c931c4b32842a670843f5e796af | [
"Apache-2.0"
] | null | null | null | JavaMyPublisher/src/javaclient/JavaClient.java | hasanalpzengin/MQTT-Implementation | 9d4efdfe5db27c931c4b32842a670843f5e796af | [
"Apache-2.0"
] | null | null | null | package javaclient;
import mqtt.MQTTClient;
import connection.Publish;
import connection.Connection;
import connection.Subscribe;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import message.Message;
public class JavaClient {
public static int status = 0;
public static void main(String[] args) {
//define object for library
MQTTClient client = new MQTTClient();
//create connection
Connection connection = client.connection("localhost", "Hasan");
if(connection.isConnected()){
//create message to publish
Message pub_message = new Message();
pub_message.setMessage("0");
pub_message.setTopic("light");
pub_message.setQos_level(2);
//create thread with publish function
//first parameter established connection
//second parameter created msg
//third parameter repeat boolean
//fourth parameter delay second
client.publish(connection, pub_message, false, 0).start();
String time = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
System.out.println(time+" : Sent");
//create Subscribe thread
//first parameter established connection
//second parameter subscribed topic
//third parameter qos level
Subscribe subscribe = new Subscribe(connection, "light", 2){
//readHandle function have to be implemented
//readHandle function's parameter message is recieved message
@Override
public void readHandle(Message message) {
String time = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
System.out.println(time+" : Recieved");
}
};
//start created thread
client.startSubscribe(subscribe);
System.out.println("Subscribed");
}
}
}
| 37.578947 | 123 | 0.618114 |
758cf15477ab2cf167b562c01c3732d81b42e866 | 36 | sql | SQL | core-services/egov-idgen/src/main/resources/db/migration/main/V20171109001824__create_swm_vehicle_schedule_transaction_num_seq_ddl.sql | pradeepkumarcm-egov/DIGIT-Dev | d8fb601fae6d919d2386f36b36dfc7fde77ebd4f | [
"MIT"
] | 11 | 2021-04-22T13:18:00.000Z | 2021-07-13T06:24:48.000Z | core-services/egov-idgen/src/main/resources/db/migration/main/V20171109001824__create_swm_vehicle_schedule_transaction_num_seq_ddl.sql | pradeepkumarcm-egov/DIGIT-Dev | d8fb601fae6d919d2386f36b36dfc7fde77ebd4f | [
"MIT"
] | 869 | 2020-01-17T04:57:48.000Z | 2022-02-16T01:18:22.000Z | core-services/egov-idgen/src/main/resources/db/migration/main/V20171109001824__create_swm_vehicle_schedule_transaction_num_seq_ddl.sql | pradeepkumarcm-egov/DIGIT-Dev | d8fb601fae6d919d2386f36b36dfc7fde77ebd4f | [
"MIT"
] | 36 | 2020-02-11T09:39:38.000Z | 2022-02-08T04:37:54.000Z | CREATE SEQUENCE SEQ_SWM_VS_TRN_NUM;
| 18 | 35 | 0.888889 |
261a385647e55e55fb9fb3ae54221dbb2d060bd6 | 1,421 | java | Java | Server/src/Message.java | FlavioLandes/Chat | 909a071e7eac8ecf52134b2f979fa938a83ffa6e | [
"MIT"
] | null | null | null | Server/src/Message.java | FlavioLandes/Chat | 909a071e7eac8ecf52134b2f979fa938a83ffa6e | [
"MIT"
] | null | null | null | Server/src/Message.java | FlavioLandes/Chat | 909a071e7eac8ecf52134b2f979fa938a83ffa6e | [
"MIT"
] | null | null | null | import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author Flávio Barreiro Landes
* E-mail: landesflavio@gmail.com
*/
public class Message implements Serializable {
private String clientName;
private String receiverName;
private String text;
private ArrayList<String> namesOnlineUsers;
private Action action;
public enum Action {
CONNECT, SEND_ALL, SEND_RESTRICT, ADD_USER_NAME_ONLINE, REMOVE_USER_NAME_ONLINE;
}
public String getClientName() {
return this.clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getReceiverName() {
return this.receiverName;
}
public void setReceiverName(String receiverName) {
this.receiverName = receiverName;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public Action getAction() {
return this.action;
}
public void setAction(Action action) {
this.action = action;
}
public ArrayList<String> getNamesOnlineUsers() {
return this.namesOnlineUsers;
}
public void setNamesOnlineUsers(ArrayList<String> namesOnlineUsers) {
this.namesOnlineUsers = namesOnlineUsers;
}
}
| 22.555556 | 91 | 0.628431 |
9944b7621e406fe10afebf7bb8af8b8aac419d9e | 9,124 | h | C | apps/linear_algebra/src/halide_blas.h | jwitz54/Halide-2016-HLS | dd95daab3a7c871dd2f15c514912e21fb3c2bb7c | [
"MIT"
] | 7 | 2017-04-05T20:52:57.000Z | 2018-11-26T10:07:10.000Z | apps/linear_algebra/src/halide_blas.h | jwitz54/Halide-2016-HLS | dd95daab3a7c871dd2f15c514912e21fb3c2bb7c | [
"MIT"
] | 10 | 2017-04-11T02:55:38.000Z | 2019-06-27T18:13:36.000Z | apps/linear_algebra/src/halide_blas.h | jwitz54/Halide-2016-HLS | dd95daab3a7c871dd2f15c514912e21fb3c2bb7c | [
"MIT"
] | 1 | 2020-07-10T16:00:39.000Z | 2020-07-10T16:00:39.000Z | #ifndef HALIDE_BLAS_H
#define HALIDE_BLAS_H
#include <cmath>
#include "HalideRuntime.h"
#include "halide_scopy_impl.h"
#include "halide_dcopy_impl.h"
#include "halide_sscal_impl.h"
#include "halide_dscal_impl.h"
#include "halide_saxpy_impl.h"
#include "halide_daxpy_impl.h"
#include "halide_sdot.h"
#include "halide_ddot.h"
#include "halide_sasum.h"
#include "halide_dasum.h"
#include "halide_sgemv_notrans.h"
#include "halide_dgemv_notrans.h"
#include "halide_sgemv_trans.h"
#include "halide_dgemv_trans.h"
#include "halide_sger_impl.h"
#include "halide_dger_impl.h"
#include "halide_sgemm_notrans.h"
#include "halide_dgemm_notrans.h"
#include "halide_sgemm_transA.h"
#include "halide_dgemm_transA.h"
#include "halide_sgemm_transB.h"
#include "halide_dgemm_transB.h"
#include "halide_sgemm_transAB.h"
#include "halide_dgemm_transAB.h"
inline int halide_scopy(buffer_t *x, buffer_t *y) {
return halide_scopy_impl(0, x, nullptr, y);
}
inline int halide_dcopy(buffer_t *x, buffer_t *y) {
return halide_dcopy_impl(0, x, nullptr, y);
}
inline int halide_sscal(float a, buffer_t *x) {
return halide_sscal_impl(a, x, nullptr, x);
}
inline int halide_dscal(double a, buffer_t *x) {
return halide_dscal_impl(a, x, nullptr, x);
}
inline int halide_saxpy(float a, buffer_t *x, buffer_t *y) {
return halide_saxpy_impl(a, x, y, y);
}
inline int halide_daxpy(double a, buffer_t *x, buffer_t *y) {
return halide_daxpy_impl(a, x, y, y);
}
inline int halide_sgemv(bool trans, float a, buffer_t *A, buffer_t *x, float b, buffer_t *y) {
if (trans) {
return halide_sgemv_trans(a, A, x, b, y, y);
} else {
return halide_sgemv_notrans(a, A, x, b, y, y);
}
}
inline int halide_dgemv(bool trans, double a, buffer_t *A, buffer_t *x, double b, buffer_t *y) {
if (trans) {
return halide_dgemv_trans(a, A, x, b, y, y);
} else {
return halide_dgemv_notrans(a, A, x, b, y, y);
}
}
inline int halide_sger(float a, buffer_t *x, buffer_t *y, buffer_t *A) {
return halide_sger_impl(a, x, y, A, A);
}
inline int halide_dger(float a, buffer_t *x, buffer_t *y, buffer_t *A) {
return halide_dger_impl(a, x, y, A, A);
}
inline int halide_sgemm(bool transA, bool transB, float a, buffer_t *A, buffer_t *B, float b, buffer_t *C) {
if (transA && transB) {
return halide_sgemm_transAB(a, A, B, b, C, C);
} else if (transA) {
return halide_sgemm_transA(a, A, B, b, C, C);
} else if (transB) {
return halide_sgemm_transB(a, A, B, b, C, C);
} else {
return halide_sgemm_notrans(a, A, B, b, C, C);
}
return -1;
}
inline int halide_dgemm(bool transA, bool transB, double a, buffer_t *A, buffer_t *B, double b, buffer_t *C) {
if (transA && transB) {
return halide_dgemm_transAB(a, A, B, b, C, C);
} else if (transA) {
return halide_dgemm_transA(a, A, B, b, C, C);
} else if (transB) {
return halide_dgemm_transB(a, A, B, b, C, C);
} else {
return halide_dgemm_notrans(a, A, B, b, C, C);
}
return -1;
}
enum HBLAS_ORDER {HblasRowMajor=101, HblasColMajor=102};
enum HBLAS_TRANSPOSE {HblasNoTrans=111, HblasTrans=112, HblasConjTrans=113};
enum HBLAS_UPLO {HblasUpper=121, HblasLower=122};
enum HBLAS_DIAG {HblasNonUnit=131, HblasUnit=132};
enum HBLAS_SIDE {HblasLeft=141, HblasRight=142};
#ifdef __cplusplus
extern "C" {
#endif
/*
* ===========================================================================
* Prototypes for level 1 BLAS functions (complex are recast as routines)
* ===========================================================================
*/
// float hblas_sdsdot(const int N, const float alpha, const float *X,
// const int incX, const float *Y, const int incY);
// double hblas_dsdot(const int N, const float *X, const int incX, const float *Y,
// const int incY);
float hblas_sdot(const int N, const float *X, const int incX,
const float *Y, const int incY);
double hblas_ddot(const int N, const double *X, const int incX,
const double *Y, const int incY);
/*
* Functions having prefixes S D SC DZ
*/
float hblas_snrm2(const int N, const float *X, const int incX);
float hblas_sasum(const int N, const float *X, const int incX);
double hblas_dnrm2(const int N, const double *X, const int incX);
double hblas_dasum(const int N, const double *X, const int incX);
/*
* Functions having standard 4 prefixes (S D C Z)
*/
// HBLAS_INDEX hblas_isamax(const int N, const float *X, const int incX);
// HBLAS_INDEX hblas_idamax(const int N, const double *X, const int incX);
// HBLAS_INDEX hblas_icamax(const int N, const void *X, const int incX);
// HBLAS_INDEX hblas_izamax(const int N, const void *X, const int incX);
/*
* ===========================================================================
* Prototypes for level 1 BLAS routines
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (s, d, c, z)
*/
// void hblas_sswap(const int N, float *X, const int incX,
// float *Y, const int incY);
void hblas_scopy(const int N, const float *X, const int incX,
float *Y, const int incY);
void hblas_saxpy(const int N, const float alpha, const float *X,
const int incX, float *Y, const int incY);
// void hblas_dswap(const int N, double *X, const int incX,
// double *Y, const int incY);
void hblas_dcopy(const int N, const double *X, const int incX,
double *Y, const int incY);
void hblas_daxpy(const int N, const double alpha, const double *X,
const int incX, double *Y, const int incY);
/*
* Routines with S and D prefix only
*/
// void hblas_srotg(float *a, float *b, float *c, float *s);
// void hblas_srotmg(float *d1, float *d2, float *b1, const float b2, float *P);
// void hblas_srot(const int N, float *X, const int incX,
// float *Y, const int incY, const float c, const float s);
// void hblas_srotm(const int N, float *X, const int incX,
// float *Y, const int incY, const float *P);
// void hblas_drotg(double *a, double *b, double *c, double *s);
// void hblas_drotmg(double *d1, double *d2, double *b1, const double b2, double *P);
// void hblas_drot(const int N, double *X, const int incX,
// double *Y, const int incY, const double c, const double s);
// void hblas_drotm(const int N, double *X, const int incX,
// double *Y, const int incY, const double *P);
/*
* Routines with S D C Z CS and ZD prefixes
*/
void hblas_sscal(const int N, const float alpha, float *X, const int incX);
void hblas_dscal(const int N, const double alpha, double *X, const int incX);
/*
* ===========================================================================
* Prototypes for level 2 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
void hblas_sgemv(const enum HBLAS_ORDER order,
const enum HBLAS_TRANSPOSE TransA, const int M, const int N,
const float alpha, const float *A, const int lda,
const float *X, const int incX, const float beta,
float *Y, const int incY);
void hblas_dgemv(const enum HBLAS_ORDER order,
const enum HBLAS_TRANSPOSE TransA, const int M, const int N,
const double alpha, const double *A, const int lda,
const double *X, const int incX, const double beta,
double *Y, const int incY);
void hblas_sger(const enum HBLAS_ORDER order, const int M, const int N,
const float alpha, const float *X, const int incX,
const float *Y, const int incY, float *A, const int lda);
void hblas_dger(const enum HBLAS_ORDER order, const int M, const int N,
const double alpha, const double *X, const int incX,
const double *Y, const int incY, double *A, const int lda);
/*
* ===========================================================================
* Prototypes for level 3 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
void hblas_sgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
const int K, const float alpha, const float *A,
const int lda, const float *B, const int ldb,
const float beta, float *C, const int ldc);
void hblas_dgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
const int K, const double alpha, const double *A,
const int lda, const double *B, const int ldb,
const double beta, double *C, const int ldc);
#ifdef __cplusplus
}
#endif
#endif // HALIDE_BLAS_H
| 36.206349 | 110 | 0.608505 |
9c9e90be8eedf138cd850023c8ad278b19c1f44c | 325 | lua | Lua | hammerspoon/.hammerspoon/init.lua | ben-z/dotfiles | 6107e2b61acabf77026d5a930ec773790e3b7e75 | [
"MIT"
] | 7 | 2016-08-29T02:22:58.000Z | 2021-05-13T18:42:56.000Z | hammerspoon/.hammerspoon/init.lua | ben-z/dotfiles | 6107e2b61acabf77026d5a930ec773790e3b7e75 | [
"MIT"
] | 3 | 2017-04-05T06:15:58.000Z | 2017-04-05T06:17:19.000Z | hammerspoon/.hammerspoon/init.lua | ben-z/dotfiles | 6107e2b61acabf77026d5a930ec773790e3b7e75 | [
"MIT"
] | 1 | 2020-04-25T17:38:36.000Z | 2020-04-25T17:38:36.000Z | -- Use Cmd+\ to show 1Password everywhere except Atom
function activate_1password()
local client = hs.application.frontmostApplication()
if client:title() == 'Atom' then
hs.eventtap.keyStroke({"cmd"}, "f12")
else
hs.eventtap.keyStroke({"cmd"}, "f11")
end
end
hs.hotkey.bind({"cmd"}, "\\", activate_1password)
| 29.545455 | 54 | 0.692308 |
0c92ac74a41c6d27584a5d7d7e530d1077058597 | 2,385 | py | Python | datasets/few_shot_test_pickle.py | PengWan-Yang/few-shot-transformer | c055239061744124c72960420cd4037495952b6d | [
"Apache-2.0"
] | 4 | 2022-02-06T19:51:19.000Z | 2022-03-15T21:19:23.000Z | datasets/few_shot_test_pickle.py | PengWan-Yang/few-shot-transformer | c055239061744124c72960420cd4037495952b6d | [
"Apache-2.0"
] | 1 | 2022-02-06T20:00:15.000Z | 2022-02-06T20:00:15.000Z | datasets/few_shot_test_pickle.py | PengWan-Yang/few-shot-transformer | c055239061744124c72960420cd4037495952b6d | [
"Apache-2.0"
] | null | null | null |
import pickle
# modify validation data
_few_shot_pickle_file = 'few_shot_test_data.pkl'
_few_shot_file = open(_few_shot_pickle_file, 'rb')
data_few_shot = pickle.load(_few_shot_file)
_few_shot_pickle_file = 'few_shot_val_data.pkl'
_few_shot_file = open(_few_shot_pickle_file, 'rb')
data_val = pickle.load(_few_shot_file)
_few_shot_pickle_file = 'few_shot_train_data.pkl'
_few_shot_file = open(_few_shot_pickle_file, 'rb')
data_train = pickle.load(_few_shot_file)
raise 1
for _list in data_few_shot:
for _video in _list:
_video['fg_name'] = _video['fg_name'].replace('/home/tao/dataset/v1-3/train_val_frames_3',
'datasets/activitynet13')
_video['bg_name'] = _video['bg_name'].replace('/home/tao/dataset/v1-3/train_val_frames_3',
'datasets/activitynet13')
pickle.dump(data_few_shot, open(_few_shot_pickle_file, "wb"))
print("done")
# modify testing data
_few_shot_pickle_file = 'few_shot_test_data.pkl'
_few_shot_file = open(_few_shot_pickle_file, 'rb')
data_few_shot = pickle.load(_few_shot_file)
for _list in data_few_shot:
for _video in _list:
_video['fg_name'] = _video['fg_name'].replace('/home/tao/dataset/v1-3/train_val_frames_3',
'datasets/activitynet13')
_video['bg_name'] = _video['bg_name'].replace('/home/tao/dataset/v1-3/train_val_frames_3',
'datasets/activitynet13')
pickle.dump(data_few_shot, open(_few_shot_pickle_file, "wb"))
print("done")
# modify training data
_few_shot_pickle_file = 'few_shot_train_data.pkl'
_few_shot_file = open(_few_shot_pickle_file, 'rb')
data_few_shot = pickle.load(_few_shot_file)
index = 0
for k, _list in data_few_shot.items():
for _video in _list:
_video['video_id'] = "query_{:0>5d}".format(index)
_video['fg_name'] = _video['fg_name'].replace('dataset/activitynet13/train_val_frames_3',
'datasets/activitynet13')
_video['bg_name'] = _video['bg_name'].replace('dataset/activitynet13/train_val_frames_3',
'datasets/activitynet13')
index = index + 1
pickle.dump(data_few_shot, open(_few_shot_pickle_file, "wb"))
print("done")
| 37.857143 | 98 | 0.65283 |
6b57d95a85a1a21c887195bb3b336da68c9f9b1a | 763 | lua | Lua | lua/discord/locale/pirate.lua | manix84/discord_gmod_addon | e84b37296f2fa4372fdca7473b41d0cce505ef37 | [
"MIT"
] | 3 | 2020-06-29T01:43:30.000Z | 2021-07-09T02:18:08.000Z | lua/discord/locale/pirate.lua | manix84/discord_gmod_addon | e84b37296f2fa4372fdca7473b41d0cce505ef37 | [
"MIT"
] | 3 | 2021-07-09T02:19:41.000Z | 2021-07-09T02:46:31.000Z | lua/discord/locale/pirate.lua | manix84/discord_gmod_addon | e84b37296f2fa4372fdca7473b41d0cce505ef37 | [
"MIT"
] | 45 | 2020-07-09T10:14:48.000Z | 2022-02-03T19:28:02.000Z | -- Talk like a pirate.
local pirate = {
MUTED_FOR_DURATION = "Ye be muted fer %s seconds.",
MUTED_FOR_ROUND = "Ye be muted 'til th' round ends.",
UNMUTED = "Ye be no longer muted.",
ERROR_MESSAGE = "Error: %s",
JOIN_DISCORD_PROMPT = "Join th' Discord server - %s",
CONNECTION_INSTRUCTIONS = "Then link to the sky by sayin' '!discord DISCORD_NAME' in th' chat. E.g. '!discord Manix84'",
NAME_NOT_FOUND = "Thar be no one on th' Discord server the name of '%s'.",
MULTIPLE_NAMES_FOUND = "Thar be many %s's. What be yer full tag, EG: '!discord Manix84#1234'",
CONNECTION_SUCCESSFUL = "'%s' (%s) successfully bound t' %s",
WELCOME_CONNECTED = "Ye be connected t' Discord.",
AUTOMATIC_MATCH = "Attemptin' t' match yer name, %s"
};
return pirate;
| 44.882353 | 122 | 0.685452 |
977170ad700ca0d7052644e423fc1cf64cdef5f8 | 753 | swift | Swift | Hummingbird/Environment.swift | glowinthedark/Hummingbird | fdc79a14c94099c3cebd68e26a9da37685ed1e3a | [
"MIT"
] | 122 | 2019-03-03T14:26:12.000Z | 2022-03-28T07:05:24.000Z | Hummingbird/Environment.swift | glowinthedark/Hummingbird | fdc79a14c94099c3cebd68e26a9da37685ed1e3a | [
"MIT"
] | 30 | 2019-02-17T09:48:09.000Z | 2022-03-02T15:41:40.000Z | Hummingbird/Environment.swift | glowinthedark/Hummingbird | fdc79a14c94099c3cebd68e26a9da37685ed1e3a | [
"MIT"
] | 17 | 2019-06-13T19:02:52.000Z | 2022-02-19T17:49:37.000Z | //
// World.swift
// Hummingbird
//
// Created by Sven A. Schmidt on 15/05/2019.
// Copyright © 2019 finestructure. All rights reserved.
//
// Motivation: https://www.pointfree.co/blog/posts/21-how-to-control-the-world
//
import Foundation
public struct Environment {
public var environment = ProcessInfo.processInfo.environment
public var date: () -> Date = { Date() }
public var defaults: () -> UserDefaults = {
UserDefaults(suiteName: "co.finestructure.Hummingbird.prefs") ?? .standard
}
#if COMMERCIAL
public var featureFlags = FeatureFlags(commercial: true)
#else
public var featureFlags = FeatureFlags(commercial: false)
#endif
public var gumroad = Gumroad()
}
var Current = Environment()
| 25.1 | 82 | 0.686587 |
b82ab7f5e33056d9b5edd4db417bf03d46d5ffe9 | 2,430 | ps1 | PowerShell | distros/windows/2016/build/scripts/fix.ps1 | arangodb-helper/build-docker-containers | 51fe68e5165cbca59cac07e6ad51af1bef85faf3 | [
"Apache-2.0"
] | 4 | 2018-01-22T17:58:21.000Z | 2020-11-23T06:28:59.000Z | distros/windows/2016/build/scripts/fix.ps1 | arangodb-helper/build-docker-containers | 51fe68e5165cbca59cac07e6ad51af1bef85faf3 | [
"Apache-2.0"
] | 1 | 2020-01-05T19:23:43.000Z | 2020-01-08T09:05:57.000Z | distros/windows/2016/build/scripts/fix.ps1 | arangodb-helper/build-docker-containers | 51fe68e5165cbca59cac07e6ad51af1bef85faf3 | [
"Apache-2.0"
] | 3 | 2016-12-06T02:25:54.000Z | 2018-02-11T17:16:02.000Z | [Environment]::SetEnvironmentVariable("Path", $env:Path + ';C:\Program Files\CMake\bin\;C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64;C:\Program Files (x86)\MSBuild\14.0\Bin\',[EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("INCLUDE", 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include;C:\Program Files (x86)\Windows Kits\10\Include\10.0.10240.0\ucrt',[EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("GYP_MSVS_OVERRIDE_PATH", "C:\Program Files (x86)\Microsoft Visual Studio 14.0", [EnvironmentVariableTarget]::Machine)
$lib = 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\lib\amd64;C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\ucrt\x64'
[Environment]::SetEnvironmentVariable("LIBPATH", $lib, [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("LIB", $lib, [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("OPENSSL_INCLUDE_DIR", 'C:\Program Files\PackageManagement\NuGet\Packages\openssl.v140.windesktop.msvcstl.dyn.rt-dyn.x64.1.0.2.0\build\native\include', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("LIB_EAY_RELEASE", 'C:\Program Files\PackageManagement\NuGet\Packages\openssl.v140.windesktop.msvcstl.dyn.rt-dyn.x64.1.0.2.0\lib\native\v140\windesktop\msvcstl\dyn\rt-dyn\x64\release\libeay32.lib', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("SSL_EAY_RELEASE", 'C:\Program Files\PackageManagement\NuGet\Packages\openssl.v140.windesktop.msvcstl.dyn.rt-dyn.x64.1.0.2.0\lib\native\v140\windesktop\msvcstl\dyn\rt-dyn\x64\release\ssleay32.lib', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("LIB_EAY_RELEASE_DLL", 'C:\Program Files\PackageManagement\NuGet\Packages\openssl.v140.windesktop.msvcstl.dyn.rt-dyn.x64.1.0.2.0\lib\native\v140\windesktop\msvcstl\dyn\rt-dyn\x64\release\libeay32.dll', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("SSL_EAY_RELEASE_DLL", 'C:\Program Files\PackageManagement\NuGet\Packages\openssl.v140.windesktop.msvcstl.dyn.rt-dyn.x64.1.0.2.0\lib\native\v140\windesktop\msvcstl\dyn\rt-dyn\x64\release\ssleay32.dll', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("_IsNativeEnvironment", 'true', [EnvironmentVariableTarget]::Machine)
| 151.875 | 277 | 0.801646 |
05fc8a172f4276be6f95e92d03bd8197c8bde6c1 | 11,523 | html | HTML | app/content/texts/eng_web/PS59.html | youfriend20012001/VNGKBible | 63f7b88f3d0d257a8730929c57e65221a6ce8824 | [
"MIT"
] | null | null | null | app/content/texts/eng_web/PS59.html | youfriend20012001/VNGKBible | 63f7b88f3d0d257a8730929c57e65221a6ce8824 | [
"MIT"
] | 4 | 2020-04-04T04:16:48.000Z | 2022-03-26T19:19:12.000Z | app/content/texts/eng_web/PS59.html | youfriend20012001/VNGKBible | 63f7b88f3d0d257a8730929c57e65221a6ce8824 | [
"MIT"
] | 1 | 2020-11-25T17:39:39.000Z | 2020-11-25T17:39:39.000Z | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Psalms 59 (WEB)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />
<script src="../../../build/mobile.js"></script>
</head>
<body dir="ltr" class="section-document">
<div class="header"><div class="nav">
<a class="name" href="PS.html">World English Bible</a><a class="location" href="PS.html">Psalms 59</a><a class="prev" href="PS58.html"><</a>
<a class="home" href="index.html">=</a>
<a class="next" href="PS60.html">></a>
</div></div>
<div class="section chapter PS PS59 eng_web eng " dir="ltr" lang="en" data-id="PS59" data-nextid="PS60" data-previd="PS58">
<div class="c">Psalm 59</div>
<div class="d">For the Chief Musician. To the tune of “Do Not Destroy.” A poem by David, when Saul sent, and they watched the house to kill him.
</div>
<div class="q">
<span class="v-num v-1">1 </span><span class="v PS59_1" data-id="PS59_1">Deliver me from my enemies, my God.</span>
</div>
<div class="q2">
<span class="v PS59_1" data-id="PS59_1">Set me on high from those who rise up against me.</span>
</div>
<div class="q">
<span class="v-num v-2">2 </span><span class="v PS59_2" data-id="PS59_2">Deliver me from the workers of iniquity.</span>
</div>
<div class="q2">
<span class="v PS59_2" data-id="PS59_2">Save me from the bloodthirsty men.</span>
</div>
<div class="q">
<span class="v-num v-3">3 </span><span class="v PS59_3" data-id="PS59_3">For, behold, they lie in wait for my soul.</span>
</div>
<div class="q2">
<span class="v PS59_3" data-id="PS59_3">The mighty gather themselves together against me,</span>
</div>
<div class="q2">
<span class="v PS59_3" data-id="PS59_3">not for my disobedience, nor for my sin, Yahweh.</span>
</div>
<div class="q">
<span class="v-num v-4">4 </span><span class="v PS59_4" data-id="PS59_4">I have done no wrong, yet they are ready to attack me.</span>
</div>
<div class="q2">
<span class="v PS59_4" data-id="PS59_4">Rise up, behold, and help me!</span>
</div>
<div class="q">
<span class="v-num v-5">5 </span><span class="v PS59_5" data-id="PS59_5">You, Yahweh God of Armies, the God of Israel,</span>
</div>
<div class="q2">
<span class="v PS59_5" data-id="PS59_5">rouse yourself to punish the nations.</span>
</div>
<div class="q2">
<span class="v PS59_5" data-id="PS59_5">Show no mercy to the wicked traitors. </span><div class="qs">Selah.</div></span>
</div>
<div class="q">
<span class="v-num v-6">6 </span><span class="v PS59_6" data-id="PS59_6">They return at evening, howling like dogs,</span>
</div>
<div class="q2">
<span class="v PS59_6" data-id="PS59_6">and prowl around the city.</span>
</div>
<div class="q">
<span class="v-num v-7">7 </span><span class="v PS59_7" data-id="PS59_7">Behold, they spew with their mouth.</span>
</div>
<div class="q2">
<span class="v PS59_7" data-id="PS59_7">Swords are in their lips,</span>
</div>
<div class="q2">
<span class="v PS59_7" data-id="PS59_7">“For”, they say, “who hears us?”</span>
</div>
<div class="q">
<span class="v-num v-8">8 </span><span class="v PS59_8" data-id="PS59_8">But you, Yahweh, laugh at them.</span>
</div>
<div class="q2">
<span class="v PS59_8" data-id="PS59_8">You scoff at all the nations.</span>
</div>
<div class="q">
<span class="v-num v-9">9 </span><span class="v PS59_9" data-id="PS59_9">Oh, my Strength, I watch for you,</span>
</div>
<div class="q2">
<span class="v PS59_9" data-id="PS59_9">for God is my high tower.</span>
</div>
<div class="q">
<span class="v-num v-10">10 </span><span class="v PS59_10" data-id="PS59_10">My God will go before me with his loving kindness.</span>
</div>
<div class="q2">
<span class="v PS59_10" data-id="PS59_10">God will let me look at my enemies in triumph.</span>
</div>
<div class="q">
<span class="v-num v-11">11 </span><span class="v PS59_11" data-id="PS59_11">Don’t kill them, or my people may forget.</span>
</div>
<div class="q2">
<span class="v PS59_11" data-id="PS59_11">Scatter them by your power, and bring them down, Lord our shield.</span>
</div>
<div class="q">
<span class="v-num v-12">12 </span><span class="v PS59_12" data-id="PS59_12">For the sin of their mouth, and the words of their lips,</span>
</div>
<div class="q2">
<span class="v PS59_12" data-id="PS59_12">let them be caught in their pride,</span>
</div>
<div class="q2">
<span class="v PS59_12" data-id="PS59_12">for the curses and lies which they utter.</span>
</div>
<div class="q">
<span class="v-num v-13">13 </span><span class="v PS59_13" data-id="PS59_13">Consume them in wrath.</span>
</div>
<div class="q2">
<span class="v PS59_13" data-id="PS59_13">Consume them, and they will be no more.</span>
</div>
<div class="q">
<span class="v PS59_13" data-id="PS59_13">Let them know that God rules in Jacob,</span>
</div>
<div class="q2">
<span class="v PS59_13" data-id="PS59_13">to the ends of the earth. </span><div class="qs">Selah.</div></span>
</div>
<div class="q">
<span class="v-num v-14">14 </span><span class="v PS59_14" data-id="PS59_14">At evening let them return.</span>
</div>
<div class="q2">
<span class="v PS59_14" data-id="PS59_14">Let them howl like a dog, and go around the city.</span>
</div>
<div class="q">
<span class="v-num v-15">15 </span><span class="v PS59_15" data-id="PS59_15">They shall wander up and down for food,</span>
</div>
<div class="q2">
<span class="v PS59_15" data-id="PS59_15">and wait all night if they aren’t satisfied.</span>
<div class="b"> </div>
</div>
<div class="q">
<span class="v-num v-16">16 </span><span class="v PS59_16" data-id="PS59_16">But I will sing of your strength.</span>
</div>
<div class="q2">
<span class="v PS59_16" data-id="PS59_16">Yes, I will sing aloud of your loving kindness in the morning.</span>
</div>
<div class="q">
<span class="v PS59_16" data-id="PS59_16">For you have been my high tower,</span>
</div>
<div class="q2">
<span class="v PS59_16" data-id="PS59_16">a refuge in the day of my distress.</span>
</div>
<div class="q">
<span class="v-num v-17">17 </span><span class="v PS59_17" data-id="PS59_17">To you, my strength, I will sing praises.</span>
</div>
<div class="q2">
<span class="v PS59_17" data-id="PS59_17">For God is my high tower, the God of my mercy.</span>
</div>
</div>
<div class="footnotes">
<span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">1:2</a><span class="text">“Yahweh” is God’s proper Name, sometimes rendered “LORD” (all caps) in other translations.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">2:2</a><span class="text">The word “Anointed” is the same as the word for “Messiah” or “Christ”</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">2:4</a><span class="text">The word translated “Lord” is “Adonai.”</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">2:12</a><span class="text">or, Kiss the son</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">3:2</a><span class="text">The Hebrew word rendered “God” is “אֱלֹהִ֑ים” (Elohim).</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">6:5</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">7:14</a><span class="text">“Behold”, from “הִנֵּה”, means look at, take notice, observe, see, or gaze at. It is often used as an interjection.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">8:5</a><span class="text">Hebrew: Elohim. The word Elohim, used here, usually means “God”, but can also mean “gods”, “princes”, or “angels”. The Septuagint reads “angels”
here.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">9:17</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">16:10</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">18:5</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">18:50</a><span class="text">or, seed</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">22:16</a><span class="text">So Dead Sea Scrolls. Masoretic Text reads, “Like a lion, they pin my hands and feet.”</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">25:13</a><span class="text">or, seed</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">30:3</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">31:17</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">34:1</a><span class="text">Psalm 34 is an acrostic poem, with each verse starting with a letter of the alphabet (ordered from Alef to Tav).</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">37:26</a><span class="text">or, seed</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">42:1</a><span class="text">The Hebrew word rendered “God” is “אֱלֹהִ֑ים” (Elohim).</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">42:8</a><span class="text">“Yahweh” is God’s proper Name, sometimes rendered “LORD” (all caps) in other translations.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">44:23</a><span class="text">The word translated “Lord” is “Adonai.”</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">45:17</a><span class="text">Alamoth is a musical term.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">49:14</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">49:14</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">49:15</a><span class="text">Sheol is the place of the dead.</span></span><span class="footnote" id="footnote-1"><span class="key">+</span><a class="backref" href="#note-1">55:15</a><span class="text">Sheol is the place of the dead.</span></span>
</div>
<div class="footer"><div class="nav">
<a class="prev" href="PS58.html"><</a>
<a class="home" href="index.html">=</a>
<a class="next" href="PS60.html">></a>
</div></div>
</body>
</html> | 72.93038 | 4,922 | 0.672568 |
fb432271cc68b0be6bcfc32a3209a999c90dec85 | 14,436 | java | Java | src/windows/classes/sun/nio/fs/WindowsSecurityDescriptor.java | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 12 | 2018-04-04T12:47:40.000Z | 2022-01-02T04:36:38.000Z | src/windows/classes/sun/nio/fs/WindowsSecurityDescriptor.java | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | null | null | null | src/windows/classes/sun/nio/fs/WindowsSecurityDescriptor.java | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2021-12-10T07:51:50.000Z | 2021-12-10T07:51:50.000Z | /*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.nio.fs;
import java.nio.file.ProviderMismatchException;
import java.nio.file.attribute.*;
import java.util.*;
import java.io.IOException;
import sun.misc.Unsafe;
import static sun.nio.fs.WindowsNativeDispatcher.*;
import static sun.nio.fs.WindowsConstants.*;
/**
* A SecurityDescriptor for use when setting a file's ACL or creating a file
* with an initial ACL.
*/
class WindowsSecurityDescriptor {
private static final Unsafe unsafe = Unsafe.getUnsafe();
/**
* typedef struct _ACL {
* BYTE AclRevision;
* BYTE Sbz1;
* WORD AclSize;
* WORD AceCount;
* WORD Sbz2;
* } ACL;
*
* typedef struct _ACE_HEADER {
* BYTE AceType;
* BYTE AceFlags;
* WORD AceSize;
* } ACE_HEADER;
*
* typedef struct _ACCESS_ALLOWED_ACE {
* ACE_HEADER Header;
* ACCESS_MASK Mask;
* DWORD SidStart;
* } ACCESS_ALLOWED_ACE;
*
* typedef struct _ACCESS_DENIED_ACE {
* ACE_HEADER Header;
* ACCESS_MASK Mask;
* DWORD SidStart;
* } ACCESS_DENIED_ACE;
*
* typedef struct _SECURITY_DESCRIPTOR {
* BYTE Revision;
* BYTE Sbz1;
* SECURITY_DESCRIPTOR_CONTROL Control;
* PSID Owner;
* PSID Group;
* PACL Sacl;
* PACL Dacl;
* } SECURITY_DESCRIPTOR;
*/
private static final short SIZEOF_ACL = 8;
private static final short SIZEOF_ACCESS_ALLOWED_ACE = 12;
private static final short SIZEOF_ACCESS_DENIED_ACE = 12;
private static final short SIZEOF_SECURITY_DESCRIPTOR = 20;
private static final short OFFSETOF_TYPE = 0;
private static final short OFFSETOF_FLAGS = 1;
private static final short OFFSETOF_ACCESS_MASK = 4;
private static final short OFFSETOF_SID = 8;
// null security descriptor
private static final WindowsSecurityDescriptor NULL_DESCRIPTOR =
new WindowsSecurityDescriptor();
// native resources
private final List<Long> sidList;
private final NativeBuffer aclBuffer, sdBuffer;
/**
* Creates the "null" SecurityDescriptor
*/
private WindowsSecurityDescriptor() {
this.sidList = null;
this.aclBuffer = null;
this.sdBuffer = null;
}
/**
* Creates a SecurityDescriptor from the given ACL
*/
private WindowsSecurityDescriptor(List<AclEntry> acl) throws IOException {
boolean initialized = false;
// SECURITY: need to copy list in case size changes during processing
acl = new ArrayList<AclEntry>(acl);
// list of SIDs
sidList = new ArrayList<Long>(acl.size());
try {
// initial size of ACL
int size = SIZEOF_ACL;
// get the SID for each entry
for (AclEntry entry: acl) {
UserPrincipal user = entry.principal();
if (!(user instanceof WindowsUserPrincipals.User))
throw new ProviderMismatchException();
String sidString = ((WindowsUserPrincipals.User)user).sidString();
try {
long pSid = ConvertStringSidToSid(sidString);
sidList.add(pSid);
// increase size to allow for entry
size += GetLengthSid(pSid) +
Math.max(SIZEOF_ACCESS_ALLOWED_ACE, SIZEOF_ACCESS_DENIED_ACE);
} catch (WindowsException x) {
throw new IOException("Failed to get SID for " + user.getName()
+ ": " + x.errorString());
}
}
// allocate memory for the ACL
aclBuffer = NativeBuffers.getNativeBuffer(size);
sdBuffer = NativeBuffers.getNativeBuffer(SIZEOF_SECURITY_DESCRIPTOR);
InitializeAcl(aclBuffer.address(), size);
// Add entry ACE to the ACL
int i = 0;
while (i < acl.size()) {
AclEntry entry = acl.get(i);
long pSid = sidList.get(i);
try {
encode(entry, pSid, aclBuffer.address());
} catch (WindowsException x) {
throw new IOException("Failed to encode ACE: " +
x.errorString());
}
i++;
}
// initialize security descriptor and set DACL
InitializeSecurityDescriptor(sdBuffer.address());
SetSecurityDescriptorDacl(sdBuffer.address(), aclBuffer.address());
initialized = true;
} catch (WindowsException x) {
throw new IOException(x.getMessage());
} finally {
// release resources if not completely initialized
if (!initialized)
release();
}
}
/**
* Releases memory associated with SecurityDescriptor
*/
void release() {
if (sdBuffer != null)
sdBuffer.release();
if (aclBuffer != null)
aclBuffer.release();
if (sidList != null) {
// release memory for SIDs
for (Long sid: sidList) {
LocalFree(sid);
}
}
}
/**
* Returns address of SecurityDescriptor
*/
long address() {
return (sdBuffer == null) ? 0L : sdBuffer.address();
}
// decode Windows ACE to NFSv4 AclEntry
private static AclEntry decode(long aceAddress)
throws IOException
{
// map type
byte aceType = unsafe.getByte(aceAddress + OFFSETOF_TYPE);
if (aceType != ACCESS_ALLOWED_ACE_TYPE && aceType != ACCESS_DENIED_ACE_TYPE)
return null;
AclEntryType type;
if (aceType == ACCESS_ALLOWED_ACE_TYPE) {
type = AclEntryType.ALLOW;
} else {
type = AclEntryType.DENY;
}
// map flags
byte aceFlags = unsafe.getByte(aceAddress + OFFSETOF_FLAGS);
Set<AclEntryFlag> flags = EnumSet.noneOf(AclEntryFlag.class);
if ((aceFlags & OBJECT_INHERIT_ACE) != 0)
flags.add(AclEntryFlag.FILE_INHERIT);
if ((aceFlags & CONTAINER_INHERIT_ACE) != 0)
flags.add(AclEntryFlag.DIRECTORY_INHERIT);
if ((aceFlags & NO_PROPAGATE_INHERIT_ACE) != 0)
flags.add(AclEntryFlag.NO_PROPAGATE_INHERIT);
if ((aceFlags & INHERIT_ONLY_ACE) != 0)
flags.add(AclEntryFlag.INHERIT_ONLY);
// map access mask
int mask = unsafe.getInt(aceAddress + OFFSETOF_ACCESS_MASK);
Set<AclEntryPermission> perms = EnumSet.noneOf(AclEntryPermission.class);
if ((mask & FILE_READ_DATA) > 0)
perms.add(AclEntryPermission.READ_DATA);
if ((mask & FILE_WRITE_DATA) > 0)
perms.add(AclEntryPermission.WRITE_DATA);
if ((mask & FILE_APPEND_DATA ) > 0)
perms.add(AclEntryPermission.APPEND_DATA);
if ((mask & FILE_READ_EA) > 0)
perms.add(AclEntryPermission.READ_NAMED_ATTRS);
if ((mask & FILE_WRITE_EA) > 0)
perms.add(AclEntryPermission.WRITE_NAMED_ATTRS);
if ((mask & FILE_EXECUTE) > 0)
perms.add(AclEntryPermission.EXECUTE);
if ((mask & FILE_DELETE_CHILD ) > 0)
perms.add(AclEntryPermission.DELETE_CHILD);
if ((mask & FILE_READ_ATTRIBUTES) > 0)
perms.add(AclEntryPermission.READ_ATTRIBUTES);
if ((mask & FILE_WRITE_ATTRIBUTES) > 0)
perms.add(AclEntryPermission.WRITE_ATTRIBUTES);
if ((mask & DELETE) > 0)
perms.add(AclEntryPermission.DELETE);
if ((mask & READ_CONTROL) > 0)
perms.add(AclEntryPermission.READ_ACL);
if ((mask & WRITE_DAC) > 0)
perms.add(AclEntryPermission.WRITE_ACL);
if ((mask & WRITE_OWNER) > 0)
perms.add(AclEntryPermission.WRITE_OWNER);
if ((mask & SYNCHRONIZE) > 0)
perms.add(AclEntryPermission.SYNCHRONIZE);
// lookup SID to create UserPrincipal
long sidAddress = aceAddress + OFFSETOF_SID;
UserPrincipal user = WindowsUserPrincipals.fromSid(sidAddress);
return AclEntry.newBuilder()
.setType(type)
.setPrincipal(user)
.setFlags(flags).setPermissions(perms).build();
}
// encode NFSv4 AclEntry as Windows ACE to given ACL
private static void encode(AclEntry ace, long sidAddress, long aclAddress)
throws WindowsException
{
// ignore non-allow/deny entries for now
if (ace.type() != AclEntryType.ALLOW && ace.type() != AclEntryType.DENY)
return;
boolean allow = (ace.type() == AclEntryType.ALLOW);
// map access mask
Set<AclEntryPermission> aceMask = ace.permissions();
int mask = 0;
if (aceMask.contains(AclEntryPermission.READ_DATA))
mask |= FILE_READ_DATA;
if (aceMask.contains(AclEntryPermission.WRITE_DATA))
mask |= FILE_WRITE_DATA;
if (aceMask.contains(AclEntryPermission.APPEND_DATA))
mask |= FILE_APPEND_DATA;
if (aceMask.contains(AclEntryPermission.READ_NAMED_ATTRS))
mask |= FILE_READ_EA;
if (aceMask.contains(AclEntryPermission.WRITE_NAMED_ATTRS))
mask |= FILE_WRITE_EA;
if (aceMask.contains(AclEntryPermission.EXECUTE))
mask |= FILE_EXECUTE;
if (aceMask.contains(AclEntryPermission.DELETE_CHILD))
mask |= FILE_DELETE_CHILD;
if (aceMask.contains(AclEntryPermission.READ_ATTRIBUTES))
mask |= FILE_READ_ATTRIBUTES;
if (aceMask.contains(AclEntryPermission.WRITE_ATTRIBUTES))
mask |= FILE_WRITE_ATTRIBUTES;
if (aceMask.contains(AclEntryPermission.DELETE))
mask |= DELETE;
if (aceMask.contains(AclEntryPermission.READ_ACL))
mask |= READ_CONTROL;
if (aceMask.contains(AclEntryPermission.WRITE_ACL))
mask |= WRITE_DAC;
if (aceMask.contains(AclEntryPermission.WRITE_OWNER))
mask |= WRITE_OWNER;
if (aceMask.contains(AclEntryPermission.SYNCHRONIZE))
mask |= SYNCHRONIZE;
// map flags
Set<AclEntryFlag> aceFlags = ace.flags();
byte flags = 0;
if (aceFlags.contains(AclEntryFlag.FILE_INHERIT))
flags |= OBJECT_INHERIT_ACE;
if (aceFlags.contains(AclEntryFlag.DIRECTORY_INHERIT))
flags |= CONTAINER_INHERIT_ACE;
if (aceFlags.contains(AclEntryFlag.NO_PROPAGATE_INHERIT))
flags |= NO_PROPAGATE_INHERIT_ACE;
if (aceFlags.contains(AclEntryFlag.INHERIT_ONLY))
flags |= INHERIT_ONLY_ACE;
if (allow) {
AddAccessAllowedAceEx(aclAddress, flags, mask, sidAddress);
} else {
AddAccessDeniedAceEx(aclAddress, flags, mask, sidAddress);
}
}
/**
* Creates a security descriptor with a DACL representing the given ACL.
*/
static WindowsSecurityDescriptor create(List<AclEntry> acl)
throws IOException
{
return new WindowsSecurityDescriptor(acl);
}
/**
* Processes the array of attributes looking for the attribute "acl:acl".
* Returns security descriptor representing the ACL or the "null" security
* descriptor if the attribute is not in the array.
*/
@SuppressWarnings("unchecked")
static WindowsSecurityDescriptor fromAttribute(FileAttribute<?>... attrs)
throws IOException
{
WindowsSecurityDescriptor sd = NULL_DESCRIPTOR;
for (FileAttribute<?> attr: attrs) {
// if more than one ACL specified then last one wins
if (sd != NULL_DESCRIPTOR)
sd.release();
if (attr == null)
throw new NullPointerException();
if (attr.name().equals("acl:acl")) {
List<AclEntry> acl = (List<AclEntry>)attr.value();
sd = new WindowsSecurityDescriptor(acl);
} else {
throw new UnsupportedOperationException("'" + attr.name() +
"' not supported as initial attribute");
}
}
return sd;
}
/**
* Extracts DACL from security descriptor.
*/
static List<AclEntry> getAcl(long pSecurityDescriptor) throws IOException {
// get address of DACL
long aclAddress = GetSecurityDescriptorDacl(pSecurityDescriptor);
// get ACE count
int aceCount = 0;
if (aclAddress == 0L) {
// no ACEs
aceCount = 0;
} else {
AclInformation aclInfo = GetAclInformation(aclAddress);
aceCount = aclInfo.aceCount();
}
ArrayList<AclEntry> result = new ArrayList<>(aceCount);
// decode each of the ACEs to AclEntry objects
for (int i=0; i<aceCount; i++) {
long aceAddress = GetAce(aclAddress, i);
AclEntry entry = decode(aceAddress);
if (entry != null)
result.add(entry);
}
return result;
}
}
| 36.732824 | 86 | 0.603838 |
38b2e3cac5349d0b657a1edf74f06e527357763d | 10,777 | c | C | src/ch8.c | ITotalJustice/chip8 | 51ba3762715542ed58cde2add23d4eed9e649eb7 | [
"MIT"
] | 3 | 2020-07-04T15:42:44.000Z | 2020-07-07T19:16:56.000Z | src/ch8.c | ITotalJustice/TotalCH8 | 51ba3762715542ed58cde2add23d4eed9e649eb7 | [
"MIT"
] | 1 | 2020-07-08T14:31:00.000Z | 2020-07-08T14:31:00.000Z | src/ch8.c | ITotalJustice/TotalCH8 | 51ba3762715542ed58cde2add23d4eed9e649eb7 | [
"MIT"
] | 1 | 2020-07-08T10:45:55.000Z | 2020-07-08T10:45:55.000Z | #include "ch8.h"
// TODO: remove these
/// Defaults.
#define CH8_VSYNC true
#define CH8_CLOCK 10
/// Helper macros.
#define CH8_opcode ch8->var.opcode
#define CH8_ram ch8->mem.ram
#define CH8_stack ch8->mem.stack
#define CH8_PC ch8->reg.pc
#define CH8_SP ch8->reg.sp
#define CH8_I ch8->reg.i
#define CH8_V ch8->reg.v
#define CH8_DT ch8->reg.st
#define CH8_ST ch8->reg.st
#define CH8_pixels ch8->display.pixels
#define CH8_width ch8->display.width
#define CH8_height ch8->display.height
#define CH8_size ch8->display.size
#define CH8_wrap ch8->display.wrap
#define CH8_draw ch8->display.draw
#define CH8_keys ch8->input.keys
#define CH8_nnn ch8->var.nnn
#define CH8_kk ch8->var.kk
#define CH8_n ch8->var.n
#define CH8_x ch8->var.x
#define CH8_y ch8->var.y
static inline void __ch8_memset(void *p, const int v, uint32_t len) {
uint8_t *ptr = (uint8_t*)p;
uint8_t value = (uint8_t)v;
while (len--) *ptr++ = value;
}
static inline void __ch8_memcpy(void *dst, const void *src, uint32_t len) {
uint8_t *d = (uint8_t*)dst;
const uint8_t *s = (const uint8_t*)src;
while (len--) *d++ = *s++;
}
#define MEMSET(p,v,len) __ch8_memset((void*)(p),(v),(len))
#define MEMCPY(d,s,len) __ch8_memcpy((void*)(d),(const void*)(s),(len))
static inline uint8_t __ch8_rand(struct CH8_Core* ch8) {
ch8->seed = (214013*ch8->seed+2531011);
return ((ch8->seed>>16)&0x7FFF) & 0xFF;
}
static void __ch8_reset(struct CH8_Core* ch8, const bool full) {
if (full) {
MEMSET(&ch8->mem, 0, sizeof(ch8->mem));
const uint8_t CH8_FONTSET[SPRITES_SIZE] = {
0xF0, 0x90, 0x90, 0x90, 0xF0, /// 0x0
0x20, 0x60, 0x20, 0x20, 0x70, /// 0x1
0xF0, 0x10, 0xF0, 0x80, 0xF0, /// 0x2
0xF0, 0x10, 0xF0, 0x10, 0xF0, /// 0x3
0x90, 0x90, 0xF0, 0x10, 0x10, /// 0x4
0xF0, 0x80, 0xF0, 0x10, 0xF0, /// 0x5
0xF0, 0x80, 0xF0, 0x90, 0xF0, /// 0x6
0xF0, 0x10, 0x20, 0x40, 0x40, /// 0x7
0xF0, 0x90, 0xF0, 0x90, 0xF0, /// 0x8
0xF0, 0x90, 0xF0, 0x10, 0xF0, /// 0x9
0xF0, 0x90, 0xF0, 0x90, 0x90, /// 0xA
0xE0, 0x90, 0xE0, 0x90, 0xE0, /// 0xB
0xF0, 0x80, 0x80, 0x80, 0xF0, /// 0xC
0xE0, 0x90, 0x90, 0x90, 0xE0, /// 0xD
0xF0, 0x80, 0xF0, 0x80, 0xF0, /// 0xE
0xF0, 0x80, 0xF0, 0x80, 0x80 /// 0xF
};
MEMCPY(CH8_ram, CH8_FONTSET, 0x50);
} else {
MEMSET(ch8->mem.stack, 0, sizeof(ch8->mem.stack));
MEMSET(ch8->mem.ram + SPRITES_SIZE, 0, sizeof(ch8->mem.ram) - SPRITES_SIZE);
}
MEMSET(&ch8->reg, 0, sizeof(ch8->reg));
MEMSET(&ch8->var, 0, sizeof(ch8->var));
MEMSET(&ch8->input, 0, sizeof(ch8->input));
MEMSET(&ch8->display, 0, sizeof(ch8->display));
CH8_width = CH8_DISPLAY_W;
CH8_height = CH8_DISPLAY_H;
CH8_size = CH8_DISPLAY_SIZE;
CH8_PC = 0x200;
}
/// Instructions.
#define CLS() do { \
MEMSET(CH8_pixels, 0, sizeof(CH8_pixels)); \
ch8->display.draw = true; \
} while(0)
#define SE(a,b) do if (a == b) CH8_PC += 2; while (0)
#define SNE(a,b) do if (a != b) CH8_PC += 2; while (0)
#define SKP(v) do if (CH8_keys[v]) CH8_PC += 2; while (0)
#define SKNP(v) do if (!CH8_keys[v]) CH8_PC += 2; while (0)
#define RET() do CH8_PC = CH8_stack[CH8_SP--]; while(0)
#define CALL(v) do { CH8_stack[++CH8_SP] = CH8_PC; CH8_PC = v; } while(0)
#define JMP(v) do CH8_PC = v; while(0)
#define LD(a,b) do a = b; while(0)
#define AND(a,b) do a &= b; while(0)
#define ADD(a,b) do a += b; while(0)
#define ADC(a,b) do { CH8_V[0xF] = (a + b) > 0xFF; ADD(a,b); } while(0)
#define SUB(a,b,r) do r = a - b; while(0)
#define SBC(a,b,r) do { CH8_V[0xF] = a > b; SUB(a,b,r); } while(0)
#define OR(a,b) do a |= b; while(0)
#define XOR(a,b) do a ^= b; while(0)
#define SHL(a) do { CH8_V[0xF] = (a >> 7) & 1; a <<= 1; } while(0)
#define SHR(a) do { CH8_V[0xF] = a & 1; a >>= 1; } while(0)
#define RND(a,mask) do a = __ch8_rand(ch8) & mask; while(0)
#define DRAW() do { \
CH8_V[0xF] = 0; \
for (uint8_t n = 0; n < CH8_n; n++) { \
const uint16_t pos = (uint32_t)(CH8_V[CH8_x] + ((CH8_V[CH8_y] + n) * CH8_width)); \
for (uint8_t bit = 0; bit < 8; bit++) { \
if (CH8_ram[CH8_I + n] & (0x80 >> bit)) { \
uint16_t bitpos = pos + bit; \
if (bitpos >= CH8_DISPLAY_SIZE) { \
if (CH8_wrap) { \
bitpos %= CH8_width; \
} \
else { \
continue; \
} \
} \
CH8_V[0xF] |= CH8_pixels[bitpos]; \
CH8_pixels[bitpos] ^= 1; \
} \
} \
} \
ch8->display.draw = true; \
} while (0)
/// Insturction groups.
#define _0000() do { \
switch (CH8_opcode & 0x00FF) { \
case 0x00E0: CLS(); break; \
case 0x00EE: RET(); break; \
} \
} while(0)
#define _1000() do JMP(CH8_nnn); while(0)
#define _2000() do CALL(CH8_nnn); while(0)
#define _3000() do SE(CH8_V[CH8_x], CH8_kk); while(0)
#define _4000() do SNE(CH8_V[CH8_x], CH8_kk); while(0)
#define _5000() do SE(CH8_V[CH8_x], CH8_V[CH8_y]); while(0)
#define _6000() do LD(CH8_V[CH8_x], CH8_kk); while(0)
#define _7000() do ADD(CH8_V[CH8_x], CH8_kk); while(0)
#define _8000() do { \
switch (CH8_opcode & 0x000F) { \
case 0x0: LD(CH8_V[CH8_x], CH8_V[CH8_y]); break; \
case 0x1: OR(CH8_V[CH8_x], CH8_V[CH8_y]); break; \
case 0x2: AND(CH8_V[CH8_x], CH8_V[CH8_y]); break; \
case 0x3: XOR(CH8_V[CH8_x], CH8_V[CH8_y]); break; \
case 0x4: ADC(CH8_V[CH8_x], CH8_V[CH8_y]); break; \
case 0x5: SBC(CH8_V[CH8_x], CH8_V[CH8_y], CH8_V[CH8_x]); break; \
case 0x6: SHR(CH8_V[CH8_x]); break; \
case 0x7: SBC(CH8_V[CH8_y], CH8_V[CH8_x], CH8_V[CH8_x]); break; \
case 0xE: SHL(CH8_V[CH8_x]); break; \
} \
} while(0)
#define _9000() do SNE(CH8_V[CH8_x], CH8_V[CH8_y]); while(0)
#define _A000() do LD(CH8_I, CH8_nnn); while(0)
#define _B000() do JMP(CH8_V[0] + CH8_nnn); while(0)
#define _C000() do RND(CH8_V[CH8_x], CH8_kk); while(0)
#define _D000() do DRAW(); while(0)
#define _E000() do { \
switch (CH8_opcode & 0x00FF) { \
case 0x009E: SKP(CH8_V[CH8_x]); break; \
case 0x00A1: SKNP(CH8_V[CH8_x]); break; \
} \
} while(0)
#define _F000() do { \
switch (CH8_opcode & 0x00FF) { \
case 0x07: LD(CH8_V[CH8_x], CH8_DT); break; \
case 0x15: LD(CH8_DT, CH8_V[CH8_x]); break; \
case 0x18: LD(CH8_ST, CH8_V[CH8_x]); break; \
case 0x1E: ADD(CH8_I, CH8_V[CH8_x]); break; \
case 0x29: LD(CH8_I, CH8_V[CH8_x] * 5); break; \
case 0x33: \
LD(CH8_ram[CH8_I], (uint8_t)(CH8_V[CH8_x] % 1000) / 100); \
LD(CH8_ram[CH8_I + 1], (CH8_V[CH8_x] % 100) / 10); \
LD(CH8_ram[CH8_I + 2], (CH8_V[CH8_x] % 10) / 1); \
break; \
case 0x55: \
for (uint8_t i = 0; i <= CH8_x; i++) \
LD(CH8_ram[CH8_I + i], CH8_V[i]); \
break; \
case 0x65: \
for (uint8_t i = 0; i <= CH8_x; i++) \
LD(CH8_V[i], CH8_ram[CH8_I + i]); \
break; \
} \
} while(0)
#define FETCH() do { \
CH8_opcode = (CH8_ram[CH8_PC] << 8) | CH8_ram[CH8_PC + 1]; \
CH8_nnn = CH8_opcode & 0x0FFF; \
CH8_n = CH8_opcode & 0x000F; \
CH8_x = (CH8_opcode & 0x0F00) >> 8; \
CH8_y = (CH8_opcode & 0x00F0) >> 4; \
CH8_kk = CH8_opcode & 0x00FF; \
CH8_PC += 2; \
} while(0)
#define EXECUTE() do { \
switch ((CH8_opcode & 0xF000) >> 12) { \
case 0x0: _0000(); break; \
case 0x1: _1000(); break; \
case 0x2: _2000(); break; \
case 0x3: _3000(); break; \
case 0x4: _4000(); break; \
case 0x5: _5000(); break; \
case 0x6: _6000(); break; \
case 0x7: _7000(); break; \
case 0x8: _8000(); break; \
case 0x9: _9000(); break; \
case 0xA: _A000(); break; \
case 0xB: _B000(); break; \
case 0xC: _C000(); break; \
case 0xD: _D000(); break; \
case 0xE: _E000(); break; \
case 0xF: _F000(); break; \
} \
} while(0)
/// API
bool ch8_savestate(const struct CH8_Core* ch8, struct ch8_savestate* out_state) {
if (!ch8 || !out_state) return false;
out_state->seed = ch8->seed;
MEMCPY(&out_state->reg, &ch8->reg, sizeof(out_state->reg));
MEMCPY(out_state->stack, ch8->mem.stack, CH8_STACK_SIZE);
MEMCPY(out_state->ram, ch8->mem.ram + SPRITES_SIZE, sizeof(out_state->ram));
MEMCPY(out_state->display, ch8->display.pixels, sizeof(out_state->display));
return true;
}
bool ch8_loadstate(struct CH8_Core* ch8, const struct ch8_savestate* state) {
if (!ch8 || !state) return false;
ch8->seed = state->seed;
MEMSET(&ch8->input, 0, sizeof(ch8->input));
MEMCPY(&ch8->reg, &state->reg, sizeof(state->reg));
MEMCPY(ch8->mem.stack, state->stack, CH8_STACK_SIZE);
MEMCPY(ch8->mem.ram + SPRITES_SIZE, state->ram, sizeof(state->ram));
MEMCPY(ch8->display.pixels, state->display, sizeof(state->display));
return true;
}
void ch8_reset(struct CH8_Core* ch8) {
__ch8_reset(ch8, false);
}
bool ch8_init(struct CH8_Core* ch8_out) {
if (!ch8_out) return false;
MEMSET(ch8_out, 0, sizeof(struct CH8_Core));
ch8_out->vsync = CH8_VSYNC;
ch8_out->clock = CH8_CLOCK;
return true;
}
bool ch8_loadrom(struct CH8_Core* ch8, const uint8_t* data, uint32_t len) {
if (!ch8 || !data || !len) return false;
if (len > CH8_MAX_ROM_SIZE) return false;
__ch8_reset(ch8, true);
MEMCPY(ch8->mem.ram + 0x200, data, len);
return true;
}
void ch8_set_key(struct CH8_Core* ch8, CH8_Key key, bool pressed) {
CH8_keys[key] = pressed;
}
bool ch8_should_draw(const struct CH8_Core* ch8) {
return ch8->display.draw;
}
bool ch8_should_sound(const struct CH8_Core* ch8) {
return ch8->reg.st > 0;
}
uint32_t ch8_get_clock(struct CH8_Core* ch8) {
return ch8->clock;
}
void ch8_set_clock(struct CH8_Core* ch8, uint32_t clock) {
ch8->clock = clock;
}
void ch8_toggle_vsync(struct CH8_Core* ch8, bool enable) {
ch8->vsync = enable;
}
bool ch8_get_pixel(const struct CH8_Core* ch8, uint8_t x, uint8_t y) {
return ch8->display.pixels[x + (ch8->display.width * y)];
}
void ch8_run(struct CH8_Core* ch8) {
ch8->display.draw = false;
for (uint32_t clock = 0; clock < ch8->clock; clock++) {
FETCH();
EXECUTE();
// break early if a draw call is made
if (ch8->display.draw && ch8->vsync) {
break;
}
}
if (CH8_DT) {
CH8_DT--;
}
if (CH8_ST) {
CH8_ST--;
}
}
| 33.996845 | 87 | 0.574093 |
0cd7b71bf7de36ad8722f58dc56d94db5fb81535 | 827 | py | Python | python/mapper.py | qoofyk/zipper | c1d77448f8d479f9ef4bf785d49cf2b41da09130 | [
"BSD-3-Clause"
] | null | null | null | python/mapper.py | qoofyk/zipper | c1d77448f8d479f9ef4bf785d49cf2b41da09130 | [
"BSD-3-Clause"
] | null | null | null | python/mapper.py | qoofyk/zipper | c1d77448f8d479f9ef4bf785d49cf2b41da09130 | [
"BSD-3-Clause"
] | null | null | null | import sys
import math
def contiguous_mapper(mpi_rank, mpi_size, num_endpoints):
group_size = math.ceil(mpi_size/num_endpoints) # round up
local_id = mpi_rank % group_size
group_id = mpi_rank // group_size
return (group_id, local_id)
def generate_endpoint_file(endpoint_list, mpi_size, mapper_func):
for i in range(mpi_size):
group_id, local_id = contiguous_mapper(i, mpi_size, len(endpoint_list))
print(endpoint_list[group_id], local_id)
# run like python 3 mapper.py 3 ip1 ip2 ip3 ip4...
if __name__ == "__main__":
#print("Running: ", sys.argv)
#print("Number of arguments: ", len(sys.argv))
mpi_size = int(sys.argv[1])
endpoint_list = sys.argv[2:]
#print("The endpoints are: " , endpoint_list)
generate_endpoint_file(endpoint_list, mpi_size, contiguous_mapper)
| 35.956522 | 79 | 0.71705 |
8ba7794dfc2b0a89d069b6d5e6493f68617e4ff4 | 1,048 | ps1 | PowerShell | imageglass/tools/chocolateyInstall.ps1 | Starz0r/nugetpkgs | 8c1485186ee90f16181b7090ab6ffa7248426bf7 | [
"CC0-1.0"
] | null | null | null | imageglass/tools/chocolateyInstall.ps1 | Starz0r/nugetpkgs | 8c1485186ee90f16181b7090ab6ffa7248426bf7 | [
"CC0-1.0"
] | null | null | null | imageglass/tools/chocolateyInstall.ps1 | Starz0r/nugetpkgs | 8c1485186ee90f16181b7090ab6ffa7248426bf7 | [
"CC0-1.0"
] | null | null | null | $ErrorActionPreference = 'Stop'
$packageArgs = @{
packageName = 'imageglass'
fileType = 'msi'
url = 'https://github.com/d2phap/ImageGlass/releases/download/6.0.12.29/ImageGlass_6.0.12.29_x86.msi'
checksum = '0780099b0765d3852778a72bcc787b51c7ca325963ad5490f142ca1f2fb3aec00688f0a6120f02a2d232093a6fe4f96bece16455dc4e6c508ace6780c4515264'
checksumType = 'sha512'
url64 = 'https://github.com/d2phap/ImageGlass/releases/download/6.0.12.29/ImageGlass_6.0.12.29_x64.msi'
checksum64 = 'd444cc919961f3330ce324f9c6b7090cf73af927a99fa6a9312b1860a133ee5fa8350431dd3a1a235f592f0670492ad6cfac728b68cdd5da36d120c228d7abbb'
checksumType64 = 'sha512'
silentArgs = '/quiet /qn /norestart'
validExitCodes = @(0)
}
Install-ChocolateyPackage @packageArgs
$packageName = $packageArgs.packageName
$installLocation = Get-AppInstallLocation $packageName
if (!$installLocation) { Write-Warning "Can't find $packageName install location"; return }
Write-Host "$packageName installed to '$installLocation'" | 52.4 | 149 | 0.773855 |
05bc7b7e36da5579b25cb7c2f658a6b27ed85546 | 187 | html | HTML | src/main/webapp/partials/home.html | tinchodias/eg-casi-hackers-xtrest-angular | f70d100a61df37bf93309e9ae9015e7fffb5aa66 | [
"MIT"
] | null | null | null | src/main/webapp/partials/home.html | tinchodias/eg-casi-hackers-xtrest-angular | f70d100a61df37bf93309e9ae9015e7fffb5aa66 | [
"MIT"
] | null | null | null | src/main/webapp/partials/home.html | tinchodias/eg-casi-hackers-xtrest-angular | f70d100a61df37bf93309e9ae9015e7fffb5aa66 | [
"MIT"
] | null | null | null |
<h1>Hello {{ authCtrl.user().username }}</h1>
<span class="label-success" data-ng-repeat="role in authCtrl.user().roles">{{ role }}</span>
<p>This view is visible to logged in users.</p> | 46.75 | 92 | 0.679144 |
3b740b5093190616770adaa289933a5c1fe0fff9 | 972 | asm | Assembly | libsrc/games/mtx/joystick.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | libsrc/games/mtx/joystick.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | libsrc/games/mtx/joystick.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | ;
; Game device library for the Memotech MTX
; Stefano Bodrato - 2011
;
; $Id: joystick.asm,v 1.2 2015/01/19 01:32:44 pauloscustodio Exp $
;
PUBLIC joystick
KEYS:
defb 0
.joystick
;__FASTCALL__ : joystick no. in HL
ld a,l
ld hl,0
dec a
jr nz,no_cursor
; RIGHT stick
;xor a
FIRE:
ld a,$df ; Strobe for HOME
call STROBE
jr nz,LEFT
set 4,l ; FIRE
LEFT:
ld a,$f7
call STROBE
jr nz,RIGHT
set 1,l ; LEFT
RIGHT:
ld a,$ef
call STROBE
jr nz,UP
set 0,l ; RIGHT
UP:
ld a,$fb
call STROBE
jr nz,DOWN
set 3,l ; UP
DOWN:
ld a,$bf
call STROBE
jr nz,DONE
set 2,l ; DOWN
DONE:
ret
.no_cursor
xor a
ld a,127 ; Strobe for SPACE
out (5),a
in a,(6)
bit 0,a
jr nz,STB
set 4,l ; FIRE
STB:
out (5),a
in a,(5)
ld d,a
and $f0
cp $f0 ; bottom row keys ?
ret nz ; no...
ld a,d
cpl
;DURL -> UDLR
ld e,a
and @1010
rra
ld d,a
ld a,e
and @0101
rla
or d
or l
ld l,a
ret
STROBE:
out (5),a
in a,(5)
cp 127
ret
| 10.681319 | 66 | 0.600823 |
906716492ce592a7a9a7a0caa589552c48a352d3 | 6,138 | py | Python | TargetDataLoaderProcess/data_loader.py | JeromeMutgeert/da-faster-rcnn | 73c8a0f765dc202fc284f659ce23c681fc3b6a64 | [
"BSD-2-Clause"
] | null | null | null | TargetDataLoaderProcess/data_loader.py | JeromeMutgeert/da-faster-rcnn | 73c8a0f765dc202fc284f659ce23c681fc3b6a64 | [
"BSD-2-Clause"
] | null | null | null | TargetDataLoaderProcess/data_loader.py | JeromeMutgeert/da-faster-rcnn | 73c8a0f765dc202fc284f659ce23c681fc3b6a64 | [
"BSD-2-Clause"
] | null | null | null | # Python 3 required. This is a seperate process.
import aiohttp
import asyncio
import async_timeout
import os
import numpy as np
import time
import cv2
# Settings:
Buffer = 100
BackBuffer = 20
Max_Query = 12
Timeout = 40
url_base = "https://test.yisual.com/images/media/download/picturethis/"
headers = {"api-key": "ccea03e0e3a08c428870393376e5cf7b7be7a55c", "api-secret": os.environ["SECRET"]}
cacheLoc = "/media/jerome/DATA/Study_d/ThesisD/TargetData/"
# dummy_im_id = "5461e5219da59bde29aed195"
# dummy_url = url_base + dummy_im_id
# counter txt's interface:
def update_fetched(fetched):
with open("fetched_temp.txt",'w') as f:
f.write(str(fetched))
f.flush()
os.fsync(f.fileno())
# atomic:
os.rename("fetched_temp.txt","fetched.txt")
def get_read():
global read
with open("read.txt",'r') as f:
numstr = f.read()
read = int(numstr)
return read
def to_filename(im_id):
return "target_{}.jpg".format(im_id)
def append_log(msg):
with open("log.txt",'a') as f:
f.write(str(time.time()) + ' :\t')
f.write(str(msg) + '\n')
async def download_coroutine(session, im_id, im_num):
# im_id = "5c59addcb71ee102f1e439ba"
cache = cacheLoc + im_id + '.jpg'
filename = to_filename(im_num)
if os.path.exists(cache):
# copy from cache:
os.system('cp {} ./{}'.format(cache,filename))
return
url = url_base + im_id
im = None
problematic = False
while type(im) == type(None):
try:
with async_timeout.timeout(Timeout):
async with session.get(url,headers=headers) as response:
with open(filename, 'wb') as f_handle:
while True:
chunk = await response.content.read(1024)
if not chunk:
# print('done')
break
f_handle.write(chunk)
f_handle.flush()
os.fsync(f_handle.fileno())
res = await response.release()
# Verify if download was succesfull:
im = cv2.imread(filename)
if type(im) == type(None):
problematic = True
append_log("{} {} Incorrect download.".format(im_num,im_id))
print("{} {} Incorrect download.".format(im_num,im_id))
except:
problematic = True
append_log("Downloading timed out, retrying {} {}".format(im_num,im_id))
print("Downloading timed out, retrying {} {}".format(im_num,im_id))
if problematic:
append_log("Succeeded! {} {}".format(im_num,im_id))
# Finally:
if os.path.exists(cacheLoc):
os.system('cp {} {}'.format(filename,cache))
return res
async def get_batch(loop,im_ids,im_nums):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [download_coroutine(session, im_id, im_num) for im_id,im_num in zip(im_ids,im_nums)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
# init gobals
present = []
fetched = 0
read = 0
removed = 0
idle_count = 0
# init/reset protocol files:
update_fetched(0)
with open("read.txt",'w') as f:
f.write('0')
f.flush()
os.fsync(f.fileno())
ids = []
with open("ids.txt",'r') as f:
ids = [i.strip() for i in f.readlines()]
def shuffle(ids, epoch):
np.random.shuffle(ids)
filename = "ids_ep{}.txt".format(epoch)
with open(filename,'w') as f:
f.write('\n'.join(ids))
f.flush()
os.system('cp {} ids_current.txt'.format(filename))
def id_generator():
i = 0
epoch = 0
shuffle(ids,epoch)
while True:
yield ids[i]
i += 1
if i == len(ids):
i = 0
epoch += 1
shuffle(ids,epoch)
print("Loaded epoch {}".format(epoch))
id_gen = id_generator()
append_log("Starting")
while True:
# update read
read = get_read()
# print(fetched,read,removed)
# refill:
if (fetched - read) < Buffer:
# TODO: determine next imgs:
load_N = read + Buffer - fetched
load_N = min(load_N,Max_Query)
im_nums = [str(i) for i in range(fetched,fetched+load_N)]
im_ids = [next(id_gen) for _ in range(fetched,fetched+load_N)]
loop = asyncio.get_event_loop()
loop.run_until_complete(get_batch(loop,im_ids,im_nums))
# done fetching
fetched += load_N
present.extend(im_nums)
# broadcast
update_fetched(fetched)
idle_count = 0
else:
# we're all set
# Check for exitting:
stop = False
idle_count += 1
if idle_count > 1000: # about 3 mins idle
append_log("Idle time-out. Exiting.")
stop = True
if (fetched - read) > Buffer: # read.txt has decreased:
append_log("Read.txt has decreased. Exiting.")
stop = True
if stop:
for im_num in present:
os.remove(to_filename(im_num))
exit()
# sleep a bit to avoid spinning.
time.sleep(.2)
# remove
while removed < (read - BackBuffer):
try:
im_num = present[0]
except:
append_log("Non-existing file reported as read. Exiting.")
exit()
present = present[1:]
try:
os.remove(to_filename(im_num))
except:
append_log("While removing: File not found: {}".format(to_filename(im_num)))
print("While removing: File not found: {}".format(to_filename(im_num)))
removed += 1 | 28.285714 | 101 | 0.531281 |
03e14528fbc619ef1aa68c92012bded32e0f940d | 1,042 | swift | Swift | Shopping List/Controller/View Controller/ItemTableViewCell.swift | MityaKimchanskii/Shopping-List | 4ee11c6b72f9a084e9f61d1fbeeab1acd70b039d | [
"Apache-2.0"
] | null | null | null | Shopping List/Controller/View Controller/ItemTableViewCell.swift | MityaKimchanskii/Shopping-List | 4ee11c6b72f9a084e9f61d1fbeeab1acd70b039d | [
"Apache-2.0"
] | null | null | null | Shopping List/Controller/View Controller/ItemTableViewCell.swift | MityaKimchanskii/Shopping-List | 4ee11c6b72f9a084e9f61d1fbeeab1acd70b039d | [
"Apache-2.0"
] | null | null | null | //
// ItemTableViewCell.swift
// Shopping List
//
// Created by Mitya Kim on 1/19/22.
//
import UIKit
protocol isDoneDelegate: AnyObject {
func itemButtonTap(_ sender: ItemTableViewCell)
}
class ItemTableViewCell: UITableViewCell {
// MARK: - IBOutlets
@IBOutlet weak var isDoneButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
var item: Item? {
didSet {
updateView()
}
}
weak var delegate: isDoneDelegate?
// MARK: - IBActions
@IBAction func isDoneButtonTapped(_ sender: Any) {
if let delegate = delegate {
delegate.itemButtonTap(self)
}
}
// MARK: - Other Methods
func updateView() {
guard let item = item else { return }
titleLabel.text = item.title
if item.isDone {
isDoneButton.setBackgroundImage(UIImage(named: "complete"), for: .normal)
} else {
isDoneButton.setBackgroundImage(UIImage(named: "incomplete"), for: .normal)
}
}
}
| 22.652174 | 87 | 0.602687 |
85bc442709656c0e67ec887ce06105664d2fd8f3 | 442 | h | C | picio.h | folkertvanheusden/termcamng | b43fdbb5d4a5114bc524109f0c0cf7b72690e4d6 | [
"Apache-2.0"
] | null | null | null | picio.h | folkertvanheusden/termcamng | b43fdbb5d4a5114bc524109f0c0cf7b72690e4d6 | [
"Apache-2.0"
] | 2 | 2022-02-24T09:14:29.000Z | 2022-02-28T08:09:18.000Z | picio.h | folkertvanheusden/termcamng | b43fdbb5d4a5114bc524109f0c0cf7b72690e4d6 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <turbojpeg.h>
void write_PNG_file(FILE *const fh, const int ncols, const int nrows, const int compression_level, uint8_t *pixels);
class myjpeg
{
private:
tjhandle jpegCompressor;
public:
myjpeg();
virtual ~myjpeg();
bool write_JPEG_memory(const int ncols, const int nrows, const int compression_level, const uint8_t *const pixels, uint8_t **out, size_t *out_len);
};
extern thread_local myjpeg my_jpeg;
| 22.1 | 148 | 0.762443 |
0766db8051b782a50868b866dfcfe68a52adc105 | 1,290 | lua | Lua | src/MainModule/Packages/Builtin/Moderation/Banning/CheckBan.lua | regginator/commander | 79cb091498d0a2198e51f7ed59787d62da5d9164 | [
"MIT"
] | 29 | 2021-02-23T05:38:49.000Z | 2021-05-15T18:59:11.000Z | src/MainModule/Packages/Builtin/Moderation/Banning/CheckBan.lua | regginator/commander | 79cb091498d0a2198e51f7ed59787d62da5d9164 | [
"MIT"
] | 46 | 2021-03-06T03:42:19.000Z | 2021-05-08T18:45:50.000Z | src/MainModule/Packages/Builtin/Moderation/Banning/CheckBan.lua | regginator/commander | 79cb091498d0a2198e51f7ed59787d62da5d9164 | [
"MIT"
] | 30 | 2021-03-06T00:54:39.000Z | 2021-05-14T01:33:16.000Z | local module = {
Name = "Check ban",
Description = "Check a player's ban status",
Location = "Player",
}
local DataStoreService
local dataStore
module.Execute = function(Client, Type, Attachment)
if Type == "command" then
local player = module.API.getUserIdWithName(Attachment)
local success, result = pcall(dataStore.GetAsync, dataStore, "data")
if success then
result = result or {}
result = result[tostring(player)] or module.Shared.LocalBans[player]
else
warn(result)
end
if success then
if result then
local message = "This player is currently banned, \n\nName: " .. Attachment .. " (" .. player .. ")\n"
warn(result.Reason)
result = message .. "Moderator: " .. tostring(result.By[2]) .. "\nDuration: " .. tostring(result.End) .. "\nReason: " .. tostring(result.Reason or "N/A")
else
result = "This player is not banned"
end
else
result = "An error occured, please try later"
end
module.API.Players.notify(Client, "CheckBan", result)
return true
elseif Type == "firstrun" then
DataStoreService = module.Services.DataStoreService
dataStore = DataStoreService:GetDataStore(module.Settings.Misc.DataStoresKey.Ban or "commander.bans")
module.Shared.LocalBans = module.Shared.LocalBans or {}
end
end
return module | 30.714286 | 157 | 0.700775 |
f172f3db2bdc9a15126e8e952f2752f841389cdd | 246 | rb | Ruby | app/models/user_buddy.rb | kjleitz/turtello | 923dae48a6444681390f53d61568ef1c110427a6 | [
"MIT"
] | null | null | null | app/models/user_buddy.rb | kjleitz/turtello | 923dae48a6444681390f53d61568ef1c110427a6 | [
"MIT"
] | null | null | null | app/models/user_buddy.rb | kjleitz/turtello | 923dae48a6444681390f53d61568ef1c110427a6 | [
"MIT"
] | null | null | null | class UserBuddy < ApplicationRecord
belongs_to :user, inverse_of: :user_buddies
belongs_to :buddy, class_name: "User", inverse_of: :user_stalkers
def user_username
user.username
end
def buddy_username
buddy.username
end
end
| 18.923077 | 67 | 0.756098 |
d970011370751b85115925aa7ed056ee9fe5aa04 | 661 | swift | Swift | swift/Problem 297/Problem 297Tests/Problem_297Tests.swift | SebastienFCT/daily-coding-problem | 209eeb24c24ad5450ce2f7dbf9678281f9c6895e | [
"MIT"
] | 10 | 2020-04-04T14:57:43.000Z | 2022-02-02T13:48:15.000Z | swift/Problem 297/Problem 297Tests/Problem_297Tests.swift | SebastienFCT/daily-coding-problem | 209eeb24c24ad5450ce2f7dbf9678281f9c6895e | [
"MIT"
] | null | null | null | swift/Problem 297/Problem 297Tests/Problem_297Tests.swift | SebastienFCT/daily-coding-problem | 209eeb24c24ad5450ce2f7dbf9678281f9c6895e | [
"MIT"
] | 3 | 2019-12-06T03:54:25.000Z | 2020-01-10T16:19:15.000Z | //
// Problem_297Tests.swift
// Problem 297Tests
//
// Created by sebastien FOCK CHOW THO on 2020-03-17.
// Copyright © 2020 sebastien FOCK CHOW THO. All rights reserved.
//
import XCTest
@testable import Problem_297
class Problem_297Tests: XCTestCase {
func test_example() {
let input = Bar(preferences: [
0: [0, 1, 3, 6],
1: [1, 4, 7],
2: [2, 4, 7, 5],
3: [3, 2, 5],
4: [5, 8]
])
let actual = input.lazyBartender()
XCTAssert(actual.count == 2)
XCTAssert(actual.contains(1))
XCTAssert(actual.contains(5))
}
}
| 20.65625 | 66 | 0.526475 |
e054bf4825e0f0a82556088e1ef187a268d028c0 | 47,406 | swift | Swift | CodeGenerator/CGSwiftCodeGenerator.swift | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
] | 5 | 2019-02-21T14:07:28.000Z | 2021-04-21T18:59:59.000Z | CodeGenerator/CGSwiftCodeGenerator.swift | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
] | 1 | 2019-03-04T12:27:59.000Z | 2019-03-04T12:27:59.000Z | CodeGenerator/CGSwiftCodeGenerator.swift | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
] | 4 | 2019-09-07T12:48:54.000Z | 2021-04-23T13:34:34.000Z | public enum CGSwiftCodeGeneratorDialect {
case Standard
case Silver
}
public class CGSwiftCodeGenerator : CGCStyleCodeGenerator {
public init() {
super.init()
// current as of Elements 8.1 and Swift 1.2
hardKeywords = ["__abstract", "__await", "__catch", "__event", "__finally", "__mapped", "__out", "__partial", "__throw", "__try", "__using", "__yield", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__",
"associativity", "autoreleasepool", "break", "case", "catch", "class", "continue", "convenience", "default", "defer", "deinit", "didSet", "do", "dynamicType",
"else", "enum", "extension", "fallthrough", "false", "final", "for", "func", "get", "guard", "if", "import", "in", "infix", "init", "inout", "internal", "is",
"lazy", "left", "let", "mutating", "nil", "none", "nonmutating", "open", "operator", "optional", "override", "postfix", "precedence", "prefix", "private", "protocol", "public",
"repeat", "required", "rethrows", "return", "right", "self", "Self", "set", "static", "strong", "struct", "subscript", "super", "switch", "throw", "throws", "true", "try", "typealias",
"unowned", "var", "weak", "where", "while", "willSet"].ToList() as! List<String>
softKeywords = ["as"].ToList() as! List<String>
keywords = List<String>()
keywords?.Add(hardKeywords)
keywords?.Add(softKeywords)
}
private var hardKeywords: List<String>
private var softKeywords: List<String>
public var Dialect: CGSwiftCodeGeneratorDialect = .Standard
public convenience init(dialect: CGSwiftCodeGeneratorDialect) {
init()
Dialect = dialect
}
public override var defaultFileExtension: String { return "swift" }
override func escapeIdentifier(_ name: String) -> String {
return "`\(name)`"
}
override func generateImport(_ imp: CGImport) {
Append("import ")
generateIdentifier(imp.Name, alwaysEmitNamespace: true)
AppendLine()
}
override func generateStatementTerminator() {
AppendLine() // no ; in Swift
}
//
// Statements
//
// in C-styleCG Base class
/*override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) {
}*/
override func generateIfElseStatement(_ statement: CGIfThenElseStatement) {
Append("if ")
generateExpression(statement.Condition)
AppendLine(" {")
incIndent()
generateStatementSkippingOuterBeginEndBlock(statement.IfStatement)
decIndent()
Append("}")
if let elseStatement = statement.ElseStatement {
AppendLine(" else {")
incIndent()
generateStatementSkippingOuterBeginEndBlock(elseStatement)
decIndent()
AppendLine("}")
} else {
AppendLine()
}
}
override func generateForToLoopStatement(_ statement: CGForToLoopStatement) {
if statement.Direction == CGLoopDirectionKind.Forward {
Append("for ")
generateIdentifier(statement.LoopVariableName)
Append(" in ")
generateExpression(statement.StartValue)
Append(" ... ")
generateExpression(statement.EndValue)
} else {
Append("for var ")
generateIdentifier(statement.LoopVariableName)
if let type = statement.LoopVariableType {
Append(": ")
generateTypeReference(type)
}
Append(" = ")
generateExpression(statement.StartValue)
Append("; ")
generateIdentifier(statement.LoopVariableName)
if statement.Direction == CGLoopDirectionKind.Forward {
Append(" <= ")
} else {
Append(" >= ")
}
generateExpression(statement.EndValue)
Append("; ")
generateIdentifier(statement.LoopVariableName)
Append("--")
}
AppendLine(" {")
incIndent()
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
decIndent()
AppendLine("}")
}
override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) {
Append("for ")
generateSingleNameOrTupleWithNames(statement.LoopVariableNames)
Append(" in ")
generateExpression(statement.Collection)
AppendLine(" {")
incIndent()
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
decIndent()
AppendLine("}")
}
override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) {
Append("while ")
generateExpression(statement.Condition)
AppendLine(" {")
incIndent()
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
decIndent()
Append("}")
}
override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) {
Append("repeat {")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(statement.Statements)
decIndent()
Append("} while ")
generateExpression(statement.Condition)
}
/*override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) {
// handled in base
}*/
override func generateSwitchStatement(_ statement: CGSwitchStatement) {
Append("switch ")
generateExpression(statement.Expression)
AppendLine(" {")
incIndent()
for c in statement.Cases {
Append("case ")
helpGenerateCommaSeparatedList(c.CaseExpressions) {
self.generateExpression($0)
}
AppendLine(":")
generateStatementsIndentedUnlessItsASingleBeginEndBlock(c.Statements)
}
if let defaultStatements = statement.DefaultCase, defaultStatements.Count > 0 {
AppendLine("default:")
generateStatementsIndentedUnlessItsASingleBeginEndBlock(defaultStatements)
}
decIndent()
AppendLine("}")
}
override func generateLockingStatement(_ statement: CGLockingStatement) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__lock ")
generateExpression(statement.Expression)
AppendLine(" {")
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
AppendLine("}")
} else {
assert(false, "generateLockingStatement is not supported in Swift")
}
}
override func generateUsingStatement(_ statement: CGUsingStatement) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__using let ")
generateIdentifier(statement.Name)
if let type = statement.`Type` {
Append(": ")
generateTypeReference(type)
}
Append(" = ")
generateExpression(statement.Value)
AppendLine(" {")
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
AppendLine("}")
} else {
assert(false, "generateUsingStatement is not supported in Swift")
}
}
override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) {
AppendLine("autoreleasepool { ")
incIndent()
generateStatementSkippingOuterBeginEndBlock(statement.NestedStatement)
decIndent()
AppendLine("}")
}
override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
AppendLine("__try {")
incIndent()
generateStatements(statement.Statements)
decIndent()
AppendLine("}")
if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 {
AppendLine("__finally {")
incIndent()
generateStatements(finallyStatements)
decIndent()
AppendLine("}")
}
if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 {
for b in catchBlocks {
if let name = b.Name, let type = b.Type {
Append("__catch ")
generateIdentifier(name)
Append(": ")
generateTypeReference(type, ignoreNullability: true)
AppendLine(" {")
} else {
AppendLine("__catch {")
}
incIndent()
generateStatements(b.Statements)
decIndent()
AppendLine("}")
}
}
//todo
} else {
assert(false, "generateTryFinallyCatchStatement is not supported in Swift, except in Silver")
}
}
/*
override func generateReturnStatement(_ statement: CGReturnStatement) {
// handled in base
}
*/
override func generateYieldStatement(_ statement: CGYieldStatement) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__yield ")
generateExpression(statement.Value)
AppendLine()
} else {
assert(false, "generateYieldStatement is not supported in Swift, except in Silver")
}
}
override func generateThrowStatement(_ statement: CGThrowStatement) {
if let value = statement.Exception {
Append("throw ")
generateExpression(value)
AppendLine()
} else {
AppendLine("throw")
}
}
/*
override func generateBreakStatement(_ statement: CGBreakStatement) {
// handled in base
}
*/
/*
override func generateContinueStatement(_ statement: CGContinueStatement) {
// handled in base
}
*/
override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) {
if statement.Constant || statement.ReadOnly {
Append("let ")
} else {
Append("var ")
}
generateIdentifier(statement.Name)
if let type = statement.`Type` {
Append(": ")
generateTypeReference(type)
}
if let value = statement.Value {
Append(" = ")
generateExpression(value)
}
AppendLine()
//todo: smartly handle non-nulables w/o a value?
}
/*
override func generateAssignmentStatement(_ statement: CGAssignmentStatement) {
// handled in base
}
*/
override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) {
if let callSite = statement.CallSite {
if let typeReferenceExpression = statement.CallSite as? CGTypeReferenceExpression {
generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true)
} else {
generateExpression(callSite)
}
Append(".")
}
Append("init(")
if let ctorName = statement.ConstructorName {
swiftGenerateCallParameters(statement.Parameters, firstParamName: removeWithPrefix(ctorName))
} else {
swiftGenerateCallParameters(statement.Parameters)
}
Append(")")
AppendLine()
}
override func generateLocalMethodStatement(_ method: CGLocalMethodStatement) {
Append("func ")
generateIdentifier(method.Name)
Append("(")
swiftGenerateDefinitionParameters(method.Parameters)
Append(")")
if method.Throws {
Append(" throws")
}
if let returnType = method.ReturnType, !returnType.IsVoid {
Append(" -> ")
returnType.startLocation = currentLocation
generateTypeReference(returnType)
returnType.endLocation = currentLocation
}
AppendLine(" {")
incIndent()
generateStatements(variables: method.LocalVariables)
generateStatements(method.Statements)
decIndent()
AppendLine("}")
}
//
// Expressions
//
/*
override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) {
// handled in base
}
*/
/*
override func generateAssignedExpression(_ expression: CGAssignedExpression) {
// handled in base
}
*/
/*
override func generateSizeOfExpression(_ expression: CGSizeOfExpression) {
// handled in base
}
*/
override func generateTypeOfExpression(_ expression: CGTypeOfExpression) {
if let typeReferenceExpression = expression.Expression as? CGTypeReferenceExpression {
generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true)
Append(".self")
} else {
Append("dynamicType(")
generateExpression(expression.Expression)
Append(")")
}
}
override func generateDefaultExpression(_ expression: CGDefaultExpression) {
Append("default(")
generateTypeReference(expression.`Type`, ignoreNullability: true)
Append(")")
}
override func generateSelectorExpression(_ expression: CGSelectorExpression) {
Append("\"\(expression.Name)\"")
}
override func generateTypeCastExpression(_ cast: CGTypeCastExpression) {
Append("(")
generateExpression(cast.Expression)
Append(" as")
if !cast.GuaranteedSafe {
if cast.ThrowsException {
Append("!")
} else{
Append("?")
}
}
Append(" ")
generateTypeReference(cast.TargetType, ignoreNullability: true)
Append(")")
}
override func generateInheritedExpression(_ expression: CGInheritedExpression) {
Append("super")
}
override func generateSelfExpression(_ expression: CGSelfExpression) {
Append("self")
}
override func generateNilExpression(_ expression: CGNilExpression) {
Append("nil")
}
override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) {
Append("newValue")
}
override func generateAwaitExpression(_ expression: CGAwaitExpression) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__await ")
generateExpression(expression.Expression)
} else {
assert(false, "generateEventDefinition is not supported in Swift, except in Silver")
}
}
override func generateAnonymousMethodExpression(_ method: CGAnonymousMethodExpression) {
Append("{")
if method.Parameters.Count > 0 {
Append(" (")
helpGenerateCommaSeparatedList(method.Parameters) { param in
self.generateIdentifier(param.Name)
if let type = param.`Type` {
self.Append(": ")
self.generateTypeReference(type)
}
}
Append(") in")
}
AppendLine()
incIndent()
generateStatements(variables: method.LocalVariables)
generateStatementsSkippingOuterBeginEndBlock(method.Statements)
decIndent()
Append("}")
}
override func generateAnonymousTypeExpression(_ type: CGAnonymousTypeExpression) {
Append("class ")
if let ancestor = type.Ancestor {
generateTypeReference(ancestor, ignoreNullability: true)
Append(" ")
}
AppendLine("{")
incIndent()
helpGenerateCommaSeparatedList(type.Members, separator: { self.AppendLine() }) { m in
if let member = m as? CGAnonymousPropertyMemberDefinition {
self.Append("var ")
self.generateIdentifier(m.Name)
self.Append(" = ")
self.generateExpression(member.Value)
self.AppendLine()
} else if let member = m as? CGAnonymousMethodMemberDefinition {
self.Append("func ")
self.generateIdentifier(m.Name)
self.Append("(")
self.swiftGenerateDefinitionParameters(member.Parameters)
self.Append(")")
if let returnType = member.ReturnType, !returnType.IsVoid {
self.Append(" -> ")
self.generateTypeReference(returnType)
}
self.AppendLine(" {")
self.incIndent()
self.generateStatements(member.Statements)
self.decIndent()
self.AppendLine("}")
}
}
decIndent()
Append("}")
}
override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) {
//todo
}
override func generateRangeExpression(_ expression: CGRangeExpression) {
generateExpression(expression.StartValue)
Append("...")
generateExpression(expression.EndValue)
}
override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) {
if let `operator` = expression.Operator, `operator` == .ForceUnwrapNullable {
generateExpression(expression.Value)
Append("!")
} else {
super.generateUnaryOperatorExpression(expression)
}
}
/*
override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) {
// handled in base
}
*/
/*
override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) {
// handled in base
}
*/
override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) {
switch (`operator`) {
case .Is: Append("is")
case .AddEvent: Append("+=") // Silver only
case .RemoveEvent: Append("-=") // Silver only
default: super.generateBinaryOperator(`operator`)
}
}
/*
override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) {
// handled in base
}
*/
/*
override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) {
// handled in base
}
*/
internal func swiftGenerateStorageModifierPrefixIfNeeded(_ storageModifier: CGStorageModifierKind) {
switch storageModifier {
case .Strong: break
case .Weak: Append("weak ")
case .Unretained: Append("unowned ")
}
}
internal func swiftGenerateCallSiteForExpression(_ expression: CGMemberAccessExpression) {
if let callSite = expression.CallSite {
if let typeReferenceExpression = expression.CallSite as? CGTypeReferenceExpression {
generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true)
} else {
generateExpression(callSite)
}
if expression.NilSafe {
Append("?")
} else if expression.UnwrapNullable {
Append("!")
}
Append(".")
}
}
func swiftGenerateCallParameters(_ parameters: List<CGCallParameter>, firstParamName: String? = nil) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
Append(", ")
}
if let name = param.Name {
generateIdentifier(name, keywords: hardKeywords)
Append(": ")
} else if p == 0, let name = firstParamName {
generateIdentifier(name)
Append(": ")
}
switch param.Modifier {
case .Out: fallthrough
case .Var:
Append("&(")
generateExpression(param.Value)
Append(")")
default:
generateExpression(param.Value)
}
}
}
func swiftGenerateAttributeParameters(_ parameters: List<CGCallParameter>) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
Append(", ")
}
if let name = param.Name {
generateIdentifier(name)
Append(" = ")
}
generateExpression(param.Value)
}
}
override func generateParameterDefinition(_ param: CGParameterDefinition) {
swiftGenerateParameterDefinition(param, emitExternal: false) // never emit the _
}
private func swiftGenerateParameterDefinition(_ param: CGParameterDefinition, emitExternal: Boolean, externalName: String? = nil) {
if emitExternal, let externalName = externalName ?? param.ExternalName {
if externalName != param.Name {
generateIdentifier(externalName)
Append(" ")
}
} else if emitExternal {
Append("_ ")
}
generateIdentifier(param.Name)
Append(": ")
switch param.Modifier {
case .Out:
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__out ")
} else {
fallthrough
}
case .Var:
Append("inout ")
default:
}
if let type = param.`Type` {
generateTypeReference(type)
} else {
assert("CGParameterDefinition needs a type, for Swift")
}
if param.Modifier == .Params {
Append("...")
}
if let defaultValue = param.DefaultValue {
Append(" = ")
generateExpression(defaultValue)
}
}
func swiftGenerateDefinitionParameters(_ parameters: List<CGParameterDefinition>, firstExternalName: String? = nil) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
Append(", ")
}
param.startLocation = currentLocation
swiftGenerateParameterDefinition(param, emitExternal: true, externalName: p == 0 ? firstExternalName : nil)
param.endLocation = currentLocation
}
}
func swiftGenerateGenericParameters(_ parameters: List<CGGenericParameterDefinition>?) {
if let parameters = parameters, parameters.Count > 0 {
Append("<")
helpGenerateCommaSeparatedList(parameters) { param in
self.generateIdentifier(param.Name)
// variance isn't supported in swift
//todo: 72081: Silver: NRE in "if let"
//if let constraints = param.Constraints, filteredConstraints = constraints.Where({ return $0 is CGGenericIsSpecificTypeConstraint}).ToList(), filteredConstraints.Count > 0 {
if let constraints = param.Constraints, constraints.Count > 0 {
let filteredConstraints = constraints.Where({ return $0 is CGGenericIsSpecificTypeConstraint })
self.Append(": ")
self.helpGenerateCommaSeparatedList(filteredConstraints) { constraint in
if let constraint2 = constraint as? CGGenericIsSpecificTypeConstraint {
self.generateTypeReference(constraint2.`Type`)
}
// other constraints aren't supported in Swift
}
}
}
Append(">")
}
}
func swiftGenerateAncestorList(_ type: CGClassOrStructTypeDefinition) {
if type.Ancestors.Count > 0 || type.ImplementedInterfaces.Count > 0 {
Append(" : ")
var needsComma = false
for ancestor in type.Ancestors {
if needsComma {
Append(", ")
}
generateTypeReference(ancestor, ignoreNullability: true)
needsComma = true
}
for interface in type.ImplementedInterfaces {
if needsComma {
Append(", ")
}
generateTypeReference(interface, ignoreNullability: true)
needsComma = true
}
}
}
override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) {
swiftGenerateCallSiteForExpression(expression)
generateIdentifier(expression.Name)
}
/*
override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) {
// handled in base
}
*/
override func generateMethodCallExpression(_ method: CGMethodCallExpression) {
swiftGenerateCallSiteForExpression(method)
generateIdentifier(method.Name)
generateGenericArguments(method.GenericArguments)
if method.CallOptionally {
Append("?")
}
Append("(")
swiftGenerateCallParameters(method.Parameters)
Append(")")
}
override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) {
generateExpression(expression.`Type`, ignoreNullability: true)
if let bounds = expression.ArrayBounds, bounds.Count > 0 {
Append("[](count: ")
helpGenerateCommaSeparatedList(bounds) { boundExpression in
self.generateExpression(boundExpression)
}
Append(")")
} else {
Append("(")
if let ctorName = expression.ConstructorName {
swiftGenerateCallParameters(expression.Parameters, firstParamName: removeWithPrefix(ctorName))
} else {
swiftGenerateCallParameters(expression.Parameters)
}
Append(")")
if let propertyInitializers = expression.PropertyInitializers, propertyInitializers.Count > 0 {
Append(" /* Property Initializers : ")
helpGenerateCommaSeparatedList(propertyInitializers) { param in
self.Append(param.Name)
self.Append(" = ")
self.generateExpression(param.Value)
}
Append(" */")
}
}
}
override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) {
swiftGenerateCallSiteForExpression(property)
generateIdentifier(property.Name)
if let params = property.Parameters, params.Count > 0 {
Append("[")
swiftGenerateCallParameters(property.Parameters)
Append("]")
}
}
override func cStyleEscapeSequenceForCharacter(_ ch: Char) -> String {
return "\\u{"+Convert.ToString(Integer(ch), 16)
}
/*
override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) {
// handled in base
}
*/
override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) {
// Swift uses " and not ', even for chars.
Append("\"\(cStyleEscapeCharactersInStringLiteral(expression.Value.ToString()))\"")
}
override func generateIntegerLiteralExpression(_ literalExpression: CGIntegerLiteralExpression) {
switch literalExpression.Base {
case 16: Append("0x"+literalExpression.StringRepresentation(base:16))
case 10: Append(literalExpression.StringRepresentation(base:10))
case 8: Append("0o"+literalExpression.StringRepresentation(base:8))
case 1: Append("0b"+literalExpression.StringRepresentation(base:1))
default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for Swift.")
}
// no C-style suffixes in Swift
}
override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) {
switch literalExpression.Base {
case 16: Append("0x"+literalExpression.StringRepresentation(base:16))
case 10: Append(literalExpression.StringRepresentation())
default: throw Exception("Base \(literalExpression.Base) float literals are not currently supported for Swift.")
}
// no C-style suffixes in Swift
}
override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) {
Append("[")
helpGenerateCommaSeparatedList(array.Elements) {
self.generateExpression($0)
}
Append("]")
}
override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) {
Append("Set([")
for e in 0 ..< expression.Elements.Count {
if e > 0 {
Append(", ")
}
generateExpression(expression.Elements[e])
}
Append("])")
}
override func generateDictionaryExpression(_ dictionary: CGDictionaryLiteralExpression) {
assert(dictionary.Keys.Count == dictionary.Values.Count, "Number of keys and values in Dictionary doesn't match.")
Append("[")
for e in 0 ..< dictionary.Keys.Count {
if e > 0 {
Append(", ")
}
generateExpression(dictionary.Keys[e])
Append(": ")
generateExpression(dictionary.Values[e])
}
Append("]")
}
/*
override func generateTupleExpression(_ expression: CGTupleLiteralExpression) {
// default handled in base
}
*/
//
// Type Definitions
//
override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) {
Append("@")
generateTypeReference(attribute.`Type`, ignoreNullability: true)
if let parameters = attribute.Parameters, parameters.Count > 0 {
Append("(")
swiftGenerateAttributeParameters(parameters)
Append(")")
}
if let comment = attribute.Comment {
Append(" ")
generateSingleLineCommentStatement(comment)
} else {
if inline {
Append(" ")
} else {
AppendLine()
}
}
}
func swiftGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind, sealed: Boolean = false, type: CGTypeDefinition? = nil) {
if let type = type, type is CGClassTypeDefinition {
switch visibility {
case .Unspecified:
if sealed {
Append("final ")
}
case .Unit, .Assembly:
Append("internal ") // non-sealed for internal use is implied
if sealed {
Append("final ")
}
case .Public:
if sealed {
Append("public final ")
} else {
Append("open ")
}
}
} else {
switch visibility {
case .Unspecified:
break;
case .Unit, .Assembly:
Append("internal ")
case .Public:
Append("public ")
}
}
}
func swiftGenerateMemberTypeVisibilityPrefix(_ visibility: CGMemberVisibilityKind, virtuality: CGMemberVirtualityKind, appendSpace: Boolean = true) {
switch visibility {
case .Unspecified: break /* no-op */
case .Private: Append("private")
case .Unit: fallthrough
case .UnitOrProtected: fallthrough
case .UnitAndProtected: fallthrough
case .Assembly: fallthrough
case .AssemblyAndProtected: Append("internal")
case .AssemblyOrProtected: fallthrough
case .Protected: fallthrough
case .Published: fallthrough
case .Public:
if virtuality == .Virtual || virtuality == .Override {
Append("open")
} else {
Append("public")
}
}
switch virtuality {
case .None: break;
case .Virtual: break; // handled above, and implied for non-pubic
case .Abstract: if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append(" __abstract") }
case .Override: Append(" override")
case .Final: Append(" final")
}
if appendSpace {
Append(" ")
}
}
func swiftGenerateStaticPrefix(_ isStatic: Boolean) {
if isStatic {
Append("static ")
}
}
func swiftGenerateAbstractPrefix(_ isAbstract: Boolean) {
if isAbstract && Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__abstract ")
}
}
func swiftGeneratePartialPrefix(_ isPartial: Boolean) {
if isPartial && Dialect == .Silver {
Append("__partial ")
}
}
override func generateAliasType(_ type: CGTypeAliasDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility)
Append("typealias ")
generateIdentifier(type.Name)
Append(" = ")
generateTypeReference(type.ActualType)
AppendLine()
}
override func generateBlockType(_ block: CGBlockTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(block.Visibility)
Append("typealias ")
generateIdentifier(block.Name)
Append(" = ")
swiftGenerateInlineBlockType(block)
AppendLine()
}
func swiftGenerateInlineBlockType(_ block: CGBlockTypeDefinition) {
if block.IsPlainFunctionPointer {
Append("@FunctionPointer ")
}
Append("(")
for p in 0 ..< block.Parameters.Count {
if p > 0 {
Append(", ")
}
if let type = block.Parameters[p].`Type` {
generateTypeReference(type)
} else {
Append("Any?")
}
}
Append(") -> ")
if let returnType = block.ReturnType, !returnType.IsVoid {
generateTypeReference(returnType)
} else {
Append("()")
}
}
override func generateEnumType(_ type: CGEnumTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility)
Append("enum ")
generateIdentifier(type.Name)
//ToDo: generic constraints
if let baseType = type.BaseType {
Append(" : ")
generateTypeReference(baseType, ignoreNullability: true)
}
AppendLine(" { ")
incIndent()
for m in type.Members {
if let m = m as? CGEnumValueDefinition {
self.generateAttributes(m.Attributes)
Append("case ")
generateIdentifier(m.Name)
if let value = m.Value {
Append(" = ")
generateExpression(value)
}
AppendLine()
}
}
decIndent()
AppendLine("}")
}
override func generateClassTypeStart(_ type: CGClassTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed, type: type)
swiftGenerateStaticPrefix(type.Static)
swiftGeneratePartialPrefix(type.Partial)
swiftGenerateAbstractPrefix(type.Abstract)
Append("class ")
generateIdentifier(type.Name)
swiftGenerateGenericParameters(type.GenericParameters)
swiftGenerateAncestorList(type)
AppendLine(" { ")
incIndent()
}
override func generateClassTypeEnd(_ type: CGClassTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateStructTypeStart(_ type: CGStructTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed, type: type)
swiftGenerateStaticPrefix(type.Static)
swiftGeneratePartialPrefix(type.Partial)
swiftGenerateAbstractPrefix(type.Abstract)
Append("struct ")
generateIdentifier(type.Name)
swiftGenerateGenericParameters(type.GenericParameters)
swiftGenerateAncestorList(type)
AppendLine(" { ")
incIndent()
}
override func generateStructTypeEnd(_ type: CGStructTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility, sealed: type.Sealed, type: type)
Append("protocol ")
generateIdentifier(type.Name)
swiftGenerateGenericParameters(type.GenericParameters)
swiftGenerateAncestorList(type)
AppendLine(" { ")
incIndent()
}
override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) {
swiftGenerateTypeVisibilityPrefix(type.Visibility)
Append("extension ")
if let ancestor = type.Ancestors.FirstOrDefault() {
generateTypeReference(ancestor, ignoreNullability: true)
} else {
generateIdentifier(type.Name)
}
Append(" ")
AppendLine("{ ")
incIndent()
}
override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) {
decIndent()
AppendLine("}")
}
//
// Type Members
//
override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
if method.Optional {
Append("optional ")
}
swiftGenerateStaticPrefix(method.Static && !type.Static)
} else {
swiftGenerateMemberTypeVisibilityPrefix(method.Visibility, virtuality: method.Virtuality)
swiftGenerateStaticPrefix(method.Static && !type.Static)
if method.External && Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__extern ")
}
}
Append("func ")
generateIdentifier(method.Name)
swiftGenerateGenericParameters(method.GenericParameters)
Append("(")
swiftGenerateDefinitionParameters(method.Parameters)
Append(")")
if method.Throws {
Append(" throws")
}
if let returnType = method.ReturnType, !returnType.IsVoid {
Append(" -> ")
returnType.startLocation = currentLocation
generateTypeReference(returnType)
returnType.endLocation = currentLocation
}
if type is CGInterfaceTypeDefinition || method.External || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
generateStatements(variables: method.LocalVariables)
generateStatements(method.Statements)
decIndent()
AppendLine("}")
}
override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
} else {
swiftGenerateMemberTypeVisibilityPrefix(ctor.Visibility, virtuality: ctor.Virtuality)
}
Append("init")
switch ctor.Nullability {
case .NullableUnwrapped: Append("!")
case .NullableNotUnwrapped: Append("?")
default:
}
Append("(")
if length(ctor.Name) > 0 {
swiftGenerateDefinitionParameters(ctor.Parameters, firstExternalName: removeWithPrefix(ctor.Name))
} else {
swiftGenerateDefinitionParameters(ctor.Parameters)
}
Append(")")
if type is CGInterfaceTypeDefinition || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
generateStatements(variables: ctor.LocalVariables)
generateStatements(ctor.Statements)
decIndent()
AppendLine("}")
}
override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) {
Append("deinit")
if type is CGInterfaceTypeDefinition || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
generateStatements(variables: dtor.LocalVariables)
generateStatements(dtor.Statements)
decIndent()
AppendLine("}")
}
override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
swiftGenerateStaticPrefix(finalizer.Static && !type.Static)
} else {
swiftGenerateMemberTypeVisibilityPrefix(finalizer.Visibility, virtuality: finalizer.Virtuality)
swiftGenerateStaticPrefix(finalizer.Static && !type.Static)
if finalizer.External && Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__extern ")
}
}
Append("func Finalizer()")
if type is CGInterfaceTypeDefinition || finalizer.External || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
generateStatements(variables: finalizer.LocalVariables)
generateStatements(finalizer.Statements)
decIndent()
AppendLine("}")
}
override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) {
swiftGenerateMemberTypeVisibilityPrefix(field.Visibility, virtuality: field.Virtuality)
swiftGenerateStaticPrefix(field.Static && !type.Static)
swiftGenerateStorageModifierPrefixIfNeeded(field.StorageModifier)
if field.Constant {
Append("let ")
} else {
Append("var ")
}
generateIdentifier(field.Name)
if let type = field.`Type` {
Append(": ")
generateTypeReference(type)
}
if let value = field.Initializer {
Append(" = ")
generateExpression(value)
} else {
swiftGenerateDefaultInitializerForType(field.`Type`)
}
AppendLine()
}
override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) {
if property.GetterVisibility != nil || property.SetterVisibility != nil {
if let v = property.GetterVisibility {
swiftGenerateMemberTypeVisibilityPrefix(v, virtuality: property.Virtuality, appendSpace: false)
Append("(get) ")
} else {
swiftGenerateMemberTypeVisibilityPrefix(property.Visibility, virtuality: property.Virtuality)
}
if let v = property.SetterVisibility {
swiftGenerateMemberTypeVisibilityPrefix(v, virtuality: property.Virtuality, appendSpace: false)
Append("(set) ")
} else {
swiftGenerateMemberTypeVisibilityPrefix(property.Visibility, virtuality: property.Virtuality, appendSpace: false)
Append("(set) ")
}
} else {
if !(type is CGInterfaceTypeDefinition) {
swiftGenerateMemberTypeVisibilityPrefix(property.Visibility, virtuality: property.Virtuality)
}
}
swiftGenerateStaticPrefix(property.Static && !type.Static)
if property.Lazy {
Append("lazy ")
}
swiftGenerateStorageModifierPrefixIfNeeded(property.StorageModifier)
if let params = property.Parameters, params.Count > 0 {
Append("subscript ")
generateIdentifier(property.Name)
Append("(")
swiftGenerateDefinitionParameters(params)
Append(")")
if let type = property.`Type` {
Append(" -> ")
generateTypeReference(type)
} else {
assert(false, "Swift Subscripts must have a well-defined type.")
}
assert(property.Initializer == nil, "Swift Subscripts cannot have an initializer.")
} else {
if property.ReadOnly && (property.IsShortcutProperty) {
Append("let ")
} else if property.WriteOnly {
Append("private(set) var ")
} else {
Append("var ")
}
generateIdentifier(property.Name)
if let type = property.`Type` {
Append(": ")
generateTypeReference(type)
}
}
if property.IsShortcutProperty {
if type is CGInterfaceTypeDefinition {
if property.ReadOnly {
Append(" { get }")
} else if property.WriteOnly {
Append(" { set }")
} else {
Append(" { get set }")
}
AppendLine()
return
}
if let value = property.Initializer {
Append(" = ")
generateExpression(value)
} else {
swiftGenerateDefaultInitializerForType(property.`Type`)
}
AppendLine()
} else {
if let value = property.Initializer {
assert(false, "Swift Properties cannot have both accessor statements and an initializer")
}
if type is CGInterfaceTypeDefinition || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
if let getStatements = property.GetStatements {
AppendLine("get {")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(getStatements)
decIndent()
AppendLine("}")
} else if let getExpresssion = property.GetExpression {
AppendLine("get {")
incIndent()
generateStatement(CGReturnStatement(getExpresssion))
decIndent()
AppendLine("}")
}
if let setStatements = property.SetStatements {
AppendLine("set {")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(setStatements)
decIndent()
AppendLine("}")
} else if let setExpression = property.SetExpression {
AppendLine("set {")
incIndent()
generateStatement(CGAssignmentStatement(setExpression, CGPropertyValueExpression.PropertyValue))
decIndent()
AppendLine("}")
}
decIndent()
AppendLine("}")
}
}
override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
swiftGenerateMemberTypeVisibilityPrefix(event.Visibility, virtuality: event.Virtuality)
swiftGenerateStaticPrefix(event.Static && !type.Static)
Append("__event ")
generateIdentifier(event.Name)
if let type = event.`Type` {
Append(": ")
generateTypeReference(type)
}
if type is CGInterfaceTypeDefinition || definitionOnly {
AppendLine()
return
}
// Todo: Add/Rmeove/raise statements?
} else {
assert(false, "generateEventDefinition is not supported in Swift, except in Silver")
}
}
override func wellKnownSymbolForCustomOperator(name: String!) -> String? {
switch name.ToUpper() {
case "implicit": return "__implicit"
case "explicit": return "__explicit"
default: return super.wellKnownSymbolForCustomOperator(name: name)
}
}
override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
if customOperator.Optional {
Append("optional ")
}
swiftGenerateStaticPrefix(customOperator.Static && !type.Static)
} else {
swiftGenerateMemberTypeVisibilityPrefix(customOperator.Visibility, virtuality: customOperator.Virtuality)
swiftGenerateStaticPrefix(customOperator.Static && !type.Static)
if customOperator.External && Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("__extern ")
}
}
Append("static func ")
if let symbol = wellKnownSymbolForCustomOperator(name: customOperator.Name) {
Append(symbol)
} else {
Append(customOperator.Name)
}
Append("(")
swiftGenerateDefinitionParameters(customOperator.Parameters)
Append(")")
if let returnType = customOperator.ReturnType, !returnType.IsVoid {
Append(" -> ")
returnType.startLocation = currentLocation
generateTypeReference(returnType)
returnType.endLocation = currentLocation
}
if type is CGInterfaceTypeDefinition || customOperator.External || definitionOnly {
AppendLine()
return
}
AppendLine(" {")
incIndent()
generateStatements(variables: customOperator.LocalVariables)
generateStatements(customOperator.Statements)
decIndent()
AppendLine("}")
}
override func generateNestedTypeDefinition(_ member: CGNestedTypeDefinition, type: CGTypeDefinition) {
generateTypeDefinition(member.`Type`)
}
//
// Type References
//
func swiftSuffixForNullability(_ nullability: CGTypeNullabilityKind, defaultNullability: CGTypeNullabilityKind) -> String {
switch nullability {
case .Unknown:
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
return "¡"
} else {
return ""
}
case .NullableUnwrapped:
return "!"
case .NullableNotUnwrapped:
return "?"
case .NotNullable:
return ""
case .Default:
return swiftSuffixForNullability(defaultNullability, defaultNullability:CGTypeNullabilityKind.Unknown)
}
}
func swiftSuffixForNullabilityForCollectionType(_ type: CGTypeReference) -> String {
return swiftSuffixForNullability(type.Nullability, defaultNullability: Dialect == CGSwiftCodeGeneratorDialect.Silver ? CGTypeNullabilityKind.NotNullable : CGTypeNullabilityKind.NullableUnwrapped)
}
func swiftGenerateDefaultInitializerForType(_ type: CGTypeReference?) {
if let type = type {
if type.ActualNullability == CGTypeNullabilityKind.NotNullable || (type.Nullability == CGTypeNullabilityKind.Default && !type.IsClassType) {
if let defaultValue = type.DefaultValue {
Append(" = ")
generateExpression(defaultValue)
}
}
}
}
override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNullability: Boolean = false) {
super.generateNamedTypeReference(type, ignoreNullability: ignoreNullability)
if !ignoreNullability {
Append(swiftSuffixForNullability(type.Nullability, defaultNullability: type.DefaultNullability))
}
}
override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) {
switch (type.Kind) {
case .Int: Append("Int")
case .UInt: Append("UInt")
case .Int8: Append("Int8")
case .UInt8: Append("UInt8")
case .Int16: Append("Int16")
case .UInt16: Append("UInt16")
case .Int32: Append("Int32")
case .UInt32: Append("UInt32")
case .Int64: Append("Int64")
case .UInt64: Append("UInt16")
case .IntPtr: Append("Int")
case .UIntPtr: Append("UInt")
case .Single: Append("Float32")
case .Double: Append("Float64")
case .Boolean: Append("Bool")
case .String: Append("String")
case .AnsiChar: Append("AnsiChar")
case .UTF16Char: Append("Char")
case .UTF32Char: Append("Character")
case .Dynamic: Append("Any")
case .InstanceType: Append("Self")
case .Void: Append("()")
case .Object: if Dialect == CGSwiftCodeGeneratorDialect.Silver { Append("Object") } else { Append("NSObject") }
case .Class: Append("AnyClass")
}
if !ignoreNullability {
Append(swiftSuffixForNullability(type.Nullability, defaultNullability: type.DefaultNullability))
}
}
override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) {
let suffix = !ignoreNullability ? swiftSuffixForNullabilityForCollectionType(type) : ""
if length(suffix) > 0 {
Append("(")
swiftGenerateInlineBlockType(type.Block)
Append(")")
Append(suffix)
} else {
swiftGenerateInlineBlockType(type.Block)
}
}
override func generatePointerTypeReference(_ type: CGPointerTypeReference) {
Append("UnsafePointer<")
generateTypeReference(type.`Type`)
Append(">")
}
override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("dynamic<")
generateTypeReference(type.`Type`)
Append(">")
if !ignoreNullability {
Append(swiftSuffixForNullability(type.Nullability, defaultNullability: .NullableUnwrapped))
}
} else {
assert(false, "generateKindOfTypeReference is not supported in Swift, except in Silver")
}
}
override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) {
Append("(")
for m in 0 ..< type.Members.Count {
if m > 0 {
Append(", ")
}
generateTypeReference(type.Members[m])
if !ignoreNullability {
Append(swiftSuffixForNullability(type.Nullability, defaultNullability: .NotNullable))
}
}
Append(")")
}
override func generateSetTypeReference(_ setType: CGSetTypeReference, ignoreNullability: Boolean = false) {
assert(false, "generateSetTypeReference is not supported in Swift")
}
override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) {
if Dialect == CGSwiftCodeGeneratorDialect.Silver {
Append("ISequence<")
generateTypeReference(sequence.`Type`)
Append(">")
if !ignoreNullability {
Append(swiftSuffixForNullability(sequence.Nullability, defaultNullability: .NullableUnwrapped))
}
} else {
assert(false, "generateSequenceTypeReference is not supported in Swift except in Silver")
}
}
override func generateArrayTypeReference(_ array: CGArrayTypeReference, ignoreNullability: Boolean = false) {
if let bounds = array.Bounds {
var count = bounds.Count
if count == 0 {
count = 1
}
switch (array.ArrayKind) {
case .Static:
fallthrough
case .Dynamic:
generateTypeReference(array.`Type`)
Append(swiftSuffixForNullabilityForCollectionType(array.`Type`))
for b in 0 ..< count {
Append("[]")
}
if !ignoreNullability {
Append(swiftSuffixForNullability(array.Nullability, defaultNullability: .NotNullable))
}
case .HighLevel:
for b in 0 ..< count {
Append("[")
}
generateTypeReference(array.`Type`)
Append(swiftSuffixForNullabilityForCollectionType(array.`Type`))
for b in 0 ..< count {
Append("]")
}
if !ignoreNullability {
Append(swiftSuffixForNullability(array.Nullability, defaultNullability: .NullableUnwrapped))
}
}
} else {
switch (array.ArrayKind) {
case .Static:
fallthrough
case .Dynamic:
generateTypeReference(array.`Type`)
Append("[]")
case .HighLevel:
Append("[")
generateTypeReference(array.`Type`)
Append("]")
}
}
// bounds are not supported in Swift
}
override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) {
Append("[")
generateTypeReference(type.KeyType)
Append(":")
generateTypeReference(type.ValueType)
Append("]")
if !ignoreNullability {
Append(swiftSuffixForNullabilityForCollectionType(type))
}
}
//
// Helpers
//
private func removeWithPrefix(_ name: String) -> String {
var name = name
if name.ToLowerInvariant().StartsWith("with") {
name = name.Substring(4)
}
return lowercaseFirstLetter(name)
}
} | 28.678766 | 207 | 0.719824 |
134d13b10e3d7c35ccc2b02626fe27434381e631 | 57,617 | c | C | FreeBSD/sys/contrib/ncsw/Peripherals/FM/HC/hc.c | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 91 | 2018-11-24T05:33:58.000Z | 2022-03-16T05:58:05.000Z | FreeBSD/sys/contrib/ncsw/Peripherals/FM/HC/hc.c | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | FreeBSD/sys/contrib/ncsw/Peripherals/FM/HC/hc.c | TigerBSD/TigerBSD | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 18 | 2018-11-24T10:35:29.000Z | 2021-04-22T07:22:10.000Z | /* Copyright (c) 2008-2011 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Freescale Semiconductor nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") as published by the Free Software
* Foundation, either version 2 of that License or (at your option) any
* later version.
*
* THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Freescale Semiconductor BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "std_ext.h"
#include "error_ext.h"
#include "sprint_ext.h"
#include "string_ext.h"
#include "fm_common.h"
#include "fm_hc.h"
#define HC_HCOR_OPCODE_PLCR_PRFL 0x0
#define HC_HCOR_OPCODE_KG_SCM 0x1
#define HC_HCOR_OPCODE_SYNC 0x2
#define HC_HCOR_OPCODE_CC 0x3
#define HC_HCOR_OPCODE_CC_CAPWAP_REASSM_TIMEOUT 0x5
#define HC_HCOR_GBL 0x20000000
#define SIZE_OF_HC_FRAME_PORT_REGS (sizeof(t_HcFrame)-sizeof(t_FmPcdKgInterModuleSchemeRegs)+sizeof(t_FmPcdKgPortRegs))
#define SIZE_OF_HC_FRAME_SCHEME_REGS sizeof(t_HcFrame)
#define SIZE_OF_HC_FRAME_PROFILES_REGS (sizeof(t_HcFrame)-sizeof(t_FmPcdKgInterModuleSchemeRegs)+sizeof(t_FmPcdPlcrInterModuleProfileRegs))
#define SIZE_OF_HC_FRAME_PROFILE_CNT (sizeof(t_HcFrame)-sizeof(t_FmPcdPlcrInterModuleProfileRegs)+sizeof(uint32_t))
#define SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC 16
#define BUILD_FD(len) \
do { \
memset(&fmFd, 0, sizeof(t_DpaaFD)); \
DPAA_FD_SET_ADDR(&fmFd, p_HcFrame); \
DPAA_FD_SET_OFFSET(&fmFd, 0); \
DPAA_FD_SET_LENGTH(&fmFd, len); \
} while (0)
#if defined(__MWERKS__) && !defined(__GNUC__)
#pragma pack(push,1)
#endif /* defined(__MWERKS__) && ... */
#define MEM_MAP_START
/**************************************************************************//**
@Description PCD KG scheme registers
*//***************************************************************************/
typedef _Packed struct t_FmPcdKgSchemeRegsWithoutCounter {
volatile uint32_t kgse_mode; /**< MODE */
volatile uint32_t kgse_ekfc; /**< Extract Known Fields Command */
volatile uint32_t kgse_ekdv; /**< Extract Known Default Value */
volatile uint32_t kgse_bmch; /**< Bit Mask Command High */
volatile uint32_t kgse_bmcl; /**< Bit Mask Command Low */
volatile uint32_t kgse_fqb; /**< Frame Queue Base */
volatile uint32_t kgse_hc; /**< Hash Command */
volatile uint32_t kgse_ppc; /**< Policer Profile Command */
volatile uint32_t kgse_gec[FM_PCD_KG_NUM_OF_GENERIC_REGS];
/**< Generic Extract Command */
volatile uint32_t kgse_dv0; /**< KeyGen Scheme Entry Default Value 0 */
volatile uint32_t kgse_dv1; /**< KeyGen Scheme Entry Default Value 1 */
volatile uint32_t kgse_ccbs; /**< KeyGen Scheme Entry Coarse Classification Bit*/
volatile uint32_t kgse_mv; /**< KeyGen Scheme Entry Match vector */
} _PackedType t_FmPcdKgSchemeRegsWithoutCounter;
typedef _Packed struct t_FmPcdKgPortRegs {
volatile uint32_t spReg;
volatile uint32_t cppReg;
} _PackedType t_FmPcdKgPortRegs;
typedef _Packed struct t_HcFrame {
volatile uint32_t opcode;
volatile uint32_t actionReg;
volatile uint32_t extraReg;
volatile uint32_t commandSequence;
union {
t_FmPcdKgInterModuleSchemeRegs schemeRegs;
t_FmPcdKgInterModuleSchemeRegs schemeRegsWithoutCounter;
t_FmPcdPlcrInterModuleProfileRegs profileRegs;
volatile uint32_t singleRegForWrite; /* for writing SP, CPP, profile counter */
t_FmPcdKgPortRegs portRegsForRead;
volatile uint32_t clsPlanEntries[CLS_PLAN_NUM_PER_GRP];
t_FmPcdCcCapwapReassmTimeoutParams ccCapwapReassmTimeout;
} hcSpecificData;
} _PackedType t_HcFrame;
#define MEM_MAP_END
#if defined(__MWERKS__) && !defined(__GNUC__)
#pragma pack(pop)
#endif /* defined(__MWERKS__) && ... */
typedef struct t_FmHc {
t_Handle h_FmPcd;
t_Handle h_HcPortDev;
t_FmPcdQmEnqueueCallback *f_QmEnqueue; /**< A callback for enqueuing frames to the QM */
t_Handle h_QmArg; /**< A handle to the QM module */
uint8_t padTill16;
uint32_t seqNum;
volatile bool wait[32];
} t_FmHc;
static __inline__ t_Error EnQFrm(t_FmHc *p_FmHc, t_DpaaFD *p_FmFd, volatile uint32_t *p_SeqNum)
{
t_Error err = E_OK;
uint32_t savedSeqNum;
uint32_t intFlags;
uint32_t timeout=100;
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
*p_SeqNum = p_FmHc->seqNum;
savedSeqNum = p_FmHc->seqNum;
p_FmHc->seqNum = (uint32_t)((p_FmHc->seqNum+1)%32);
ASSERT_COND(!p_FmHc->wait[savedSeqNum]);
p_FmHc->wait[savedSeqNum] = TRUE;
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
DBG(TRACE, ("Send Hc, SeqNum %d, FD@0x%x, fd offset 0x%x",
savedSeqNum,DPAA_FD_GET_ADDR(p_FmFd),DPAA_FD_GET_OFFSET(p_FmFd)));
err = p_FmHc->f_QmEnqueue(p_FmHc->h_QmArg, (void *)p_FmFd);
if(err)
RETURN_ERROR(MINOR, err, ("HC enqueue failed"));
while (p_FmHc->wait[savedSeqNum] && --timeout)
XX_UDelay(100);
if (!timeout)
RETURN_ERROR(MINOR, E_TIMEOUT, ("HC Callback, timeout exceeded"));
return err;
}
static t_Error CcHcDoDynamicChange(t_FmHc *p_FmHc, t_Handle p_OldPointer, t_Handle p_NewPointer)
{
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
t_Error err = E_OK;
ASSERT_COND(p_FmHc);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_CC);
p_HcFrame->actionReg = FmPcdCcGetNodeAddrOffsetFromNodeInfo(p_FmHc->h_FmPcd, p_NewPointer);
if(p_HcFrame->actionReg == (uint32_t)ILLEGAL_BASE)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("Something wrong with base address"));
}
p_HcFrame->actionReg |= 0xc0000000;
p_HcFrame->extraReg = FmPcdCcGetNodeAddrOffsetFromNodeInfo(p_FmHc->h_FmPcd, p_OldPointer);
if(p_HcFrame->extraReg == (uint32_t)ILLEGAL_BASE)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("Something wrong with base address"));
}
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
XX_FreeSmart(p_HcFrame);
return E_OK;
}
static t_Error HcDynamicChange(t_FmHc *p_FmHc,t_List *h_OldPointersLst, t_List *h_NewPointersLst, t_Handle *h_Params)
{
t_List *p_PosOld, *p_PosNew;
uint16_t i = 0;
t_Error err = E_OK;
uint8_t numOfModifiedPtr;
SANITY_CHECK_RETURN_ERROR((LIST_NumOfObjs(h_NewPointersLst) == LIST_NumOfObjs(h_OldPointersLst)),E_INVALID_STATE);
numOfModifiedPtr = (uint8_t)LIST_NumOfObjs(h_NewPointersLst);
p_PosNew = NCSW_LIST_FIRST(h_NewPointersLst);
p_PosOld = NCSW_LIST_FIRST(h_OldPointersLst);
for(i = 0; i < numOfModifiedPtr; i++)
{
err = CcHcDoDynamicChange(p_FmHc, p_PosOld, p_PosNew);
if(err)
{
FmPcdCcReleaseModifiedDataStructure(p_FmHc->h_FmPcd, h_OldPointersLst, h_NewPointersLst, i, h_Params);
RETURN_ERROR(MAJOR, err, ("For part of nodes changes are done - situation is danger"));
}
p_PosNew = NCSW_LIST_NEXT(p_PosNew);
p_PosOld = NCSW_LIST_NEXT(p_PosOld);
}
err = FmPcdCcReleaseModifiedDataStructure(p_FmHc->h_FmPcd, h_OldPointersLst, h_NewPointersLst, i, h_Params);
if(err)
RETURN_ERROR(MAJOR, err, NO_MSG);
return E_OK;
}
t_Handle FmHcConfigAndInit(t_FmHcParams *p_FmHcParams)
{
t_FmHc *p_FmHc;
t_FmPortParams fmPortParam;
t_Error err = E_OK;
p_FmHc = (t_FmHc *)XX_Malloc(sizeof(t_FmHc));
if (!p_FmHc)
{
REPORT_ERROR(MINOR, E_NO_MEMORY, ("HC obj"));
return NULL;
}
memset(p_FmHc,0,sizeof(t_FmHc));
p_FmHc->h_FmPcd = p_FmHcParams->h_FmPcd;
p_FmHc->f_QmEnqueue = p_FmHcParams->params.f_QmEnqueue;
p_FmHc->h_QmArg = p_FmHcParams->params.h_QmArg;
if (!FmIsMaster(p_FmHcParams->h_Fm))
return (t_Handle)p_FmHc;
/*
TKT056919 - axi12axi0 can hang if read request follows the single byte write on the very next cycle
TKT038900 - FM dma lockup occur due to AXI slave protocol violation
*/
#ifdef FM_LOCKUP_ALIGNMENT_ERRATA_FMAN_SW004
p_FmHc->padTill16 = 16 - (sizeof(t_FmHc) % 16);
#endif /* FM_LOCKUP_ALIGNMENT_ERRATA_FMAN_SW004 */
memset(&fmPortParam, 0, sizeof(fmPortParam));
fmPortParam.baseAddr = p_FmHcParams->params.portBaseAddr;
fmPortParam.portType = e_FM_PORT_TYPE_OH_HOST_COMMAND;
fmPortParam.portId = p_FmHcParams->params.portId;
fmPortParam.liodnBase = p_FmHcParams->params.liodnBase;
fmPortParam.h_Fm = p_FmHcParams->h_Fm;
fmPortParam.specificParams.nonRxParams.errFqid = p_FmHcParams->params.errFqid;
fmPortParam.specificParams.nonRxParams.dfltFqid = p_FmHcParams->params.confFqid;
fmPortParam.specificParams.nonRxParams.qmChannel = p_FmHcParams->params.qmChannel;
p_FmHc->h_HcPortDev = FM_PORT_Config(&fmPortParam);
if(!p_FmHc->h_HcPortDev)
{
REPORT_ERROR(MAJOR, E_INVALID_HANDLE, ("FM HC port!"));
XX_Free(p_FmHc);
return NULL;
}
/* final init */
if ((err = FM_PORT_Init(p_FmHc->h_HcPortDev)) != E_OK)
{
REPORT_ERROR(MAJOR, err, ("FM HC port!"));
FmHcFree(p_FmHc);
return NULL;
}
if ((err = FM_PORT_Enable(p_FmHc->h_HcPortDev)) != E_OK)
{
REPORT_ERROR(MAJOR, err, ("FM HC port!"));
FmHcFree(p_FmHc);
return NULL;
}
return (t_Handle)p_FmHc;
}
void FmHcFree(t_Handle h_FmHc)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
if (!p_FmHc)
return;
if (p_FmHc->h_HcPortDev)
FM_PORT_Free(p_FmHc->h_HcPortDev);
XX_Free(p_FmHc);
}
#if (defined(DEBUG_ERRORS) && (DEBUG_ERRORS > 0))
t_Error FmHcDumpRegs(t_Handle h_FmHc)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
SANITY_CHECK_RETURN_ERROR(p_FmHc, E_INVALID_HANDLE);
SANITY_CHECK_RETURN_ERROR(p_FmHc->h_HcPortDev, E_INVALID_HANDLE);
return FM_PORT_DumpRegs(p_FmHc->h_HcPortDev);
}
#endif /* (defined(DEBUG_ERRORS) && ... */
void FmHcTxConf(t_Handle h_FmHc, t_DpaaFD *p_Fd)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
uint32_t intFlags;
ASSERT_COND(p_FmHc);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
p_HcFrame = (t_HcFrame *)PTR_MOVE(DPAA_FD_GET_ADDR(p_Fd), DPAA_FD_GET_OFFSET(p_Fd));
DBG(TRACE, ("Hc Conf, SeqNum %d, FD@0x%x, fd offset 0x%x",
p_HcFrame->commandSequence, DPAA_FD_GET_ADDR(p_Fd), DPAA_FD_GET_OFFSET(p_Fd)));
if (!(p_FmHc->wait[p_HcFrame->commandSequence]))
REPORT_ERROR(MINOR, E_INVALID_FRAME, ("Not an Host-Command frame received!"));
else
p_FmHc->wait[p_HcFrame->commandSequence] = FALSE;
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
}
t_Handle FmHcPcdKgSetScheme(t_Handle h_FmHc, t_FmPcdKgSchemeParams *p_Scheme)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_FmPcdKgInterModuleSchemeRegs schemeRegs;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint32_t intFlags;
uint8_t physicalSchemeId, relativeSchemeId;
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
REPORT_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
return NULL;
}
if(!p_Scheme->modify)
{
/* check that schemeId is in range */
if(p_Scheme->id.relativeSchemeId >= FmPcdKgGetNumOfPartitionSchemes(p_FmHc->h_FmPcd))
{
REPORT_ERROR(MAJOR, E_NOT_IN_RANGE, ("Scheme is out of range"));
XX_FreeSmart(p_HcFrame);
return NULL;
}
relativeSchemeId = p_Scheme->id.relativeSchemeId;
if (FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, FALSE))
{
XX_FreeSmart(p_HcFrame);
return NULL;
}
physicalSchemeId = FmPcdKgGetPhysicalSchemeId(p_FmHc->h_FmPcd, relativeSchemeId);
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildReadSchemeActionReg(physicalSchemeId);
p_HcFrame->extraReg = 0xFFFFF800;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
/* check if this scheme is already used */
if (FmPcdKgHwSchemeIsValid(p_HcFrame->hcSpecificData.schemeRegs.kgse_mode))
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
REPORT_ERROR(MAJOR, E_ALREADY_EXISTS, ("Scheme is already used"));
XX_FreeSmart(p_HcFrame);
return NULL;
}
}
else
{
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
physicalSchemeId = (uint8_t)(PTR_TO_UINT(p_Scheme->id.h_Scheme)-1);
relativeSchemeId = FmPcdKgGetRelativeSchemeId(p_FmHc->h_FmPcd, physicalSchemeId);
if( relativeSchemeId == FM_PCD_KG_NUM_OF_SCHEMES)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
REPORT_ERROR(MAJOR, E_NOT_IN_RANGE, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
err = FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, TRUE);
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
if (err)
{
XX_FreeSmart(p_HcFrame);
return NULL;
}
}
err = FmPcdKgBuildScheme(p_FmHc->h_FmPcd, p_Scheme, &schemeRegs);
if(err)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
REPORT_ERROR(MAJOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWriteSchemeActionReg(physicalSchemeId, p_Scheme->schemeCounter.update);
p_HcFrame->extraReg = 0xFFFFF800;
memcpy(&p_HcFrame->hcSpecificData.schemeRegs, &schemeRegs, sizeof(t_FmPcdKgInterModuleSchemeRegs));
if(!p_Scheme->schemeCounter.update)
{
p_HcFrame->hcSpecificData.schemeRegs.kgse_dv0 = schemeRegs.kgse_dv0;
p_HcFrame->hcSpecificData.schemeRegs.kgse_dv1 = schemeRegs.kgse_dv1;
p_HcFrame->hcSpecificData.schemeRegs.kgse_ccbs = schemeRegs.kgse_ccbs;
p_HcFrame->hcSpecificData.schemeRegs.kgse_mv = schemeRegs.kgse_mv;
}
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
FmPcdKgValidateSchemeSw(p_FmHc->h_FmPcd, relativeSchemeId);
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
return (t_Handle)(UINT_TO_PTR(physicalSchemeId + 1));
}
t_Error FmHcPcdKgDeleteScheme(t_Handle h_FmHc, t_Handle h_Scheme)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint8_t relativeSchemeId;
uint8_t physicalSchemeId = (uint8_t)(PTR_TO_UINT(h_Scheme)-1);
relativeSchemeId = FmPcdKgGetRelativeSchemeId(p_FmHc->h_FmPcd, physicalSchemeId);
if ((err = FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, FALSE)) != E_OK)
RETURN_ERROR(MAJOR, err, NO_MSG);
if(relativeSchemeId == FM_PCD_KG_NUM_OF_SCHEMES)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MAJOR, E_NOT_IN_RANGE, NO_MSG);
}
err = FmPcdKgCheckInvalidateSchemeSw(p_FmHc->h_FmPcd, relativeSchemeId);
if (err)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWriteSchemeActionReg(physicalSchemeId, TRUE);
p_HcFrame->extraReg = 0xFFFFF800;
memset(&p_HcFrame->hcSpecificData.schemeRegs, 0, sizeof(t_FmPcdKgInterModuleSchemeRegs));
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
FmPcdKgInvalidateSchemeSw(p_FmHc->h_FmPcd, relativeSchemeId);
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
return E_OK;
}
t_Error FmHcPcdKgCcGetSetParams(t_Handle h_FmHc, t_Handle h_Scheme, uint32_t requiredAction)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint8_t relativeSchemeId;
uint8_t physicalSchemeId = (uint8_t)(PTR_TO_UINT(h_Scheme)-1);
uint32_t tmpReg32 = 0;
relativeSchemeId = FmPcdKgGetRelativeSchemeId(p_FmHc->h_FmPcd, physicalSchemeId);
if( relativeSchemeId == FM_PCD_KG_NUM_OF_SCHEMES)
RETURN_ERROR(MAJOR, E_NOT_IN_RANGE, NO_MSG);
if (FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, FALSE))
RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Lock of the scheme FAILED"));
if(!FmPcdKgGetPointedOwners(p_FmHc->h_FmPcd, relativeSchemeId) ||
!(FmPcdKgGetRequiredAction(p_FmHc->h_FmPcd, relativeSchemeId) & requiredAction))
{
if(requiredAction & UPDATE_NIA_ENQ_WITHOUT_DMA)
{
if((FmPcdKgGetNextEngine(p_FmHc->h_FmPcd, relativeSchemeId) == e_FM_PCD_DONE) && (FmPcdKgGetDoneAction(p_FmHc->h_FmPcd, relativeSchemeId) == e_FM_PCD_ENQ_FRAME))
{
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildReadSchemeActionReg(physicalSchemeId);
p_HcFrame->extraReg = 0xFFFFF800;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
/* check if this scheme is already used */
if (!FmPcdKgHwSchemeIsValid(p_HcFrame->hcSpecificData.schemeRegs.kgse_mode))
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_ALREADY_EXISTS, ("Scheme is already used"));
}
tmpReg32 = p_HcFrame->hcSpecificData.schemeRegs.kgse_mode;
ASSERT_COND(tmpReg32 & (NIA_ENG_BMI | NIA_BMI_AC_ENQ_FRAME));
p_HcFrame->hcSpecificData.schemeRegs.kgse_mode = tmpReg32 | NIA_BMI_AC_ENQ_FRAME_WITHOUT_DMA;
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWriteSchemeActionReg(physicalSchemeId, FALSE);
p_HcFrame->extraReg = 0x80000000;
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
XX_FreeSmart(p_HcFrame);
}
else if (FmPcdKgGetNextEngine(p_FmHc->h_FmPcd, relativeSchemeId) == e_FM_PCD_PLCR)
{
if((FmPcdKgIsDirectPlcr(p_FmHc->h_FmPcd, relativeSchemeId) == FALSE) ||
(FmPcdKgIsDistrOnPlcrProfile(p_FmHc->h_FmPcd, relativeSchemeId) == TRUE))
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MAJOR, E_NOT_SUPPORTED, ("In this situation PP can not be with distribution and has to be shared"));
}
err = FmPcdPlcrCcGetSetParams(p_FmHc->h_FmPcd, FmPcdKgGetRelativeProfileId(p_FmHc->h_FmPcd, relativeSchemeId), requiredAction);
if(err)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
}
}
}
FmPcdKgUpatePointedOwner(p_FmHc->h_FmPcd, relativeSchemeId,TRUE);
FmPcdKgUpdateRequiredAction(p_FmHc->h_FmPcd, relativeSchemeId,requiredAction);
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
return E_OK;
}
uint32_t FmHcPcdKgGetSchemeCounter(t_Handle h_FmHc, t_Handle h_Scheme)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint32_t retVal;
uint8_t relativeSchemeId;
uint8_t physicalSchemeId = (uint8_t)(PTR_TO_UINT(h_Scheme)-1);
relativeSchemeId = FmPcdKgGetRelativeSchemeId(p_FmHc->h_FmPcd, physicalSchemeId);
if( relativeSchemeId == FM_PCD_KG_NUM_OF_SCHEMES)
{
REPORT_ERROR(MAJOR, E_NOT_IN_RANGE, NO_MSG);
return 0;
}
if ((err = FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, FALSE)) != E_OK)
{
REPORT_ERROR(MAJOR, err, ("Scheme lock"));
return 0;
}
/* first read scheme and check that it is valid */
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
REPORT_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
return 0;
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildReadSchemeActionReg(physicalSchemeId);
p_HcFrame->extraReg = 0xFFFFF800;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return 0;
}
if (!FmPcdKgHwSchemeIsValid(p_HcFrame->hcSpecificData.schemeRegs.kgse_mode))
{
REPORT_ERROR(MAJOR, E_ALREADY_EXISTS, ("Scheme is invalid"));
XX_FreeSmart(p_HcFrame);
return 0;
}
retVal = p_HcFrame->hcSpecificData.schemeRegs.kgse_spc;
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
return retVal;
}
t_Error FmHcPcdKgSetSchemeCounter(t_Handle h_FmHc, t_Handle h_Scheme, uint32_t value)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint8_t relativeSchemeId, physicalSchemeId = (uint8_t)(PTR_TO_UINT(h_Scheme)-1);
relativeSchemeId = FmPcdKgGetRelativeSchemeId(p_FmHc->h_FmPcd, physicalSchemeId);
if( relativeSchemeId == FM_PCD_KG_NUM_OF_SCHEMES)
RETURN_ERROR(MAJOR, E_NOT_IN_RANGE, NO_MSG);
if ((err = FmPcdKgSchemeTryLock(p_FmHc->h_FmPcd, relativeSchemeId, FALSE)) != E_OK)
RETURN_ERROR(MAJOR, err, NO_MSG);
/* first read scheme and check that it is valid */
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildReadSchemeActionReg(physicalSchemeId);
p_HcFrame->extraReg = 0xFFFFF800;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
/* check that scheme is valid */
if (!FmPcdKgHwSchemeIsValid(p_HcFrame->hcSpecificData.schemeRegs.kgse_mode))
{
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_ALREADY_EXISTS, ("Scheme is invalid"));
}
/* Write scheme back, with modified counter */
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWriteSchemeActionReg(physicalSchemeId, TRUE);
p_HcFrame->extraReg = 0xFFFFF800;
/* write counter */
p_HcFrame->hcSpecificData.schemeRegs.kgse_spc = value;
BUILD_FD(sizeof(t_HcFrame));
err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence);
FmPcdKgReleaseSchemeLock(p_FmHc->h_FmPcd, relativeSchemeId);
XX_FreeSmart(p_HcFrame);
return err;
}
t_Error FmHcPcdKgSetClsPlan(t_Handle h_FmHc, t_FmPcdKgInterModuleClsPlanSet *p_Set)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint32_t i;
t_Error err = E_OK;
ASSERT_COND(p_FmHc);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
for(i=p_Set->baseEntry;i<p_Set->baseEntry+p_Set->numOfClsPlanEntries;i+=8)
{
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWriteClsPlanBlockActionReg((uint8_t)(i / CLS_PLAN_NUM_PER_GRP));
p_HcFrame->extraReg = 0xFFFFF800;
memcpy((void*)&p_HcFrame->hcSpecificData.clsPlanEntries, (void *)&p_Set->vectors[i-p_Set->baseEntry], CLS_PLAN_NUM_PER_GRP*sizeof(uint32_t));
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
}
XX_FreeSmart(p_HcFrame);
return err;
}
t_Error FmHcPcdKgDeleteClsPlan(t_Handle h_FmHc, uint8_t grpId)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_FmPcdKgInterModuleClsPlanSet *p_ClsPlanSet;
/* clear clsPlan entries in memory */
p_ClsPlanSet = (t_FmPcdKgInterModuleClsPlanSet *)XX_Malloc(sizeof(t_FmPcdKgInterModuleClsPlanSet));
if (!p_ClsPlanSet)
RETURN_ERROR(MAJOR, E_NO_MEMORY, ("memory allocation failed for p_ClsPlanSetd"));
memset(p_ClsPlanSet, 0, sizeof(t_FmPcdKgInterModuleClsPlanSet));
p_ClsPlanSet->baseEntry = FmPcdKgGetClsPlanGrpBase(p_FmHc->h_FmPcd, grpId);
p_ClsPlanSet->numOfClsPlanEntries = FmPcdKgGetClsPlanGrpSize(p_FmHc->h_FmPcd, grpId);
ASSERT_COND(p_ClsPlanSet->numOfClsPlanEntries <= FM_PCD_MAX_NUM_OF_CLS_PLANS);
if (FmHcPcdKgSetClsPlan(p_FmHc, p_ClsPlanSet) != E_OK)
RETURN_ERROR(MAJOR, E_INVALID_STATE, NO_MSG);
XX_Free(p_ClsPlanSet);
FmPcdKgDestroyClsPlanGrp(p_FmHc->h_FmPcd, grpId);
return E_OK;
}
t_Error FmHcPcdCcCapwapTimeoutReassm(t_Handle h_FmHc, t_FmPcdCcCapwapReassmTimeoutParams *p_CcCapwapReassmTimeoutParams )
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
uint32_t intFlags;
t_DpaaFD fmFd;
t_Error err;
SANITY_CHECK_RETURN_VALUE(h_FmHc, E_INVALID_HANDLE,0);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_CC_CAPWAP_REASSM_TIMEOUT);
memcpy(&p_HcFrame->hcSpecificData.ccCapwapReassmTimeout, p_CcCapwapReassmTimeoutParams, sizeof(t_FmPcdCcCapwapReassmTimeoutParams));
BUILD_FD(sizeof(t_HcFrame));
err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence);
XX_FreeSmart(p_HcFrame);
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
t_Error FmHcPcdPlcrCcGetSetParams(t_Handle h_FmHc,uint16_t absoluteProfileId, uint32_t requiredAction)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
t_Error err;
uint32_t tmpReg32 = 0;
uint32_t requiredActionTmp, pointedOwnersTmp;
SANITY_CHECK_RETURN_VALUE(h_FmHc, E_INVALID_HANDLE,0);
if (absoluteProfileId >= FM_PCD_PLCR_NUM_ENTRIES)
RETURN_ERROR(MAJOR, E_INVALID_VALUE,("Policer profile out of range"));
if (FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, absoluteProfileId, FALSE))
return ERROR_CODE(E_BUSY);
requiredActionTmp = FmPcdPlcrGetRequiredAction(p_FmHc->h_FmPcd, absoluteProfileId);
pointedOwnersTmp = FmPcdPlcrGetPointedOwners(p_FmHc->h_FmPcd, absoluteProfileId);
if(!pointedOwnersTmp || !(requiredActionTmp & requiredAction))
{
if(requiredAction & UPDATE_NIA_ENQ_WITHOUT_DMA)
{
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
/* first read scheme and check that it is valid */
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildReadPlcrActionReg(absoluteProfileId);
p_HcFrame->extraReg = 0x00008000;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
/* check that profile is valid */
if (!FmPcdPlcrHwProfileIsValid(p_HcFrame->hcSpecificData.profileRegs.fmpl_pemode))
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_ALREADY_EXISTS, ("Policer is already used"));
}
tmpReg32 = p_HcFrame->hcSpecificData.profileRegs.fmpl_pegnia;
if(!(tmpReg32 & (NIA_ENG_BMI | NIA_BMI_AC_ENQ_FRAME)))
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Next engine of this policer profile has to be assigned to FM_PCD_DONE"));
}
tmpReg32 |= NIA_BMI_AC_ENQ_FRAME_WITHOUT_DMA;
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionReg(absoluteProfileId);
p_HcFrame->actionReg |= FmPcdPlcrBuildNiaProfileReg(TRUE, FALSE, FALSE);
p_HcFrame->extraReg = 0x00008000;
p_HcFrame->hcSpecificData.singleRegForWrite = tmpReg32;
BUILD_FD(SIZE_OF_HC_FRAME_PROFILE_CNT);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
tmpReg32 = p_HcFrame->hcSpecificData.profileRegs.fmpl_peynia;
if(!(tmpReg32 & (NIA_ENG_BMI | NIA_BMI_AC_ENQ_FRAME)))
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Next engine of this policer profile has to be assigned to FM_PCD_DONE"));
}
tmpReg32 |= NIA_BMI_AC_ENQ_FRAME_WITHOUT_DMA;
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionReg(absoluteProfileId);
p_HcFrame->actionReg |= FmPcdPlcrBuildNiaProfileReg(FALSE, TRUE, FALSE);
p_HcFrame->extraReg = 0x00008000;
p_HcFrame->hcSpecificData.singleRegForWrite = tmpReg32;
BUILD_FD(SIZE_OF_HC_FRAME_PROFILE_CNT);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
tmpReg32 = p_HcFrame->hcSpecificData.profileRegs.fmpl_pernia;
if(!(tmpReg32 & (NIA_ENG_BMI | NIA_BMI_AC_ENQ_FRAME)))
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Next engine of this policer profile has to be assigned to FM_PCD_DONE"));
}
tmpReg32 |= NIA_BMI_AC_ENQ_FRAME_WITHOUT_DMA;
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionReg(absoluteProfileId);
p_HcFrame->actionReg |= FmPcdPlcrBuildNiaProfileReg(FALSE, FALSE, TRUE);
p_HcFrame->extraReg = 0x00008000;
p_HcFrame->hcSpecificData.singleRegForWrite = tmpReg32;
BUILD_FD(SIZE_OF_HC_FRAME_PROFILE_CNT);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
XX_FreeSmart(p_HcFrame);
}
}
FmPcdPlcrUpatePointedOwner(p_FmHc->h_FmPcd, absoluteProfileId, TRUE);
FmPcdPlcrUpdateRequiredAction(p_FmHc->h_FmPcd, absoluteProfileId, requiredAction);
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
return E_OK;
}
t_Handle FmHcPcdPlcrSetProfile(t_Handle h_FmHc,t_FmPcdPlcrProfileParams *p_Profile)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_FmPcdPlcrInterModuleProfileRegs profileRegs;
t_Error err = E_OK;
uint32_t intFlags;
uint16_t profileIndx;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
if (p_Profile->modify)
{
profileIndx = (uint16_t)(PTR_TO_UINT(p_Profile->id.h_Profile)-1);
if (FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, profileIndx, FALSE))
return NULL;
}
else
{
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
err = FmPcdPlcrGetAbsoluteProfileId(p_FmHc->h_FmPcd,
p_Profile->id.newParams.profileType,
p_Profile->id.newParams.h_FmPort,
p_Profile->id.newParams.relativeProfileId,
&profileIndx);
if (err)
{
REPORT_ERROR(MAJOR, err, NO_MSG);
return NULL;
}
err = FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, profileIndx, TRUE);
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
if (err)
return NULL;
}
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
REPORT_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
return NULL;
}
if(!p_Profile->modify)
{
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildReadPlcrActionReg(profileIndx);
p_HcFrame->extraReg = 0x00008000;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, profileIndx);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
/* check if this scheme is already used */
if (FmPcdPlcrHwProfileIsValid(p_HcFrame->hcSpecificData.profileRegs.fmpl_pemode))
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, profileIndx);
REPORT_ERROR(MAJOR, E_ALREADY_EXISTS, ("Policer is already used"));
XX_FreeSmart(p_HcFrame);
return NULL;
}
}
memset(&profileRegs, 0, sizeof(t_FmPcdPlcrInterModuleProfileRegs));
err = FmPcdPlcrBuildProfile(p_FmHc->h_FmPcd, p_Profile, &profileRegs);
if(err)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, profileIndx);
REPORT_ERROR(MAJOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionRegs(profileIndx);
p_HcFrame->extraReg = 0x00008000;
memcpy(&p_HcFrame->hcSpecificData.profileRegs, &profileRegs, sizeof(t_FmPcdPlcrInterModuleProfileRegs));
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, profileIndx);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return NULL;
}
FmPcdPlcrValidateProfileSw(p_FmHc->h_FmPcd, profileIndx);
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, profileIndx);
XX_FreeSmart(p_HcFrame);
return UINT_TO_PTR((uint64_t)profileIndx+1);
}
t_Error FmHcPcdPlcrDeleteProfile(t_Handle h_FmHc, t_Handle h_Profile)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
uint16_t absoluteProfileId = (uint16_t)(PTR_TO_UINT(h_Profile)-1);
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
if (FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, absoluteProfileId, FALSE))
return ERROR_CODE(E_BUSY);
FmPcdPlcrInvalidateProfileSw(p_FmHc->h_FmPcd, absoluteProfileId);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionReg(absoluteProfileId);
p_HcFrame->actionReg |= 0x00008000;
p_HcFrame->extraReg = 0x00008000;
memset(&p_HcFrame->hcSpecificData.profileRegs, 0, sizeof(t_FmPcdPlcrInterModuleProfileRegs));
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
return E_OK;
}
t_Error FmHcPcdPlcrSetProfileCounter(t_Handle h_FmHc, t_Handle h_Profile, e_FmPcdPlcrProfileCounters counter, uint32_t value)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
uint16_t absoluteProfileId = (uint16_t)(PTR_TO_UINT(h_Profile)-1);
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
if (FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, absoluteProfileId, FALSE))
return ERROR_CODE(E_BUSY);
/* first read scheme and check that it is valid */
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildReadPlcrActionReg(absoluteProfileId);
p_HcFrame->extraReg = 0x00008000;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
/* check that profile is valid */
if (!FmPcdPlcrHwProfileIsValid(p_HcFrame->hcSpecificData.profileRegs.fmpl_pemode))
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MAJOR, E_ALREADY_EXISTS, ("Policer is already used"));
}
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildWritePlcrActionReg(absoluteProfileId);
p_HcFrame->actionReg |= FmPcdPlcrBuildCounterProfileReg(counter);
p_HcFrame->extraReg = 0x00008000;
p_HcFrame->hcSpecificData.singleRegForWrite = value;
BUILD_FD(SIZE_OF_HC_FRAME_PROFILE_CNT);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
return E_OK;
}
uint32_t FmHcPcdPlcrGetProfileCounter(t_Handle h_FmHc, t_Handle h_Profile, e_FmPcdPlcrProfileCounters counter)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
uint16_t absoluteProfileId = (uint16_t)(PTR_TO_UINT(h_Profile)-1);
t_Error err = E_OK;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
uint32_t retVal = 0;
SANITY_CHECK_RETURN_VALUE(h_FmHc, E_INVALID_HANDLE,0);
if (FmPcdPlcrProfileTryLock(p_FmHc->h_FmPcd, absoluteProfileId, FALSE))
return 0;
/* first read scheme and check that it is valid */
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
{
REPORT_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
return 0;
}
memset(p_HcFrame, 0, sizeof(t_HcFrame));
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_PLCR_PRFL);
p_HcFrame->actionReg = FmPcdPlcrBuildReadPlcrActionReg(absoluteProfileId);
p_HcFrame->extraReg = 0x00008000;
BUILD_FD(SIZE_OF_HC_FRAME_READ_OR_CC_DYNAMIC);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
REPORT_ERROR(MINOR, err, NO_MSG);
XX_FreeSmart(p_HcFrame);
return 0;
}
/* check that profile is valid */
if (!FmPcdPlcrHwProfileIsValid(p_HcFrame->hcSpecificData.profileRegs.fmpl_pemode))
{
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
REPORT_ERROR(MAJOR, E_ALREADY_EXISTS, ("invalid Policer profile"));
return 0;
}
switch (counter)
{
case e_FM_PCD_PLCR_PROFILE_GREEN_PACKET_TOTAL_COUNTER:
retVal = p_HcFrame->hcSpecificData.profileRegs.fmpl_pegpc;
break;
case e_FM_PCD_PLCR_PROFILE_YELLOW_PACKET_TOTAL_COUNTER:
retVal = p_HcFrame->hcSpecificData.profileRegs.fmpl_peypc;
break;
case e_FM_PCD_PLCR_PROFILE_RED_PACKET_TOTAL_COUNTER:
retVal = p_HcFrame->hcSpecificData.profileRegs.fmpl_perpc;
break;
case e_FM_PCD_PLCR_PROFILE_RECOLOURED_YELLOW_PACKET_TOTAL_COUNTER:
retVal = p_HcFrame->hcSpecificData.profileRegs.fmpl_perypc;
break;
case e_FM_PCD_PLCR_PROFILE_RECOLOURED_RED_PACKET_TOTAL_COUNTER:
retVal = p_HcFrame->hcSpecificData.profileRegs.fmpl_perrpc;
break;
default:
REPORT_ERROR(MAJOR, E_INVALID_SELECTION, NO_MSG);
}
FmPcdPlcrReleaseProfileLock(p_FmHc->h_FmPcd, absoluteProfileId);
XX_FreeSmart(p_HcFrame);
return retVal;
}
t_Error FmHcPcdCcModifyTreeNextEngine(t_Handle h_FmHc, t_Handle h_CcTree, uint8_t grpId, uint8_t index, t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
uint32_t intFlags;
t_List h_OldPointersLst, h_NewPointersLst;
t_Handle h_Params;
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
err = FmPcdCcTreeTryLock(h_CcTree);
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
if (err)
return err;
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcModifyNextEngineParamTree(p_FmHc->h_FmPcd, h_CcTree, grpId, index, p_FmPcdCcNextEngineParams,
&h_OldPointersLst, &h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcTreeReleaseLock(h_CcTree);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcTreeReleaseLock(h_CcTree);
return err;
}
t_Error FmHcPcdCcModifyNodeMissNextEngine(t_Handle h_FmHc, t_Handle h_CcNode, t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Handle h_Params;
t_List h_OldPointersLst, h_NewPointersLst;
t_Error err = E_OK;
t_List h_List;
uint32_t intFlags;
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcModifyMissNextEngineParamNode(p_FmHc->h_FmPcd, h_CcNode, p_FmPcdCcNextEngineParams, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return E_OK;
}
t_Error FmHcPcdCcRemoveKey(t_Handle h_FmHc, t_Handle h_CcNode, uint8_t keyIndex)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Handle h_Params;
t_List h_OldPointersLst, h_NewPointersLst;
t_Error err = E_OK;
t_List h_List;
uint32_t intFlags;
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcRemoveKey(p_FmHc->h_FmPcd,h_CcNode,keyIndex, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return err;
}
t_Error FmHcPcdCcAddKey(t_Handle h_FmHc, t_Handle h_CcNode, uint8_t keyIndex, uint8_t keySize, t_FmPcdCcKeyParams *p_KeyParams)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Handle h_Params;
t_List h_OldPointersLst, h_NewPointersLst;
t_Error err = E_OK;
t_List h_List;
uint32_t intFlags;
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcAddKey(p_FmHc->h_FmPcd,h_CcNode,keyIndex,keySize, p_KeyParams, &h_OldPointersLst,&h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return err;
}
t_Error FmHcPcdCcModifyKey(t_Handle h_FmHc, t_Handle h_CcNode, uint8_t keyIndex, uint8_t keySize, uint8_t *p_Key, uint8_t *p_Mask)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_List h_OldPointersLst, h_NewPointersLst;
t_Error err = E_OK;
t_List h_List;
uint32_t intFlags;
t_Handle h_Params;
UNUSED(keySize);
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcModifyKey(p_FmHc->h_FmPcd, h_CcNode, keyIndex, keySize, p_Key, p_Mask, &h_OldPointersLst,&h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return err;
}
t_Error FmHcPcdCcModifyNodeNextEngine(t_Handle h_FmHc, t_Handle h_CcNode, uint8_t keyIndex, t_FmPcdCcNextEngineParams *p_FmPcdCcNextEngineParams)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_Error err = E_OK;
t_List h_OldPointersLst, h_NewPointersLst;
t_List h_List;
uint32_t intFlags;
t_Handle h_Params;
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
err = FmPcdCcModiyNextEngineParamNode(p_FmHc->h_FmPcd, h_CcNode, keyIndex, p_FmPcdCcNextEngineParams, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return err;
}
t_Error FmHcPcdCcModifyKeyAndNextEngine(t_Handle h_FmHc, t_Handle h_CcNode, uint8_t keyIndex, uint8_t keySize, t_FmPcdCcKeyParams *p_KeyParams)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_List h_OldPointersLst, h_NewPointersLst;
t_Error err = E_OK;
t_List h_List;
uint32_t intFlags;
t_Handle h_Params;
INIT_LIST(&h_OldPointersLst);
INIT_LIST(&h_NewPointersLst);
INIT_LIST(&h_List);
intFlags = FmPcdLock(p_FmHc->h_FmPcd);
if ((err = FmPcdCcNodeTreeTryLock(p_FmHc->h_FmPcd, h_CcNode, &h_List)) != E_OK)
{
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
return err;
}
FmPcdUnlock(p_FmHc->h_FmPcd, intFlags);
err = FmPcdCcModifyKeyAndNextEngine(p_FmHc->h_FmPcd,h_CcNode,keyIndex,keySize, p_KeyParams, &h_OldPointersLst,&h_NewPointersLst, &h_Params);
if(err)
{
FmPcdCcNodeTreeReleaseLock(&h_List);
RETURN_ERROR(MAJOR, err, NO_MSG);
}
err = HcDynamicChange(p_FmHc, &h_OldPointersLst, &h_NewPointersLst, &h_Params);
FmPcdCcNodeTreeReleaseLock(&h_List);
return err;
}
t_Error FmHcKgWriteSp(t_Handle h_FmHc, uint8_t hardwarePortId, uint32_t spReg, bool add)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
t_Error err = E_OK;
ASSERT_COND(p_FmHc);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
/* first read SP register */
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildReadPortSchemeBindActionReg(hardwarePortId);
p_HcFrame->extraReg = 0xFFFFF800;
BUILD_FD(SIZE_OF_HC_FRAME_PORT_REGS);
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
/* spReg is the first reg, so we can use it both for read and for write */
if(add)
p_HcFrame->hcSpecificData.portRegsForRead.spReg |= spReg;
else
p_HcFrame->hcSpecificData.portRegsForRead.spReg &= ~spReg;
p_HcFrame->actionReg = FmPcdKgBuildWritePortSchemeBindActionReg(hardwarePortId);
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
XX_FreeSmart(p_HcFrame);
return E_OK;
}
t_Error FmHcKgWriteCpp(t_Handle h_FmHc, uint8_t hardwarePortId, uint32_t cppReg)
{
t_FmHc *p_FmHc = (t_FmHc*)h_FmHc;
t_HcFrame *p_HcFrame;
t_DpaaFD fmFd;
t_Error err = E_OK;
ASSERT_COND(p_FmHc);
p_HcFrame = (t_HcFrame *)XX_MallocSmart((sizeof(t_HcFrame) + p_FmHc->padTill16), 0, 16);
if (!p_HcFrame)
RETURN_ERROR(MINOR, E_NO_MEMORY, ("HC Frame obj"));
memset(p_HcFrame, 0, sizeof(t_HcFrame));
/* first read SP register */
p_HcFrame->opcode = (uint32_t)(HC_HCOR_GBL | HC_HCOR_OPCODE_KG_SCM);
p_HcFrame->actionReg = FmPcdKgBuildWritePortClsPlanBindActionReg(hardwarePortId);
p_HcFrame->extraReg = 0xFFFFF800;
p_HcFrame->hcSpecificData.singleRegForWrite = cppReg;
BUILD_FD(sizeof(t_HcFrame));
if ((err = EnQFrm(p_FmHc, &fmFd, &p_HcFrame->commandSequence)) != E_OK)
{
XX_FreeSmart(p_HcFrame);
RETURN_ERROR(MINOR, err, NO_MSG);
}
XX_FreeSmart(p_HcFrame);
return E_OK;
}
| 36.35142 | 174 | 0.660083 |
2274b243b72b0ef841d436da79ef1de04551fab7 | 1,195 | dart | Dart | test/features/home/domain/usecases/get_user_uid_test.dart | tenhobi/game-without-name | 777c4be70d6e9f1392be0645fc92066825b530f1 | [
"MIT"
] | 8 | 2019-10-22T13:02:17.000Z | 2020-01-01T12:39:40.000Z | test/features/home/domain/usecases/get_user_uid_test.dart | tenhobi/game-without-name | 777c4be70d6e9f1392be0645fc92066825b530f1 | [
"MIT"
] | 9 | 2019-10-21T13:23:22.000Z | 2020-01-05T13:31:07.000Z | test/features/home/domain/usecases/get_user_uid_test.dart | tenhobi/totally_not_chernobyl | 777c4be70d6e9f1392be0645fc92066825b530f1 | [
"MIT"
] | null | null | null | import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:totally_not_chernobyl/core/usecases/usecase.dart';
import 'package:totally_not_chernobyl/feature/home/domain/repositories/auth_repository.dart';
import 'package:totally_not_chernobyl/feature/home/domain/usecases/get_user_uid.dart';
class MockAuthRepository extends Mock implements AuthRepository {}
void main() {
GetUserUid usecase;
MockAuthRepository mockAuthRepository;
setUp(() {
mockAuthRepository = MockAuthRepository();
usecase = GetUserUid(mockAuthRepository);
});
final tUid = '123';
final tIs = true;
test(
'should get uid of the user from the repository',
() async {
// arrange
when(mockAuthRepository.isLoggedIn()).thenAnswer((_) async => Right(tIs));
when(mockAuthRepository.getUid()).thenAnswer((_) async => Right(tUid));
// act
final result = await usecase(NoParams());
// assert
expect(result, Right(tUid));
verify(mockAuthRepository.isLoggedIn());
verify(mockAuthRepository.getUid());
verifyNoMoreInteractions(mockAuthRepository);
},
);
}
| 31.447368 | 93 | 0.721339 |
56098fa5a566b5ae358d10c79845076818efde90 | 2,595 | go | Go | pkg/cache/redis.go | tilezen/tapalcatl | e0ed0567cddb2104f2bb1e15684fc2c257046cdd | [
"BSD-3-Clause"
] | 13 | 2018-01-03T09:37:06.000Z | 2021-06-28T10:57:56.000Z | pkg/cache/redis.go | tilezen/tapalcatl | e0ed0567cddb2104f2bb1e15684fc2c257046cdd | [
"BSD-3-Clause"
] | 31 | 2016-12-21T21:39:03.000Z | 2021-06-09T19:23:24.000Z | pkg/cache/redis.go | tilezen/tapalcatl | e0ed0567cddb2104f2bb1e15684fc2c257046cdd | [
"BSD-3-Clause"
] | 3 | 2018-01-31T15:49:14.000Z | 2020-02-18T10:34:31.000Z | package cache
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/tilezen/tapalcatl/pkg/state"
"github.com/tilezen/tapalcatl/pkg/tile"
)
type redisCache struct {
client *redis.Client
}
func (m *redisCache) Get(ctx context.Context, key string) ([]byte, error) {
bytes, err := m.client.Get(ctx, key).Bytes()
if err != nil {
if err == redis.Nil {
// Redis responds with a Nil error if there was a miss.
return nil, nil
}
return nil, err
}
return bytes, nil
}
func (m *redisCache) Set(ctx context.Context, key string, val []byte, ttl time.Duration) error {
err := m.client.Set(ctx, key, val, ttl).Err()
if err != nil {
return fmt.Errorf("error setting to redis: %w", err)
}
return nil
}
func (m *redisCache) GetTile(ctx context.Context, req *state.ParseResult) (*state.VectorTileResponseData, error) {
key := buildVectorTileKey(req)
item, err := m.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("error getting from redis: %w", err)
}
if item == nil {
return nil, nil
}
response, err := unmarshallVectorTileData(item)
if err != nil {
return nil, err
}
return response, nil
}
func (m *redisCache) SetTile(ctx context.Context, req *state.ParseResult, resp *state.VectorTileResponseData, ttl time.Duration) error {
key := buildVectorTileKey(req)
marshalled, err := marshallVectorTileData(resp)
if err != nil {
return fmt.Errorf("error marshalling to redis: %w", err)
}
err = m.Set(ctx, key, marshalled, ttl)
if err != nil {
return fmt.Errorf("error setting to redis: %w", err)
}
return nil
}
func (m *redisCache) GetMetatile(ctx context.Context, req *state.ParseResult, metaCoord tile.TileCoord) (*state.MetatileResponseData, error) {
key := buildMetatileKey(req, metaCoord)
item, err := m.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("error getting from redis: %w", err)
}
if item == nil {
return nil, nil
}
response, err := unmarshallMetatileData(item)
if err != nil {
return nil, err
}
return response, nil
}
func (m *redisCache) SetMetatile(ctx context.Context, req *state.ParseResult, metaCoord tile.TileCoord, resp *state.MetatileResponseData, ttl time.Duration) error {
key := buildMetatileKey(req, metaCoord)
marshalled, err := marshallMetatileData(resp)
if err != nil {
return fmt.Errorf("error marshalling to redis: %w", err)
}
err = m.Set(ctx, key, marshalled, ttl)
if err != nil {
return fmt.Errorf("error setting to redis: %w", err)
}
return nil
}
func NewRedisCache(client *redis.Client) Cache {
return &redisCache{
client: client,
}
}
| 22.179487 | 164 | 0.686705 |
389602788daca0be414f0f18338b4fba6c1d0b1c | 140 | asm | Assembly | libsrc/_DEVELOPMENT/math/float/math32/lm32/c/sdcc/___fssub_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/_DEVELOPMENT/math/float/math32/lm32/c/sdcc/___fssub_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/_DEVELOPMENT/math/float/math32/lm32/c/sdcc/___fssub_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z |
SECTION code_fp_math32
PUBLIC ___fssub_callee
EXTERN cm32_sdcc_fssub_callee
defc ___fssub_callee = cm32_sdcc_fssub_callee
| 20 | 49 | 0.792857 |
90d20b4f8add3703f5cb3ecfdf27458a36925d7a | 3,027 | py | Python | external_system/models.py | Wellheor1/l2 | d980210921c545c68fe9d5522bb693d567995024 | [
"MIT"
] | null | null | null | external_system/models.py | Wellheor1/l2 | d980210921c545c68fe9d5522bb693d567995024 | [
"MIT"
] | null | null | null | external_system/models.py | Wellheor1/l2 | d980210921c545c68fe9d5522bb693d567995024 | [
"MIT"
] | null | null | null | from django.db import models
class FsliRefbookTest(models.Model):
"""
Таблица справочников ФСЛИ: https://nsi.rosminzdrav.ru/#!/refbook/1.2.643.5.1.13.13.11.1080
"""
code_fsli = models.CharField(max_length=20, db_index=True, help_text='Уникальный код ФСЛИ')
code_loinc = models.CharField(max_length=20, help_text='Код LOINC')
title = models.CharField(max_length=1000, db_index=True, help_text='Полное наименование')
english_title = models.CharField(max_length=1000, db_index=True, help_text='Английское наименование')
short_title = models.CharField(max_length=1000, db_index=True, help_text='Краткое наименование')
synonym = models.CharField(max_length=255, help_text='Синоним')
analit = models.CharField(max_length=255, help_text='Аналит')
analit_props = models.CharField(max_length=255, help_text='Свойства аналита')
dimension = models.CharField(max_length=255, help_text='Размерность')
unit = models.CharField(max_length=100, help_text='Единица измерения')
sample = models.CharField(max_length=100, help_text='Образец')
time_characteristic_sample = models.CharField(max_length=100, help_text='Временная характеристика образца')
method_type = models.CharField(max_length=500, help_text='Тип метода')
scale_type = models.CharField(max_length=100, help_text='Тип шкалы измерения')
actual = models.CharField(max_length=100, help_text='Статус')
active = models.BooleanField(default=True, help_text='Единица измерения')
test_group = models.CharField(max_length=100, help_text='Группа тестов')
code_nmu = models.CharField(max_length=100, help_text='Код НМУ')
ordering = models.IntegerField(help_text='Порядок сортировки', blank=True, default=None, null=True)
def __str__(self):
return f"{self.code_fsli} – {self.title}"
class InstrumentalResearchRefbook(models.Model):
"""
Таблица справочников: https://nsi.rosminzdrav.ru/#!/refbook/1.2.643.5.1.13.13.11.1471/
"""
code_nsi = models.CharField(default='', max_length=20, db_index=True, help_text='Уникальный код')
title = models.CharField(default='', max_length=1000, db_index=True, help_text='Полное наименование')
method = models.CharField(default='', max_length=300, db_index=True, help_text='Метод')
area = models.CharField(default='', max_length=300, db_index=True, help_text='Область')
localization = models.CharField(default='', max_length=300, db_index=True, help_text='Локализация')
code_nmu = models.CharField(default='', max_length=300, db_index=True, help_text='Код исследования НМУ')
def __str__(self):
return f"{self.code_nsi} – {self.title}-{self.area}-{self.code_nmu}"
class BodySiteRefbook(models.Model):
"""
Область исследования: 1.2.643.2.69.1.1.1.57/
"""
code = models.CharField(max_length=20, db_index=True, help_text='Код')
title = models.CharField(max_length=1000, db_index=True, help_text='Полное наименование')
def __str__(self):
return f"{self.code} – {self.title}"
| 51.305085 | 111 | 0.73406 |
7d6b5c39dac37f967e6952d9e9de295efe07198c | 1,578 | html | HTML | index.html | ralexstokes/eth2-fork-mon | 192d37e9a3e3c380f511a79ef3ab8aac6fcda27f | [
"MIT"
] | 9 | 2020-10-16T21:38:56.000Z | 2022-01-20T08:55:38.000Z | index.html | ralexstokes/eth2-fork-mon | 192d37e9a3e3c380f511a79ef3ab8aac6fcda27f | [
"MIT"
] | 2 | 2021-05-12T22:15:40.000Z | 2021-05-12T22:27:32.000Z | index.html | ralexstokes/eth2-fork-mon | 192d37e9a3e3c380f511a79ef3ab8aac6fcda27f | [
"MIT"
] | 3 | 2021-01-06T00:17:12.000Z | 2021-05-03T20:25:26.000Z | <!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href=
"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity=
"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous" type="text/css">
<link rel="stylesheet" href="style.css" type="text/css">
<title>eth2-fork-mon</title>
</head>
<body>
<div id="root">
<div class="container-fluid">
<div class="row my-2">
<div class="col"></div>
<div class="col-10">
<h3>loading...</h3>
</div>
<div class="col"></div>
</div>
</div>
</div><script src=
"https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity=
"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous" type="text/javascript">
</script><script src=
"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous" type="text/javascript">
</script><script src="/cljs-out/prod-main.js" type=
"text/javascript">
</script>
</body>
</html>
| 33.574468 | 103 | 0.574144 |
fb511da915a41399e1f89e4fea45b4baffa6d40b | 989 | java | Java | src/test/java/DatabaseRule.java | AdamCraig/recipe-box | 7bec6d2639f071e0cdf01b61c1b612b74e29ce8a | [
"MIT",
"Unlicense"
] | null | null | null | src/test/java/DatabaseRule.java | AdamCraig/recipe-box | 7bec6d2639f071e0cdf01b61c1b612b74e29ce8a | [
"MIT",
"Unlicense"
] | null | null | null | src/test/java/DatabaseRule.java | AdamCraig/recipe-box | 7bec6d2639f071e0cdf01b61c1b612b74e29ce8a | [
"MIT",
"Unlicense"
] | null | null | null | import org.junit.rules.ExternalResource;
import org.sql2o.*;
public class DatabaseRule extends ExternalResource {
@Override
protected void before() {
DB.sql2o = new Sql2o("jdbc:postgresql://localhost:5432/cooking_test", null, null);
}
@Override
protected void after() {
try(Connection con = DB.sql2o.open()) {
String deleteIngredientsQuery = "DELETE FROM ingredients *;";
String deleteRecipesQuery = "DELETE FROM recipes *;";
String deleteIngredientsRecipesQuery = "DELETE FROM ingredients_recipes *;";
String deleteTagsQuery = "DELETE FROM tags *;";
String deleteRecipesTagsQuery = "DELETE FROM recipes_tags *;";
con.createQuery(deleteIngredientsQuery).executeUpdate();
con.createQuery(deleteRecipesQuery).executeUpdate();
con.createQuery(deleteIngredientsRecipesQuery).executeUpdate();
con.createQuery(deleteTagsQuery).executeUpdate();
con.createQuery(deleteRecipesTagsQuery).executeUpdate();
}
}
}
| 35.321429 | 86 | 0.724975 |
f422140e868bfe55810fd19f63d4e9f0a47866a9 | 8,543 | sql | SQL | public/sql/hotelspa3.sql | orobles95/Hotel-Spa | 2ebe191a885c674ff95a0b4f071427fa530df413 | [
"MIT"
] | null | null | null | public/sql/hotelspa3.sql | orobles95/Hotel-Spa | 2ebe191a885c674ff95a0b4f071427fa530df413 | [
"MIT"
] | 1 | 2021-01-06T02:42:54.000Z | 2021-01-06T02:42:54.000Z | public/sql/hotelspa3.sql | orobles95/Hotel-Spa | 2ebe191a885c674ff95a0b4f071427fa530df413 | [
"MIT"
] | 1 | 2021-05-22T17:31:22.000Z | 2021-05-22T17:31:22.000Z | -- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 28-05-2018 a las 21:35:51
-- Versión del servidor: 10.1.30-MariaDB
-- Versión de PHP: 7.2.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `hotelspa`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `admins`
--
------------------------------------------------
--
-- Estructura de tabla para la tabla `migrations`
--
-- Volcado de datos para la tabla `migrations`
--
-------------------------------------------
--
-- Estructura de tabla para la tabla `password_resets`
--
-----------------------------------------------------
--
-- Estructura de tabla para la tabla `reservas`
--
CREATE TABLE `reservas` (
`id` int(10) UNSIGNED NOT NULL,
`room` varchar(50) NOT NULL,
`fechaentrada` int(25) NOT NULL,
`fechasalida` int(25) NOT NULL,
`huespedes` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `reservasrestaurants`
--
CREATE TABLE `reservasrestaurants` (
`id` int(10) NOT NULL,
`restaurant` varchar(50) NOT NULL,
`fechaentrada` varchar(25) NOT NULL,
`comensales` int(11) NOT NULL,
`hora` varchar(25) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `reservasrestaurants`
--
INSERT INTO `reservasrestaurants` (`id`, `restaurant`, `fechaentrada`, `comensales`, `hora`, `created_at`, `updated_at`) VALUES
(2, 'Spring Space', '04/05/2018', 0, '13:00', '2018-05-28 16:35:23', '2018-05-28 16:35:23'),
(3, 'Spring Space', '04/05/2018', 0, '15:30', '2018-05-28 16:36:24', '2018-05-28 16:36:24'),
(4, 'Spring Space', '03/05/2018', 1, '22:00', '2018-05-28 16:38:26', '2018-05-28 16:38:26'),
(5, 'Spring Space', '05/05/2018', 2, '13:00', '2018-05-28 16:38:51', '2018-05-28 16:38:51'),
(6, 'Spring Space', 'Selecciona la fecha', 1, '13:00', '2018-05-28 16:45:05', '2018-05-28 16:45:05'),
(7, 'Spring Space', 'Selecciona la fecha', 1, '13:00', '2018-05-28 16:48:15', '2018-05-28 16:48:15'),
(8, 'Spring Space', 'Selecciona la fecha', 1, '13:00', '2018-05-28 16:48:18', '2018-05-28 16:48:18'),
(9, 'Spring Space', 'Selecciona la fecha', 1, '13:00', '2018-05-28 17:14:17', '2018-05-28 17:14:17');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `reservasspas`
--
CREATE TABLE `reservasspas` (
`id` int(10) UNSIGNED NOT NULL,
`spa` varchar(50) NOT NULL,
`fechaentrada` varchar(25) NOT NULL,
`personas` int(11) DEFAULT NULL,
`hora` varchar(25) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `reservasspas`
--
INSERT INTO `reservasspas` (`id`, `spa`, `fechaentrada`, `personas`, `hora`, `created_at`, `updated_at`) VALUES
(1, 'Circuito Termal', '06/05/2018', 1, '13:00', '2018-05-28 17:09:16', '2018-05-28 17:09:16'),
(2, 'Circuito Termal', 'Selecciona la fecha', 1, '13:00', '2018-05-28 17:14:22', '2018-05-28 17:14:22'),
(3, 'Termal Aqua', 'Selecciona la fecha', 1, '13:00', '2018-05-28 17:14:27', '2018-05-28 17:14:27');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `reservastratamientos`
--
CREATE TABLE `reservastratamientos` (
`id` int(10) UNSIGNED NOT NULL,
`tratamiento` varchar(50) NOT NULL,
`fechaentrada` varchar(25) NOT NULL,
`hora` varchar(25) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `reservastratamientos`
--
INSERT INTO `reservastratamientos` (`id`, `tratamiento`, `fechaentrada`, `hora`, `created_at`, `updated_at`) VALUES
(1, 'Drenaje Linfático', '04/05/2018', '13:00', '2018-05-28 17:31:45', '2018-05-28 17:31:45'),
(2, 'Masaje Corporal', 'Selecciona la fecha', '13:00', '2018-05-28 17:33:54', '2018-05-28 17:33:54'),
(3, 'Lifting Facial', 'Selecciona la fecha', '13:00', '2018-05-28 17:33:59', '2018-05-28 17:33:59');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `restaurants`
--
CREATE TABLE `restaurants` (
`id` varchar(15) NOT NULL,
`nom` varchar(50) NOT NULL,
`img` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `restaurants`
--
INSERT INTO `restaurants` (`id`, `nom`, `img`) VALUES
('0', 'Spring Space', ''),
('1', 'Delicias Supremas', ''),
('2', 'Media Luna', ''),
('3', 'Sunset Chill Out', '');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `rooms`
--
CREATE TABLE `rooms` (
`id` varchar(15) NOT NULL,
`nom` varchar(50) NOT NULL,
`img` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `rooms`
--
INSERT INTO `rooms` (`id`, `nom`, `img`) VALUES
('0', 'Suite Presidencial', 'suitePresidencial.jpg'),
('1', 'Suite Superior', 'suiteSuperior.jpg'),
('2', 'Suite Estándar', 'SuiteStandar.jpg'),
('3', 'Habitación Superior', 'habitacionSuperior.jpg'),
('4', 'Habitación Estándar', 'habitacionStandar.jpg');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `spas`
--
CREATE TABLE `spas` (
`id` varchar(15) NOT NULL,
`nom` varchar(50) NOT NULL,
`img` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `spas`
--
INSERT INTO `spas` (`id`, `nom`, `img`) VALUES
('0', 'Circuito Termal', ''),
('1', 'Termal Aqua', ''),
('2', 'Divinium', '');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tratamientos`
--
CREATE TABLE `tratamientos` (
`id` varchar(15) NOT NULL,
`nom` varchar(50) NOT NULL,
`img` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `tratamientos`
--
INSERT INTO `tratamientos` (`id`, `nom`, `img`) VALUES
('0', 'Masaje Corporal', ''),
('1', 'Lifting Facial', ''),
('2', 'Drenaje Linfático', ''),
('3', 'Terapia geotermal', '');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `reservas`
--
ALTER TABLE `reservas`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `reservasrestaurants`
--
ALTER TABLE `reservasrestaurants`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `reservasspas`
--
ALTER TABLE `reservasspas`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `reservastratamientos`
--
ALTER TABLE `reservastratamientos`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `restaurants`
--
ALTER TABLE `restaurants`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `rooms`
--
ALTER TABLE `rooms`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `spas`
--
ALTER TABLE `spas`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `tratamientos`
--
ALTER TABLE `tratamientos`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `reservas`
--
ALTER TABLE `reservas`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=66;
--
-- AUTO_INCREMENT de la tabla `reservasrestaurants`
--
ALTER TABLE `reservasrestaurants`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT de la tabla `reservasspas`
--
ALTER TABLE `reservasspas`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `reservastratamientos`
--
ALTER TABLE `reservastratamientos`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 27.120635 | 127 | 0.618986 |
1e67f13e459b7fce75be9062087fdf4c689c03b6 | 7,245 | sql | SQL | resources/sql/app_db.sql | Marcelo-Kawamura/VestibulApp_API | 82fddee448c4a88bcd2e35045592fd5df691cb2b | [
"MIT"
] | null | null | null | resources/sql/app_db.sql | Marcelo-Kawamura/VestibulApp_API | 82fddee448c4a88bcd2e35045592fd5df691cb2b | [
"MIT"
] | null | null | null | resources/sql/app_db.sql | Marcelo-Kawamura/VestibulApp_API | 82fddee448c4a88bcd2e35045592fd5df691cb2b | [
"MIT"
] | null | null | null | -- MySQL Script generated by MySQL Workbench
-- Tue Dec 26 19:56:30 2017
-- 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 mydb
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `mydb` ;
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`user_student`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`user_student` ;
CREATE TABLE IF NOT EXISTS `mydb`.`user_student` (
`student_id` INT NOT NULL,
`student_cpf` VARCHAR(45) NULL,
`student_name` VARCHAR(45) NULL,
`student_last_name` VARCHAR(45) NULL,
`student_email` VARCHAR(45) NULL,
`student_password` VARCHAR(32) NULL,
PRIMARY KEY (`student_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`plan`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`plan` ;
CREATE TABLE IF NOT EXISTS `mydb`.`plan` (
`plan_id` INT NOT NULL,
`plan_price` FLOAT NOT NULL,
`plan_name` VARCHAR(45) NOT NULL,
`plan_duration` INT NOT NULL,
`plan_description` VARCHAR(100) NULL,
PRIMARY KEY (`plan_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`payment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`payment` ;
CREATE TABLE IF NOT EXISTS `mydb`.`payment` (
`payment_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`payment_datetime` DATETIME NOT NULL,
`payment_value` FLOAT NOT NULL,
`payment_discount` FLOAT NULL,
`payment_description` VARCHAR(100) NULL,
`user_student_student_id` INT NOT NULL,
`plan_plan_id` INT NOT NULL,
PRIMARY KEY (`payment_id`),
UNIQUE INDEX `payment_id_UNIQUE` (`payment_id` ASC),
INDEX `fk_payment_user_student_idx` (`user_student_student_id` ASC),
INDEX `fk_payment_plan1_idx` (`plan_plan_id` ASC),
CONSTRAINT `fk_payment_user_student`
FOREIGN KEY (`user_student_student_id`)
REFERENCES `mydb`.`user_student` (`student_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_payment_plan1`
FOREIGN KEY (`plan_plan_id`)
REFERENCES `mydb`.`plan` (`plan_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`problem_topic`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`problem_topic` ;
CREATE TABLE IF NOT EXISTS `mydb`.`problem_topic` (
`topic_id` INT NOT NULL,
`topic_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`topic_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`problem`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`problem` ;
CREATE TABLE IF NOT EXISTS `mydb`.`problem` (
`problem_id` INT NOT NULL,
`problem_name` VARCHAR(45) NOT NULL,
`problem_topic_topic_id` INT NOT NULL,
`problem_type` INT NOT NULL,
`problem_type_id` INT NOT NULL,
PRIMARY KEY (`problem_id`),
INDEX `fk_problem_problem_topic1_idx` (`problem_topic_topic_id` ASC),
CONSTRAINT `fk_problem_problem_topic1`
FOREIGN KEY (`problem_topic_topic_id`)
REFERENCES `mydb`.`problem_topic` (`topic_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`dependency_set`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`dependency_set` ;
CREATE TABLE IF NOT EXISTS `mydb`.`dependency_set` (
`dependency_id` INT NOT NULL,
`dependency_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`dependency_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`map_problem_dependency`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`map_problem_dependency` ;
CREATE TABLE IF NOT EXISTS `mydb`.`map_problem_dependency` (
`map_description` VARCHAR(100) NULL,
`dependency_set_dependency_id` INT NOT NULL,
`problem_problem_id` INT NOT NULL,
PRIMARY KEY (`dependency_set_dependency_id`, `problem_problem_id`),
INDEX `fk_map_problem_dependency_problem1_idx` (`problem_problem_id` ASC),
CONSTRAINT `fk_map_problem_dependency_dependency_set1`
FOREIGN KEY (`dependency_set_dependency_id`)
REFERENCES `mydb`.`dependency_set` (`dependency_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_map_problem_dependency_problem1`
FOREIGN KEY (`problem_problem_id`)
REFERENCES `mydb`.`problem` (`problem_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`user_manager`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`user_manager` ;
CREATE TABLE IF NOT EXISTS `mydb`.`user_manager` (
`manager_id` INT NOT NULL,
`manager_email` VARCHAR(45) NOT NULL,
`manager_password` VARCHAR(32) NOT NULL,
PRIMARY KEY (`manager_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`maintenance`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`maintenance` ;
CREATE TABLE IF NOT EXISTS `mydb`.`maintenance` (
`maintenance_id` INT NOT NULL,
`maintenance_description` VARCHAR(100) NULL,
`user_manager_manager_id` INT NOT NULL,
`maintenance_datetime` DATETIME NULL,
PRIMARY KEY (`maintenance_id`),
INDEX `fk_maintenance_user_manager1_idx` (`user_manager_manager_id` ASC),
CONSTRAINT `fk_maintenance_user_manager1`
FOREIGN KEY (`user_manager_manager_id`)
REFERENCES `mydb`.`user_manager` (`manager_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`student_problem`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`student_problem` ;
CREATE TABLE IF NOT EXISTS `mydb`.`student_problem` (
`student_problem_state` INT NULL,
`user_student_student_id` INT NOT NULL,
`problem_problem_id` INT NOT NULL,
PRIMARY KEY (`user_student_student_id`, `problem_problem_id`),
INDEX `fk_student_problem_problem1_idx` (`problem_problem_id` ASC),
CONSTRAINT `fk_student_problem_user_student1`
FOREIGN KEY (`user_student_student_id`)
REFERENCES `mydb`.`user_student` (`student_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_student_problem_problem1`
FOREIGN KEY (`problem_problem_id`)
REFERENCES `mydb`.`problem` (`problem_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| 34.336493 | 76 | 0.598482 |
4761fbe46c7518abd2391c032272fc70d00f377b | 8,082 | ps1 | PowerShell | Module/Public/Common/Start-SilentProcess.ps1 | Brownserve-UK/Brownserve.PSTools | 3ee430aa2029fb1d2d8f656a20c3b98c983b3e52 | [
"MIT"
] | null | null | null | Module/Public/Common/Start-SilentProcess.ps1 | Brownserve-UK/Brownserve.PSTools | 3ee430aa2029fb1d2d8f656a20c3b98c983b3e52 | [
"MIT"
] | 11 | 2021-10-04T22:32:07.000Z | 2021-12-07T10:22:36.000Z | Module/Public/Common/Start-SilentProcess.ps1 | Brownserve-UK/Brownserve.PSTools | 3ee430aa2029fb1d2d8f656a20c3b98c983b3e52 | [
"MIT"
] | null | null | null | function Start-SilentProcess
{
[CmdletBinding()]
param
(
# The path to the command to be run
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[Alias("PSPath")]
[ValidateNotNullOrEmpty()]
[string]
$FilePath,
# An optional list of arguments to be passed to it
[Parameter(
Mandatory = $false,
Position = 1,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[Alias("Arguments")]
[array]
$ArgumentList,
# If set will set the working directory for the called command
[Parameter(
Mandatory = $false,
Position = 2,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[ValidateNotNullOrEmpty()]
[string]
$WorkingDirectory,
# The exit codes expected from this process when it has been successful
[Parameter(
Mandatory = $false
)]
[array]
$ExitCodes = @(0),
# The path to where the redirected output should be stored
# Defaults to the contents of the environment variable 'RepoLogDirectory' if available
# If that isn't set then defaults to a temp directory
[Parameter(
Mandatory = $false
)]
[ValidateNotNullOrEmpty()]
[string]
$RedirectOutputPath,
# The prefix to use on the redirected streams, defaults to the command run time
[Parameter(
Mandatory = $false
)]
[ValidateNotNullOrEmpty()]
[string]
$RedirectOutputPrefix,
# The suffix for the redirected streams (defaults to log)
[Parameter(
Mandatory = $false
)]
[ValidateNotNullOrEmpty()]
[string]
$RedirectOutputSuffix = "log",
# By default this won't return any output from the called command
# however if this param is set then the result of stdout is returned as an object at the end along with the locations of the stdout and stderr files
# This can be useful if you need the output from the command or when debugging
[Parameter(
Mandatory = $false
)]
[switch]
$PassThru
)
Write-Warning "This command is deprecated and will be removed in a future release, please use 'Invoke-NativeCommand' instead"
# Start off by ensuring we can find the command and then get it's full path.
# This is useful when using things like Set-Alias as the Start-Process command won't have access to these
# So instead we can pass in the full path to the command
Write-Verbose "Finding absolute path to command $FilePath"
try
{
$AbsoluteCommandPath = (Get-Command $FilePath -ErrorAction Stop).Definition
}
catch
{
throw "Could not find command $FilePath.`n$($_.Exception.Message)"
}
# Set redirected output to the repos log directory if it exists, otherwise to temp
if (!$RedirectOutputPath)
{
if ($global:RepoLogDirectory)
{
$RedirectOutputPath = $global:RepoLogDirectory
}
else
{
# Determine our temp directory depending on flavour of PowerShell
if ($PSVersionTable.PSEdition -eq 'Desktop')
{
$RedirectOutputPath = $env:TEMP
}
else
{
$RedirectOutputPath = (Get-PSDrive Temp).Root
}
}
}
# Check the redirect stream path is valid
try
{
$RedirectOutputPathCheck = Get-Item $RedirectOutputPath -Force
}
catch
{
throw "$RedirectOutputPath does not appear to be a valid directory."
}
if (!$RedirectOutputPathCheck.PSIsContainer)
{
throw "$RedirectOutputPath must be a directory"
}
Write-Verbose "Redirecting output to: $RedirectOutputPath"
# If we don't have a redirect output prefix then create one
if (-not $RedirectOutputPrefix)
{
# See if the value in $FilePath is a path or just a command name.
# If it's a path we don't want to use that as a prefix for our redirected output files as it could be stupidly long
# If it's a command name then we can just straight up use that as our redirect name
try
{
$isPath = Resolve-Path $FilePath -ErrorAction Stop
}
catch
{
$RedirectOutputPrefix = $FilePath
}
# We've got a path, do some work to extract just the name of the program from the file path
if ($isPath)
{
try
{
$RedirectOutputPrefix = $isPath | Get-Item | Select-Object -ExpandProperty Name -ErrorAction Stop
}
catch
{
# Don't throw, we'll still get a valid filename below anyways it'll just be missing a prefix
Write-Warning "Failed to auto-generate RedirectOutputPrefix"
}
}
}
# Define our redirected stream names
$StdOutFileName = "$($RedirectOutputPrefix)_$(Get-Date -Format yyMMddhhmm)_stdout.$($RedirectOutputSuffix)"
$StdErrFileName = "$($RedirectOutputPrefix)_$(Get-Date -Format yyMMddhhmm)_stderr.$($RedirectOutputSuffix)"
# Set the paths
$StdOutFilePath = Join-Path $RedirectOutputPath -ChildPath $StdOutFileName
$StdErrFilePath = Join-Path $RedirectOutputPath -ChildPath $StdErrFileName
# Set the default calling params
$ProcessParams = @{
FilePath = $AbsoluteCommandPath
RedirectStandardError = $StdErrFilePath
RedirectStandardOutput = $StdOutFilePath
PassThru = $true
NoNewWindow = $true
Wait = $true
}
# Add optional params if we have them
if ($ArgumentList)
{
$ProcessParams.Add('ArgumentList', $ArgumentList)
}
if ($WorkingDirectory)
{
$ProcessParams.Add('WorkingDirectory', $WorkingDirectory)
}
# Run the process
# We've changed these writes to use the debug stream instead,
# this way we can still capture this information when we want to debug a command but we avoid polluting the
# verbose stream which is used in a lot of our builds.
# This should fix #7 and stop us leaking passwords and such in our builds 😬
Write-Debug "Calling '$AbsoluteCommandPath' with arguments: '$($ArgumentList -join ' ')'"
Write-Debug "Valid exit codes: $($ExitCodes -join ', ')"
try
{
$Process = Start-Process @ProcessParams
}
catch
{
# If we get a failure at this stage we won't have any stderr to grab so just return our exception
throw $_.Exception.Message
}
# Check the exit code is expected, if not grab the contents of stderr (if we can) and return it
if ($Process.ExitCode -notin $ExitCodes)
{
$ErrorContent = Get-Content $StdErrFilePath -Raw -ErrorAction SilentlyContinue
# Write-Error is preferable to 'throw' as it gives much cleaner output, it also allows more control over how errors are handled
Write-Error "$FilePath has returned a non-zero exit code: $($Process.ExitCode).`n$ErrorContent"
}
# If we've requested the output from this command then return it along with the paths to our StdOut and StdErr files should we need them
if ($PassThru)
{
try
{
$OutputContent = Get-Content $StdOutFilePath
Return [pscustomobject]@{
StdOutFilePath = $StdOutFilePath
StdErrFilePath = $StdErrFilePath
OutputContent = $OutputContent
}
}
catch
{
Write-Error "Unable to get contents of $StdOutFilePath.`n$($_.Exception.Message)"
}
}
} | 34.686695 | 156 | 0.603316 |
17425c1f75bb0a919ed669cb05ab0d889fd86e0a | 279 | html | HTML | hay-core/src/main/resources/pages/v1/root.html | asalimonov/Hay | ecde761cb6feefae06610111d55a5f81be327340 | [
"MIT"
] | 1 | 2017-10-02T18:01:23.000Z | 2017-10-02T18:01:23.000Z | hay-core/src/main/resources/pages/v1/root.html | asalimonov/Hay | ecde761cb6feefae06610111d55a5f81be327340 | [
"MIT"
] | null | null | null | hay-core/src/main/resources/pages/v1/root.html | asalimonov/Hay | ecde761cb6feefae06610111d55a5f81be327340 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Hay library endpoint</title>
</head>
<body>
Hello! You are on the Hay library endpoint page.</br>
<a href="~/v1/about">About</a></br>
<a href="~/v1/health">Health-check endpoint</a>
</body>
</html> | 23.25 | 53 | 0.645161 |
624168718fa927a37963adc3ed2ffb5f665b6f7d | 1,499 | ps1 | PowerShell | src/Blockchain/test/Update-AzBlockchainTransactionNode.Tests.ps1 | mbentancour/azure-powershell | 142042fb26c23663340dbecd460bcd60866f6aca | [
"MIT"
] | 3 | 2021-02-08T06:47:47.000Z | 2021-02-08T09:53:19.000Z | src/Blockchain/test/Update-AzBlockchainTransactionNode.Tests.ps1 | mbentancour/azure-powershell | 142042fb26c23663340dbecd460bcd60866f6aca | [
"MIT"
] | 12 | 2015-02-05T09:42:44.000Z | 2021-04-16T13:19:58.000Z | src/Blockchain/test/Update-AzBlockchainTransactionNode.Tests.ps1 | mbentancour/azure-powershell | 142042fb26c23663340dbecd460bcd60866f6aca | [
"MIT"
] | 4 | 2015-08-09T10:30:06.000Z | 2019-12-12T10:33:41.000Z | $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1'
if (-Not (Test-Path -Path $loadEnvPath)) {
$loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1'
}
. ($loadEnvPath)
$TestRecordingFile = Join-Path $PSScriptRoot 'Update-AzBlockchainTransactionNode.Recording.json'
$currentPath = $PSScriptRoot
while(-not $mockingPath) {
$mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File
$currentPath = Split-Path -Path $currentPath -Parent
}
. ($mockingPath | Select-Object -First 1).FullName
Describe 'Update-AzBlockchainTransactionNode' {
$passwd2 = 'strongMemberAccountPassword@2' | ConvertTo-SecureString -AsPlainText -Force
$passwd3 = 'strongMemberAccountPassword@3' | ConvertTo-SecureString -AsPlainText -Force
It 'UpdateExpanded' {
{ Update-AzBlockchainTransactionNode -BlockchainMemberName $env.blockchainMember -Name $env.blockchainTransactionNode -ResourceGroupName $env.resourceGroup -Password $passwd2 } | Should -Not -Throw
}
It 'UpdateViaIdentityExpanded' {
#$PSDefaultParameterValues["Disabled"] = $True
{
$tNode = Get-AzBlockchainTransactionNode -BlockchainMemberName $env.blockchainMember -ResourceGroupName $env.resourceGroup -Name $env.blockchainTransactionNode
Update-AzBlockchainTransactionNode -InputObject $tNode -Password $passwd3
} | Should -Not -Throw
#$PSDefaultParameterValues["Disabled"] = $False
}
}
| 48.354839 | 206 | 0.724483 |
e927b59f7569c44bd99a86b9bd1124f4b2a01bfb | 76 | rb | Ruby | book-code/15-using-test-doubles-effectively/12/api_request_tracker/lib/metrics_reporter.rb | buithehoa/rspec-3-book | 3f07d77683689e25d946d3d634e459fab4269c02 | [
"MIT"
] | 1 | 2018-07-29T06:38:49.000Z | 2018-07-29T06:38:49.000Z | book-code/15-using-test-doubles-effectively/12/api_request_tracker/lib/metrics_reporter.rb | buithehoa/rspec-3-book | 3f07d77683689e25d946d3d634e459fab4269c02 | [
"MIT"
] | null | null | null | book-code/15-using-test-doubles-effectively/12/api_request_tracker/lib/metrics_reporter.rb | buithehoa/rspec-3-book | 3f07d77683689e25d946d3d634e459fab4269c02 | [
"MIT"
] | null | null | null | class MetricsReporter
def self.increment(metric_name)
# ...
end
end
| 12.666667 | 33 | 0.697368 |
86525b6b419de3faee6ef5e9a8dca62daa6e8680 | 4,115 | rs | Rust | rafx-plugins/src/pipelines/basic/graph_generator/bloom_blur_pass.rs | StratusFearMe21/rafx-sdl2 | c824afd933ad31dad9d1023095661790de3653c8 | [
"Apache-2.0",
"MIT"
] | 346 | 2020-11-30T20:52:26.000Z | 2022-03-29T03:24:53.000Z | rafx-plugins/src/pipelines/basic/graph_generator/bloom_blur_pass.rs | StratusFearMe21/rafx-sdl2 | c824afd933ad31dad9d1023095661790de3653c8 | [
"Apache-2.0",
"MIT"
] | 86 | 2020-12-05T03:34:50.000Z | 2022-02-12T05:02:41.000Z | rafx-plugins/src/pipelines/basic/graph_generator/bloom_blur_pass.rs | StratusFearMe21/rafx-sdl2 | c824afd933ad31dad9d1023095661790de3653c8 | [
"Apache-2.0",
"MIT"
] | 20 | 2020-12-08T10:02:43.000Z | 2022-03-12T02:25:12.000Z | use crate::phases::PostProcessRenderPhase;
use rafx::framework::{MaterialPassResource, ResourceArc};
use rafx::graph::*;
use rafx::render_features::RenderPhase;
use super::RenderGraphContext;
use super::EMPTY_VERTEX_LAYOUT;
use crate::shaders;
use rafx::api::RafxSampleCount;
#[derive(PartialEq)]
pub(super) enum BlurDirection {
Horizontal,
Vertical,
}
pub(super) struct BloomBlurPass {
pub(super) color: RenderGraphImageUsageId,
}
pub(super) fn bloom_blur_pass(
context: &mut RenderGraphContext,
bloom_blur_material_pass: ResourceArc<MaterialPassResource>,
bloom_extract_pass: &super::BloomExtractPass,
) -> BloomBlurPass {
let mut blur_src = bloom_extract_pass.hdr_image;
for _ in 0..context.graph_config.blur_pass_count {
blur_src = bloom_blur_internal_pass(
context,
&bloom_blur_material_pass,
blur_src,
BlurDirection::Vertical,
);
blur_src = bloom_blur_internal_pass(
context,
&bloom_blur_material_pass,
blur_src,
BlurDirection::Horizontal,
);
}
return BloomBlurPass { color: blur_src };
}
fn bloom_blur_internal_pass(
context: &mut RenderGraphContext,
bloom_blur_material_pass: &ResourceArc<MaterialPassResource>,
blur_src: RenderGraphImageUsageId,
blur_direction: BlurDirection,
) -> RenderGraphImageUsageId {
let node = context
.graph
.add_node("BloomBlur", RenderGraphQueue::DefaultGraphics);
let blur_dst = context.graph.create_color_attachment(
node,
0,
Some(Default::default()),
RenderGraphImageConstraint {
samples: Some(RafxSampleCount::SampleCount1),
format: Some(context.graph_config.color_format),
..Default::default()
},
Default::default(),
);
context.graph.set_image_name(blur_dst, "blur_dst");
let sample_image =
context
.graph
.sample_image(node, blur_src, Default::default(), Default::default());
context.graph.set_image_name(blur_src, "blur_src");
let bloom_blur_material_pass = bloom_blur_material_pass.clone();
context.graph.set_renderpass_callback(node, move |args| {
// Get the color image from before
let sample_image = args.graph_context.image_view(sample_image);
// Get the pipeline
let pipeline = args
.graph_context
.resource_context()
.graphics_pipeline_cache()
.get_or_create_graphics_pipeline(
PostProcessRenderPhase::render_phase_index(),
&bloom_blur_material_pass,
&args.render_target_meta,
&EMPTY_VERTEX_LAYOUT,
)?;
let descriptor_set_layouts = &pipeline.get_raw().descriptor_set_layouts;
// Set up a descriptor set pointing at the image so we can sample from it
let mut descriptor_set_allocator = args
.graph_context
.resource_context()
.create_descriptor_set_allocator();
let horizontal = if blur_direction == BlurDirection::Horizontal {
1
} else {
0
};
let bloom_blur_material_dyn_set = descriptor_set_allocator.create_descriptor_set(
&descriptor_set_layouts[shaders::bloom_blur_frag::TEX_DESCRIPTOR_SET_INDEX],
shaders::bloom_blur_frag::DescriptorSet0Args {
tex: sample_image.as_ref().unwrap(),
config: &shaders::bloom_blur_frag::ConfigUniform {
horizontal,
..Default::default()
},
},
)?;
// Explicit flush since we're going to use the descriptors immediately
descriptor_set_allocator.flush_changes()?;
// Draw calls
let command_buffer = &args.command_buffer;
command_buffer.cmd_bind_pipeline(&*pipeline.get_raw().pipeline)?;
bloom_blur_material_dyn_set.bind(command_buffer)?;
command_buffer.cmd_draw(3, 0)?;
Ok(())
});
blur_dst
}
| 31.653846 | 89 | 0.641555 |
6fe9b8e0e6d09532b5e8ba4adc4743045fc5ec41 | 1,199 | psm1 | PowerShell | lib/core/perfcounter/Test-IcingaPerformanceCounterCategory.psm1 | hamangku/sans | d95cea5b18a13504cb17b12f7aa78c9b3bb847da | [
"MIT"
] | 45 | 2019-10-31T16:51:08.000Z | 2022-01-28T13:17:14.000Z | lib/core/perfcounter/Test-IcingaPerformanceCounterCategory.psm1 | hamangku/sans | d95cea5b18a13504cb17b12f7aa78c9b3bb847da | [
"MIT"
] | 210 | 2019-11-05T10:42:10.000Z | 2022-03-31T15:51:23.000Z | lib/core/perfcounter/Test-IcingaPerformanceCounterCategory.psm1 | hamangku/sans | d95cea5b18a13504cb17b12f7aa78c9b3bb847da | [
"MIT"
] | 31 | 2019-11-26T13:50:30.000Z | 2022-03-25T14:53:18.000Z | <#
.SYNOPSIS
Test if a certain Performance Counter category exist on the systems and returns
either true or false depending on the state
.DESCRIPTION
Test if a certain Performance Counter category exist on the systems and returns
either true or false depending on the state
.FUNCTIONALITY
Test if a certain Performance Counter category exist on the systems and returns
either true or false depending on the state
.EXAMPLE
PS>Test-IcingaPerformanceCounterCategory -Category 'Processor';
True
.PARAMETER Category
The name of the category to test for
.INPUTS
System.String
.OUTPUTS
System.Boolean
.LINK
https://github.com/Icinga/icinga-powershell-framework
#>
function Test-IcingaPerformanceCounterCategory()
{
param (
[string]$Category
);
if ([string]::IsNullOrEmpty($Category)) {
return $FALSE;
}
try {
$Counter = New-Object System.Diagnostics.PerformanceCounterCategory($Category);
if ($null -eq $Counter -Or [string]::IsNullOrEmpty($Counter.CategoryType)) {
return $FALSE;
}
} catch {
return $FALSE;
}
return $TRUE;
}
| 25.510638 | 88 | 0.671393 |
bfe559509b88f095c547d816321df370583d83f0 | 3,297 | swift | Swift | com.stakwork.sphinx.desktop/Scenes/Dashboard/Chat/Collection View Items/Groups/GroupRequestCollectionViewItem.swift | stakwork/sphinx-mac | e1f7f643a3195fda8f5b2298b63b5ec434b0ea03 | [
"MIT"
] | null | null | null | com.stakwork.sphinx.desktop/Scenes/Dashboard/Chat/Collection View Items/Groups/GroupRequestCollectionViewItem.swift | stakwork/sphinx-mac | e1f7f643a3195fda8f5b2298b63b5ec434b0ea03 | [
"MIT"
] | 2 | 2022-01-06T18:17:58.000Z | 2022-02-10T01:37:14.000Z | com.stakwork.sphinx.desktop/Scenes/Dashboard/Chat/Collection View Items/Groups/GroupRequestCollectionViewItem.swift | stakwork/sphinx-mac | e1f7f643a3195fda8f5b2298b63b5ec434b0ea03 | [
"MIT"
] | null | null | null | //
// GroupRequestCollectionViewItem.swift
// Sphinx
//
// Created by Tomas Timinskas on 04/08/2020.
// Copyright © 2020 Sphinx. All rights reserved.
//
import Cocoa
class GroupRequestCollectionViewItem: CommonGroupActionCollectionViewItem {
@IBOutlet weak var groupApprovalLabel: NSTextField!
@IBOutlet weak var acceptButtonBox: NSBox!
@IBOutlet weak var acceptButton: NSButton!
@IBOutlet weak var declineButtonBox: NSBox!
@IBOutlet weak var declineButton: NSButton!
static let kRowHeight: CGFloat = 65.0
public enum Button: Int {
case Approve
case Reject
}
var contact: UserContact? = nil
var message: TransactionMessage? = nil
var enabled = true
override func viewDidLoad() {
super.viewDidLoad()
acceptButtonBox.wantsLayer = true
acceptButtonBox.layer?.cornerRadius = acceptButtonBox.frame.size.height / 2
declineButtonBox.wantsLayer = true
declineButtonBox.layer?.cornerRadius = declineButtonBox.frame.size.height / 2
}
override func getCornerRadius() -> CGFloat {
return 8
}
override func configureMessage(message: TransactionMessage) {
let senderId = message.senderId
self.contact = UserContact.getContactWith(id: senderId)
self.message = message
let activeMember = message.chat?.isActiveMember(id: senderId) ?? true
let declined = message.isDeclinedRequest()
let accepted = message.isApprovedRequest()
let pending = !declined && !accepted
setLabel(message: message, declined: declined, accepted: accepted)
self.enabled = !activeMember && pending
acceptButtonBox .alphaValue = declined ? 0.5 : 1.0
acceptButton.alphaValue = declined ? 0.5 : 1.0
declineButtonBox.alphaValue = accepted ? 0.5 : 1.0
declineButton.alphaValue = accepted ? 0.5 : 1.0
}
func setLabel(message: TransactionMessage?, declined: Bool, accepted: Bool) {
groupApprovalLabel.stringValue = message?.getGroupMessageText() ?? ""
let senderNickname = message?.getMessageSenderNickname() ?? "name.unknown".localized
if accepted {
groupApprovalLabel.stringValue = String(format: "admin.request.approved".localized, senderNickname)
} else if declined {
groupApprovalLabel.stringValue = String(format: "admin.request.rejected".localized, senderNickname)
}
}
public static func getRowHeight() -> CGFloat {
return GroupRequestCollectionViewItem.kRowHeight
}
@IBAction func buttonClicked(_ sender: NSButton) {
if !enabled {
return
}
guard let message = self.message else {
return
}
NewMessageBubbleHelper().showLoadingWheel()
switch (sender.tag) {
case Button.Approve.rawValue:
delegate?.shouldApproveMember(requestMessage: message)
break
case Button.Reject.rawValue:
delegate?.shouldRejectMember(requestMessage: message)
break
default:
break
}
enabled = false
}
}
| 30.813084 | 111 | 0.631483 |
1422b023b361ea4dc405a4fc54351b88bc289e20 | 6,645 | swift | Swift | PrebidMobileTests/RenderingTests/Tests/3dPartyWrappers/OpenMeasurement/PBMOpenMeasurementWrapperTest.swift | aclrys/prebid-mobile-ios | 918633be1817a17e46c012fecd7ed7d59446a672 | [
"Apache-2.0"
] | null | null | null | PrebidMobileTests/RenderingTests/Tests/3dPartyWrappers/OpenMeasurement/PBMOpenMeasurementWrapperTest.swift | aclrys/prebid-mobile-ios | 918633be1817a17e46c012fecd7ed7d59446a672 | [
"Apache-2.0"
] | 1 | 2022-01-20T12:41:56.000Z | 2022-01-20T12:41:56.000Z | PrebidMobileTests/RenderingTests/Tests/3dPartyWrappers/OpenMeasurement/PBMOpenMeasurementWrapperTest.swift | aclrys/prebid-mobile-ios | 918633be1817a17e46c012fecd7ed7d59446a672 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import PrebidMobile
let ValidOMPartnerName = "Openx"
let InvalidOMPartnerName = ""
extension PBMOpenMeasurementWrapper {
@objc var partnerName: String? {
return ValidOMPartnerName
}
}
class PBMOpenMeasurementWrapperErrorMock : PBMOpenMeasurementWrapper {
override var partnerName: String? {
return InvalidOMPartnerName
}
}
class PBMOpenMeasurementWrapperTest: XCTestCase {
func testInitialization() {
let measurement = PBMOpenMeasurementWrapper()
XCTAssertNil(measurement.jsLib)
}
func testLocalJSLibWrongBundle() {
let loadJSLibExpectation = expectation(description: "load js lib expectation")
let measurement = PBMOpenMeasurementWrapper()
measurement.initializeJSLib(with: Bundle.main, completion: {
XCTAssertNil(measurement.jsLib)
loadJSLibExpectation.fulfill();
})
waitForExpectations(timeout: 2)
}
func testLocalJSLib() {
let loadJSLibExpectation = expectation(description: "load js lib expectation")
let measurement = PBMOpenMeasurementWrapper()
measurement.initializeJSLib(with: PBMFunctions.bundleForSDK(), completion: {
XCTAssertNotNil(measurement.jsLib)
loadJSLibExpectation.fulfill();
})
waitForExpectations(timeout: 2)
}
func testInjectJSLib() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "test JS";
let html = "<html><\\html>"
guard let htmlWithMeasurementJS = try? measurement.injectJSLib(html) else {
XCTFail()
return
}
XCTAssertNotNil(htmlWithMeasurementJS.range(of: measurement.jsLib!))
}
func testInitWebViewSession() {
let measurement = PBMOpenMeasurementWrapper()
let session = measurement.initializeWebViewSession(WKWebView(), contentUrl: nil)
XCTAssertNotNil(session)
}
func testInitWebViewSessionWithoutCredentials() {
let measurement = PBMOpenMeasurementWrapperErrorMock()
let session = measurement.initializeWebViewSession(WKWebView(), contentUrl: nil)
XCTAssertNil(session)
}
func testInitNativeVideoSession() {
let measurement = PBMOpenMeasurementWrapper()
// No js lib - fail
XCTAssertNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:nil))
measurement.jsLib = ""
// Empty resources - fail
XCTAssertNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:nil))
// Still empty resources - fail
XCTAssertNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:PBMVideoVerificationParameters()))
let verificationParams = PBMVideoVerificationParameters()
verificationParams.verificationResources.add(PBMVideoVerificationResource())
// Still empty resources - fail
XCTAssertNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams))
verificationParams.verificationResources.removeLastObject()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
// Resources fine but js is empty - fail
XCTAssertNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams))
measurement.jsLib = "{}"
XCTAssertNotNil(measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams))
}
func testInitNativeVideoSessionHappyPath() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let verificationParams = PBMVideoVerificationParameters()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
let session = measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams)
XCTAssertNotNil(session)
}
func testInitNativeVideoSessionWithoutCredentials() {
let measurement = PBMOpenMeasurementWrapperErrorMock()
measurement.jsLib = "{}"
let verificationParams = PBMVideoVerificationParameters()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
let session = measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams)
XCTAssertNil(session)
}
func testInitEventTrackerForSessions() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let verificationParams = PBMVideoVerificationParameters()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
let nativeVideoSession = measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams)
XCTAssertNotNil(nativeVideoSession)
XCTAssertNotNil(nativeVideoSession?.eventTracker)
let webViewSession = measurement.initializeWebViewSession(WKWebView(), contentUrl: nil)
XCTAssertNotNil(webViewSession)
XCTAssertNotNil(webViewSession?.eventTracker)
}
}
| 35.918919 | 129 | 0.681114 |
047673ad87837335ef125197c4c041f122d4092d | 3,340 | java | Java | yoti-sdk/src/main/java/com/yoti/mobile/android/sdk/model/Scenario.java | RobertLK/android-sdk-button | b6cd864b1d8ba561695584d7eb6b37e677d8b981 | [
"MIT"
] | 7 | 2018-02-16T12:25:17.000Z | 2021-09-29T09:40:27.000Z | yoti-sdk/src/main/java/com/yoti/mobile/android/sdk/model/Scenario.java | RobertLK/android-sdk-button | b6cd864b1d8ba561695584d7eb6b37e677d8b981 | [
"MIT"
] | 12 | 2018-07-03T14:49:32.000Z | 2022-03-30T15:56:19.000Z | yoti-sdk/src/main/java/com/yoti/mobile/android/sdk/model/Scenario.java | RobertLK/android-sdk-button | b6cd864b1d8ba561695584d7eb6b37e677d8b981 | [
"MIT"
] | 9 | 2018-02-23T15:41:31.000Z | 2021-09-21T10:38:28.000Z | package com.yoti.mobile.android.sdk.model;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import com.yoti.mobile.android.sdk.exceptions.YotiSDKNotValidScenarioException;
/**
* This Object will hold all the necessary attributes to successfully perform a sharing of attributes
* according to what has been defined when you created your application and scenario on the Yoti dashboard.
*/
public class Scenario {
private String useCaseId;
private String clientSDKId;
private String scenarioId;
private String callbackAction;
private String qrCodeUrl;
private String callbackBackendAction;
private String callbackBackendUrl;
public String getUseCaseId() {
return useCaseId;
}
public void setUseCaseId(String useCaseId) {
this.useCaseId = useCaseId;
}
public String getClientSDKId() {
return clientSDKId;
}
public void setClientSDKId(String sdkId) {
this.clientSDKId = sdkId;
}
public String getScenarioId() {
return scenarioId;
}
public void setScenarioId(String scenarioId) {
this.scenarioId = scenarioId;
}
public String getCallbackAction() {
return callbackAction;
}
public void setCallbackAction(String callbackAction) {
this.callbackAction = callbackAction;
}
public void setQrCodeUrl(String qrCodeUrl) {
this.qrCodeUrl = qrCodeUrl;
}
public String getQrCodeUrl() {
return qrCodeUrl;
}
public String getCallbackBackendAction() {
return callbackBackendAction;
}
public void setCallbackBackendAction(String callbackBackendAction) {
this.callbackBackendAction = callbackBackendAction;
}
public String getCallbackBackendUrl() {
return callbackBackendUrl;
}
public void setCallbackBackendUrl(String callbackBackendUrl) {
this.callbackBackendUrl = callbackBackendUrl;
}
public boolean isValid() {
return !TextUtils.isEmpty(this.useCaseId)
&& !TextUtils.isEmpty(this.clientSDKId)
&& !TextUtils.isEmpty(this.scenarioId)
&& !TextUtils.isEmpty(this.callbackAction);
}
public static class Builder {
private final Scenario mScenario;
public Builder() {
this.mScenario = new Scenario();
}
public Builder setUseCaseId(@NonNull String id) throws YotiSDKNotValidScenarioException {
if (TextUtils.isEmpty(id)) {
throw new YotiSDKNotValidScenarioException("Use case id cannot be null");
}
mScenario.setUseCaseId(id);
return this;
}
public Builder setClientSDKId(String id) {
mScenario.setClientSDKId(id);
return this;
}
public Builder setScenarioId(String id) {
mScenario.setScenarioId(id);
return this;
}
public Builder setBackendCallbackAction(String action) {
mScenario.setCallbackBackendAction(action);
return this;
}
public Builder setCallbackAction(String action) {
mScenario.setCallbackAction(action);
return this;
}
public Scenario create() {
return mScenario;
}
}
}
| 25.692308 | 107 | 0.65 |
d41c9e815dbf975710bb171b58414a59af40208b | 173 | sql | SQL | src/main/resources/db/migration/V47__remove_up_down_support.sql | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 6 | 2022-02-09T09:59:08.000Z | 2022-02-16T19:17:39.000Z | src/main/resources/db/migration/V47__remove_up_down_support.sql | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | null | null | null | src/main/resources/db/migration/V47__remove_up_down_support.sql | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T16:03:28.000Z | 2022-02-09T16:03:28.000Z | DROP TABLE down_stream_provisioning_communicator;
DROP TABLE provisioning_audit_log;
ALTER TABLE certificateauthority DROP COLUMN down_stream_provisioning_communicator_id;
| 43.25 | 87 | 0.907514 |
a8035e113623e96e15bb12597fb1d703ed642dc5 | 1,280 | swift | Swift | FreeAPS/Sources/APS/GlucoseManager.swift | masha146/freeaps | b0bceaf7598f2351774aecf14402a695c809a144 | [
"MIT"
] | null | null | null | FreeAPS/Sources/APS/GlucoseManager.swift | masha146/freeaps | b0bceaf7598f2351774aecf14402a695c809a144 | [
"MIT"
] | null | null | null | FreeAPS/Sources/APS/GlucoseManager.swift | masha146/freeaps | b0bceaf7598f2351774aecf14402a695c809a144 | [
"MIT"
] | 1 | 2021-11-06T09:37:30.000Z | 2021-11-06T09:37:30.000Z | import Combine
import Foundation
import SwiftDate
import Swinject
protocol GlucoseManager {}
final class BaseGlucoseManager: GlucoseManager, Injectable {
private let processQueue = DispatchQueue(label: "BaseGlucoseManager.processQueue")
@Injected() var glucoseStogare: GlucoseStorage!
@Injected() var nightscoutManager: NightscoutManager!
@Injected() var apsManager: APSManager!
private var lifetime = Set<AnyCancellable>()
private let timer = DispatchTimer(timeInterval: 10)
init(resolver: Resolver) {
injectServices(resolver)
subscribe()
}
private func subscribe() {
timer.publisher
.receive(on: processQueue)
.flatMap { date -> AnyPublisher<[BloodGlucose], Never> in
guard self.glucoseStogare.syncDate().timeIntervalSince1970 + 4.minutes.timeInterval <= date.timeIntervalSince1970
else {
return Just([]).eraseToAnyPublisher()
}
return self.nightscoutManager.fetchGlucose()
}
.sink { glucose in
if !glucose.isEmpty {
self.apsManager.heartbeatNow()
}
}
.store(in: &lifetime)
timer.resume()
}
}
| 31.219512 | 129 | 0.61875 |
bc01c562a40486b40fbf5c6f8f9fc71f46aea49b | 4,310 | rs | Rust | src/cloud_flight.rs | FlowerAce/hyperx-cloud-flight | 6ae59ea3446a6dba7be9d2f19b8147fd00ec024d | [
"MIT"
] | 8 | 2021-10-29T21:27:08.000Z | 2022-01-31T08:20:33.000Z | src/cloud_flight.rs | FlowerAce/hyperx-cloud-flight | 6ae59ea3446a6dba7be9d2f19b8147fd00ec024d | [
"MIT"
] | 5 | 2021-11-13T19:27:22.000Z | 2022-02-21T16:52:37.000Z | src/cloud_flight.rs | FlowerAce/hyperx-cloud-flight | 6ae59ea3446a6dba7be9d2f19b8147fd00ec024d | [
"MIT"
] | 2 | 2021-12-16T00:16:15.000Z | 2021-12-28T06:46:46.000Z | use hidapi::{HidApi, HidDevice};
use log::{debug, info};
use std::cell::Cell;
const VENDOR_ID: u16 = 0x0951;
const PRODUCT_IDS: [u16; 2] = [0x1723, 0x16c4];
const BATTERY_TRIGGER_PACKET: [u8; 20] = {
let mut buf = [0; 20];
buf[0] = 0x21;
buf[1] = 0xff;
buf[2] = 0x05;
buf
};
fn battery_percent(charge_state: u8, value: u8) -> u8 {
match charge_state {
0x0e => match value {
0..=89 => 10,
90..=119 => 15,
120..=148 => 20,
149..=159 => 25,
160..=169 => 30,
170..=179 => 35,
180..=189 => 40,
190..=199 => 45,
200..=209 => 50,
210..=219 => 55,
220..=239 => 60,
240..=255 => 65,
},
0x0f => match value {
0..=19 => 70,
20..=49 => 75,
50..=69 => 80,
70..=99 => 85,
100..=119 => 90,
120..=129 => 95,
130..=255 => 100,
},
_ => 0,
}
}
pub enum Event {
Battery { value: u8 },
BatteryCharging,
VolumeUp,
VolumeDown,
Muted,
Unmuted,
PowerOff,
PowerOn,
Ignored,
}
pub struct CloudFlight {
device: HidDevice,
pub powered: Cell<bool>,
pub muted: Cell<bool>,
pub charging: Cell<bool>,
pub battery: Cell<u8>,
}
impl CloudFlight {
pub fn new() -> Self {
let api = HidApi::new().unwrap();
let device = PRODUCT_IDS
.iter()
.map(|pid| api.open(VENDOR_ID, *pid))
.filter(|device| device.is_ok())
.map(|device| device.unwrap())
.last();
if device.is_none() {
panic!("Not found any compatible device");
}
CloudFlight {
device: device.unwrap(),
powered: Cell::new(true),
muted: Cell::new(false),
charging: Cell::new(false),
battery: Cell::new(100),
}
}
pub fn read(&self) -> Event {
let mut buf = [0u8; 32];
let bytes = self.device.read_timeout(&mut buf, 500).unwrap();
debug!("Read: {}, {:02x?}", bytes, buf);
match bytes {
2 => {
if buf[0] == 0x64 {
if buf[1] == 0x01 {
self.battery();
self.powered.set(true);
info!("Power on");
return Event::PowerOn;
} else if buf[1] == 0x03 {
self.powered.set(false);
info!("Power off");
return Event::PowerOff;
}
}
if buf[0] == 0x65 {
if buf[1] == 0x04 {
self.muted.set(true);
info!("Muted");
return Event::Muted;
} else {
self.muted.set(false);
info!("Unmuted");
return Event::Unmuted;
}
}
return Event::Ignored;
}
5 => {
if buf[1] == 0x01 {
info!("Volume up");
return Event::VolumeUp;
} else if buf[1] == 0x02 {
info!("Volume down");
return Event::VolumeDown;
}
return Event::Ignored;
}
20 => {
if buf[3] == 0x10 || buf[3] == 0x11 {
info!("Battery charging");
self.charging.set(true);
if buf[4] >= 20 {
return Event::BatteryCharging;
}
return Event::Battery { value: 100 };
}
let b_percent = battery_percent(buf[3], buf[4]);
info!("Battery {}", b_percent);
self.charging.set(false);
self.battery.set(b_percent);
return Event::Battery { value: b_percent };
}
_ => return Event::Ignored,
}
}
pub fn battery(&self) {
self.device.write(&BATTERY_TRIGGER_PACKET).unwrap();
}
}
unsafe impl Sync for CloudFlight {}
| 28.543046 | 69 | 0.403016 |
04f1c3248a6fdf47633fe80ceeff659e5d013b4d | 6,186 | java | Java | packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java | protodevnan0/midnight_frameworks_base | e9fdb38c69ba964ec83bffa5796c6945ae6859ec | [
"Apache-2.0"
] | null | null | null | packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java | protodevnan0/midnight_frameworks_base | e9fdb38c69ba964ec83bffa5796c6945ae6859ec | [
"Apache-2.0"
] | null | null | null | packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java | protodevnan0/midnight_frameworks_base | e9fdb38c69ba964ec83bffa5796c6945ae6859ec | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.systemui.statusbar;
import android.annotation.NonNull;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import androidx.core.graphics.ColorUtils;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.colorextraction.ColorExtractor;
import com.android.internal.colorextraction.drawable.ScrimDrawable;
/**
* A view which can draw a scrim
*/
public class ScrimView extends View {
private final ColorExtractor.GradientColors mColors;
private float mViewAlpha = 1.0f;
private Drawable mDrawable;
private PorterDuffColorFilter mColorFilter;
private int mTintColor;
private Runnable mChangeRunnable;
public ScrimView(Context context) {
this(context, null);
}
public ScrimView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ScrimView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public ScrimView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mDrawable = new ScrimDrawable();
mDrawable.setCallback(this);
mColors = new ColorExtractor.GradientColors();
updateColorWithTint(false);
}
@Override
protected void onDraw(Canvas canvas) {
if (mDrawable.getAlpha() > 0) {
mDrawable.draw(canvas);
}
}
public void setDrawable(Drawable drawable) {
mDrawable = drawable;
mDrawable.setCallback(this);
mDrawable.setBounds(getLeft(), getTop(), getRight(), getBottom());
mDrawable.setAlpha((int) (255 * mViewAlpha));
invalidate();
}
@Override
public void invalidateDrawable(@NonNull Drawable drawable) {
super.invalidateDrawable(drawable);
if (drawable == mDrawable) {
invalidate();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
mDrawable.setBounds(left, top, right, bottom);
invalidate();
}
}
public void setColors(@NonNull ColorExtractor.GradientColors colors) {
setColors(colors, false);
}
public void setColors(@NonNull ColorExtractor.GradientColors colors, boolean animated) {
if (colors == null) {
throw new IllegalArgumentException("Colors cannot be null");
}
if (mColors.equals(colors)) {
return;
}
mColors.set(colors);
updateColorWithTint(animated);
}
@VisibleForTesting
Drawable getDrawable() {
return mDrawable;
}
public ColorExtractor.GradientColors getColors() {
return mColors;
}
public void setTint(int color) {
setTint(color, false);
}
public void setTint(int color, boolean animated) {
if (mTintColor == color) {
return;
}
mTintColor = color;
updateColorWithTint(animated);
}
private void updateColorWithTint(boolean animated) {
if (mDrawable instanceof ScrimDrawable) {
// Optimization to blend colors and avoid a color filter
ScrimDrawable drawable = (ScrimDrawable) mDrawable;
float tintAmount = Color.alpha(mTintColor) / 255f;
int mainTinted = ColorUtils.blendARGB(mColors.getMainColor(), mTintColor,
tintAmount);
drawable.setColor(mainTinted, animated);
} else {
boolean hasAlpha = Color.alpha(mTintColor) != 0;
if (hasAlpha) {
PorterDuff.Mode targetMode = mColorFilter == null ? Mode.SRC_OVER :
mColorFilter.getMode();
if (mColorFilter == null || mColorFilter.getColor() != mTintColor) {
mColorFilter = new PorterDuffColorFilter(mTintColor, targetMode);
}
} else {
mColorFilter = null;
}
mDrawable.setColorFilter(mColorFilter);
mDrawable.invalidateSelf();
}
if (mChangeRunnable != null) {
mChangeRunnable.run();
}
}
public int getTint() {
return mTintColor;
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
/**
* It might look counterintuitive to have another method to set the alpha instead of
* only using {@link #setAlpha(float)}. In this case we're in a hardware layer
* optimizing blend modes, so it makes sense.
*
* @param alpha Gradient alpha from 0 to 1.
*/
public void setViewAlpha(float alpha) {
if (alpha != mViewAlpha) {
mViewAlpha = alpha;
mDrawable.setAlpha((int) (255 * alpha));
if (mChangeRunnable != null) {
mChangeRunnable.run();
}
}
}
public float getViewAlpha() {
return mViewAlpha;
}
public void setChangeRunnable(Runnable changeRunnable) {
mChangeRunnable = changeRunnable;
}
@Override
protected boolean canReceivePointerEvents() {
return false;
}
}
| 30.17561 | 94 | 0.641448 |
5851a7bb3ce6133e681c43d3927e84ef485c975f | 486 | h | C | app/window/PageCategory.h | Rexagon/kanji-tutor | fc33654be500053612741eedd6bf8e22f5ee2a60 | [
"Apache-2.0"
] | null | null | null | app/window/PageCategory.h | Rexagon/kanji-tutor | fc33654be500053612741eedd6bf8e22f5ee2a60 | [
"Apache-2.0"
] | 1 | 2017-05-19T09:16:25.000Z | 2017-05-20T21:05:53.000Z | app/window/PageCategory.h | Rexagon/kanji-tutor | fc33654be500053612741eedd6bf8e22f5ee2a60 | [
"Apache-2.0"
] | null | null | null | #ifndef PAGECATEGORY_H
#define PAGECATEGORY_H
#include "../widgets/LessonListItem.h"
#include "../models/Category.h"
#include "Page.h"
class PageCategory : public Page
{
Q_OBJECT
public:
PageCategory(Ui::MainWindow* ui);
void setCategory(Category* category);
signals:
void backButtonPressed();
void kanjiButtonPressed(Category* category);
void testsButtonPressed(Category* category);
void lessonSelected(LessonListItem* listItem, Lesson* lesson);
};
#endif // PAGECATEGORY_H
| 21.130435 | 63 | 0.773663 |
f6cea845c31c4a5e54744adb2045f1fd82b05614 | 655 | asm | Assembly | programs/oeis/211/A211422.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/211/A211422.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/211/A211422.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A211422: Number of ordered triples (w,x,y) with all terms in {-n,...,0,...,n} and w^2 + x*y = 0.
; 1,9,17,25,41,49,57,65,81,105,113,121,137,145,153,161,193,201,225,233,249,257,265,273,289,329,337,361,377,385,393,401,433,441,449,457,505,513,521,529,545,553,561,569,585,609,617,625,657,713,753,761,777,785,809,817,833,841,849,857,873,881,889,913,977,985,993,1001,1017,1025,1033,1041,1089,1097,1105,1145,1161,1169,1177,1185,1217,1289,1297,1305,1321,1329,1337,1345,1361,1369,1393,1401,1417,1425,1433,1441,1473,1481,1537,1561
lpb $0
sub $0,1
mov $1,$0
div $0,90860
max $1,0
seq $1,120486 ; Partial sums of A000188.
lpe
mul $1,8
add $1,1
mov $0,$1
| 46.785714 | 423 | 0.694656 |
7f0dc7c5570afb87f0bb8b7b8b383de2b0e831e1 | 849 | rs | Rust | src/ast/main.rs | oxur/oxur | db8e9d67076e665987e9aa48fc1af6bd2f67d04b | [
"Apache-2.0"
] | null | null | null | src/ast/main.rs | oxur/oxur | db8e9d67076e665987e9aa48fc1af6bd2f67d04b | [
"Apache-2.0"
] | 14 | 2020-01-11T17:20:54.000Z | 2020-02-12T05:55:22.000Z | src/ast/main.rs | oxur/oxur | db8e9d67076e665987e9aa48fc1af6bd2f67d04b | [
"Apache-2.0"
] | null | null | null | use oxur::ast::dump;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
fn main() {
if let Err(error) = try_main() {
let _ = writeln!(io::stderr(), "{}", error);
process::exit(1);
}
}
fn try_main() -> Result<(), dump::Error> {
let mut args = env::args_os();
let _ = args.next(); // executable name
let filepath = match (args.next(), args.next()) {
(Some(arg), None) => PathBuf::from(arg),
_ => return Err(dump::Error::IncorrectUsage),
};
let code = fs::read_to_string(&filepath).map_err(dump::Error::ReadFile)?;
let syntax = syn::parse_file(&code).map_err({
|error| dump::Error::ParseFile {
error,
filepath,
source_code: code,
}
})?;
println!("{:#?}", syntax);
Ok(())
}
| 23.583333 | 77 | 0.537102 |
4b2eaa5e7e0771c0426c585fcf28cc7337860782 | 3,409 | html | HTML | src/app/shared/components/cn-tree/cn-tree.component.html | sz5t/SmartAutoBusiness-2.0 | 902d85228b3c656bd87d525a706717d807ee31d1 | [
"MIT"
] | null | null | null | src/app/shared/components/cn-tree/cn-tree.component.html | sz5t/SmartAutoBusiness-2.0 | 902d85228b3c656bd87d525a706717d807ee31d1 | [
"MIT"
] | 10 | 2020-02-16T12:00:01.000Z | 2022-02-26T15:47:41.000Z | src/app/shared/components/cn-tree/cn-tree.component.html | sz5t/SmartAutoBusiness-2.0 | 902d85228b3c656bd87d525a706717d807ee31d1 | [
"MIT"
] | 1 | 2020-04-21T11:06:49.000Z | 2020-04-21T11:06:49.000Z | <nz-spin nzTip="loading..." [nzSpinning]="isLoading">
<form *ngIf="config.checkStrictlyShow" checkStrictly nz-form nzLayout="inline">
<nz-form-item>
<nz-form-label><label>无关联勾选</label></nz-form-label>
<nz-form-control><nz-switch [(ngModel)]="this.config['checkStrictly']" name="checkStrictly"></nz-switch></nz-form-control>
</nz-form-item>
</form>
<nz-input-group *ngIf="config.showSearch" [nzSuffix]="suffixIcon" style="width: 100%;">
<input type="text" nz-input placeholder="查询" [(ngModel)]="searchValue" />
</nz-input-group>
<ng-template #suffixIcon>
<i nz-icon nzType="search"></i>
</ng-template>
<nz-tree #treeObj [nzData]="nodes" [nzAsyncData]="config.async" [nzExpandAll]="config.expandAll"
[nzCheckStrictly]="config.checkStrictly" [nzCheckable]="config.showCheckBox" [nzShowLine]="config.showLine"
(nzClick)="clickNode($event)" (nzExpandChange)="expandNode($event)" [nzTreeTemplate]="nzTreeTemplate"
[nzSearchValue]="searchValue" (nzSearchValueChange)="nzEvent($event)" [nzSelectedKeys]="defaultSelectedKeys">
</nz-tree>
<!-- -->
<ng-template #nzTreeTemplate let-node>
<span class="custom-node" [class.active]="ACTIVED_NODE?.key === node.key">
<span
*ngIf="!node.isLeaf">
<i nz-icon style="padding-right: 3px;" [nzType]="node.isExpanded ? 'folder-open' : 'folder'" (click)="openFolder(node)"></i>
<cn-custom-group-state *ngIf="config.enableState" [config]="leftIconState" [(currentValue)]="node"
(updateValue)="iconStateValueChange($event)" ></cn-custom-group-state>
<ng-container *ngIf="node.isMatched">
<span class="file-name"> {{searchTargetString(node.title)[0]}}</span>
<span class="highlight"> {{searchTargetString(node.title)[1]}} </span>
<span class="file-name">{{searchTargetString(node.title)[2]}}</span>
</ng-container>
<ng-container *ngIf="!node.isMatched">
<span class="file-name">{{ node.title }}</span>
</ng-container>
<cn-custom-group-state *ngIf="config.enableState" [config]="rightIconState" [(currentValue)]="node" (updateValue)="iconStateValueChange($event)" ></cn-custom-group-state>
<span class="folder-desc" *ngIf="config.desc">{{ node?.origin[config.desc] }}</span>
</span>
<span *ngIf="node.isLeaf">
<i nz-icon nzType="file" style="padding-right: 3px;"></i>
<cn-custom-group-state *ngIf="config.enableState" [config]="leftIconState" [(currentValue)]="node"
(updateValue)="iconStateValueChange($event)" ></cn-custom-group-state>
<ng-container *ngIf="node.isMatched">
<span class="file-name"> {{searchTargetString(node.title)[0]}}</span>
<span class="highlight"> {{searchTargetString(node.title)[1]}} </span>
<span class="file-name">{{searchTargetString(node.title)[2]}}</span>
</ng-container>
<ng-container *ngIf="!node.isMatched">
<span class="file-name">{{ node.title }}</span>
</ng-container>
<cn-custom-group-state *ngIf="config.enableState" [config]="rightIconState" [(currentValue)]="node"
(updateValue)="iconStateValueChange($event)" ></cn-custom-group-state>
<span class="file-desc" *ngIf="config.desc">{{ node?.origin[config.desc] }}</span>
</span>
</span>
</ng-template>
</nz-spin>
| 52.446154 | 181 | 0.63479 |
b3a445db7d6d0dcb2c32040eaaaa49f604f5a9a2 | 395 | rb | Ruby | lib/csv_db/matches.rb | moniya/ligbot | b53c686e059ab85f86ea62a75a1969033f01eec1 | [
"MIT"
] | 1 | 2015-01-09T20:45:36.000Z | 2015-01-09T20:45:36.000Z | lib/csv_db/matches.rb | moniya/ligbot | b53c686e059ab85f86ea62a75a1969033f01eec1 | [
"MIT"
] | null | null | null | lib/csv_db/matches.rb | moniya/ligbot | b53c686e059ab85f86ea62a75a1969033f01eec1 | [
"MIT"
] | null | null | null | class Matches
def initialize(matches_file_path)
@matches_file_path = matches_file_path
end
def setup
FileUtils.touch @matches_file_path
end
def add match
str = "#{match.team1_id},#{match.team2_id},#{match.team1_goals},#{match.team2_goals}"
File.open(@matches_file_path, "a") { |f| f.puts str }
end
def delete_all
File.write @matches_file_path, ''
end
end
| 19.75 | 89 | 0.698734 |
751303fedb54e00a5695f8e34ee1ce8bd1ad28aa | 193 | asm | Assembly | chapter04/00-Add/Add.asm | TheVainBoy/nand2tetris | fff82a86c39e68698775d238efbd3817cf6e6261 | [
"MIT"
] | 1 | 2016-03-04T18:08:41.000Z | 2016-03-04T18:08:41.000Z | chapter04/00-Add/Add.asm | TheVainBoy/nand2tetris | fff82a86c39e68698775d238efbd3817cf6e6261 | [
"MIT"
] | null | null | null | chapter04/00-Add/Add.asm | TheVainBoy/nand2tetris | fff82a86c39e68698775d238efbd3817cf6e6261 | [
"MIT"
] | null | null | null | @i
M=1
@sum
M=0
(LOOP)
@i
D=M
@100
D=D-A
@END
D;JGT
@i
D=M
@sum
M=D+M
@i
M=M+1
@LOOP
0;JMP
(END)
@END
0;JMP
| 8.041667 | 9 | 0.305699 |
aeb4dd2ee7a5543c7c4e2cb3231e8b02eec99f15 | 494 | dart | Dart | lib/controllers/gamedetailsController.dart | BikashKalita/IgniteFlutter | 527a08cc2a82e7cf7fc1b64f3d40903a0de13e83 | [
"MIT"
] | null | null | null | lib/controllers/gamedetailsController.dart | BikashKalita/IgniteFlutter | 527a08cc2a82e7cf7fc1b64f3d40903a0de13e83 | [
"MIT"
] | null | null | null | lib/controllers/gamedetailsController.dart | BikashKalita/IgniteFlutter | 527a08cc2a82e7cf7fc1b64f3d40903a0de13e83 | [
"MIT"
] | null | null | null | import 'package:get/get.dart';
import 'package:ignitev2/services/api.dart';
import '../models/gameinfo.dart';
class GameDetailsController extends GetxController {
var isLoading = true.obs;
var gameInfo = GameDetailsModel().obs;
Future<void> fetchGameDetails(String slug) async {
try {
isLoading(true);
var info = await ApiService.getGameDetails(slug);
if (info != null) {
gameInfo.value = info;
}
} finally {
isLoading(false);
}
}
}
| 22.454545 | 55 | 0.65587 |
fba776fbf9d26578ba33ab9d2a3121361188df47 | 1,337 | c | C | Game/Source/flesh.c | Acknex/LotterShock | 36863095cc4afaf4f3b96fa6476e272409a7a458 | [
"CC0-1.0"
] | 4 | 2018-07-01T22:04:51.000Z | 2018-07-04T21:20:58.000Z | Game/Source/flesh.c | Acknex/LotterShock | 36863095cc4afaf4f3b96fa6476e272409a7a458 | [
"CC0-1.0"
] | 115 | 2018-06-29T20:54:42.000Z | 2018-08-20T14:35:55.000Z | Game/Source/flesh.c | Acknex/LotterShock | 36863095cc4afaf4f3b96fa6476e272409a7a458 | [
"CC0-1.0"
] | null | null | null | #include "flesh.h"
#include "enemy_hit.h"
#include "splatter.h"
#define FL_SPLATTERCNT skill21
#define FL_ORIGINALROT skill22
#define FL_ORIGINALROT skill23
#define FL_ORIGINALROT skill24
BMAP* FLESH_bmapSplatter[5];
SOUND* FLESH_sndSplatter[3];
action Flesh()
{
framework_setup(my, SUBSYSTEM_FLESH);
ENEMY_HIT_init(me);
}
void FLESH_GlobalInit()
{
FLESH_bmapSplatter[0] = bmap_create("splatter_red_01.png");
FLESH_bmapSplatter[1] = bmap_create("splatter_red_02.png");
FLESH_bmapSplatter[2] = bmap_create("splatter_red_03.png");
FLESH_bmapSplatter[3] = bmap_create("splatter_red_04.png");
FLESH_bmapSplatter[4] = bmap_create("splatter_red_05.png");
FLESH_sndSplatter[0] = snd_create("splat1.ogg");
FLESH_sndSplatter[1] = snd_create("splat2.ogg");
FLESH_sndSplatter[2] = snd_create("splat3.ogg");
int i;
for (i= 0; i < 5; i++)
{
bmap_preload(FLESH_bmapSplatter[i]);
}
}
void FLESH_Update()
{
ENTITY * ptr;
SUBSYSTEM_LOOP(ptr, SUBSYSTEM_FLESH)
{
ptr->FL_SPLATTERCNT = maxv(0, ptr->FL_SPLATTERCNT - time_step);
//abuse enemy hit system
if (ptr->DAMAGE_HIT && ptr->FL_SPLATTERCNT <= 0)
{
ptr->DAMAGE_HIT = 0;
ptr->FL_SPLATTERCNT = 8;
SPLATTER_explode(20, ptr, 800, FLESH_bmapSplatter, 5);
var i = integer(random(3));
ent_playsound2(ptr, FLESH_sndSplatter[i], 10000, 10000);
}
}
}
| 24.309091 | 65 | 0.724009 |
52a0e7679b5f4e8d25a851a64e074e9581d37374 | 6,769 | psm1 | PowerShell | Module/Public/InstallHelpers/Install.Artifacts.Functions.psm1 | derek-baker/AzureDevOpsHelpers | 5369fbb3bd1451ffecda3bbf21c828e96def156a | [
"MIT"
] | null | null | null | Module/Public/InstallHelpers/Install.Artifacts.Functions.psm1 | derek-baker/AzureDevOpsHelpers | 5369fbb3bd1451ffecda3bbf21c828e96def156a | [
"MIT"
] | null | null | null | Module/Public/InstallHelpers/Install.Artifacts.Functions.psm1 | derek-baker/AzureDevOpsHelpers | 5369fbb3bd1451ffecda3bbf21c828e96def156a | [
"MIT"
] | null | null | null | Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop";
#Requires -Version 5.0
# INTENT: Should create a timestamped copy of a dir
function BackUpDir(
[Parameter(mandatory=$true)]
[string] $srcDir,
[Parameter(mandatory=$false)]
[string] $newDirPostfix = "$(Get-Date -f yyyy-MM-dd_hh-mm-ss).BAK"
) {
try {
[string] $dest = "$srcDir.$newDirPostfix"
Move-Item -Path $srcDir -Destination $dest
return "Backed up existing files to $dest."
}
catch {
return 'Destination dir did not exist yet. Skipped backup.'
}
}
# INTENT: Remove artifacts that should not be deployed.
# TODO: Figure out how to make mutually exclusive param sets
# The first and third params should be mandatory on a mutex basis.
function PurgeUnnecessaryFilesFromSource(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $workDir,
[Parameter(mandatory=$true)]
[string[]] $filesToNotInstall
) {
# If we do want to preserve existing settings...
if ($preserveSettings -eq $true) {
Get-ChildItem -Path $workDir -Recurse | Where-Object {
# TODO: This is sketchy. It could be the case that two files of the same name exist...
$filesToNotInstall -contains $_.Name
} | ForEach-Object {
# ...we'll remove files from source to prevent overwriting existing settings files later
Remove-Item -Path $_.FullName -Force
}
return 'Purged unnecessary files before install.'
}
}
function CopyNewFilesIntoDir(
[Parameter(mandatory=$true)]
[string] $distArtifactsParentDir,
[Parameter(mandatory=$true)]
[string] $destDirPath,
[Parameter(mandatory=$false)]
[string] $excludePattern = "*_Install*"
) {
if ( (Test-Path -Path $destDirPath) -eq $false) {
New-Item -ItemType Directory $destDirPath
}
Get-ChildItem -Path $distArtifactsParentDir | `
Where-Object {
$_.Name -notlike $excludePattern
} | `
ForEach-Object {
Copy-Item $_.FullName -Destination "$destDirPath" -Recurse -Force
}
return 'Copied new files.'
}
# WARNING: This code updates <appSettings> values ONLY IF the key (see $appSettingsDict) exists.
function UpdateXmlConfigAppSettings(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $configFilePath,
# EX: @{ ClientSettingsProvider_ServiceUri = $serviceUrl; ClientSettingsProvider_ServicePort = $servicePort }
[Parameter(mandatory=$true)]
[System.Collections.Hashtable] $appSettingsDict
) {
if ($preserveSettings -eq $false) {
# Update other config values
[xml] $webConfig = Get-Content $configFilePath
foreach($key in $appSettingsDict.Keys) {
$node = $webConfig.SelectSingleNode("//appSettings/add[@key = '$key']")
if ($null -ne $node) {
$node.SetAttribute('value', $appSettingsDict[$key])
}
else {
throw "$appSettingsDict[$key] is not a valid key in AppSettings"
}
}
$webConfig.Save($configFilePath)
return "Updated $configFilePath''s AppSettings"
}
return "Skipped updating $configFilePath''s AppSettings"
}
function UpdateXmlConfigAppConnectionStringDataSource(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $configFilePath,
[Parameter(mandatory=$true)]
[string] $dbInstance
) {
if ($preserveSettings -eq $false) {
# Update connection string
$content = Get-Content $configFilePath
# NOTE: Below is a RegEx
$newContent = $content -replace 'data source=.*?;', "data source=$dbInstance;"
Set-Content -Path $configFilePath -Value $newContent
return "Updated connection string data-source in $configFilePath"
}
return "Skipped updating connection string data-source in $configFilePath."
}
function UpdateXmlConfigAppConnectionStringInitialCatalog(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $configFilePath,
[Parameter(mandatory=$true)]
[string] $appName
) {
if ($preserveSettings -eq $false) {
# Update connection string
$content = Get-Content $configFilePath
# NOTE: Below is a RegEx
$newContent = $content -replace 'initial catalog=.*?;', "initial catalog=$appName;"
Set-Content -Path $configFilePath -Value $newContent
return "Updated connection string initial catalog in $configFilePath"
}
return "Skipped updating connection string initial catalog in $configFilePath."
}
function UpdateXmlConfigAppConnectionStringAuthMethod(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $configFilePath,
[Parameter(mandatory=$true)]
[string] $authInfo
) {
if ($preserveSettings -eq $false) {
# Update connection string
$content = Get-Content $configFilePath
# NOTE: Below is a RegEx
$newContent = $content -replace 'Integrated Security=.*?;', $authInfo
Set-Content -Path $configFilePath -Value $newContent
return "Updated connection string initial catalog in $configFilePath"
}
return "Skipped updating connection string initial catalog in $configFilePath."
}
# INTENT: Some scripts used during install should be deleted
function RemoveSensitiveArtifacts(
[Parameter(mandatory=$true)]
[string] $artifactsLocation
) {
$dir = Get-Item $artifactsLocation
$dir | Remove-Item -Recurse -Force
}
# NOTE: You may want $desiredFileContent to have a length greater than 1
function InstallJsonFile(
[Parameter(mandatory=$true)]
[bool] $preserveSettings,
[Parameter(mandatory=$true)]
[string] $filePath,
# EX: @( @{ username = "Administrator" }, @{ username = "FakeEditor" })
[Parameter(mandatory=$true)]
[System.Object[]] $desiredFileContent
) {
if ($preserveSettings -eq $false) {
if ( (Test-Path -Path $filePath) -eq $false) {
New-Item -Type File -Path $filePath -Force
}
$jsonContent = $desiredFileContent | ConvertTo-Json
Set-Content -Path $filePath -Value $jsonContent
return "Installed JSON file at: $filePath"
}
}
Export-ModuleMember -Function "*" | 32.233333 | 114 | 0.631112 |
3c320fb72e3f7d726d5cbb35d21bffc83c991e5b | 2,886 | ps1 | PowerShell | docker/windows-dev/scripts/test.ps1 | mabrarov/build-scripts | 038dffe71e3dc31144917ded4f035137f77df917 | [
"MIT"
] | 28 | 2017-12-26T21:34:10.000Z | 2022-03-31T17:08:45.000Z | docker/windows-dev/scripts/test.ps1 | mabrarov/build-scripts | 038dffe71e3dc31144917ded4f035137f77df917 | [
"MIT"
] | 2 | 2019-08-16T18:09:27.000Z | 2021-01-14T04:47:37.000Z | docker/windows-dev/scripts/test.ps1 | mabrarov/build-scripts | 038dffe71e3dc31144917ded4f035137f77df917 | [
"MIT"
] | 7 | 2020-03-10T19:24:14.000Z | 2022-01-18T09:53:16.000Z | #
# Copyright (c) 2017 Marat Abrarov (abrarov@gmail.com)
#
# Distributed under the MIT License (see accompanying LICENSE)
#
# Stop immediately if any error happens
$ErrorActionPreference = "Stop"
$project_dir = (Get-Item "${PSScriptRoot}").Parent.FullName
$image_repository = "${env:DOCKER_USER}/$(Split-Path "${project_dir}" -Leaf)"
Write-Host "Running Chocolatey package manager in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" choco --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of Chocolatey package manager"
}
Write-Host "Running 7-Zip in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\Program Files\7-Zip\7z.exe" i
if (${LastExitCode} -ne 0) {
throw "Failed to get help from 7-Zip command line utility"
}
Write-Host "Running Git in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" git --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of Git"
}
Write-Host "Running CMake in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\cmake\bin\cmake.exe" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of CMake"
}
Write-Host "Running MSYS2 GNU Make in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\msys64\usr\bin\make" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of MSYS2 GNU Make"
}
Write-Host "Running MSYS2 GNU tar in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\msys64\usr\bin\tar" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of MSYS2 GNU tar"
}
Write-Host "Running MSYS2 GNU patch in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\msys64\usr\bin\patch" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of MSYS2 GNU patch"
}
Write-Host "Running ActivePerl in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\Perl\bin\perl.exe" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of ActivePerl"
}
Write-Host "Running Python 2 in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\Python2\python.exe" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of Python 2"
}
Write-Host "Running Python 3 in container created from ${image_repository}:latest image"
docker run --rm "${image_repository}:latest" "C:\Python3\python.exe" --version
if (${LastExitCode} -ne 0) {
throw "Failed to get version of Python 3"
}
| 40.083333 | 107 | 0.716216 |
f6675ba6d3c565871b5ce480b2374c1374ecf2b2 | 1,546 | sql | SQL | db_ngaji.sql | langpp/kitangaji.com | 0754be94e96ed1f786e06d4075878240628f0d01 | [
"MIT"
] | null | null | null | db_ngaji.sql | langpp/kitangaji.com | 0754be94e96ed1f786e06d4075878240628f0d01 | [
"MIT"
] | null | null | null | db_ngaji.sql | langpp/kitangaji.com | 0754be94e96ed1f786e06d4075878240628f0d01 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.1.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jul 11, 2019 at 04:21 PM
-- Server version: 5.6.16
-- PHP Version: 5.5.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `db_ngaji`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_user`
--
CREATE TABLE IF NOT EXISTS `tbl_user` (
`id_user` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`password` text NOT NULL,
`status_user` int(11) NOT NULL,
PRIMARY KEY (`id_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `tbl_user`
--
INSERT INTO `tbl_user` (`id_user`, `username`, `email`, `password`, `status_user`) VALUES
(1, 'admin', 'admin@ngaji.com', '21232f297a57a5a743894a0e4a801fc3', 999),
(2, 'donatur', 'donatur@ngaji.com', '1a5323fe0ccb9955fdf55edb9c70ceea', 1),
(3, 'guru', 'guru@ngaji.com', '77e69c137812518e359196bb2f5e9bb9', 2),
(4, 'murid', 'murid@ngaji.com', '8779fd433a4bbdf35442d79476edafac', 3);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 30.313725 | 89 | 0.688875 |
2f125aa273fe1d9e6d8d078ea739f77012ccde29 | 649 | asm | Assembly | src/hook_parserDeclarePrototype.asm | szapp/Ninja | 7b018a5aa82bdb9f1eadea910ed1ff4711d4485a | [
"MIT"
] | 17 | 2018-07-11T20:53:46.000Z | 2022-03-01T18:20:42.000Z | src/hook_parserDeclarePrototype.asm | szapp/Ninja | 7b018a5aa82bdb9f1eadea910ed1ff4711d4485a | [
"MIT"
] | 24 | 2018-10-23T07:47:33.000Z | 2021-02-09T09:06:25.000Z | src/hook_parserDeclarePrototype.asm | szapp/Ninja | 7b018a5aa82bdb9f1eadea910ed1ff4711d4485a | [
"MIT"
] | null | null | null | ; Hook prototype parsing in zCParser::DeclarePrototype
%include "inc/macros.inc"
%if GOTHIC_BASE_VERSION == 1
%include "inc/symbols_g1.inc"
%elif GOTHIC_BASE_VERSION == 2
%include "inc/symbols_g2.inc"
%endif
%ifidn __OUTPUT_FORMAT__, bin
org g1g2(0x6F36B2,0x79CF72)
%endif
bits 32
section .text align=1 ; Prevent auto-alignment
jmp parser_check_prototype
; Overwrites
; %if GOTHIC_BASE_VERSION == 1
; push 0x4DF
; %elif GOTHIC_BASE_VERSION == 2
; push 0x3C
; call operator_new
; %endif
| 22.37931 | 99 | 0.580894 |
3ef53114f9b37fecf69b37364065d30398f17397 | 7,384 | h | C | RecoParticleFlow/PFProducer/interface/PFMuonAlgo.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | RecoParticleFlow/PFProducer/interface/PFMuonAlgo.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | RecoParticleFlow/PFProducer/interface/PFMuonAlgo.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | #ifndef RecoParticleFlow_PFProducer_PFMuonAlgo_h
#define RecoParticleFlow_PFProducer_PFMuonAlgo_h
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowReco/interface/PFBlockElement.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/MuonReco/interface/Muon.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"
class PFMuonAlgo {
typedef reco::Muon::MuonTrackTypePair MuonTrackTypePair;
typedef reco::Muon::MuonTrackType MuonTrackType;
public:
/// constructor
PFMuonAlgo();
void setParameters(const edm::ParameterSet&);
/// destructor
virtual ~PFMuonAlgo() {;}
////STATIC MUON ID METHODS
static bool isMuon( const reco::PFBlockElement& elt );
static bool isLooseMuon( const reco::PFBlockElement& elt );
static bool isGlobalTightMuon( const reco::PFBlockElement& elt );
static bool isGlobalLooseMuon( const reco::PFBlockElement& elt );
static bool isTrackerTightMuon( const reco::PFBlockElement& elt );
static bool isTrackerLooseMuon( const reco::PFBlockElement& elt );
static bool isIsolatedMuon( const reco::PFBlockElement& elt );
static bool isMuon( const reco::MuonRef& muonRef );
static bool isLooseMuon( const reco::MuonRef& muonRef );
static bool isGlobalTightMuon( const reco::MuonRef& muonRef );
static bool isGlobalLooseMuon( const reco::MuonRef& muonRef );
static bool isTrackerTightMuon( const reco::MuonRef& muonRef );
static bool isTrackerLooseMuon( const reco::MuonRef& muonRef );
static bool isIsolatedMuon( const reco::MuonRef& muonRef );
static bool isTightMuonPOG(const reco::MuonRef& muonRef);
static void printMuonProperties( const reco::MuonRef& muonRef );
////POST CLEANING AND MOMEMNTUM ASSIGNMENT
bool hasValidTrack(const reco::MuonRef& muonRef,bool loose =false);
//Make a PF Muon : Basic method
bool reconstructMuon(reco::PFCandidate&, const reco::MuonRef&,bool allowLoose = false);
//Assign a different track to the muon
void changeTrack(reco::PFCandidate&,const MuonTrackTypePair&);
//PF Post cleaning algorithm
void setInputsForCleaning(const reco::VertexCollection*);
void postClean(reco::PFCandidateCollection *);
void addMissingMuons(edm::Handle<reco::MuonCollection>, reco::PFCandidateCollection* cands);
std::unique_ptr<reco::PFCandidateCollection> transferCleanedCosmicCandidates() {
return std::move(pfCosmicsMuonCleanedCandidates_);
}
std::unique_ptr<reco::PFCandidateCollection> transferCleanedTrackerAndGlobalCandidates() {
return std::move(pfCleanedTrackerAndGlobalMuonCandidates_);
}
std::unique_ptr<reco::PFCandidateCollection> transferCleanedFakeCandidates() {
return std::move(pfFakeMuonCleanedCandidates_);
}
std::unique_ptr<reco::PFCandidateCollection> transferPunchThroughCleanedMuonCandidates() {
return std::move(pfPunchThroughMuonCleanedCandidates_);
}
std::unique_ptr<reco::PFCandidateCollection> transferPunchThroughCleanedHadronCandidates() {
return std::move(pfPunchThroughHadronCleanedCandidates_);
}
std::unique_ptr<reco::PFCandidateCollection> transferAddedMuonCandidates() {
return std::move(pfAddedMuonCandidates_);
}
private:
//Gives the track with the smallest Dpt/Pt
MuonTrackTypePair getTrackWithSmallestError(const std::vector<MuonTrackTypePair>&);
std::vector<reco::Muon::MuonTrackTypePair> muonTracks(const reco::MuonRef& muon,bool includeSA = false,double dpt = 1e+9);
//Gets the good tracks
std::vector<reco::Muon::MuonTrackTypePair> goodMuonTracks(const reco::MuonRef& muon,bool includeSA = false);
//Estimate MET and SUmET for post cleaning
void estimateEventQuantities(const reco::PFCandidateCollection* );
//Post cleaning Sub-methods
bool cleanMismeasured(reco::PFCandidate&,unsigned int);
bool cleanPunchThroughAndFakes(reco::PFCandidate&,reco::PFCandidateCollection* ,unsigned int );
void removeDeadCandidates(reco::PFCandidateCollection*, const std::vector<unsigned int>&);
//helpers
std::pair<double,double> getMinMaxMET2(const reco::PFCandidate&);
std::vector<MuonTrackTypePair> tracksWithBetterMET(const std::vector<MuonTrackTypePair>& ,const reco::PFCandidate&);
std::vector<MuonTrackTypePair> tracksPointingAtMET(const std::vector<MuonTrackTypePair>&);
//Output collections for post cleaning
/// the collection of cosmics cleaned muon candidates
std::unique_ptr<reco::PFCandidateCollection> pfCosmicsMuonCleanedCandidates_;
/// the collection of tracker/global cleaned muon candidates
std::unique_ptr<reco::PFCandidateCollection> pfCleanedTrackerAndGlobalMuonCandidates_;
/// the collection of fake cleaned muon candidates
std::unique_ptr<reco::PFCandidateCollection> pfFakeMuonCleanedCandidates_;
/// the collection of punch-through cleaned muon candidates
std::unique_ptr<reco::PFCandidateCollection> pfPunchThroughMuonCleanedCandidates_;
/// the collection of punch-through cleaned neutral hadron candidates
std::unique_ptr<reco::PFCandidateCollection> pfPunchThroughHadronCleanedCandidates_;
/// the collection of added muon candidates
std::unique_ptr<reco::PFCandidateCollection> pfAddedMuonCandidates_;
std::vector<unsigned int > maskedIndices_;
//////////////////////////////////////////////////////////////////////////////////////
const reco::VertexCollection * vertices_;
//Configurables
double maxDPtOPt_;
int minTrackerHits_;
int minPixelHits_;
reco::TrackBase::TrackQuality trackQuality_;
double errorCompScale_;
double eventFractionCleaning_;
double sumetPU_;
double dzPV_;
bool postCleaning_;
double minPostCleaningPt_;
double eventFactorCosmics_;
double metSigForCleaning_;
double metSigForRejection_;
double metFactorCleaning_;
double eventFractionRejection_;
double metFactorRejection_;
double metFactorHighEta_;
double ptFactorHighEta_;
double metFactorFake_;
double minPunchThroughMomentum_;
double minPunchThroughEnergy_;
double punchThroughFactor_;
double punchThroughMETFactor_;
double cosmicRejDistance_;
double sumet_;
double METX_;
double METY_;
///////COMPARATORS
class TrackMETComparator {
public:
TrackMETComparator(double METX,double METY) {metx_ = METX; mety_=METY;}
~TrackMETComparator() {}
bool operator()(const MuonTrackTypePair& mu1,const MuonTrackTypePair& mu2) {
return pow(metx_+mu1.first->px(),2)+pow(mety_+mu1.first->py(),2) < pow(metx_+mu2.first->px(),2)+pow(mety_+mu2.first->py(),2);
}
private:
double metx_;
double mety_;
};
class IndexPtComparator {
public:
IndexPtComparator(const reco::PFCandidateCollection* coll):coll_(coll) {
}
~IndexPtComparator() {}
bool operator()(int mu1,int mu2) {
return coll_->at(mu1).pt() > coll_->at(mu2).pt();
}
private:
const reco::PFCandidateCollection * coll_;
};
class TrackPtErrorSorter {
public:
TrackPtErrorSorter() {}
~TrackPtErrorSorter() {}
bool operator()(const MuonTrackTypePair& mu1,const MuonTrackTypePair& mu2) {
return mu1.first->ptError()/mu1.first->pt() < mu2.first->ptError()/mu2.first->pt();
}
};
};
#endif
| 30.512397 | 131 | 0.752438 |
2d8f8db03d3d96b1d00e5ca8d42b0704b4880b30 | 8,779 | rs | Rust | codegen/src/lib.rs | HFQR/xitca-web | ee2d4fa9e88b2be149c9ca3454bc14d90f8f9ca2 | [
"Apache-2.0"
] | 9 | 2021-11-09T04:16:32.000Z | 2022-03-24T01:14:14.000Z | codegen/src/lib.rs | HFQR/xitca-web | ee2d4fa9e88b2be149c9ca3454bc14d90f8f9ca2 | [
"Apache-2.0"
] | 10 | 2021-11-07T13:31:18.000Z | 2022-03-17T23:00:20.000Z | codegen/src/lib.rs | HFQR/xitca-web | ee2d4fa9e88b2be149c9ca3454bc14d90f8f9ca2 | [
"Apache-2.0"
] | 3 | 2021-10-30T06:38:06.000Z | 2021-11-28T23:22:50.000Z | use proc_macro::TokenStream;
use quote::{__private::Span, quote};
use syn::{
Data, FnArg, GenericArgument, Ident, ImplItem, ImplItemMethod, Pat, PatIdent, PathArguments, ReturnType, Stmt, Type,
};
#[proc_macro_derive(State, attributes(borrow))]
pub fn state_impl(item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::DeriveInput);
let ty_ident = &input.ident;
let _generics = &input.generics;
let ty = match input.data {
Data::Struct(ref ty) => ty,
_ => todo!(),
};
let fields = ty
.fields
.iter()
.enumerate()
.filter(|(_, field)| {
field.attrs.iter().any(|attr| {
attr.path
.segments
.first()
.filter(|seg| seg.ident.to_string().as_str() == "borrow")
.is_some()
})
})
.map(|(_, field)| {
let ident = field.ident.as_ref().unwrap();
let ty = &field.ty;
quote! {
impl ::core::borrow::Borrow<#ty> for #ty_ident {
fn borrow(&self) -> &#ty {
&self.#ident
}
}
}
});
quote! { #(#fields)* }.into()
}
#[proc_macro_attribute]
pub fn service_impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
middleware_impl(_attr, item)
}
#[proc_macro_attribute]
pub fn middleware_impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemImpl);
// Collect type path from impl.
let service_ty = match input.self_ty.as_ref() {
Type::Path(path) => path,
_ => panic!("impl macro must be used on a TypePath"),
};
// collect generics.
let generic_ty = &input.generics.params;
let where_clause = &input.generics.where_clause;
// find methods from impl.
let new_service_impl =
find_async_method(&input.items, "new_service").expect("new_service method can not be located");
// collect ServiceFactory type
let mut inputs = new_service_impl.sig.inputs.iter();
let (factory_ident, factory_ty) = match inputs.next().unwrap() {
FnArg::Receiver(_) => panic!("new_service method does not accept Self as receiver"),
FnArg::Typed(ty) => match (ty.pat.as_ref(), ty.ty.as_ref()) {
(Pat::Wild(_), Type::Reference(ty_ref)) if ty_ref.mutability.is_none() => {
(default_pat_ident("_factory"), &ty_ref.elem)
}
(Pat::Ident(ident), Type::Reference(ty_ref)) if ty_ref.mutability.is_none() => {
(ident.to_owned(), &ty_ref.elem)
}
_ => panic!("new_service must receive ServiceFactory type as immutable reference"),
},
};
let (arg_ident, arg_ty) = match inputs.next().unwrap() {
FnArg::Receiver(_) => panic!("new_service method must not receive Self as receiver"),
FnArg::Typed(ty) => match ty.pat.as_ref() {
Pat::Wild(_) => (default_pat_ident("_service"), &*ty.ty),
Pat::Ident(ident) => (ident.to_owned(), &*ty.ty),
_ => panic!("new_service method must use <arg: Arg> as second function argument"),
},
};
let factory_stmts = &new_service_impl.block.stmts;
let ready_impl = ReadyImpl::try_from_items(&input.items);
let CallImpl {
req_ident,
req_ty,
res_ty,
err_ty,
call_stmts,
} = CallImpl::from_items(&input.items);
let base = quote! {
impl<#generic_ty> ::xitca_service::BuildService<#arg_ty> for #factory_ty
#where_clause
{
type Service = #service_ty;
type Error = #err_ty;
type Future = impl ::core::future::Future<Output = Result<Self::Service, Self::Error>>;
fn build(&self, #arg_ident: #arg_ty) -> Self::Future {
let #factory_ident = self.clone();
async move {
#(#factory_stmts)*
}
}
}
impl<#generic_ty> ::xitca_service::Service<#req_ty> for #service_ty
#where_clause
{
type Response = #res_ty;
type Error = #err_ty;
type Future<'f> where Self: 'f = impl ::core::future::Future<Output = Result<Self::Response, Self::Error>>;
#[inline]
fn call(&self, #req_ident: #req_ty) -> Self::Future<'_> {
async move {
#(#call_stmts)*
}
}
}
};
match ready_impl {
Some(ReadyImpl {
ready_stmts,
ready_ret_ty: ready_res_ty,
}) => quote! {
#base
impl<#generic_ty> ::xitca_service::ready::ReadyService<#req_ty> for #service_ty
#where_clause
{
type Ready = #ready_res_ty;
type ReadyFuture<'f> = impl ::core::future::Future<Output = Self::Ready> where Self: 'f ;
#[inline]
fn ready(&self) -> Self::ReadyFuture<'_> {
async move {
#(#ready_stmts)*
}
}
}
}
.into(),
None => base.into(),
}
}
fn find_async_method<'a>(items: &'a [ImplItem], ident_str: &'a str) -> Option<&'a ImplItemMethod> {
items.iter().find_map(|item| match item {
ImplItem::Method(method) if method.sig.ident.to_string().as_str() == ident_str => {
assert!(method.sig.asyncness.is_some(), "{} method must be async fn", ident_str);
Some(method)
}
_ => None,
})
}
struct CallImpl<'a> {
req_ident: PatIdent,
req_ty: &'a Type,
res_ty: &'a Type,
err_ty: &'a Type,
call_stmts: &'a [Stmt],
}
impl<'a> CallImpl<'a> {
fn from_items(items: &'a [ImplItem]) -> Self {
// collect Request, Response and Error type.
let call_impl = find_async_method(items, "call").expect("call method can not be located");
let mut inputs = call_impl.sig.inputs.iter();
// ignore receiver and move on.
// TODO: Check the first fn arg and make sure it's a Receiver of &Self.
let _ = inputs.next().unwrap();
let (req_ident, req_ty) = match inputs.next().unwrap() {
FnArg::Receiver(_) => panic!("call method does not accept Self as second argument"),
FnArg::Typed(ty) => match ty.pat.as_ref() {
Pat::Wild(_) => (default_pat_ident("_req"), &*ty.ty),
Pat::Ident(ident) => (ident.to_owned(), &*ty.ty),
_ => panic!("call must use req: Request as second function argument"),
},
};
let (res_ty, err_ty) = extract_res_ty(&call_impl.sig.output);
let call_stmts = &call_impl.block.stmts;
CallImpl {
req_ident,
req_ty,
res_ty,
err_ty,
call_stmts,
}
}
}
struct ReadyImpl<'a> {
ready_stmts: &'a [Stmt],
ready_ret_ty: &'a Type,
}
impl<'a> ReadyImpl<'a> {
fn try_from_items(items: &'a [ImplItem]) -> Option<Self> {
find_async_method(items, "ready").map(|ready_impl| {
let ready_ret_ty = ready_ret_ty(&ready_impl.sig.output);
let ready_stmts = &ready_impl.block.stmts;
Self {
ready_stmts,
ready_ret_ty,
}
})
}
}
// Extract Result<T, E> types from a return type of function.
fn extract_res_ty(ret: &ReturnType) -> (&Type, &Type) {
if let ReturnType::Type(_, ty) = ret {
if let Type::Path(path) = ty.as_ref() {
let seg = path.path.segments.first().unwrap();
if seg.ident.to_string().as_str() == "Result" {
if let PathArguments::AngleBracketed(ref arg) = seg.arguments {
if let (Some(GenericArgument::Type(ok_ty)), Some(GenericArgument::Type(err_ty))) =
(arg.args.first(), arg.args.last())
{
return (ok_ty, err_ty);
}
}
}
}
}
panic!("build method must output Result<Self, <Error>>")
}
// Extract types from a return type of function.
fn ready_ret_ty(ret: &ReturnType) -> &Type {
if let ReturnType::Type(_, ty) = ret {
return ty;
}
panic!("ready method must output ReadyService::Ready type")
}
// generate a default PatIdent
fn default_pat_ident(ident: &str) -> PatIdent {
PatIdent {
attrs: Vec::with_capacity(0),
by_ref: None,
mutability: None,
ident: Ident::new(ident, Span::call_site()),
subpat: None,
}
}
| 32.514815 | 120 | 0.537647 |
c25d8951b0f36417efa492efc2fe70d8123fc706 | 1,388 | go | Go | wipe/wipe_test.go | 0x9ef/go-wiper | 9c4041500a2a08844d08ea61337ad939de4af46e | [
"MIT"
] | 8 | 2021-11-14T12:00:08.000Z | 2021-12-12T17:09:44.000Z | wipe/wipe_test.go | 0x9ef/go-wiper | 9c4041500a2a08844d08ea61337ad939de4af46e | [
"MIT"
] | null | null | null | wipe/wipe_test.go | 0x9ef/go-wiper | 9c4041500a2a08844d08ea61337ad939de4af46e | [
"MIT"
] | null | null | null | // Copyright (c) 2021 0x9ef. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package wipe_test
import (
"math/rand"
"os"
"testing"
"time"
"github.com/0x9ef/go-wiper/wipe"
)
const _100KB = 100 * 1024
const _1MB = 1 * 1024 * 1024
const _500MB = 500 * _1MB
const _1GB = 1000 * _1MB
func generateFile(path string, size int) {
fd, err := os.Create(path)
if err != nil {
panic(err)
}
defer fd.Close()
buf := make([]byte, size)
rand.Seed(time.Now().UnixNano())
rand.Read(buf)
if _, err := fd.Write(buf); err != nil {
panic(err)
}
}
func TestSmall100KB(t *testing.T) {
rule := wipe.RuleFast
path := "tests/open_test_small100KB.bin"
generateFile(path, _100KB)
if err := wipe.Wipe(path, rule); err != nil {
panic(err)
}
}
func TestSmall1MB(t *testing.T) {
rule := wipe.RuleFast
path := "tests/open_test_small1MB.bin"
generateFile(path, _1MB)
if err := wipe.Wipe(path, rule); err != nil {
panic(err)
}
}
func TestLarge500MB(t *testing.T) {
rule := wipe.RuleFast
path := "tests/open_test_large500MB.bin"
generateFile(path, _500MB)
if err := wipe.Wipe(path, rule); err != nil {
panic(err)
}
}
func TestLarge1GB(t *testing.T) {
rule := wipe.RuleFast
path := "tests/open_test_large1GB.bin"
generateFile(path, _1GB)
if err := wipe.Wipe(path, rule); err != nil {
panic(err)
}
}
| 19.828571 | 56 | 0.663545 |
fb4a3e03bd954d2ede27aa6078dd9d2b5eaaa957 | 1,612 | java | Java | src/main/java/de/unibremen/gradelog/model/package-info.java | 1cy1c3/gradelog | 9a3b6e92f46761e0db60428d77db62bc496e22c2 | [
"MIT"
] | null | null | null | src/main/java/de/unibremen/gradelog/model/package-info.java | 1cy1c3/gradelog | 9a3b6e92f46761e0db60428d77db62bc496e22c2 | [
"MIT"
] | null | null | null | src/main/java/de/unibremen/gradelog/model/package-info.java | 1cy1c3/gradelog | 9a3b6e92f46761e0db60428d77db62bc496e22c2 | [
"MIT"
] | null | null | null | /**
* Die Klassen dieses Pakets repräsentieren die Datensicht (siehe Kapitel 6 auf Seite 62),
* d. h. sie halten die jeweiligen Attribute und Objekte dieser Klassen können modifiziert,
* erstellt oder gelöscht werden. Dabei werden die Models in Bezug auf deren Konstrukte
* wie z. B. Attribute mit sog. Annotationen versehen, d. h. es wird unter anderem
* verdeutlicht, welche Attribute zur eigentlichen Entität gehören bzw. Beziehungen zu
* anderen Entitäten verdeutlicht. Letztendlich wird dann dieses modifizierte Objekt
* an die DAO übergeben, welche sich dann explizit um die Persistenz kümmert (siehe
* Kapitel 5.1.3 auf Seite 46).
* Anhand dieses Pakets lässt sich bereits ablesen, dass wir das Entwurfsmuster Fassade
* verwenden. Hierbei dient die Klasse User als Fassade, welche mittels Sets und Listen
* Zugang zu den Subsystemen bietet. Auf die Subsysteme wird hierbei selten bis gar nicht
* von außen zugegriffen. Wir haben uns für dieses Entwurfsmuster entschieden, da wir so
* eine einfache Modularisierung unserer Software gewährleisten können (siehe Strategie
* 1 der Issue Card 8). Zudem verwenden wir diese Strategie, da die einzelnen Module
* sich alle nach den Nutzern richten müssen, um eine möglichst große Individualisierung
* zu gewährleisten. Als Beispiel sei hier der Stundenplan erwähnt, welcher an jeden User
* angepasst werden muss. Durch diese Modularisierung ist es uns auch möglich, einzelne
* Module zu verwerfen oder neue Module hinzuzufügen. Somit können wir die Strategie
* 1 unserer Issue Cards 9 und 11 erfüllen.
*/
package de.unibremen.gradelog.model;
| 67.166667 | 91 | 0.793424 |
97bb068b953c7a42999ec3b7575b0637254f6201 | 667 | swift | Swift | TableBuilder/TableBuilder/Source/Core/Protocols/ConfigurableCell.swift | makskovalko/MagicTableBuilder | 332033443fdb69c63924ffe942e113c246546680 | [
"MIT"
] | 8 | 2018-04-02T07:17:31.000Z | 2019-09-27T13:50:48.000Z | TableBuilder/TableBuilder/Source/Core/Protocols/ConfigurableCell.swift | makskovalko/MagicTableBuilder | 332033443fdb69c63924ffe942e113c246546680 | [
"MIT"
] | null | null | null | TableBuilder/TableBuilder/Source/Core/Protocols/ConfigurableCell.swift | makskovalko/MagicTableBuilder | 332033443fdb69c63924ffe942e113c246546680 | [
"MIT"
] | 1 | 2019-03-01T17:30:05.000Z | 2019-03-01T17:30:05.000Z | //
// ConfigurableCell.swift
// TableBuilder
//
// Created by Maksim on 3/30/18.
// Copyright © 2018 Maksim. All rights reserved.
//
import UIKit
public protocol ConfigurableCell {
associatedtype Value
static var reuseId: String { get }
static var nib: UINib? { get }
static var height: CGFloat { get }
func configure(with value: Value)
}
public extension ConfigurableCell where Self: UITableViewCell {
public static var reuseId: String {
return NSStringFromClass(Self.self)
}
public static var nib: UINib? {
return nil
}
public static var height: CGFloat {
return 44
}
}
| 19.617647 | 63 | 0.644678 |
413d822ed78e3a9d3d042c9819116e26372accba | 1,141 | c | C | projects/stm32l452-st-nucleo/board/devices.c | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 1 | 2022-03-26T09:59:37.000Z | 2022-03-26T09:59:37.000Z | projects/stm32l452-st-nucleo/board/devices.c | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 1 | 2021-06-24T04:27:40.000Z | 2021-06-24T04:27:40.000Z | projects/stm32l452-st-nucleo/board/devices.c | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 2 | 2021-06-24T04:08:28.000Z | 2022-03-07T06:37:24.000Z | extern ADC_HandleTypeDef hadc1;
OS_HAL_DEVICE_DEFINE("ADC_HandleTypeDef", "adc1", hadc1);
extern CAN_HandleTypeDef hcan1;
OS_HAL_DEVICE_DEFINE("CAN_HandleTypeDef", "can1", hcan1);
extern CRC_HandleTypeDef hcrc;
OS_HAL_DEVICE_DEFINE("CRC_HandleTypeDef", "crc", hcrc);
extern DAC_HandleTypeDef hdac1;
OS_HAL_DEVICE_DEFINE("DAC_HandleTypeDef", "dac1", hdac1);
extern IWDG_HandleTypeDef hiwdg;
OS_HAL_DEVICE_DEFINE("IWDG_HandleTypeDef", "iwdg", hiwdg);
extern LPTIM_HandleTypeDef hlptim1;
OS_HAL_DEVICE_DEFINE("LPTIM_HandleTypeDef", "lptim1", hlptim1);
extern RNG_HandleTypeDef hrng;
OS_HAL_DEVICE_DEFINE("RNG_HandleTypeDef", "rng", hrng);
extern RTC_HandleTypeDef hrtc;
OS_HAL_DEVICE_DEFINE("RTC_HandleTypeDef", "rtc", hrtc);
extern SPI_HandleTypeDef hspi1;
OS_HAL_DEVICE_DEFINE("SPI_HandleTypeDef", "spi1", hspi1);
extern TIM_HandleTypeDef htim1;
OS_HAL_DEVICE_DEFINE("TIM_HandleTypeDef", "tim1", htim1);
extern UART_HandleTypeDef huart1;
OS_HAL_DEVICE_DEFINE("UART_HandleTypeDef", "uart1", huart1);
extern UART_HandleTypeDef huart2;
OS_HAL_DEVICE_DEFINE("UART_HandleTypeDef", "uart2", huart2);
| 30.837838 | 64 | 0.789658 |
a5545cd618810f7b129d34003ea2d0d86518fb4f | 686 | asm | Assembly | screen_left.asm | peckhamdata/cgl-6502 | 65bfe3449b3d684da95a2cd4b2ec5ce7e4d18864 | [
"MIT"
] | 4 | 2020-01-24T06:46:10.000Z | 2022-02-28T15:44:08.000Z | screen_left.asm | peckhamdata/cgl-6502 | 65bfe3449b3d684da95a2cd4b2ec5ce7e4d18864 | [
"MIT"
] | null | null | null | screen_left.asm | peckhamdata/cgl-6502 | 65bfe3449b3d684da95a2cd4b2ec5ce7e4d18864 | [
"MIT"
] | 1 | 2020-12-07T19:36:31.000Z | 2020-12-07T19:36:31.000Z | screen_left: txa
pha
ldx #$00
lda #<screen
sta $02
lda #>screen
sta $03
row_loop: ldy #$00
col_loop: inc $02
lda ($02),y
dec $02
sta ($02),y
iny
cpy #$27
bne col_loop
lda #$20
sta ($02),y
lda $02
adc #$27
sta $02
bcc next_row
inc $03
next_row: inx
cpx #$19
bne row_loop
pla
tax
rts | 24.5 | 28 | 0.276968 |
c42cde675372de9de3a1d78ac7505ef7a011c710 | 6,405 | h | C | PhysX_3.4/Source/SimulationController/include/ScArticulationCore.h | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | 1 | 2019-12-09T16:03:55.000Z | 2019-12-09T16:03:55.000Z | PhysX_3.4/Source/SimulationController/include/ScArticulationCore.h | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | PhysX_3.4/Source/SimulationController/include/ScArticulationCore.h | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_SCP_ARTICULATION_CORE
#define PX_PHYSICS_SCP_ARTICULATION_CORE
#include "ScActorCore.h"
#include "DyArticulation.h"
namespace physx
{
class PxvArticulation;
namespace IG
{
class NodeIndex;
}
namespace Sc
{
typedef Dy::FsData ArticulationDriveCache;
class ArticulationSim;
class BodyCore;
class ArticulationCore
{
//= ATTENTION! =====================================================================================
// Changing the data layout of this class breaks the binary serialization format. See comments for
// PX_BINARY_SERIAL_VERSION. If a modification is required, please adjust the getBinaryMetaData
// function. If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION
// accordingly.
//==================================================================================================
//---------------------------------------------------------------------------------
// Construction, destruction & initialization
//---------------------------------------------------------------------------------
// PX_SERIALIZATION
public:
ArticulationCore(const PxEMPTY) : mSim(NULL) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationCore();
~ArticulationCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
PxU32 getInternalDriveIterations() const;
void setInternalDriveIterations(const PxU32 v);
PxU32 getExternalDriveIterations() const;
void setExternalDriveIterations(const PxU32 v);
PxU32 getMaxProjectionIterations() const;
void setMaxProjectionIterations(const PxU32 v);
PxReal getSeparationTolerance() const;
void setSeparationTolerance(const PxReal v);
PxReal getSleepThreshold() const;
void setSleepThreshold(const PxReal v);
PxReal getFreezeThreshold() const;
void setFreezeThreshold(const PxReal v);
PxReal getWakeCounter() const;
void setWakeCounter(const PxReal v);
void setWakeCounterInternal(const PxReal v);
bool isSleeping() const;
void wakeUp(PxReal wakeCounter);
void putToSleep();
PxU16 getSolverIterationCounts() const;
void setSolverIterationCounts(PxU16 c);
PxArticulation* getPxArticulation();
const PxArticulation* getPxArticulation() const;
//---------------------------------------------------------------------------------
// Drive Cache API
//---------------------------------------------------------------------------------
ArticulationDriveCache* createDriveCache(PxReal compliance,
PxU32 driveIterations) const;
void updateDriveCache(ArticulationDriveCache& cache,
PxReal compliance,
PxU32 driveIterations) const;
void releaseDriveCache(ArticulationDriveCache& cache) const;
PxU32 getCacheLinkCount(const ArticulationDriveCache& cache) const;
void applyImpulse(BodyCore& link,
const ArticulationDriveCache& driveCache,
const PxVec3& force,
const PxVec3& torque);
void computeImpulseResponse(BodyCore& link,
PxVec3& linearResponse,
PxVec3& angularResponse,
const ArticulationDriveCache& driveCache,
const PxVec3& force,
const PxVec3& torque) const;
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
PX_FORCE_INLINE void setSim(ArticulationSim* sim)
{
PX_ASSERT((sim==0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ArticulationSim* getSim() const { return mSim; }
PX_FORCE_INLINE const Dy::ArticulationCore& getCore() { return mCore; }
static PX_FORCE_INLINE ArticulationCore& getArticulationCore(ArticulationCore& core)
{
size_t offset = PX_OFFSET_OF(ArticulationCore, mCore);
return *reinterpret_cast<ArticulationCore*>(reinterpret_cast<PxU8*>(&core) - offset);
}
IG::NodeIndex getIslandNodeIndex() const;
private:
ArticulationSim* mSim;
Dy::ArticulationCore mCore;
};
} // namespace Sc
}
#endif
| 37.45614 | 101 | 0.603591 |
c16372ed910214e0b49c5e2c9a350b6734bf85f3 | 447 | rs | Rust | crates/futures-rs_01/tests/inspect.rs | Zha0Chan/crates-sgx | 73dc6d9e130757d9e585ee757b3d94d5078512a9 | [
"Apache-2.0"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | crates/futures-rs_01/tests/inspect.rs | Zha0Chan/crates-sgx | 73dc6d9e130757d9e585ee757b3d94d5078512a9 | [
"Apache-2.0"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | third_party/rust_crates/vendor/futures/tests/inspect.rs | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | 1 | 2021-07-11T09:06:13.000Z | 2021-07-11T09:06:13.000Z | extern crate futures;
use futures::prelude::*;
use futures::future::{ok, err};
#[test]
fn smoke() {
let mut counter = 0;
{
let work = ok::<u32, u32>(40).inspect(|val| { counter += *val; });
assert_eq!(work.wait(), Ok(40));
}
assert_eq!(counter, 40);
{
let work = err::<u32, u32>(4).inspect(|val| { counter += *val; });
assert_eq!(work.wait(), Err(4));
}
assert_eq!(counter, 40);
}
| 18.625 | 74 | 0.521253 |
afaf2af6e9aa0d110902b3ff5a0fc7404cc5de16 | 1,747 | html | HTML | index.html | MirumSG/mirumsg.github.io | 0e120bbe2129b2382c7aeaf55af1246478a1aef9 | [
"MIT"
] | null | null | null | index.html | MirumSG/mirumsg.github.io | 0e120bbe2129b2382c7aeaf55af1246478a1aef9 | [
"MIT"
] | null | null | null | index.html | MirumSG/mirumsg.github.io | 0e120bbe2129b2382c7aeaf55af1246478a1aef9 | [
"MIT"
] | null | null | null | ---
layout: default
title: Home
---
<h1>Mirum SG Front-End Development Guidelines and Documentation</h1>
<hr/>
<div class="posts">
Guidelines:
<ol>
<div class="post">
{% for post in paginator.posts %}
<li>
<h4>
<a href="{{ post.url }}">
{{ post.title }}
</a>
</h4>
<span class="post-date small">{{ post.date | date_to_string }}</span>
</li>
{% endfor %}
</div>
</ol>
</div>
<!--
<div class="pagination">
{% if paginator.next_page %}
<a class="pagination-item older" href="{{ site.baseurl }}page{{paginator.next_page}}">Older</a>
{% else %}
<span class="pagination-item older">Older</span>
{% endif %}
{% if paginator.previous_page %}
{% if paginator.page == 2 %}
<a class="pagination-item newer" href="{{ site.baseurl }}">Newer</a>
{% else %}
<a class="pagination-item newer" href="{{ site.baseurl }}page{{paginator.previous_page}}">Newer</a>
{% endif %}
{% else %}
<span class="pagination-item newer">Newer</span>
{% endif %}
</div>-->
<!--<section>
<h4>Built with:</h4>
<div id="opensource-logo">
<p>
<a class="open-source__sass" href="http://sass-lang.com" title="Visit the Sass homepage"><span class="is-hidden">Sass</span></a>
<a class="open-source__node" href="http://nodejs.org" title="Visit the NodeJS homepage"><span class="is-hidden">NodeJS</span></a>
<a class="open-source__gulp" href="http://gulpjs.com" title="Visit the Gulp homepage"><span class="is-hidden">Gulp</span></a>
<a class="open-source__handlebars" href="http://handlebarsjs.com" title="Visit the HandlebarsJS homepage"><span class="is-hidden">Handlebars</span></a>
</p>
</div>
</section>-->
| 32.962264 | 157 | 0.597023 |
40bb9b4b97c244fe18d0f36e87b61d1c37c6edc9 | 8,238 | py | Python | code/analysis.py | ellagale/constructionist_binary_NN_tester | d4fbe9e0e33d94468edc2f3247097f4e3399e1b9 | [
"MIT"
] | null | null | null | code/analysis.py | ellagale/constructionist_binary_NN_tester | d4fbe9e0e33d94468edc2f3247097f4e3399e1b9 | [
"MIT"
] | null | null | null | code/analysis.py | ellagale/constructionist_binary_NN_tester | d4fbe9e0e33d94468edc2f3247097f4e3399e1b9 | [
"MIT"
] | null | null | null | import numpy as np
import matplotlib.pyplot as plt
import itertools
import threading
import imp
"""This module is for developing the machinery required to make neural nets and analyse local and global codes
This module does stuff.
"""
__version__ = '0.1'
__author__ = 'Ella Gale'
__date__ = 'Jan 2017'
class ThreadedRunner(object):
""" run a task across multiple processors, taking care not to overload them """
def __init__(self, tasks , maxparallel=8):
"""
tasks: an array of tuples of the form (function,arguments) to call
maxparallel: the maximum number of threads to be running at once
"""
self.threads = [threading.Thread(target=f,kwargs=k) for (f,k) in tasks]
# TODO: spin up seperate thread managers to maximise throughput
self.maxparallel = 8
self.next_thread=0
def run(self, threadrunlimit=None):
"""
threadrunlimit: only run this many threads at most total,
if None (default) then run all threads
"""
runcount = len(self.threads[self.next_thread:])
if threadrunlimit is not None:
runcount = min(runcount, threadrunlimit)
next_thread=0
while runcount>0:
batch = self.threads[next_thread:next_thread+self.maxparallel]
# cannot start threads while imp lock is held.
toLock = imp.lock_held()
if toLock:
imp.release_lock()
# Start all threads in this batch
for thread in batch:
thread.start()
# Wait for them all to finish
for thread in batch:
thread.join
# rest lock state
if toLock:
imp.acquire_lock()
runcount = runcount - len(batch)
next_thread = next_thread+len(batch)
def HelloWorld(word):
print(word)
def normalise_to_zero_one_interval(y, ymin, ymax):
"""Because I always forget the bloody formula"""
if ymin > ymax: raise TypeError('min and max values the wrong way round!')
return (y - ymin) / (ymax - ymin)
def global_charactor(y):
"""Function from Karplus and Brooks 1995 J. Compu. Chem
expects a column vector"""
"N.B. this does not currently work as advertised!"
print('You are using global_character WHICH IS NOT CORRECT!!\n')
if len(y.shape) != 1: raise TypeError('globalCharacter() not handed a vector ')
y = y / np.linalg.norm(y)
r = y.shape[0]
# y has to be normalised for this formula to work!
gc = (r**-0.5*sum(abs(y))) ** 4.0 # this is the original formula, now we normalise it
return normalise_to_zero_one_interval(gc, 1, r**4)
def fk_plotter(dks, noOfK, lRange=None, error=0.15, xaxis=1, title=None, xlabel=None, ylabel=None, showPlots=1, savePlots=0):
"""Produces F(k) plots for each layer of neurons"""
"lRange = range of layers to plot"
"error = error below 1 which we consider significant"
"xaxis = where to draw the xaxis line"
if lRange == None:
lRange = range(len(dks))
for l in lRange:
#l is the number of layers -- send a smaller dks if you don't want them all!
fig=plt.figure(l)
x_data = np.array(range(noOfK)) + 1
marker = itertools.cycle(['o', '>', '<', 'v', '8', 'd', 's', 'p', '*'])
for n in range(len(dks[l])):
# n is the number neurons in a layer
y_data = dks[l][n].fs
plt.plot(x_data, y_data, label=str(n), marker=marker.next(), alpha=1)
if not xaxis == None:
# note, if you don't want an xaxis, set xaxis='off'
plt.axhline(xaxis)
else:
plt.axhline(0)
plt.xlim([min(x_data)-0.25, max(x_data)+1])
#plt.legend()
plt.legend(bbox_to_anchor=(0.9, 1.1), loc='best', ncol=2, framealpha=0.5).draggable()
#ax.legend().draggable()
plt.plot([0., noOfK], [1-error, 1-error])
if title == None:
plt.title('Layer '+ str(l+1))
else:
plt.title(title)
if xlabel == None:
plt.xlabel('K')
else:
plt.xlabel(xlabel)
if ylabel == None:
plt.ylabel('f(K)')
else:
plt.ylabel(ylabel)
if showPlots == 1:
plt.show()
if savePlots == 1:
fig.savefig('Fk' + str(l) + '.png', dpi=fig.dpi)
def jitterer(out, z):
"""This function jitters the x axis
1: matrix of layer activations of the form:
2. which layer number to do
outputs a transposed matrix of no of neurons rows and no of data columns"""
Jx=np.ones(out[z].T.shape)
for i in range(out[z].T.shape[0]):
'this is the number of neurons'
for j in range(out[z].T.shape[1]):
'this is the number of data'
Jx[i,j] = i + 1 + np.random.uniform(-0.25,0.25)
return Jx
def local_charactor(y):
"""Function from Karplus and Brooks 1995 Compu Chem
expects a column vector"""
if len(y.shape) != 1: raise TypeError('localCharacter() not handed a vector ')
y = y / np.linalg.norm(y)
# y has to be normalised for this formula to work!
lc = sum(y ** 4.0) # this is hte original formula, we now normalise the output as well
return normalise_to_zero_one_interval(lc, y.shape[0] ** -1, 1)
def plotter(x, y, labels=['x','y'], legend=None, linestyle=['o-', '+-', '*.-'], xaxis=None, showPlots=1, savePlots=0):
"""Make nice plots automatically"""
fig=plt.figure(1)
xrange = max(x)-min(x)
yrange = max(y.flatten()) - min(y.flatten())
if not legend==None:
for i in range(len(y)):
plt.plot(x, y[i], linestyle[i/3], label=legend[i])
else:
for i in range(len(y)):
plt.plot(x, y[i], linestyle[i/3])
if not xaxis == None:
# note, if you don't want an xaxis, set xaxis='off'
plt.axhline(xaxis)
else:
plt.axhline(0)
plt.axis([min(x.flatten())-0.1*xrange, max(x.flatten())+0.1*xrange,
min(y.flatten())-0.1*yrange, max(y.flatten())+0.1*yrange])
plt.ylabel(labels[1])
plt.xlabel(labels[0])
if not legend==None:
plt.legend(framealpha=0.5)
if showPlots == 1:
plt.show()
if savePlots == 1:
fig.savefig('Hk' + str(x[0]) + '.png', dpi=fig.dpi)
def simple_layer_activation_plotter(out):
"""The original layer activation plotter, not the proper jitter plot"""
noOfLayers = len(out)
for l in range(noOfLayers):
plt.figure(l)
t = a.jitterer(out, l)
# yrange=max(out[l])-min(out[l])
plt.plot(t, out[l].T, '+', label='training')
plt.ylabel('Activation')
plt.xlabel('Neuron no.')
# plt.axis([min(t)-0.25, max(t)+0.25, min(out[l])-0.1*yrange, max(out[l]+0.1*yrange)])
# plt.legend()
plt.show()
####################################################
## downloaded code
"""
Demo of a function to create Hinton diagrams.
Hinton diagrams are useful for visualizing the values of a 2D array (e.g.
a weight matrix): Positive and negative values are represented by white and
black squares, respectively, and the size of each square represents the
magnitude of each value.
Initial idea from David Warde-Farley on the SciPy Cookbook
"""
def hinton(matrix, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
ax.invert_yaxis()
if __name__ == '__main__':
hinton(np.random.rand(20, 20) - 0.5)
plt.show()
## writing model to file and reading it back in test
| 33.62449 | 125 | 0.594319 |
2f00f39bd8fac0790d3234582ffef94b81ee5be1 | 11,334 | php | PHP | resources/views/admin/dashboard.blade.php | JesusAdrianQP/Totos-SistemaWeb-G4 | 456b22c57b648959251bb618f1af864740ca51ec | [
"MIT"
] | null | null | null | resources/views/admin/dashboard.blade.php | JesusAdrianQP/Totos-SistemaWeb-G4 | 456b22c57b648959251bb618f1af864740ca51ec | [
"MIT"
] | null | null | null | resources/views/admin/dashboard.blade.php | JesusAdrianQP/Totos-SistemaWeb-G4 | 456b22c57b648959251bb618f1af864740ca51ec | [
"MIT"
] | null | null | null | @extends('layouts.admin')
@section('title', 'DashBoard Principal - Menú')
@section('content-admin')
<!-- Loading screen -->
<div
x-ref="loading"
class="fixed inset-0 z-50 flex items-center justify-center text-white bg-black bg-opacity-50"
style="backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px)"
>
Loading.....
</div>
<div class="flex flex-col flex-1 h-full overflow-hidden">
@include('components.navbar-admin')
<!-- Main content -->
<main class="flex-1 max-h-full p-5 overflow-hidden overflow-y-scroll">
<!-- Main content header -->
<div
class="flex flex-col items-start justify-between pb-6 space-y-4 border-b lg:items-center lg:space-y-0 lg:flex-row"
>
<h1 class="text-2xl font-semibold whitespace-nowrap">Platos del Menú</h1>
</div>
<!-- Start Content -->
<div class="grid grid-cols-1 gap-5 mt-6 sm:grid-cols-2 lg:grid-cols-4">
<div class="p-4 transition-shadow border rounded-lg shadow-sm hover:shadow-lg">
<div class="flex items-start justify-between">
<div class="flex flex-col space-y-2">
<span class="text-gray-400">Consumidores totales</span>
<span class="text-lg font-semibold">200,000</span>
</div>
<div class="bg-gray-200 rounded-md w-20 h-20">
<img src="{{ asset('image/pizza.svg') }}" class="w-20 h-20">
</div>
</div>
<div>
<span class="inline-block px-2 text-sm text-white bg-green-300 rounded">14%</span>
<span>más que el 2020</span>
</div>
</div>
<div class="p-4 transition-shadow border rounded-lg shadow-sm hover:shadow-lg">
<div class="flex items-start justify-between">
<div class="flex flex-col space-y-2">
<span class="text-gray-400">Ganancias</span>
<span class="text-lg font-semibold">S/. 500,550.00</span>
</div>
<div class="bg-gray-200 rounded-md w-20 h-20">
<img src="{{ asset('image/bolsa-de-dinero.svg') }}" class="w-20 h-20 py-2">
</div>
</div>
<div>
<span class="inline-block px-2 text-sm text-white bg-green-300 rounded">30%</span>
<span>más que el 2020</span>
</div>
</div>
</div>
<!-- Table see (https://tailwindui.com/components/application-ui/lists/tables) -->
<h3 class="mt-6 text-xl">Platos del menú</h3>
<button onclick="mostrarModal()"
class="mt-2 flex items-center justify-center w-1/2 lg:w-1/6 px-2 py-2 space-x-1 tracking-wider bg-cuarto-500 border rounded-md focus:outline-none focus:ring"
>
<span>
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</span>
<span class="text-white bold"> Agregar plato </span>
</button>
<div class="flex flex-col mt-6">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
<div class="overflow-hidden border-b border-gray-200 rounded-md shadow-md">
<table class="min-w-full overflow-x-scroll divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th
scope="col"
class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
Plato
</th>
<th
scope="col"
class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
Descripción
</th>
<th
scope="col"
class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
Categoría
</th>
<th
scope="col"
class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
Precio Regular
</th>
<th
scope="col"
class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
Precio Familiar
</th>
<th scope="col" class="relative px-6 py-3">
<span class="sr-only">Edit</span>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
@foreach($dishes as $dish)
<tr class="transition-all hover:bg-gray-100 hover:shadow-lg">
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="flex-shrink-0 w-10 h-10">
<img
class="w-10 h-10 rounded-full"
src="{{asset($dish->file)}}"
alt=""
/>
</div>
<div class="ml-4">
<div class="text-sm font-medium text-gray-900">{{$dish->name}}</div>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm text-gray-900" style="white-space: pre-wrap; word-wrap: break-word; font-family: inherit;">{{$dish->description}}</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<span
class="inline-flex px-2 text-xs font-semibold leading-5 text-primero-600 bg-cuarto-300 rounded-full"
>
{{$dish->category}}
</span>
</td>
<td class="px-6 py-4 text-sm text-gray-500 whitespace-nowrap">S/. {{$dish->price_normal}}</td>
<td class="px-6 py-4 text-sm text-gray-500 whitespace-nowrap">S/. {{$dish->price_familiar}}</td>
<td class="px-6 py-4 text-sm font-medium text-right whitespace-nowrap">
<div class="flex item-center justify-center">
<div class="w-4 mr-2 transform hover:text-purple-500 hover:scale-110">
<a href="{{route("dishes.edit",[$dish])}}">
<svg class="w-4 h-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
</svg>
</a>
</div>
<div class="w-4 mr-2 transform hover:text-purple-500 hover:scale-110">
<form action="{{route("dishes.destroy", [$dish])}}" method="POST">
@method("delete")
@csrf
<button type="submit">
<svg class="w-4 h-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</form>
</a>
</div>
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
@include('components.register-dish')
</div>
@endsection | 61.597826 | 265 | 0.359979 |
5730ed81f1a0f67b4e7ec6b787d2f5c98990f367 | 360 | h | C | deps/src/gropt/incl/slasd3.h | pnavaro/ElasticFDA.jl | 0ed8c3f483c3a62f4215a6b65894da34e77eefc1 | [
"MIT"
] | 7 | 2017-02-05T23:39:14.000Z | 2021-06-03T06:41:47.000Z | deps/src/gropt/incl/slasd3.h | pnavaro/ElasticFDA.jl | 0ed8c3f483c3a62f4215a6b65894da34e77eefc1 | [
"MIT"
] | 3 | 2016-08-31T20:48:32.000Z | 2021-12-15T02:18:36.000Z | deps/src/gropt/incl/slasd3.h | pnavaro/ElasticFDA.jl | 0ed8c3f483c3a62f4215a6b65894da34e77eefc1 | [
"MIT"
] | 6 | 2016-07-12T02:13:16.000Z | 2020-09-22T17:42:16.000Z | #ifdef __cplusplus
extern "C" {
#endif
#include "f2c.h"
int slasd3_(integer *nl, integer *nr, integer *sqre, integer *k, real *d__, real *q, integer *ldq, real *dsigma, real *u, integer *ldu, real *u2, integer *ldu2, real *vt, integer *ldvt, real *vt2, integer *ldvt2, integer *idxc, integer *ctot, real *z__, integer *info);
#ifdef __cplusplus
}
#endif | 32.727273 | 269 | 0.686111 |
ec1d4450c03e41ed57ee5d749a01a100687f8281 | 402 | lua | Lua | mods/creox_game/src/item/items.lua | TehnoTheDragon/Creox | 1ac46aba3b7f2b62209df06fe85a3a0ab88c8e2c | [
"MIT"
] | null | null | null | mods/creox_game/src/item/items.lua | TehnoTheDragon/Creox | 1ac46aba3b7f2b62209df06fe85a3a0ab88c8e2c | [
"MIT"
] | null | null | null | mods/creox_game/src/item/items.lua | TehnoTheDragon/Creox | 1ac46aba3b7f2b62209df06fe85a3a0ab88c8e2c | [
"MIT"
] | null | null | null | local Builder = creox.game.Builder.Item
--> Items
Builder.create_item("wood_plank").texture("wood_plank.png").max_stack(16).build()
Builder.create_item("wood_stick").texture("wood_stick.png").max_stack(64).build()
Builder.create_item("processed_wood_stick").texture("processed_wood_stick.png").max_stack(64).build()
Builder.create_item("emerald").texture("faceted_jewelry_1.png").max_stack(16).build() | 57.428571 | 101 | 0.788557 |
332dfca284f4f89521f1d0f9ccafaec0f3569819 | 1,225 | dart | Dart | lib/model/friend.dart | TingzhouJia/flutter-chat | c0b1810cca9e3348948bb154ca039d148b07dbe4 | [
"MIT"
] | 8 | 2020-10-07T16:44:55.000Z | 2022-03-29T01:11:44.000Z | lib/model/friend.dart | TingzhouJia/flutter-chat | c0b1810cca9e3348948bb154ca039d148b07dbe4 | [
"MIT"
] | 1 | 2020-07-18T12:05:48.000Z | 2020-07-18T12:05:48.000Z | lib/model/friend.dart | TingzhouJia/flutter-chat | c0b1810cca9e3348948bb154ca039d148b07dbe4 | [
"MIT"
] | 5 | 2021-04-13T13:56:24.000Z | 2021-12-22T12:19:12.000Z |
import "package:built_collection/built_collection.dart";
import "package:built_value/built_value.dart";
import 'package:learnflutter/model/user.dart';
// ignore: prefer_double_quotes
part 'friend.g.dart';
abstract class Friend implements Built<Friend, FriendBuilder> {
@nullable
User get user;
String get background;
bool get notification;
bool get strongNotification;
bool get setTop;
String get nickName;
Friend._();
factory Friend([void Function(FriendBuilder) updates]) = _$Friend;
}
enum FriendSetting { NOTIFICATION, STRONG_NOTIFICATION,SET_TOP }
class FriendHelper {
static String stringOf(FriendSetting visibility) {
switch (visibility) {
case FriendSetting.NOTIFICATION:
return "notification";
case FriendSetting.STRONG_NOTIFICATION:
return "strongNotif";
case FriendSetting.SET_TOP:
return "setTop";
}
return null;
}
static FriendSetting valueOf(String string) {
switch (string) {
case "notification":
return FriendSetting.NOTIFICATION;
case "strongNotif":
return FriendSetting.STRONG_NOTIFICATION;
case "setTop":
return FriendSetting.SET_TOP;
}
return null;
}
}
| 20.416667 | 68 | 0.705306 |
046109a702b50ad308e4233a3e5ac78dca5c2aa7 | 1,209 | java | Java | core/src/main/java/io/smallrye/openapi/runtime/io/extension/ExtensionConstant.java | renegrob/smallrye-open-api | 1a5dfaa35775ff0f93786cf89a48eb0a07a5ada4 | [
"Apache-2.0"
] | 68 | 2018-05-27T23:12:12.000Z | 2022-03-03T08:43:59.000Z | core/src/main/java/io/smallrye/openapi/runtime/io/extension/ExtensionConstant.java | renegrob/smallrye-open-api | 1a5dfaa35775ff0f93786cf89a48eb0a07a5ada4 | [
"Apache-2.0"
] | 599 | 2018-06-13T06:11:35.000Z | 2022-03-31T14:03:18.000Z | core/src/main/java/io/smallrye/openapi/runtime/io/extension/ExtensionConstant.java | phillip-kruger/smallrye-open-api | c64e47ef65f61290b46664ebe2649fa1fcc1dc8c | [
"Apache-2.0"
] | 72 | 2018-05-29T07:34:24.000Z | 2022-03-18T04:00:54.000Z | package io.smallrye.openapi.runtime.io.extension;
import org.eclipse.microprofile.openapi.annotations.extensions.Extension;
import org.eclipse.microprofile.openapi.annotations.extensions.Extensions;
import org.jboss.jandex.DotName;
/**
* Constants related to Extension.
*
* @see <a href=
* "https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions">specificationExtensions</a>
*
* @author Phillip Kruger (phillip.kruger@redhat.com)
* @author Eric Wittmann (eric.wittmann@gmail.com)
*/
public class ExtensionConstant {
static final DotName DOTNAME_EXTENSIONS = DotName.createSimple(Extensions.class.getName());
static final DotName DOTNAME_EXTENSION = DotName.createSimple(Extension.class.getName());
public static final String PROP_NAME = "name";
public static final String PROP_VALUE = "value";
public static final String EXTENSION_PROPERTY_PREFIX = "x-";
public static final String PROP_PARSE_VALUE = "parseValue";
public static boolean isExtensionField(String fieldName) {
return fieldName.toLowerCase().startsWith(ExtensionConstant.EXTENSION_PROPERTY_PREFIX);
}
private ExtensionConstant() {
}
}
| 36.636364 | 134 | 0.763441 |
5b66d4bb92150c275eaa868837164ee497fd43ab | 320 | lua | Lua | workspace/source/first/run/init.client.lua | Vyon/Stacking-Bricks | 45344c2de29dd34a9418b1678eeca7e7989fae67 | [
"Apache-2.0"
] | null | null | null | workspace/source/first/run/init.client.lua | Vyon/Stacking-Bricks | 45344c2de29dd34a9418b1678eeca7e7989fae67 | [
"Apache-2.0"
] | null | null | null | workspace/source/first/run/init.client.lua | Vyon/Stacking-Bricks | 45344c2de29dd34a9418b1678eeca7e7989fae67 | [
"Apache-2.0"
] | null | null | null | local tween_service = game:GetService('TweenService')
local lighting = game:GetService('Lighting')
task.spawn(function()
while true do
local tween = tween_service:Create(lighting, TweenInfo.new(1, Enum.EasingStyle.Linear), { ClockTime = (lighting.ClockTime + .1) })
tween:Play()
tween.Completed:Wait()
end
end) | 29.090909 | 132 | 0.74375 |
313caf4b6294f9962973d8eaa53441e53c0774e2 | 487 | asm | Assembly | oeis/156/A156649.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/156/A156649.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/156/A156649.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A156649: Decimal expansion of (9+4*sqrt(2))/7.
; Submitted by Jon Maiga
; 2,0,9,3,8,3,6,3,2,1,3,5,6,0,5,4,3,1,3,6,0,0,9,6,4,9,8,5,2,6,2,6,8,4,6,1,6,3,2,5,5,2,6,7,8,5,9,2,9,6,8,4,6,1,3,2,4,3,8,1,6,9,9,3,1,3,7,5,6,1,4,1,6,2,6,4,0,6,1,1,6,5,0,5,7,3,6,4,3,0,5,3,3,0,0,8,0,8,9,8
bin $1,$0
mov $2,1
mov $3,$0
mul $3,3
lpb $3
add $2,$1
add $1,$2
mov $5,3
add $5,$2
add $1,$5
add $2,$1
sub $3,1
lpe
mul $1,2
add $2,$5
mov $4,10
pow $4,$0
div $2,$4
div $1,$2
mov $0,$1
mod $0,10
| 18.730769 | 201 | 0.525667 |
aa3e8f91c49c0e06a96af7a76c7eb5ecd8d99a33 | 156 | sql | SQL | src/main/resources/dbmigrate/mysql/data_dict/V1_6_0_1__data.sql | kll5h/ShinetechOA | 3d1d776b798327fbcb4584c21cd1d40cc298ec4e | [
"Apache-2.0"
] | 2 | 2018-10-19T08:54:56.000Z | 2018-10-19T08:55:07.000Z | src/main/resources/dbmigrate/mysql/data_dict/V1_6_0_1__data.sql | tuguangquan/lemon | 1218ab7d65ce69cb6b2162b1fce28fdc5577d13e | [
"Apache-2.0"
] | 2 | 2022-01-21T23:50:21.000Z | 2022-03-31T21:05:21.000Z | src/main/resources/dbmigrate/mysql/data_dict/V1_6_0_1__data.sql | tuguangquan/lemon | 1218ab7d65ce69cb6b2162b1fce28fdc5577d13e | [
"Apache-2.0"
] | 2 | 2020-11-13T02:55:28.000Z | 2021-01-22T03:50:15.000Z |
UPDATE DICT_TYPE SET TENANT_ID='1';
UPDATE DICT_SCHEMA SET TENANT_ID='1';
UPDATE DICT_INFO SET TENANT_ID='1';
UPDATE DICT_DATA SET TENANT_ID='1';
| 19.5 | 38 | 0.730769 |
f8c0ef9c08855e0461959181375fa533129d4532 | 114 | sql | SQL | templates/init/pg_long.sql | erthalion/ansible-ycsb | 86916fbc4128629df77090b49819a9a4c4d15ea4 | [
"MIT"
] | 9 | 2017-12-23T15:26:12.000Z | 2020-05-21T15:48:43.000Z | templates/init/pg_long.sql | erthalion/ansible-ycsb | 86916fbc4128629df77090b49819a9a4c4d15ea4 | [
"MIT"
] | 1 | 2018-04-04T08:02:59.000Z | 2018-04-24T13:11:01.000Z | templates/init/pg_long.sql | erthalion/ansible-ycsb | 86916fbc4128629df77090b49819a9a4c4d15ea4 | [
"MIT"
] | 1 | 2017-11-18T11:47:05.000Z | 2017-11-18T11:47:05.000Z | \set id random(1, {{ recordcount }})
select * from (select * from test_short_long limit 100000) q
order by time;
| 22.8 | 60 | 0.710526 |
63c16c3847ffb0dfea4b44dacbe59ddcbf6d25eb | 899 | sql | SQL | sp_GetSectionFromTable.sql | ImClarky/sqlsrv-pagination | c370475bfcb07eb7ab2fd59ca4b6fb512ad57af2 | [
"MIT"
] | 2 | 2016-02-26T16:50:19.000Z | 2018-06-13T13:11:56.000Z | sp_GetSectionFromTable.sql | ImClarky/sqlsrv-pagination | c370475bfcb07eb7ab2fd59ca4b6fb512ad57af2 | [
"MIT"
] | null | null | null | sp_GetSectionFromTable.sql | ImClarky/sqlsrv-pagination | c370475bfcb07eb7ab2fd59ca4b6fb512ad57af2 | [
"MIT"
] | null | null | null | -- Execute this script in your SQL Server to create the Stored Procedure
-- Change the parameter type values to your needs i.e. @schema nvarchar(15) -> nvarchar(30)
-- The values currently are just placeholders deemed large enough
CREATE PROCEDURE [dbo].[GetSectionFromTable]
@schema nvarchar(15),
@table nvarchar(100),
@orderCol nvarchar(100),
@limit int,
@page int
AS
DECLARE @sql nvarchar(1000)
SELECT @sql =
N'
SELECT * FROM
(SELECT *, ROW_NUMBER() over(ORDER BY '+ QUOTENAME(@orderCol) +' DESC) as RowNum
FROM '+ QUOTENAME(@schema) + '.' + QUOTENAME(@table) +'
) as [table]
WHERE
[table].[RowNum] BETWEEN (('+ CAST(@page as nvarchar(3)) +' - 1) * '+ CAST(@limit as nvarchar(3)) +') + 1 AND '+ CAST(@limit as nvarchar(3)) +' * ('+ CAST(@page as nvarchar(3)) +')
ORDER BY
'+ QUOTENAME(@orderCol) +' DESC
'
EXEC sp_executesql @sql
GO
| 29 | 185 | 0.642937 |
b0d1b5d63fa2f690c92c3c3af0b7842446eee9e5 | 172 | rs | Rust | src/lib.rs | snf/z3-sys | 8387e939c602e545b8c3877d44596264dfb758e3 | [
"MIT"
] | 3 | 2015-12-23T07:16:34.000Z | 2016-05-14T10:36:49.000Z | src/lib.rs | snf/z3-sys | 8387e939c602e545b8c3877d44596264dfb758e3 | [
"MIT"
] | null | null | null | src/lib.rs | snf/z3-sys | 8387e939c602e545b8c3877d44596264dfb758e3 | [
"MIT"
] | 1 | 2019-03-05T02:54:24.000Z | 2019-03-05T02:54:24.000Z | #![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
extern crate libc;
type __builtin_va_list = libc::c_void;
include!("ffi.rs");
| 19.111111 | 38 | 0.75 |
0fe0d7c0b8fedf3fc61d0fa53184fa229f320317 | 8,611 | swift | Swift | Shared/Schrodinger RK4.swift | MMalaker57/Homework-4 | 10f5e7c7248fc49022de7a65ea55f060a17a5594 | [
"MIT"
] | null | null | null | Shared/Schrodinger RK4.swift | MMalaker57/Homework-4 | 10f5e7c7248fc49022de7a65ea55f060a17a5594 | [
"MIT"
] | null | null | null | Shared/Schrodinger RK4.swift | MMalaker57/Homework-4 | 10f5e7c7248fc49022de7a65ea55f060a17a5594 | [
"MIT"
] | null | null | null | //
// Schrodinger RK4.swift
// Test Plot Threaded
//
// Created by Matthew Malaker on 2/25/22.
//
import Foundation
import SwiftUI
import CorePlot
class Schrodinger: NSObject, ObservableObject {
var potential = Potential()
// var potentialV: (onedArray: [Double], xArray: [Double], yArray: [Double]) = ([],[],[])
var hbar2over2m = 0.0
//k and l are the same type of variable but are used in the separate RK4 solutions
//we need 2 solutions because we have a second order equation and need to solve for psi' and psi, not just psi
//We do this because we only have a relation for psi' from psi'', which itself is a variation of psi, but psi' is unknown
//past the initial condition.
// var k1: Double = 0.0
// var k2: Double = 0.0
// var k3: Double = 0.0
// var k4: Double = 0.0
// var l1: Double = 0.0
// var l2: Double = 0.0
// var l3: Double = 0.0
// var l4: Double = 0.0
// 2 2
//- hbar partial psi
//-------- ----------- + VPsi = EPsi
// 2m 2
// partial x
// 2 2
//- hbar partial psi
//-------- ----------- + (V-E)Psi = 0
// 2m 2
// partial x
// We need to solve for E, Psi, and the functional
//
//Psi'' = (2m(V-E)/hbar^2)*Psi
//
//
//
//
override init() {
//Must call super init before initializing plot
super.init()
let hbar = 6.582119569e-16
let hbar2 = pow((6.582119569e-16),2.0)
let massE = 510998.946/(pow(299792458.0e10,2.0))
hbar2over2m = hbar2/(2.0*massE)
// print(hbar2over2m)
}
func setV(choice: String, xMin: Double, xMax: Double, stepSize: Double){
potential.getPotential(potentialToGet: choice, xMin: xMin, xMax: xMax, stepSize: stepSize)
}
func calculatePsiForE(xMin: Double, xMax: Double, stepSize: Double, potentialStr: String, E: Double)->[Double]{
var potentialString = ""
var psi: [Double] = []
var psiforE: [(E: Double, psi: [Double])] = []
var psiPrime: [Double] = []
var psiDoublePrime: [Double] = []
var psiWithE: [Double] = []
psi.removeAll()
psiPrime.removeAll()
psi.append(0.0)
psiPrime.append(5.0)
// potential.getPotential(potentialToGet: potentialStr, xMin: xMin, xMax: xMax, stepSize: stepSize)
var potentialV = potential.potential
// var eStep = 0.1
// var maxE = 30.0
var maeta = Int((xMax-xMin)/stepSize)
//Solving a second order equation requires we solve two first orders. We have that
var currentPsi = 0.0
var nextPsi = 0.0
var currentPsiPrime = psiPrime[0]
var nextPsiPrime = 0.0
var currentPsiDoublePrime = 0.0
print(potentialV.yArray.count)
for i in stride(from: 0, to: maeta, by: 1){
// print("V = \(potentialV.yArray[i])")
currentPsiDoublePrime = ((potentialV.yArray[i]-E)*currentPsi)/hbar2over2m
let k1 = currentPsiPrime
let l1 = currentPsiDoublePrime
let VAverage = ((potentialV.yArray[i+1]-potentialV.yArray[i])/2.0)
let k2 = currentPsiPrime + (stepSize * (k1 / 2.0))
let l2 = ((VAverage-E)/hbar2over2m) * (currentPsi + (stepSize*l1)/2.0)
let k3 = currentPsiPrime + (stepSize * (k2 / 2.0))
let l3 = ((VAverage-E)/hbar2over2m) * (currentPsi + (stepSize*l2)/2.0)
let k4 = currentPsiPrime + (stepSize * k3)
let l4 = ((potentialV.yArray[i+1]-E)/hbar2over2m) * (currentPsi + (stepSize*l3))
nextPsi = currentPsi + (stepSize/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4)
nextPsiPrime = currentPsiPrime + (stepSize/6.0)*(l1 + 2.0*l2 + 2.0*l3 + l4)
// nextPsi = currentPsi + stepSize*k1
// nextPsiPrime = currentPsiPrime + stepSize*l1
// print("Psi = \(nextPsi)")
// print("PsiPrime = \(nextPsiPrime)")
psi.append(nextPsi)
psiPrime.append(nextPsiPrime)
currentPsi = nextPsi
currentPsiPrime = nextPsiPrime
}
nextPsi = 0.0
nextPsiPrime = 0.0
currentPsi = 0.0
currentPsiPrime = 0.0
potentialString = ""
psiforE = []
psiPrime = []
psiDoublePrime = []
psiWithE = psi
return psiWithE
}
func separateGoodE(minX: Double, maxX: Double, stepSize: Double, potentialStr: String, data: [(E: Double, psi: [Double])])->[(E: Double, psi: [Double])] {
var psiforESep: [(E: Double, psi: [Double])] = []
var EList: [Double] = []
var psiAtA: [Double] = []
var psiList: [[Double]] = []
let maeta = Int((maxX - minX) / stepSize)
var pointsBeforeCross: [Int] = []
var numberofZeroes: Int = 0
let twoStep = 2.0 * stepSize //Just to not double stepSize many times. It's best to do it once
for i in data{
var temp = i.psi.last ?? 0.0
psiAtA.append(temp) //If you put he definition of temp into this line, you get an error.
psiList.append(i.psi)
EList.append(i.E)
}
//We now have a function psi(A,E). We need to calculate the zeroes
//To do this, we need the derivative of the function at each point we use. We can either calculate it at each point
//or calculate it as we go. The latter is more efficient
//We first should find how many zeroes there are
//ironically, this is not a terrible way to find the zeroes
for i in stride(from: 1, to: psiAtA.count-1, by: 1){
if(psiAtA[i]*psiAtA[i+1] < 0){
numberofZeroes += 1
pointsBeforeCross.append(i)
}
}
//Calculate zeroes
for root in stride(from: 0, to: numberofZeroes, by: 1){
var eta = pointsBeforeCross[root]
var calculatedPsi: [Double] = []
var E = Double(EList[pointsBeforeCross[root]])
var functionalPrime = (psiAtA[eta+1] - psiAtA[eta])/((EList[eta+1]-EList[eta])) // initial
var currentValue = psiAtA[eta]
for i in stride(from: 1, to: 20, by: 1){
//Break if the derivative is too flat and continuing would cause problem
// if(functionalPrime < 0.01){
// psiforESep.append((E: EList[eta], psi: psiList[eta]))
// break
// }
// print("E= \(E) and currentValue = \(currentValue) and functionalPrime = \(functionalPrime)")
let oldE = E
E = oldE - (currentValue/functionalPrime)
let oldFunctionalValue = currentValue
calculatedPsi = calculatePsiForE(xMin: minX, xMax: maxX, stepSize: stepSize, potentialStr: potentialStr, E: E)
currentValue = calculatedPsi.last!
//derivative
functionalPrime = (currentValue - oldFunctionalValue)/((E-oldE))
if(abs(currentValue) < 0.0001){
psiforESep.append((E: E, psi: calculatedPsi))
break
}
}
}
return psiforESep
}
func normalize(data: (E: Double, psi: [Double]), stepSize: Double) -> (E: Double, psi: [Double]){
var psiarray = data.psi
var normarray: [Double] = []
var normed: (E: Double, psi: [Double]) = (E: data.E, [])
var integral: Double = 0.0
//We need to integrate the two wavefunctions
for i in psiarray{
integral += pow(i,2.0)*stepSize
}
for i in psiarray{
normarray.append(i*pow(integral,-0.5))
}
normed = (data.E, normarray)
return normed
}
}
| 32.011152 | 158 | 0.503194 |
cbd9471e837598434faa18da15de96aac0585948 | 9,813 | go | Go | recordwants.go | brotherlogic/recordwants | 8a8f9e0a9e6db01b093b68edf6bbb87d8611ffff | [
"Apache-2.0"
] | null | null | null | recordwants.go | brotherlogic/recordwants | 8a8f9e0a9e6db01b093b68edf6bbb87d8611ffff | [
"Apache-2.0"
] | 2,481 | 2018-01-27T02:47:29.000Z | 2022-02-23T20:34:23.000Z | recordwants.go | brotherlogic/recordwants | 8a8f9e0a9e6db01b093b68edf6bbb87d8611ffff | [
"Apache-2.0"
] | 2 | 2018-10-21T02:49:31.000Z | 2018-10-21T04:09:16.000Z | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/brotherlogic/goserver"
"github.com/brotherlogic/goserver/utils"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/resolver"
pbgh "github.com/brotherlogic/githubcard/proto"
pbg "github.com/brotherlogic/goserver/proto"
rapb "github.com/brotherlogic/recordadder/proto"
rbpb "github.com/brotherlogic/recordbudget/proto"
pbrc "github.com/brotherlogic/recordcollection/proto"
rcpb "github.com/brotherlogic/recordcollection/proto"
pb "github.com/brotherlogic/recordwants/proto"
)
func init() {
resolver.Register(&utils.DiscoveryServerResolverBuilder{})
}
var (
//wants - the print queue
wants = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordwants_total_wants",
Help: "The size of the wants queue",
})
covered = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordwants_total_done",
Help: "The size of the wants queue",
})
lists = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordwants_num_lists",
Help: "The size of the wants queue",
})
)
const (
// KEY - where the wants are stored
KEY = "/github.com/brotherlogic/recordwants/config"
)
type alerter interface {
alert(ctx context.Context, want *pb.MasterWant, c, total int)
}
type prodAlerter struct {
dial func(ctx context.Context, server string) (*grpc.ClientConn, error)
}
func (p *prodAlerter) alert(ctx context.Context, want *pb.MasterWant, c, total int) {
conn, err := p.dial(ctx, "githubcard")
if err == nil {
defer conn.Close()
client := pbgh.NewGithubClient(conn)
client.AddIssue(ctx, &pbgh.Issue{Service: "recordwants", Title: fmt.Sprintf("Want Processing Needed!"), Body: fmt.Sprintf("%v/%v - %v", c, total, want)}, grpc.FailFast(false))
}
}
type recordAdder interface {
getAdds(ctx context.Context) ([]int32, error)
}
type prodRecordAdder struct {
dial func(ctx context.Context, server string) (*grpc.ClientConn, error)
}
func (p *prodRecordAdder) getAdds(ctx context.Context) ([]int32, error) {
conn, err := p.dial(ctx, "recordadder")
if err != nil {
return []int32{}, err
}
defer conn.Close()
client := rapb.NewAddRecordServiceClient(conn)
resp, err := client.ListQueue(ctx, &rapb.ListQueueRequest{})
if err != nil {
return []int32{}, err
}
nums := []int32{}
for _, add := range resp.GetRequests() {
nums = append(nums, add.GetId())
}
return nums, err
}
type recordGetter interface {
getAllRecords(ctx context.Context, id int32) ([]int32, error)
getRecordsSince(ctx context.Context, since int64) ([]int32, error)
getRecords(ctx context.Context, id int32) ([]int32, error)
getRecord(ctx context.Context, id int32) (*pbrc.Record, error)
getWants(ctx context.Context) ([]*pbrc.Want, error)
unwant(ctx context.Context, want *pb.MasterWant) error
want(ctx context.Context, want *pb.MasterWant) error
}
type prodGetter struct {
dial func(ctx context.Context, server string) (*grpc.ClientConn, error)
Log func(message string)
}
func (p *prodGetter) getRecordsSince(ctx context.Context, since int64) ([]int32, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return []int32{}, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
resp, err := client.QueryRecords(ctx, &pbrc.QueryRecordsRequest{Query: &pbrc.QueryRecordsRequest_UpdateTime{since}})
if err != nil {
return []int32{}, err
}
return resp.GetInstanceIds(), err
}
func (p *prodGetter) getRecords(ctx context.Context, id int32) ([]int32, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return []int32{}, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
resp, err := client.QueryRecords(ctx, &pbrc.QueryRecordsRequest{Query: &pbrc.QueryRecordsRequest_ReleaseId{id}})
if err != nil {
return []int32{}, err
}
return resp.GetInstanceIds(), err
}
func (p *prodGetter) getAllRecords(ctx context.Context, id int32) ([]int32, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return []int32{}, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
resp, err := client.GetRecord(ctx, &pbrc.GetRecordRequest{ReleaseId: id})
if err != nil {
return []int32{}, err
}
return resp.GetRecord().GetRelease().GetOtherVersions(), nil
}
func (p *prodGetter) getRecord(ctx context.Context, instanceID int32) (*pbrc.Record, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return nil, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
resp, err := client.GetRecord(ctx, &pbrc.GetRecordRequest{InstanceId: instanceID})
if err != nil {
return nil, err
}
return resp.GetRecord(), err
}
func (p *prodGetter) getWants(ctx context.Context) ([]*pbrc.Want, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return nil, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
resp, err := client.GetWants(ctx, &pbrc.GetWantsRequest{})
if err != nil {
return nil, err
}
return resp.GetWants(), nil
}
func (p *prodGetter) unwant(ctx context.Context, want *pb.MasterWant) error {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
_, err = client.UpdateWant(ctx, &pbrc.UpdateWantRequest{Update: &pbrc.Want{ReleaseId: want.GetRelease().GetId()}, Remove: true})
p.Log(fmt.Sprintf("UNWANT PROC %v -> %v", want.GetRelease().GetId(), err))
return err
}
func (p *prodGetter) want(ctx context.Context, want *pb.MasterWant) error {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
_, err = client.UpdateWant(ctx, &pbrc.UpdateWantRequest{Update: &pbrc.Want{ReleaseId: want.GetRelease().GetId()}})
p.Log(fmt.Sprintf("WANT %v (%v) -> %v", want.GetRelease().GetId(), want.GetLevel(), err))
return err
}
//Server main server type
type Server struct {
*goserver.GoServer
recordGetter recordGetter
alerter alerter
lastRun time.Time
lastProc int32
lastPull int32
pull string
mmonth int32
lastUnwant string
budgetPull time.Duration
recordAdder recordAdder
testing bool
}
// Init builds the server
func Init() *Server {
s := &Server{
&goserver.GoServer{},
&prodGetter{},
&prodAlerter{},
time.Now(),
-1,
-1,
"",
0,
"",
0,
&prodRecordAdder{},
false,
}
s.recordGetter = &prodGetter{dial: s.FDialServer, Log: s.Log}
s.alerter = &prodAlerter{dial: s.FDialServer}
s.recordAdder = &prodRecordAdder{dial: s.FDialServer}
return s
}
func (s *Server) save(ctx context.Context, config *pb.Config) error {
return s.KSclient.Save(ctx, KEY, config)
}
func (s *Server) load(ctx context.Context) (*pb.Config, error) {
config := &pb.Config{}
data, _, err := s.KSclient.Read(ctx, KEY, config)
if err != nil {
return nil, err
}
//Clean out the wants here
wmap := make(map[int32]*pb.MasterWant)
config = data.(*pb.Config)
if config.Spends == nil {
config.Spends = make(map[int32]*pb.RecordSpend)
}
for _, want := range config.Wants {
if val, ok := wmap[want.GetRelease().GetId()]; ok {
val.Superwant = val.Superwant || want.Superwant
} else {
wmap[want.GetRelease().GetId()] = want
}
}
config = data.(*pb.Config)
config.Wants = []*pb.MasterWant{}
for _, want := range wmap {
config.Wants = append(config.Wants, want)
}
wants.Set(float64(len(config.Wants)))
done := 0
count := 0
for _, want := range config.Wants {
if want.Level == pb.MasterWant_UNKNOWN {
done++
}
if want.Level == pb.MasterWant_LIST {
count++
}
}
covered.Set(float64(done))
lists.Set(float64(count))
return config, err
}
// DoRegister does RPC registration
func (s *Server) DoRegister(server *grpc.Server) {
pb.RegisterWantServiceServer(server, s)
rcpb.RegisterClientUpdateServiceServer(server, s)
}
// ReportHealth alerts if we're not healthy
func (s *Server) ReportHealth() bool {
return true
}
// Shutdown close the server
func (s *Server) Shutdown(ctx context.Context) error {
return nil
}
// Mote promotes/demotes this server
func (s *Server) Mote(ctx context.Context, master bool) error {
return nil
}
func (s *Server) getBudget(ctx context.Context) (int32, error) {
if s.testing {
s.RaiseIssue("Testing in Prod", "You Fool")
return 0, nil
}
conn, err := s.FDialServer(ctx, "recordbudget")
if err != nil {
return 0, err
}
defer conn.Close()
client := rbpb.NewRecordBudgetServiceClient(conn)
budg, err := client.GetBudget(ctx, &rbpb.GetBudgetRequest{Year: int32(time.Now().Year())})
if err != nil {
return 0, err
}
return budg.GetBudget() + budg.GetSolds() - budg.GetSpends() - budg.GetPreSpends(), nil
}
// GetState gets the state of the server
func (s *Server) GetState() []*pbg.State {
return []*pbg.State{}
}
func main() {
var quiet = flag.Bool("quiet", false, "Show all output")
var clear = flag.Bool("clear_suuper", false, "Clears all super wants")
flag.Parse()
//Turn off logging
if *quiet {
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
}
server := Init()
server.PrepServer()
server.Register = server
err := server.RegisterServerV2("recordwants", false, true)
if err != nil {
return
}
if *clear {
ctx, cancel := utils.BuildContext("recordwants", "recordwants")
defer cancel()
config, err := server.load(ctx)
if err != nil {
log.Fatalf("Unable to read wants: %v", err)
}
for _, w := range config.Wants {
w.Superwant = false
}
server.save(ctx, config)
log.Fatalf("Saved out cleared wants")
}
server.Serve()
}
| 24.780303 | 177 | 0.695914 |
3a28b6ca70dbc7bdff5d55ac91c023f394d0de33 | 274 | dart | Dart | lib/screens/widgets/action_button/action_button.dart | bhavinpatolia3/Flutter-Finance-App | d22477dfb267f8fbc47c2f4192f6126d7d9a9f33 | [
"MIT"
] | 1 | 2019-08-05T20:36:20.000Z | 2019-08-05T20:36:20.000Z | lib/screens/widgets/action_button/action_button.dart | bhavinpatolia3/Flutter-Finance-App | d22477dfb267f8fbc47c2f4192f6126d7d9a9f33 | [
"MIT"
] | null | null | null | lib/screens/widgets/action_button/action_button.dart | bhavinpatolia3/Flutter-Finance-App | d22477dfb267f8fbc47c2f4192f6126d7d9a9f33 | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
class ActionButton extends StatelessWidget {
Widget build(BuildContext context) {
return IconButton(
icon: Icon(
Icons.sort,
textDirection: TextDirection.rtl,
),
onPressed: () {},
);
}
}
| 19.571429 | 44 | 0.627737 |
2f2abdf9ba99134d7c277a4590b2aee1981c4b20 | 3,255 | php | PHP | app/Http/Controllers/GoogleController.php | namdhgc/crawl-data-amazon | 0090a45531a791358347497ff73722ed320c0752 | [
"MIT"
] | null | null | null | app/Http/Controllers/GoogleController.php | namdhgc/crawl-data-amazon | 0090a45531a791358347497ff73722ed320c0752 | [
"MIT"
] | null | null | null | app/Http/Controllers/GoogleController.php | namdhgc/crawl-data-amazon | 0090a45531a791358347497ff73722ed320c0752 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use \Illuminate\Session\Middleware\StartSession;
use App\Http\Models\Customer as ModelCustomer;
use Spr\Base\Response\Response;
use Illuminate\Http\Request;
use Auth;
use Lang;
use Url;
use Hash;
class GoogleController extends Controller
{
public function loginWithGoogle(Request $request)
{
$code = $request->get('code');
$googleService = \OAuth::consumer('Google', route('web-get-login-google-callback'));
// check if code is valid
// if code is provided get user data and sign in
if ( ! is_null($code))
{
}
// if not ask for permission first
else
{
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to google login url
return redirect((string)$url);
}
}
public function callbackGoogle(Request $request) {
$code = $request->get('code');
$googleService = \OAuth::consumer('Google');
if ( ! is_null($code))
{
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$user = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$table = 'customers';
$first_name = $user['family_name'];
$last_name = $user['given_name'];
$google_id = $user['id'];
$username = $user['email'];
$email = $user['email'];
$roles = Config::get('spr.system.roles.customer.id');
$created_at = strtotime(\Carbon\Carbon::now()->toDateTimeString());
$where = [];
$ModelCustomer = new ModelCustomer();
$check = $ModelCustomer->checkExistsUser($username);
if ($check['response'] != null) {
// user existed
} else {
$data = [
'username' => $username,
'first_name' => $first_name,
'last_name' => $last_name,
'google_id' => $google_id,
'email' => $email,
'roles' => $roles,
'password' => Hash::make(bin2hex(random_bytes(4))),
'created_at' => $created_at
];
$inserted_id = ModelCustomer::insertData($data, $where)['response'];
}
$where = [
[
'fields' => 'google_id',
'operator' => '=',
'value' => $google_id
]
];
$user_id = $ModelCustomer->selectData($table, $where)['response'][0]->id;
Auth::guard('customer')->loginUsingId($user_id);
$results['meta']['code'] = 200;
$results['meta']['success'] = true;
$results['meta']['msg'] = Lang::get('message.web.success.0003');
}
return $results;
}
} | 30.420561 | 112 | 0.482335 |
2f25c6c1d09de30c5780c738519190bdad4d528a | 6,008 | php | PHP | application/components/classes/database.php | olijen/massmail | f58bb9e944aa795c418844aa124568c889df806e | [
"Apache-2.0"
] | null | null | null | application/components/classes/database.php | olijen/massmail | f58bb9e944aa795c418844aa124568c889df806e | [
"Apache-2.0"
] | null | null | null | application/components/classes/database.php | olijen/massmail | f58bb9e944aa795c418844aa124568c889df806e | [
"Apache-2.0"
] | null | null | null | <?php
class DataBase {
private static $db = null; // Единственный экземпляр класса, чтобы не создавать множество подключений
private $mysqli; // Идентификатор соединения
private $sym_query = "{?}"; // "Символ значения в запросе"
public static $queryLog = false;
/* Получение экземпляра класса. Если он уже существует, то возвращается, если его не было, то создаётся и возвращается (паттерн Singleton) */
public static function getDB()
{
if (self::$db == null) self::$db = new DataBase();
return self::$db;
}
public static function log($status = true)
{
self::$queryLog = $status;
}
/* private-конструктор, подключающийся к базе данных, устанавливающий локаль и кодировку соединения */
private function __construct()
{
$dbConf = Registry::get('dbConf');
$this->mysqli = new mysqli(/*'p:'.*/DB_HOST, DB_USER, DB_PWD, DB_NAME);
$this->mysqli->query("SET lc_time_names = 'ru_RU'");
$this->mysqli->query("SET NAMES 'utf8'");
}
/* Вспомогательный метод, который заменяет "символ значения в запросе" на конкретное значение, которое проходит через "функции безопасности" */
private function getQuery($query, $params)
{
if ($params) {
for ($i = 0; $i < count($params); $i++) {
$pos = strpos($query, $this->sym_query);
$arg = "'".$this->mysqli->real_escape_string($params[$i])."'";
$query = substr_replace($query, $arg, $pos, strlen($this->sym_query));
}
}
if (self::$queryLog) {
echo $query.'<hr>';
}
return $query;
}
/* SELECT-метод, возвращающий таблицу результатов */
public function select($query, $params = false)
{
$result_set = $this->mysqli->query($this->getQuery($query, $params));
if (!$result_set) return false;
return $this->resultSetToArray($result_set);
}
/* SELECT-метод, возвращающий одну строку с результатом */
public function selectRow($query, $params = false)
{
$result_set = $this->mysqli->query($this->getQuery($query, $params));
if ($result_set->num_rows != 1) return false;
else return $result_set->fetch_assoc();
}
/* SELECT-метод, возвращающий значение из конкретной ячейки */
public function selectCell($query, $params = false)
{
$result_set = $this->mysqli->query($this->getQuery($query, $params));
if ((!$result_set) || ($result_set->num_rows != 1)) return false;
else {
$arr = array_values($result_set->fetch_assoc());
return $arr[0];
}
}
/* НЕ-SELECT методы (INSERT, UPDATE, DELETE). Если запрос INSERT, то возвращается id последней вставленной записи */
public function query($query, $params = false)
{
$success = $this->mysqli->query($this->getQuery($query, $params));
if ($success) {
if ($this->mysqli->insert_id === 0) return true;
else return $this->mysqli->insert_id;
}
else return false;
}
//UPDATE
public function update($table, $where, $data)
{
$params = array();
$col_val = NULL;
foreach ($data as $column => $value){
//$sql = "UPDATE $table SET $column = $value WHERE $where";
//mysql_query($sql) or die(mysql_error());
$col_val .= '`'.$column.'` = {?},';
$params[] = $value;
}
$query = 'UPDATE `'.$table.'` SET '.substr($col_val, 0, strlen($col_val)-1).' WHERE '.$where;
$success = $this->mysqli->query($this->getQuery($query, $params));
if ($success) return true;
else return false;
}
//UPDATE CELL
public function updateCell($table, $column, $value, $where)
{
$params = array();
$query = 'UPDATE `'.$table.'` SET `'.$column.'` = '.$value.' WHERE '.$where;
$success = $this->mysqli->query($this->getQuery($query, array($value)));
if ($success) return true;
else return false;
}
//DELETE
public function delete($table, $where)
{//DELETE
$query = 'DELETE FROM `'.$table.'` WHERE '.$where;
$success = $this->mysqli->query($this->getQuery($query, array($value)));
if ($success) return true;
else return false;
}
public function insert($table, $data)
{//Добавление новой строки в БД
$columns = "";
$values = "";
$params = array();
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= '`'.$column.'`';
$values .= ($values == "") ? "" : ", ";
$values .= '{?}';
$params[] = $value;
}
$query = 'INSERT INTO `'.$table.'` ('.$columns.') values ('.$values.')';
$success = $this->mysqli->query($this->getQuery($query, $params));
if ($success) {
return $this->mysqli->insert_id;
}
else {
return false;
}
}
public function inDB($col, $table, $cel, $value)
{
$query =
"SELECT `".$this->oneWord($col)."`
FROM `".$this->oneWord($table)."`
WHERE `".$this->oneWord($cel)."` = {?}";
$params = array($value);
$res = $this->select($query, $params);
if (count($res) == 0) return false;
else return true;
}
/* Преобразование result_set в двумерный массив */
private function resultSetToArray($result_set) {
$array = array();
while (($row = $result_set->fetch_assoc()) != false) {
$array[] = $row;
}
return $array;
}
/* При уничтожении объекта закрывается соединение с базой данных */
public function __destruct() {
if ($this->mysqli) $this->mysqli->close();
}
public function oneWord($str)
{
return str_replace(' ', '', $str);
}
}
?> | 33.564246 | 147 | 0.544607 |
684aee3fb89a18a1f0ba6387a7a7a673ed390c7a | 7,917 | htm | HTML | docs/mpi-3.1/mpi31-report/node472.htm | wgropp/mpi-forum.github.io | 2675689c0401df7db37f7872a158781072cf2379 | [
"MIT"
] | null | null | null | docs/mpi-3.1/mpi31-report/node472.htm | wgropp/mpi-forum.github.io | 2675689c0401df7db37f7872a158781072cf2379 | [
"MIT"
] | null | null | null | docs/mpi-3.1/mpi31-report/node472.htm | wgropp/mpi-forum.github.io | 2675689c0401df7db37f7872a158781072cf2379 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang=en>
<head>
<!-- This file was generated by tohtml from appLang-CNames.tex -->
<!-- with the command
tohtml -default -basedef mpi3defs.txt -numbers -indexname myindex -dosnl -htables -quietlatex -allgif -endpage mpi3-forum-tail.htm -Wnoredef -o mpi31-report.tex mpi-report.tex
-->
<title>Groups, Contexts, Communicators, and Caching C Bindings</title>
</head>
<body style="background-color:#FFFFFF">
<hr><h2><span id="Node472">398. Groups, Contexts, Communicators, and Caching C Bindings</span></h2>
<a href="node471.htm#Node471"><img width=16 height=16 src="previous.gif" alt="Previous"></a><a href="node468.htm#Node468"><img width=16 height=16 src="up.gif" alt="Up"></a><a href="node473.htm#Node473"><img width=16 height=16 src="next.gif" alt="Next"></a><br>
<b>Up: </b><a href="node468.htm#Node468"> C Bindings</a>
<b>Next: </b><a href="node473.htm#Node473"> Process Topologies C Bindings</a>
<b>Previous: </b><a href="node471.htm#Node471"> Collective Communication C Bindings</a>
<p>
<tt> int MPI_COMM_DUP_FN(MPI_Comm oldcomm, int comm_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_COMM_NULL_COPY_FN(MPI_Comm oldcomm, int comm_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_COMM_NULL_DELETE_FN(MPI_Comm comm, int comm_keyval, void *attribute_val, void *extra_state) <br></tt>
<tt> int MPI_Comm_compare(MPI_Comm comm1, MPI_Comm comm2, int *result) <br></tt>
<tt> int MPI_Comm_create(MPI_Comm comm, MPI_Group group, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_create_group(MPI_Comm comm, MPI_Group group, int tag, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_create_keyval(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, int *comm_keyval, void *extra_state) <br></tt>
<tt> int MPI_Comm_delete_attr(MPI_Comm comm, int comm_keyval) <br></tt>
<tt> int MPI_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_dup_with_info(MPI_Comm comm, MPI_Info info, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_free(MPI_Comm *comm) <br></tt>
<tt> int MPI_Comm_free_keyval(int *comm_keyval) <br></tt>
<tt> int MPI_Comm_get_attr(MPI_Comm comm, int comm_keyval, void *attribute_val, int *flag) <br></tt>
<tt> int MPI_Comm_get_info(MPI_Comm comm, MPI_Info *info_used) <br></tt>
<tt> int MPI_Comm_get_name(MPI_Comm comm, char *comm_name, int *resultlen) <br></tt>
<tt> int MPI_Comm_group(MPI_Comm comm, MPI_Group *group) <br></tt>
<tt> int MPI_Comm_idup(MPI_Comm comm, MPI_Comm *newcomm, MPI_Request *request) <br></tt>
<tt> int MPI_Comm_rank(MPI_Comm comm, int *rank) <br></tt>
<tt> int MPI_Comm_remote_group(MPI_Comm comm, MPI_Group *group) <br></tt>
<tt> int MPI_Comm_remote_size(MPI_Comm comm, int *size) <br></tt>
<tt> int MPI_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val) <br></tt>
<tt> int MPI_Comm_set_info(MPI_Comm comm, MPI_Info info) <br></tt>
<tt> int MPI_Comm_set_name(MPI_Comm comm, const char *comm_name) <br></tt>
<tt> int MPI_Comm_size(MPI_Comm comm, int *size) <br></tt>
<tt> int MPI_Comm_split(MPI_Comm comm, int color, int key, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_split_type(MPI_Comm comm, int split_type, int key, MPI_Info info, MPI_Comm *newcomm) <br></tt>
<tt> int MPI_Comm_test_inter(MPI_Comm comm, int *flag) <br></tt>
<tt> int MPI_Group_compare(MPI_Group group1,MPI_Group group2, int *result) <br></tt>
<tt> int MPI_Group_difference(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_excl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_free(MPI_Group *group) <br></tt>
<tt> int MPI_Group_incl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_intersection(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_range_excl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_range_incl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup) <br></tt>
<tt> int MPI_Group_rank(MPI_Group group, int *rank) <br></tt>
<tt> int MPI_Group_size(MPI_Group group, int *size) <br></tt>
<tt> int MPI_Group_translate_ranks(MPI_Group group1, int n, const int ranks1[], MPI_Group group2, int ranks2[]) <br></tt>
<tt> int MPI_Group_union(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) <br></tt>
<tt> int MPI_Intercomm_create(MPI_Comm local_comm, int local_leader, MPI_Comm peer_comm, int remote_leader, int tag, MPI_Comm *newintercomm) <br></tt>
<tt> int MPI_Intercomm_merge(MPI_Comm intercomm, int high, MPI_Comm *newintracomm) <br></tt>
<tt> int MPI_TYPE_DUP_FN(MPI_Datatype oldtype, int type_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_TYPE_NULL_COPY_FN(MPI_Datatype oldtype, int type_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_TYPE_NULL_DELETE_FN(MPI_Datatype datatype, int type_keyval, void *attribute_val, void *extra_state) <br></tt>
<tt> int MPI_Type_create_keyval(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, int *type_keyval, void *extra_state) <br></tt>
<tt> int MPI_Type_delete_attr(MPI_Datatype datatype, int type_keyval) <br></tt>
<tt> int MPI_Type_free_keyval(int *type_keyval) <br></tt>
<tt> int MPI_Type_get_attr(MPI_Datatype datatype, int type_keyval, void *attribute_val, int *flag) <br></tt>
<tt> int MPI_Type_get_name(MPI_Datatype datatype, char *type_name, int *resultlen) <br></tt>
<tt> int MPI_Type_set_attr(MPI_Datatype datatype, int type_keyval, void *attribute_val) <br></tt>
<tt> int MPI_Type_set_name(MPI_Datatype datatype, const char *type_name) <br></tt>
<tt> int MPI_WIN_DUP_FN(MPI_Win oldwin, int win_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_WIN_NULL_COPY_FN(MPI_Win oldwin, int win_keyval, void *extra_state, void *attribute_val_in, void *attribute_val_out, int *flag) <br></tt>
<tt> int MPI_WIN_NULL_DELETE_FN(MPI_Win win, int win_keyval, void *attribute_val, void *extra_state) <br></tt>
<tt> int MPI_Win_create_keyval(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, int *win_keyval, void *extra_state) <br></tt>
<tt> int MPI_Win_delete_attr(MPI_Win win, int win_keyval) <br></tt>
<tt> int MPI_Win_free_keyval(int *win_keyval) <br></tt>
<tt> int MPI_Win_get_attr(MPI_Win win, int win_keyval, void *attribute_val, int *flag) <br></tt>
<tt> int MPI_Win_get_name(MPI_Win win, char *win_name, int *resultlen) <br></tt>
<tt> int MPI_Win_set_attr(MPI_Win win, int win_keyval, void *attribute_val) <br></tt>
<tt> int MPI_Win_set_name(MPI_Win win, const char *win_name) <br></tt>
<P>
<P>
<hr>
<a href="node471.htm#Node471"><img width=16 height=16 src="previous.gif" alt="Previous"></a><a href="node468.htm#Node468"><img width=16 height=16 src="up.gif" alt="Up"></a><a href="node473.htm#Node473"><img width=16 height=16 src="next.gif" alt="Next"></a><br>
<b>Up: </b><a href="node468.htm#Node468"> C Bindings</a>
<b>Next: </b><a href="node473.htm#Node473"> Process Topologies C Bindings</a>
<b>Previous: </b><a href="node471.htm#Node471"> Collective Communication C Bindings</a>
<p>
<HR>
Return to <A HREF="node523.htm">MPI-3.1 Standard Index</A><BR>
Return to <A HREF="http://www.mpi-forum.org/index.html">MPI Forum Home Page</A><BR>
<HR>
<FONT SIZE=-1>(Unofficial) MPI-3.1 of June 4, 2015<BR>
HTML Generated on June 4, 2015
</FONT>
</body>
</html>
| 82.46875 | 261 | 0.724517 |
3b145f6afb4c7f2a80e30b1f7328ab74b479f2ac | 3,959 | h | C | Source/Lib/C_DEFAULT/EbPictureOperators_C.h | bhavnahariMCW/SVT-HEVC | a81089ff6f5ea1dade035aff9de04d281b7e6867 | [
"BSD-2-Clause-Patent"
] | 1 | 2018-11-03T10:13:09.000Z | 2018-11-03T10:13:09.000Z | Source/Lib/C_DEFAULT/EbPictureOperators_C.h | bhavnahariMCW/SVT-HEVC | a81089ff6f5ea1dade035aff9de04d281b7e6867 | [
"BSD-2-Clause-Patent"
] | null | null | null | Source/Lib/C_DEFAULT/EbPictureOperators_C.h | bhavnahariMCW/SVT-HEVC | a81089ff6f5ea1dade035aff9de04d281b7e6867 | [
"BSD-2-Clause-Patent"
] | null | null | null | /*
* Copyright(c) 2018 Intel Corporation
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
#ifndef EbPictureOperators_C_h
#define EbPictureOperators_C_h
#include "EbTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
void PictureAverageKernel(
EB_BYTE src0,
EB_U32 src0Stride,
EB_BYTE src1,
EB_U32 src1Stride,
EB_BYTE dst,
EB_U32 dstStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
void PictureAverageKernel1Line_C(
EB_BYTE src0,
EB_BYTE src1,
EB_BYTE dst,
EB_U32 areaWidth);
void PictureCopyKernel(
EB_BYTE src,
EB_U32 srcStride,
EB_BYTE dst,
EB_U32 dstStride,
EB_U32 areaWidth,
EB_U32 areaHeight,
EB_U32 bytesPerSample);
void PictureAdditionKernel(
EB_U8 *predPtr,
EB_U32 predStride,
EB_S16 *residualPtr,
EB_U32 residualStride,
EB_U8 *reconPtr,
EB_U32 reconStride,
EB_U32 width,
EB_U32 height);
void PictureAdditionKernel16bit(
EB_U16 *predPtr,
EB_U32 predStride,
EB_S16 *residualPtr,
EB_U32 residualStride,
EB_U16 *reconPtr,
EB_U32 reconStride,
EB_U32 width,
EB_U32 height);
void CopyKernel8Bit(
EB_BYTE src,
EB_U32 srcStride,
EB_BYTE dst,
EB_U32 dstStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
void CopyKernel16Bit(
EB_BYTE src,
EB_U32 srcStride,
EB_BYTE dst,
EB_U32 dstStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
void ResidualKernelSubSampled(
EB_U8 *input,
EB_U32 inputStride,
EB_U8 *pred,
EB_U32 predStride,
EB_S16 *residual,
EB_U32 residualStride,
EB_U32 areaWidth,
EB_U32 areaHeight,
EB_U8 lastLine);
void ResidualKernel(
EB_U8 *input,
EB_U32 inputStride,
EB_U8 *pred,
EB_U32 predStride,
EB_S16 *residual,
EB_U32 residualStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
void ResidualKernel16bit(
EB_U16 *input,
EB_U32 inputStride,
EB_U16 *pred,
EB_U32 predStride,
EB_S16 *residual,
EB_U32 residualStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
void ZeroOutCoeffKernel(
EB_S16* coeffbuffer,
EB_U32 coeffStride,
EB_U32 coeffOriginIndex,
EB_U32 areaWidth,
EB_U32 areaHeight);
void FullDistortionKernel_32bit(
EB_S16 *coeff,
EB_U32 coeffStride,
EB_S16 *reconCoeff,
EB_U32 reconCoeffStride,
EB_U64 distortionResult[2],
EB_U32 areaWidth,
EB_U32 areaHeight);
void FullDistortionKernelCbfZero_32bit(
EB_S16 *coeff,
EB_U32 coeffStride,
EB_S16 *reconCoeff,
EB_U32 reconCoeffStride,
EB_U64 distortionResult[2],
EB_U32 areaWidth,
EB_U32 areaHeight);
void FullDistortionKernelIntra_32bit(
EB_S16 *coeff,
EB_U32 coeffStride,
EB_S16 *reconCoeff,
EB_U32 reconCoeffStride,
EB_U64 distortionResult[2],
EB_U32 areaWidth,
EB_U32 areaHeight);
EB_U64 SpatialFullDistortionKernel(
EB_U8 *input,
EB_U32 inputStride,
EB_U8 *recon,
EB_U32 reconStride,
EB_U32 areaWidth,
EB_U32 areaHeight);
EB_U64 Compute8x8Satd(
EB_S16 *diff);
EB_U64 Compute8x8Satd_U8(
EB_U8 *diff,
EB_U64 *dcValue,
EB_U32 srcStride);
#ifdef __cplusplus
}
#endif
#endif // EbPictureOperators_C_h | 24.899371 | 56 | 0.569336 |
3d616faf9077f322a597bc52ea320a4b4d6376b2 | 2,503 | swift | Swift | GoodWall/GoodWall/Model/Experience/ExperienceComment.swift | KeithGapusan/MVVMSearchController | 68ec6841387ab7a71d1cd69610e5d13ab86d75e2 | [
"MIT"
] | null | null | null | GoodWall/GoodWall/Model/Experience/ExperienceComment.swift | KeithGapusan/MVVMSearchController | 68ec6841387ab7a71d1cd69610e5d13ab86d75e2 | [
"MIT"
] | null | null | null | GoodWall/GoodWall/Model/Experience/ExperienceComment.swift | KeithGapusan/MVVMSearchController | 68ec6841387ab7a71d1cd69610e5d13ab86d75e2 | [
"MIT"
] | null | null | null | //
// ExperienceComment.swift
// Model Generated using keith model generator/
// Created on August 10, 2018
import Foundation
class ExperienceComment : NSObject, NSCoding{
var authorId : Int!
var body : String!
var created : String!
var id : Int!
var modified : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
authorId = dictionary["author_id"] as? Int
body = dictionary["body"] as? String
created = dictionary["created"] as? String
id = dictionary["id"] as? Int
modified = dictionary["modified"] as? String
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if authorId != nil{
dictionary["author_id"] = authorId
}
if body != nil{
dictionary["body"] = body
}
if created != nil{
dictionary["created"] = created
}
if id != nil{
dictionary["id"] = id
}
if modified != nil{
dictionary["modified"] = modified
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder)
{
authorId = aDecoder.decodeObject(forKey: "author_id") as? Int
body = aDecoder.decodeObject(forKey: "body") as? String
created = aDecoder.decodeObject(forKey: "created") as? String
id = aDecoder.decodeObject(forKey: "id") as? Int
modified = aDecoder.decodeObject(forKey: "modified") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encode(with aCoder: NSCoder)
{
if authorId != nil{
aCoder.encode(authorId, forKey: "author_id")
}
if body != nil{
aCoder.encode(body, forKey: "body")
}
if created != nil{
aCoder.encode(created, forKey: "created")
}
if id != nil{
aCoder.encode(id, forKey: "id")
}
if modified != nil{
aCoder.encode(modified, forKey: "modified")
}
}
}
| 28.123596 | 183 | 0.574511 |
3bf51abf15d4324b080f6f2694fe9be0b6ca2b24 | 3,059 | h | C | third_party/parallel-inet/src/applications/httptools/HttpBrowserDirect.h | eniac/MimicNet | c0790679f8c220c75c33ace67e2735816aac6815 | [
"MIT"
] | 15 | 2021-08-20T08:10:01.000Z | 2022-03-24T21:24:50.000Z | third_party/parallel-inet/src/applications/httptools/HttpBrowserDirect.h | eniac/MimicNet | c0790679f8c220c75c33ace67e2735816aac6815 | [
"MIT"
] | 1 | 2022-03-30T09:03:39.000Z | 2022-03-30T09:03:39.000Z | third_party/parallel-inet/src/applications/httptools/HttpBrowserDirect.h | eniac/MimicNet | c0790679f8c220c75c33ace67e2735816aac6815 | [
"MIT"
] | 3 | 2021-08-20T08:10:34.000Z | 2021-12-02T06:15:02.000Z | // ***************************************************************************
//
// HttpTools Project
//
// This file is a part of the HttpTools project. The project was created at
// Reykjavik University, the Laboratory for Dependable Secure Systems (LDSS).
// Its purpose is to create a set of OMNeT++ components to simulate browsing
// behaviour in a high-fidelity manner along with a highly configurable
// Web server component.
//
// Maintainer: Kristjan V. Jonsson (LDSS) kristjanvj@gmail.com
// Project home page: code.google.com/p/omnet-httptools
//
// ***************************************************************************
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// 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.
//
// ***************************************************************************
#ifndef __INET_HTTPBROWSERDIRECT_H
#define __INET_HTTPBROWSERDIRECT_H
#include "HttpBrowserBase.h"
/**
* A simulated browser module for OMNeT++ simulations.
*
* This module implements direct message passing between modules.
*
* @see HttpBrowserBase
* @see HttpBrowser
*
* @author Kristjan V. Jonsson (kristjanvj@gmail.com)
* @version 1.0
*/
class INET_API HttpBrowserDirect : public HttpBrowserBase
{
protected:
/** @name cSimpleModule redefinitions */
//@{
/** Initialization of the component and startup of browse event scheduling */
virtual void initialize(int stage);
/** Report final statistics */
virtual void finish();
/** Handle incoming messages. See the parent class for details. */
virtual void handleMessage(cMessage *msg);
/** Returns the number of initialization stages. Two required. */
virtual int numInitStages() const { return 4; }
//@}
protected:
/** @name Implementation of methods for sending requests to a server. See parent class for details. */
//@{
/** Sends a scripted browse event to a specific server */
virtual void sendRequestToServer(BrowseEvent be);
/** Send a request to server. Uses the recipient stamped in the request. */
virtual void sendRequestToServer(HttpRequestMessage *request);
/** Sends a generic request to a randomly chosen server */
virtual void sendRequestToRandomServer();
/** Sends a number of queued messages to the specified server */
virtual void sendRequestsToServer(std::string www, HttpRequestQueue queue);
//@}
};
#endif
| 35.569767 | 110 | 0.647597 |
6944b654bb4e8a3de2f01730914869d478cb4b39 | 77 | sql | SQL | fixtures/doctests/psql-ref/008/input.sql | SKalt/pg_sql_parser_tests | 1e22b4bf2ccecfe0544692e93a6e63113c9db054 | [
"BSD-3-Clause"
] | null | null | null | fixtures/doctests/psql-ref/008/input.sql | SKalt/pg_sql_parser_tests | 1e22b4bf2ccecfe0544692e93a6e63113c9db054 | [
"BSD-3-Clause"
] | null | null | null | fixtures/doctests/psql-ref/008/input.sql | SKalt/pg_sql_parser_tests | 1e22b4bf2ccecfe0544692e93a6e63113c9db054 | [
"BSD-3-Clause"
] | null | null | null | => SELECT 'hello' AS var1, 10 AS var2
-> \gset
=> \echo :var1 :var2
hello 10
| 15.4 | 37 | 0.623377 |
20533806312b0fb8552ee162e5fdcd821f4861f6 | 807 | kt | Kotlin | app/src/main/java/androidx/navigation/fragment/KeepAliveHostFragment.kt | lymons/NavigationUIDemo | 1fdfed0ceb9606aed40f7e5d93807bc1d209bfce | [
"Apache-2.0"
] | null | null | null | app/src/main/java/androidx/navigation/fragment/KeepAliveHostFragment.kt | lymons/NavigationUIDemo | 1fdfed0ceb9606aed40f7e5d93807bc1d209bfce | [
"Apache-2.0"
] | null | null | null | app/src/main/java/androidx/navigation/fragment/KeepAliveHostFragment.kt | lymons/NavigationUIDemo | 1fdfed0ceb9606aed40f7e5d93807bc1d209bfce | [
"Apache-2.0"
] | null | null | null | package androidx.navigation.fragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.navigation.Navigator
class KeepAliveHostFragment: NavHostFragment() {
@Navigator.Name("fragment")
private class InternalKeepAliveNavigator constructor(host: Fragment,
manager: FragmentManager,
containerId: Int
) : KeepAliveNavigator(host, manager, containerId) {
override fun getValidateHostClassName(): String = (KeepAliveHostFragment::class.java).name
}
override fun createFragmentNavigator(): Navigator<out FragmentNavigator.Destination> {
return InternalKeepAliveNavigator(this, childFragmentManager, id)
}
}
| 38.428571 | 98 | 0.675341 |
1bee028fb728d905e25dd2462652e8eab448de2e | 5,699 | py | Python | Bio/KEGG/Compound/__init__.py | rwst/biopython | d8280b25e3fefdf7aebb7700a7080879a4146200 | [
"BSD-3-Clause"
] | 1 | 2019-08-05T02:52:42.000Z | 2019-08-05T02:52:42.000Z | Bio/KEGG/Compound/__init__.py | rwst/biopython | d8280b25e3fefdf7aebb7700a7080879a4146200 | [
"BSD-3-Clause"
] | null | null | null | Bio/KEGG/Compound/__init__.py | rwst/biopython | d8280b25e3fefdf7aebb7700a7080879a4146200 | [
"BSD-3-Clause"
] | 1 | 2019-04-12T20:52:12.000Z | 2019-04-12T20:52:12.000Z | # Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# Copyright 2007 by Michiel de Hoon. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Code to work with the KEGG Ligand/Compound database.
Functions:
- parse - Returns an iterator giving Record objects.
Classes:
- Record - A representation of a KEGG Ligand/Compound.
"""
# other Biopython stuff
from __future__ import print_function
from Bio.KEGG import _write_kegg
from Bio.KEGG import _wrap_kegg
# Set up line wrapping rules (see Bio.KEGG._wrap_kegg)
name_wrap = [0, "",
(" ", "$", 1, 1),
("-", "$", 1, 1)]
id_wrap = lambda indent: [indent, "", (" ", "", 1, 0)]
struct_wrap = lambda indent: [indent, "", (" ", "", 1, 1)]
class Record(object):
"""Holds info from a KEGG Ligand/Compound record.
Attributes:
- entry The entry identifier.
- name A list of the compund names.
- formula The chemical formula for the compound
- mass The molecular weight for the compound
- pathway A list of 3-tuples: ('PATH', pathway id, pathway)
- enzyme A list of the EC numbers.
- structures A list of 2-tuples: (database, list of struct ids)
- dblinks A list of 2-tuples: (database, list of link ids)
"""
def __init__(self):
"""Initialize as new record."""
self.entry = ""
self.name = []
self.formula = ""
self.mass = ""
self.pathway = []
self.enzyme = []
self.structures = []
self.dblinks = []
def __str__(self):
"""Return a string representation of this Record."""
return (self._entry() +
self._name() +
self._formula() +
self._mass() +
self._pathway() +
self._enzyme() +
self._structures() +
self._dblinks() +
"///")
def _entry(self):
return _write_kegg("ENTRY",
[self.entry])
def _name(self):
return _write_kegg("NAME",
[_wrap_kegg(l, wrap_rule=name_wrap)
for l in self.name])
def _formula(self):
return _write_kegg("FORMULA",
[self.formula])
def _mass(self):
return _write_kegg("MASS",
[self.mass])
def _pathway(self):
s = []
for entry in self.pathway:
s.append(entry[0] + " " + entry[1])
return _write_kegg("PATHWAY",
[_wrap_kegg(l, wrap_rule=id_wrap(16))
for l in s])
def _enzyme(self):
return _write_kegg("ENZYME",
[_wrap_kegg(l, wrap_rule=name_wrap)
for l in self.enzyme])
def _structures(self):
s = []
for entry in self.structures:
s.append(entry[0] + ": " + " ".join(entry[1]) + " ")
return _write_kegg("STRUCTURES",
[_wrap_kegg(l, wrap_rule=struct_wrap(5))
for l in s])
def _dblinks(self):
s = []
for entry in self.dblinks:
s.append(entry[0] + ": " + " ".join(entry[1]))
return _write_kegg("DBLINKS",
[_wrap_kegg(l, wrap_rule=id_wrap(9))
for l in s])
def parse(handle):
"""Parse a KEGG Ligan/Compound file, returning Record objects.
This is an iterator function, typically used in a for loop. For
example, using one of the example KEGG files in the Biopython
test suite,
>>> with open("KEGG/compound.sample") as handle:
... for record in parse(handle):
... print("%s %s" % (record.entry, record.name[0]))
...
C00023 Iron
C00017 Protein
C00099 beta-Alanine
C00294 Inosine
C00298 Trypsin
C00348 all-trans-Undecaprenyl phosphate
C00349 2-Methyl-3-oxopropanoate
C01386 NH2Mec
"""
record = Record()
for line in handle:
if line[:3] == "///":
yield record
record = Record()
continue
if line[:12] != " ":
keyword = line[:12]
data = line[12:].strip()
if keyword == "ENTRY ":
words = data.split()
record.entry = words[0]
elif keyword == "NAME ":
data = data.strip(";")
record.name.append(data)
elif keyword == "ENZYME ":
while data:
column = data[:16]
data = data[16:]
enzyme = column.strip()
record.enzyme.append(enzyme)
elif keyword == "PATHWAY ":
map, name = data.split(" ")
pathway = ('PATH', map, name)
record.pathway.append(pathway)
elif keyword == "FORMULA ":
record.formula = data
elif keyword == "MASS ":
record.mass = data
elif keyword == "DBLINKS ":
if ":" in data:
key, values = data.split(":")
values = values.split()
row = (key, values)
record.dblinks.append(row)
else:
row = record.dblinks[-1]
key, values = row
values.extend(data.split())
row = key, values
record.dblinks[-1] = row
if __name__ == "__main__":
from Bio._utils import run_doctest
run_doctest()
| 31.142077 | 70 | 0.511844 |
10c63fdf3b90c65c7a06fb0ceeea5d0e5d91be72 | 2,119 | sql | SQL | deployments/db/migrations/000001_create_schema.down.sql | gamaops/mono-sso | e4f806a850c08063c1f89784fb6cad5ece3d0daf | [
"Apache-2.0"
] | null | null | null | deployments/db/migrations/000001_create_schema.down.sql | gamaops/mono-sso | e4f806a850c08063c1f89784fb6cad5ece3d0daf | [
"Apache-2.0"
] | null | null | null | deployments/db/migrations/000001_create_schema.down.sql | gamaops/mono-sso | e4f806a850c08063c1f89784fb6cad5ece3d0daf | [
"Apache-2.0"
] | null | null | null | DROP SEQUENCE IF EXISTS sso.setup_admin;
ALTER TABLE sso.token DROP CONSTRAINT pk_sso_token;
ALTER TABLE sso.token DROP CONSTRAINT pk_sso_token_id;
ALTER TABLE sso.token DROP CONSTRAINT fk_sso_token_account_id;
ALTER TABLE sso.token DROP CONSTRAINT fk_sso_token_client_id;
ALTER TABLE sso.grant DROP CONSTRAINT pk_sso_grant;
ALTER TABLE sso.grant DROP CONSTRAINT unq_sso_grant_scope_id_account_id;
ALTER TABLE sso.grant DROP CONSTRAINT fk_sso_grant_scope_id;
ALTER TABLE sso.grant DROP CONSTRAINT fk_sso_grant_account_id;
ALTER TABLE sso.scope_i18n DROP CONSTRAINT pk_sso_scope_i18n;
ALTER TABLE sso.scope_i18n DROP CONSTRAINT unq_sso_scope_i18n_scope_id_locale;
ALTER TABLE sso.scope_i18n DROP CONSTRAINT fk_sso_scope_i18n_scope_id;
ALTER TABLE sso.scope DROP CONSTRAINT pk_sso_scope;
ALTER TABLE sso.scope DROP CONSTRAINT unq_sso_scope_id;
ALTER TABLE sso.scope DROP CONSTRAINT unq_sso_scope_scope_client_id;
ALTER TABLE sso.scope DROP CONSTRAINT fk_sso_scope_client_id;
DROP INDEX IF EXISTS idx_sso_scope_scope;
ALTER TABLE sso.client DROP CONSTRAINT pk_sso_client;
ALTER TABLE sso.client DROP CONSTRAINT unq_sso_client_id;
ALTER TABLE sso.account_tenant DROP CONSTRAINT unq_sso_account_tenant;
ALTER TABLE sso.account_tenant DROP CONSTRAINT fk_sso_account_tenant_account_id;
ALTER TABLE sso.account_tenant DROP CONSTRAINT fk_sso_account_tenant_tenant_id;
ALTER TABLE sso.account_identifier DROP CONSTRAINT unq_sso_account_identifier_identifier;
ALTER TABLE sso.account_identifier DROP CONSTRAINT fk_sso_account_identifier_account;
ALTER TABLE sso.account DROP CONSTRAINT pk_sso_account;
ALTER TABLE sso.account DROP CONSTRAINT unq_sso_account_id;
ALTER TABLE sso.tenant DROP CONSTRAINT pk_sso_tenant;
ALTER TABLE sso.tenant DROP CONSTRAINT unq_sso_tenant_id;
DROP TABLE IF EXISTS sso.tenant;
DROP TABLE IF EXISTS sso.account;
DROP TABLE IF EXISTS sso.account_tenant;
DROP TABLE IF EXISTS sso.account_identifier;
DROP TABLE IF EXISTS sso.client;
DROP TABLE IF EXISTS sso.scope;
DROP TABLE IF EXISTS sso.scope_i18n;
DROP TABLE IF EXISTS sso.grant;
DROP TABLE IF EXISTS sso.token;
DROP SCHEMA IF EXISTS sso; | 43.244898 | 89 | 0.858424 |
6b688e5ec552a6762a5bc483fca6f941db0f7539 | 515 | asm | Assembly | oeis/081/A081606.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/081/A081606.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/081/A081606.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A081606: Numbers having at least one 1 in their ternary representation.
; Submitted by Jamie Morken(s1)
; 1,3,4,5,7,9,10,11,12,13,14,15,16,17,19,21,22,23,25,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,55,57,58,59,61,63,64,65,66,67,68,69,70,71,73,75,76,77,79,81,82,83,84,85,86
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
add $0,1
sub $2,1
sub $0,$2
seq $0,88917 ; Central Delannoy numbers (mod 3); Characteristic function for Cantor set.
add $3,$0
lpe
mov $0,$3
add $0,1
| 30.294118 | 208 | 0.660194 |
c453cdde959da9211425fd87b2e7d351928551b9 | 3,395 | h | C | ugene/src/corelibs/U2Core/src/globals/AppResources.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/corelibs/U2Core/src/globals/AppResources.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/corelibs/U2Core/src/globals/AppResources.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef _U2_APPRESOURCES_H_
#define _U2_APPRESOURCES_H_
#include <U2Core/global.h>
#include <QtCore/QHash>
namespace U2 {
/** Thread resource - number of threads */
#define RESOURCE_THREAD 1
/** Memory resource - amount of memory in megabytes */
#define RESOURCE_MEMORY 2
/** CUDA GPU resource - ensures that device is busy or not*/
#define RESOURCE_CUDA_GPU 3
/** OPENCL GPU resource - ensures that device is busy or not*/
#define RESOURCE_OPENCL_GPU 4
/**
Project resource. There is 1 project active in the system and if the resource is locked
no project load/unload operation is possible
*/
#define RESOURCE_PROJECT 5
class U2CORE_EXPORT AppResource {
public:
AppResource(): resourceId(9), currentUse(0), maxUse(0){}
AppResource(int id, int _maxUse, const QString& _name, const QString& _suffix = QString())
: resourceId(id), currentUse(0), maxUse(_maxUse), name(_name), suffix(_suffix){};
virtual ~AppResource(){}
bool isAvailable(int n=1) const {return currentUse + n <= maxUse;}
void acquire(int n=1) {assert(isAvailable(n)); currentUse += n;}
void release(int n=1) {assert(currentUse-n>=0);currentUse -= n;}
int resourceId;
int currentUse;
int maxUse;
QString name;
QString suffix;
};
#define MIN_MEMORY_SIZE 200
class U2CORE_EXPORT AppResourcePool : public QObject {
Q_OBJECT
public:
AppResourcePool();
virtual ~AppResourcePool();
int getIdealThreadCount() const {return idealThreadCount;}
void setIdealThreadCount(int n);
int getMaxThreadCount() const {return threadResource->maxUse;}
void setMaxThreadCount(int n);
int getMaxMemorySizeInMB() const {return memResource->maxUse;}
void setMaxMemorySizeInMB(int m);
static bool getCurrentAppMemory(int& mb); //size in megabytes, false is estimation only is used
static bool isSSE2Enabled();
void registerResource(AppResource* r);
AppResource* getResource(int id) const;
static AppResourcePool* instance();
static int getTotalPhysicalMemory();
static const int x32MaxMemoryLimitMb = 3*512; // 1536Mb
static const int x64MaxMemoryLimitMb = 2*1024*1024; // 2Tb
private:
static const int defaultMemoryLimitMb = 8*1024;
QHash<int, AppResource*> resources;
int idealThreadCount;
AppResource* threadResource;
AppResource* memResource;
AppResource* projectResouce;
AppResource* phyTreeResource;
AppResource* listenLogInGTest;
};
}//namespace
#endif
| 29.521739 | 99 | 0.713991 |
86c5a6dbface8ed4c519a096c5af66bc808c364e | 2,284 | go | Go | client/payment_type/bank_reconciliation_payment_type_get_responses.go | bjerkio/go-tripletex | a4114481e1ddc5203ce42e260a72f71ec19025c8 | [
"Apache-2.0"
] | 1 | 2020-08-01T13:52:41.000Z | 2020-08-01T13:52:41.000Z | client/payment_type/bank_reconciliation_payment_type_get_responses.go | bjerkio/go-tripletex | a4114481e1ddc5203ce42e260a72f71ec19025c8 | [
"Apache-2.0"
] | 19 | 2020-06-22T11:40:00.000Z | 2021-11-11T16:41:23.000Z | client/payment_type/bank_reconciliation_payment_type_get_responses.go | bjerkio/go-tripletex | a4114481e1ddc5203ce42e260a72f71ec19025c8 | [
"Apache-2.0"
] | null | null | null | // Code generated by go-swagger; DO NOT EDIT.
package payment_type
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/bjerkio/tripletex-go/v2/models"
)
// BankReconciliationPaymentTypeGetReader is a Reader for the BankReconciliationPaymentTypeGet structure.
type BankReconciliationPaymentTypeGetReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *BankReconciliationPaymentTypeGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewBankReconciliationPaymentTypeGetOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewBankReconciliationPaymentTypeGetOK creates a BankReconciliationPaymentTypeGetOK with default headers values
func NewBankReconciliationPaymentTypeGetOK() *BankReconciliationPaymentTypeGetOK {
return &BankReconciliationPaymentTypeGetOK{}
}
/*BankReconciliationPaymentTypeGetOK handles this case with default header values.
successful operation
*/
type BankReconciliationPaymentTypeGetOK struct {
Payload *models.ResponseWrapperBankReconciliationPaymentType
}
func (o *BankReconciliationPaymentTypeGetOK) Error() string {
return fmt.Sprintf("[GET /bank/reconciliation/paymentType/{id}][%d] bankReconciliationPaymentTypeGetOK %+v", 200, o.Payload)
}
func (o *BankReconciliationPaymentTypeGetOK) GetPayload() *models.ResponseWrapperBankReconciliationPaymentType {
return o.Payload
}
func (o *BankReconciliationPaymentTypeGetOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ResponseWrapperBankReconciliationPaymentType)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| 32.628571 | 167 | 0.79641 |