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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26b7778db10ef296ab3ff8ebad69887b946bdc91 | 233 | java | Java | citiies-api/src/test/java/com/github/jeffersonklamas/citiiesapi/CitiiesApiApplicationTests.java | jeffersonklamas/api-rest-consulta-cidades | d5e085bde0ab5e4328412ad8b4cd057e66ca4cb4 | [
"MIT"
] | null | null | null | citiies-api/src/test/java/com/github/jeffersonklamas/citiiesapi/CitiiesApiApplicationTests.java | jeffersonklamas/api-rest-consulta-cidades | d5e085bde0ab5e4328412ad8b4cd057e66ca4cb4 | [
"MIT"
] | null | null | null | citiies-api/src/test/java/com/github/jeffersonklamas/citiiesapi/CitiiesApiApplicationTests.java | jeffersonklamas/api-rest-consulta-cidades | d5e085bde0ab5e4328412ad8b4cd057e66ca4cb4 | [
"MIT"
] | null | null | null | package com.github.jeffersonklamas.citiiesapi;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CitiiesApiApplicationTests {
@Test
void contextLoads() {
}
}
| 16.642857 | 60 | 0.802575 |
0a1a559dcefd33545297d5fc4cd6717afc63a205 | 441 | ts | TypeScript | src/index.ts | henrythasler/alexa-skill-tutorial | bb625073c153675ba21396a571fc2e82379fc0ac | [
"MIT"
] | null | null | null | src/index.ts | henrythasler/alexa-skill-tutorial | bb625073c153675ba21396a571fc2e82379fc0ac | [
"MIT"
] | null | null | null | src/index.ts | henrythasler/alexa-skill-tutorial | bb625073c153675ba21396a571fc2e82379fc0ac | [
"MIT"
] | null | null | null | import { SkillBuilders } from 'ask-sdk-core';
import { TutorialSkill } from './tutorial-skill';
const tutorialSkill = new TutorialSkill();
export const handler = SkillBuilders.custom()
.addRequestHandlers(
tutorialSkill.LaunchRequestHandler,
tutorialSkill.HelpIntentHandler,
tutorialSkill.CancelAndStopIntentHandler,
tutorialSkill.SessionEndedRequestHandler
)
.addErrorHandlers()
.lambda();
| 29.4 | 49 | 0.727891 |
c9aafb670ecd808905b22b631c00b8b09fdcb9dd | 2,212 | swift | Swift | FirebaseAuthentication/ViewController.swift | publicvoidgeek/FirebaseAuthenticationP1 | dba34f1ed7ab6710e1e4fc94b19cb3e75697b52c | [
"MIT"
] | null | null | null | FirebaseAuthentication/ViewController.swift | publicvoidgeek/FirebaseAuthenticationP1 | dba34f1ed7ab6710e1e4fc94b19cb3e75697b52c | [
"MIT"
] | null | null | null | FirebaseAuthentication/ViewController.swift | publicvoidgeek/FirebaseAuthenticationP1 | dba34f1ed7ab6710e1e4fc94b19cb3e75697b52c | [
"MIT"
] | null | null | null | //
// ViewController.swift
// FirebaseAuthentication
//
// Created by sanamsuri on 12/08/18.
// Copyright © 2018 sanamsuri. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController {
// Outlets
@IBOutlet weak var emailOu: UITextField!
@IBOutlet weak var passwordOu: UITextField!
// Variables
// Constants
let userDefault = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
if userDefault.bool(forKey: "usersignedin") {
performSegue(withIdentifier: "Segue_To_Signin", sender: self)
}
}
func createUser(email: String, password: String) {
Auth.auth().createUser(withEmail: email, password: password) { ( result, error) in
if error == nil {
// User created
print("User Created")
// Sign in user
self.signInUser(email: email, password: password)
} else {
print(error?.localizedDescription)
}
}
}
func signInUser(email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if error == nil {
// Signed in
print("User Signed In")
self.userDefault.set(true, forKey: "usersignedin")
self.userDefault.synchronize()
self.performSegue(withIdentifier: "Segue_To_Signin", sender: self)
} else if (error?._code == AuthErrorCode.userNotFound.rawValue) {
self.createUser(email: email, password: password)
} else {
print(error)
print(error?.localizedDescription)
}
}
}
// Actions
@IBAction func signInBtnPressed(_ sender: Any) {
signInUser(email: emailOu.text!, password: passwordOu.text!)
}
}
| 23.784946 | 90 | 0.547016 |
952e79905313efa6099434c1a2aa8c4550001a4a | 108 | css | CSS | src/styles.css | yasu-s/overlay-sample | a67e028353ac5ed21c1bdb19528738a5b21f2cd3 | [
"MIT"
] | null | null | null | src/styles.css | yasu-s/overlay-sample | a67e028353ac5ed21c1bdb19528738a5b21f2cd3 | [
"MIT"
] | null | null | null | src/styles.css | yasu-s/overlay-sample | a67e028353ac5ed21c1bdb19528738a5b21f2cd3 | [
"MIT"
] | null | null | null | @import "~@angular/cdk/overlay-prebuilt.css";
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
| 36 | 61 | 0.759259 |
38904f68b3fad133229a985db24c3bf0dbf068c0 | 3,098 | sql | SQL | src/main/resources/conf/oracleScript.sql | sumantrai/ShoppingMart | f746d52578716ec0b59bccc1aa7942147db085a9 | [
"Apache-2.0"
] | null | null | null | src/main/resources/conf/oracleScript.sql | sumantrai/ShoppingMart | f746d52578716ec0b59bccc1aa7942147db085a9 | [
"Apache-2.0"
] | 1 | 2017-09-04T16:56:03.000Z | 2017-09-04T16:56:03.000Z | src/main/resources/conf/oracleScript.sql | sumantrai/ShoppingMart | f746d52578716ec0b59bccc1aa7942147db085a9 | [
"Apache-2.0"
] | null | null | null | create sequence t1_seq start with 1 increment by 1 nomaxvalue;
create sequence t2_seq start with 1 increment by 1 nomaxvalue;
INSERT INTO USER_PROFILE(ID,type)
VALUES (t1_seq.nextval, 'USER');
INSERT INTO USER_PROFILE(ID,type)
VALUES (t1_seq.nextval,'DBA');
INSERT INTO APP_USERS(id,sso_id, password, first_name, last_name, email)
VALUES (t1_seq.nextval,'PURU','$2a$06$cXoaG0fGDQB4KkBB63qA5.dYESECFNf8/0G5lX1tio8ChW2FjuQQm', 'Purusottam','Singh','puru@xyz.com');
INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
SELECT usr.id, profile.ID FROM app_users usr left join user_profile profile
on usr.sso_id='PURU' and profile.type='ADMIN';
CREATE TABLE persistent_logins (
username VARCHAR(64) NOT NULL,
series VARCHAR(64) NOT NULL,
token VARCHAR(64) NOT NULL,
last_used TIMESTAMP NOT NULL,
PRIMARY KEY (series)
);
CREATE TABLE APP_USER_USER_PROFILE (
user_id INT NOT NULL,
user_profile_id INT NOT NULL,
PRIMARY KEY (user_id, user_profile_id),
CONSTRAINT FK_APP_USER FOREIGN KEY (user_id) REFERENCES APP_USERS (id),
CONSTRAINT FK_USER_PROFILE FOREIGN KEY (user_profile_id) REFERENCES USER_PROFILE (id)
);
/*All User's gets stored in APP_USER table*/
create table APP_USER (
id BIGINT NOT NULL AUTO_INCREMENT,
sso_id VARCHAR(30) NOT NULL,
password VARCHAR(100) NOT NULL,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
PRIMARY KEY (id),
UNIQUE (sso_id)
);
/* USER_PROFILE table contains all possible roles */
create table USER_PROFILE(
id BIGINT NOT NULL AUTO_INCREMENT,
type VARCHAR(30) NOT NULL,
PRIMARY KEY (id),
UNIQUE (type)
);
/* JOIN TABLE for MANY-TO-MANY relationship*/
CREATE TABLE APP_USER_USER_PROFILE (
user_id BIGINT NOT NULL,
user_profile_id BIGINT NOT NULL,
PRIMARY KEY (user_id, user_profile_id),
CONSTRAINT FK_APP_USER FOREIGN KEY (user_id) REFERENCES APP_USER (id),
CONSTRAINT FK_USER_PROFILE FOREIGN KEY (user_profile_id) REFERENCES USER_PROFILE (id)
);
/* Populate USER_PROFILE Table */
INSERT INTO USER_PROFILE(type)
VALUES ('USER');
INSERT INTO USER_PROFILE(type)
VALUES ('ADMIN');
INSERT INTO USER_PROFILE(type)
VALUES ('DBA');
/* Populate one Admin User which will further create other users for the application using GUI */
INSERT INTO APP_USER(sso_id, password, first_name, last_name, email)
VALUES ('sam','$2a$10$4eqIF5s/ewJwHK1p8lqlFOEm2QIA0S8g6./Lok.pQxqcxaBZYChRm', 'Sam','Smith','samy@xyz.com');
/* Populate JOIN Table */
INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id)
SELECT user.id, profile.id FROM app_user user, user_profile profile
where user.sso_id='sam' and profile.type='ADMIN';
/* Create persistent_logins Table used to store rememberme related stuff*/
CREATE TABLE persistent_logins (
username VARCHAR(64) NOT NULL,
series VARCHAR(64) NOT NULL,
token VARCHAR(64) NOT NULL,
last_used TIMESTAMP NOT NULL,
PRIMARY KEY (series)
); | 34.422222 | 132 | 0.721433 |
5d1347d971cd2691ad3213e281a5909776a73885 | 140 | kt | Kotlin | basic_apps/task_schedule/app/src/main/java/com/example/taskschedule/entities/UserEntity.kt | LucasGeek/Android-Native-APPS | c4885d49adbd0cd6af461ca5a954bf9f28ce002e | [
"MIT"
] | null | null | null | basic_apps/task_schedule/app/src/main/java/com/example/taskschedule/entities/UserEntity.kt | LucasGeek/Android-Native-APPS | c4885d49adbd0cd6af461ca5a954bf9f28ce002e | [
"MIT"
] | null | null | null | basic_apps/task_schedule/app/src/main/java/com/example/taskschedule/entities/UserEntity.kt | LucasGeek/Android-Native-APPS | c4885d49adbd0cd6af461ca5a954bf9f28ce002e | [
"MIT"
] | null | null | null | package com.example.taskschedule.entities
class UserEntity (val id: Int, val name: String, val email: String, val password: String = "") {} | 46.666667 | 97 | 0.742857 |
bd408506a73ff41c77de6d850103e68027810c08 | 1,093 | rs | Rust | src/main.rs | faraaz-baig/olloor | 70f45b48b6dfb054b1f51ab55842dfcb182fc325 | [
"MIT"
] | null | null | null | src/main.rs | faraaz-baig/olloor | 70f45b48b6dfb054b1f51ab55842dfcb182fc325 | [
"MIT"
] | null | null | null | src/main.rs | faraaz-baig/olloor | 70f45b48b6dfb054b1f51ab55842dfcb182fc325 | [
"MIT"
] | null | null | null | #![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
use rocket::response::Redirect;
mod utils;
#[get("/")]
fn index() -> &'static str {
"Welcome to olloor!"
}
#[get("/search?<cmd>")]
fn search(cmd: String) -> Redirect {
println!("You typed in {}", cmd);
let command = utils::get_command_from_query_string(&cmd);
let redirect_url = match command {
"gh" => utils::github::construct_github_url(&cmd),
"tw" => utils::twitter::construct_twitter_url(&cmd),
"go" => utils::google::construct_google_search_url(&cmd),
"yt" => utils::youtube::construct_youtube_url(&cmd),
"ig" => utils::instagram::construct_instagram_url(&cmd),
"fb" => utils::facebook::construct_facebook_url(&cmd),
"db" => utils::dribbble::construct_dribbble_url(&cmd),
"hn" => utils::hackernews::construct_hackernews_url(&cmd),
_ => utils::duckduckgo::construct_duckduckgo_search_url(&cmd),
};
Redirect::to(redirect_url)
}
fn main() {
rocket::ignite().mount("/", routes![index, search]).launch();
}
| 28.763158 | 70 | 0.638609 |
c7ea9f7b62d0694b1b4217e06daa638d87b66891 | 239 | java | Java | src/main/java/io/github/vampirestudios/obsidian/api/obsidian/TextureAndModelInformation.java | vampire-studios/Obsidian | a1d43a78c14272807954111aec3e6f1dc3acd5fb | [
"CC0-1.0"
] | 3 | 2021-03-03T18:27:08.000Z | 2021-10-18T07:30:53.000Z | src/main/java/io/github/vampirestudios/obsidian/api/obsidian/TextureAndModelInformation.java | vampire-studios/Obsidian | a1d43a78c14272807954111aec3e6f1dc3acd5fb | [
"CC0-1.0"
] | 4 | 2021-08-02T07:48:34.000Z | 2021-08-03T17:03:16.000Z | src/main/java/io/github/vampirestudios/obsidian/api/obsidian/TextureAndModelInformation.java | vampire-studios/Obsidian | a1d43a78c14272807954111aec3e6f1dc3acd5fb | [
"CC0-1.0"
] | 2 | 2020-12-04T18:47:14.000Z | 2021-01-09T00:03:22.000Z | package io.github.vampirestudios.obsidian.api.obsidian;
import net.minecraft.util.Identifier;
import java.util.Map;
public class TextureAndModelInformation {
public Map<String, Identifier> textures;
public Identifier parent;
} | 19.916667 | 55 | 0.790795 |
437bedebb256fe41023d70a8b4d2313d4a24d111 | 11,383 | go | Go | service/endpoint.go | jirenius/rest2res | 9a64fa84fea1eb741368be5875aea096f59ce32a | [
"MIT"
] | 12 | 2019-05-07T01:30:30.000Z | 2021-12-12T14:57:06.000Z | service/endpoint.go | jirenius/rest2res | 9a64fa84fea1eb741368be5875aea096f59ce32a | [
"MIT"
] | null | null | null | service/endpoint.go | jirenius/rest2res | 9a64fa84fea1eb741368be5875aea096f59ce32a | [
"MIT"
] | null | null | null | package service
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
res "github.com/jirenius/go-res"
"github.com/jirenius/timerqueue"
)
type endpoint struct {
s *Service
url string
urlParams []string
refreshCount int
cachedURLs map[string]*cachedResponse
access res.AccessHandler
timeout time.Duration
group string
resetPatterns []string
tq *timerqueue.Queue
mu sync.RWMutex
node
}
type cachedResponse struct {
reloads int
reqParams map[string]string
crs map[string]cachedResource
rerr *res.Error
}
type cachedResource struct {
typ resourceType
model map[string]interface{}
collection []interface{}
}
type resourceType byte
const defaultRefreshDuration = time.Second * 3
const (
resourceTypeUnset resourceType = iota
resourceTypeModel
resourceTypeCollection
)
func newEndpoint(s *Service, cep *EndpointCfg) (*endpoint, error) {
if cep.URL == "" {
return nil, errors.New("missing url")
}
if cep.Pattern == "" {
return nil, errors.New("missing pattern")
}
urlParams, err := urlParams(cep.URL)
if err != nil {
return nil, err
}
ep := &endpoint{
s: s,
url: cep.URL,
urlParams: urlParams,
refreshCount: cep.RefreshCount,
cachedURLs: make(map[string]*cachedResponse),
access: cep.Access,
timeout: time.Millisecond * time.Duration(cep.Timeout),
}
ep.tq = timerqueue.New(ep.handleRefresh, time.Millisecond*time.Duration(cep.RefreshTime))
return ep, nil
}
func (ep *endpoint) handler() res.Handler {
return res.Handler{
Access: ep.access,
GetResource: ep.getResource,
Group: ep.url,
}
}
func (ep *endpoint) handleRefresh(i interface{}) {
ep.s.Debugf("Refreshing %s", i)
url := i.(string)
// Check if url is cached
ep.mu.RLock()
cresp, ok := ep.cachedURLs[url]
ep.mu.RUnlock()
if !ok {
ep.s.Logf("Url %s not found in cache on refresh", url)
return
}
params := cresp.reqParams
ep.s.res.WithGroup(url, func(s *res.Service) {
cresp.reloads++
if cresp.rerr != nil || cresp.reloads > ep.refreshCount {
// Reset resources
ep.mu.Lock()
delete(ep.cachedURLs, url)
ep.mu.Unlock()
resetResources := make([]string, len(ep.resetPatterns))
for i, rp := range ep.resetPatterns {
for _, param := range ep.urlParams {
rp = strings.Replace(rp, "${"+param+"}", params[param], 1)
}
resetResources[i] = rp
}
ep.s.res.Reset(resetResources, nil)
return
}
defer ep.tq.Add(i)
ncresp := ep.getURL(url, params)
if ncresp.rerr != nil {
ep.s.Logf("Error refreshing url %s:\n\t%s", url, ncresp.rerr.Message)
return
}
for rid, nv := range ncresp.crs {
v, ok := cresp.crs[rid]
if ok {
r, err := ep.s.res.Resource(rid)
if err != nil {
// This shouldn't be possible. Let's panic.
panic(fmt.Sprintf("error getting res resource %s:\n\t%s", rid, err))
}
updateResource(v, nv, r)
delete(cresp.crs, rid)
}
}
// for rid := range cresp.crs {
// r, err := ep.s.res.Resource(rid)
// r.DeleteEvent()
// }
// Replacing the old cachedResources with the new ones
cresp.crs = ncresp.crs
})
}
func updateResource(v, nv cachedResource, r res.Resource) {
switch v.typ {
case resourceTypeModel:
updateModel(v.model, nv.model, r)
case resourceTypeCollection:
updateCollection(v.collection, nv.collection, r)
}
}
func updateModel(a, b map[string]interface{}, r res.Resource) {
ch := make(map[string]interface{})
for k := range a {
if _, ok := b[k]; !ok {
ch[k] = res.DeleteAction
}
}
for k, v := range b {
ov, ok := a[k]
if !(ok && reflect.DeepEqual(v, ov)) {
ch[k] = v
}
}
r.ChangeEvent(ch)
}
func updateCollection(a, b []interface{}, r res.Resource) {
var i, j int
// Do a LCS matric calculation
// https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
s := 0
m := len(a)
n := len(b)
// Trim of matches at the start and end
for s < m && s < n && reflect.DeepEqual(a[s], b[s]) {
s++
}
if s == m && s == n {
return
}
for s < m && s < n && reflect.DeepEqual(a[m-1], b[n-1]) {
m--
n--
}
var aa, bb []interface{}
if s > 0 || m < len(a) {
aa = a[s:m]
m = m - s
} else {
aa = a
}
if s > 0 || n < len(b) {
bb = b[s:n]
n = n - s
} else {
bb = b
}
// Create matrix and initialize it
w := m + 1
c := make([]int, w*(n+1))
for i = 0; i < m; i++ {
for j = 0; j < n; j++ {
if reflect.DeepEqual(aa[i], bb[j]) {
c[(i+1)+w*(j+1)] = c[i+w*j] + 1
} else {
v1 := c[(i+1)+w*j]
v2 := c[i+w*(j+1)]
if v2 > v1 {
c[(i+1)+w*(j+1)] = v2
} else {
c[(i+1)+w*(j+1)] = v1
}
}
}
}
idx := m + s
i = m
j = n
rm := 0
var adds [][3]int
addCount := n - c[w*(n+1)-1]
if addCount > 0 {
adds = make([][3]int, 0, addCount)
}
Loop:
for {
m = i - 1
n = j - 1
switch {
case i > 0 && j > 0 && reflect.DeepEqual(aa[m], bb[n]):
idx--
i--
j--
case j > 0 && (i == 0 || c[i+w*n] >= c[m+w*j]):
adds = append(adds, [3]int{n, idx, rm})
j--
case i > 0 && (j == 0 || c[i+w*n] < c[m+w*j]):
idx--
r.RemoveEvent(idx)
rm++
i--
default:
break Loop
}
}
// Do the adds
l := len(adds) - 1
for i := l; i >= 0; i-- {
add := adds[i]
r.AddEvent(bb[add[0]], add[1]-rm+add[2]+l-i)
}
}
func (ep *endpoint) getResource(r res.GetRequest) {
// Replace param placeholders
url := ep.url
for _, param := range ep.urlParams {
url = strings.Replace(url, "${"+param+"}", r.PathParam(param), 1)
}
// Check if url is cached
ep.mu.RLock()
cresp, ok := ep.cachedURLs[url]
ep.mu.RUnlock()
if !ok {
if ep.timeout > 0 {
r.Timeout(ep.timeout)
}
cresp = ep.cacheURL(url, r.PathParams())
}
// Return any encountered error when getting the endpoint
if cresp.rerr != nil {
r.Error(cresp.rerr)
return
}
// Check if resource exists
cr, ok := cresp.crs[r.ResourceName()]
if !ok {
r.NotFound()
return
}
switch cr.typ {
case resourceTypeModel:
r.Model(cr.model)
case resourceTypeCollection:
r.Collection(cr.collection)
}
}
func (ep *endpoint) cacheURL(url string, reqParams map[string]string) *cachedResponse {
cresp := ep.getURL(url, reqParams)
ep.mu.Lock()
ep.cachedURLs[url] = cresp
ep.mu.Unlock()
ep.tq.Add(url)
return cresp
}
func (ep *endpoint) getURL(url string, reqParams map[string]string) *cachedResponse {
cr := cachedResponse{reqParams: reqParams}
// Make HTTP request
resp, err := http.Get(url)
if err != nil {
ep.s.Debugf("Error fetching endpoint: %s\n\t%s", url, err)
cr.rerr = res.InternalError(err)
return &cr
}
defer resp.Body.Close()
// Handle non-2XX status codes
if resp.StatusCode == 404 {
cr.rerr = res.ErrNotFound
return &cr
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
cr.rerr = res.InternalError(fmt.Errorf("unexpected response code: %d", resp.StatusCode))
return &cr
}
// Read body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
cr.rerr = res.InternalError(err)
return &cr
}
// Unmarshal body
var v value
if err = json.Unmarshal(body, &v); err != nil {
cr.rerr = res.InternalError(err)
return &cr
}
// Traverse the data
crs := make(map[string]cachedResource)
err = ep.traverse(crs, v, nil, reqParams)
if err != nil {
cr.rerr = res.InternalError(fmt.Errorf("invalid data structure for %s: %s", url, err))
return &cr
}
cr.crs = crs
return &cr
}
func (ep *endpoint) traverse(crs map[string]cachedResource, v value, path []string, reqParams map[string]string) error {
var err error
switch v.typ {
case valueTypeObject:
_, err = traverseModel(crs, v, path, &ep.node, reqParams, "")
case valueTypeArray:
_, err = traverseCollection(crs, v, path, &ep.node, reqParams, "")
default:
return errors.New("endpoint didn't respond with a json object or array")
}
if err != nil {
return err
}
return nil
}
func traverseModel(crs map[string]cachedResource, v value, path []string, n *node, reqParams map[string]string, pathPart string) (res.Ref, error) {
if n.typ != resourceTypeModel {
return "", fmt.Errorf("expected a model at %s", pathStr(path))
}
// Append path part
switch n.ptyp {
case pathTypeDefault:
path = append(path, pathPart)
case pathTypeProperty:
idv, ok := v.obj[n.idProp]
if !ok {
return "", fmt.Errorf("missing id property %s at:\n\t%s", n.idProp, pathStr(path))
}
switch idv.typ {
case valueTypeString:
var idstr string
err := json.Unmarshal(idv.raw, &idstr)
if err != nil {
return "", err
}
path = append(path, idstr)
case valueTypeNumber:
path = append(path, string(idv.raw))
default:
return "", fmt.Errorf("invalid id value for property %s at:\n\t%s", n.idProp, pathStr(path))
}
path = append(path)
}
model := make(map[string]interface{})
for k, kv := range v.obj {
// Get next node
next := n.nodes[k]
if next == nil {
next = n.param
}
switch kv.typ {
case valueTypeObject:
if next != nil {
ref, err := traverseModel(crs, kv, path, next, reqParams, k)
if err != nil {
return "", err
}
model[k] = ref
}
case valueTypeArray:
if next != nil {
ref, err := traverseCollection(crs, kv, path, next, reqParams, k)
if err != nil {
return "", err
}
model[k] = ref
}
default:
if next != nil {
return "", fmt.Errorf("unexpected primitive value for property %s at %s", k, pathStr(path))
}
model[k] = kv
}
}
// Create rid
p := make([]interface{}, len(n.params))
for j, pp := range n.params {
switch pp.typ {
case paramTypeURL:
p[j] = reqParams[pp.name]
case paramTypePath:
p[j] = path[pp.idx]
}
}
rid := fmt.Sprintf(n.pattern, p...)
crs[rid] = cachedResource{
typ: resourceTypeModel,
model: model,
}
return res.Ref(rid), nil
}
func traverseCollection(crs map[string]cachedResource, v value, path []string, n *node, reqParams map[string]string, pathPart string) (res.Ref, error) {
if n.typ != resourceTypeCollection {
return "", fmt.Errorf("expected a collection at %s", pathStr(path))
}
if n.ptyp != pathTypeRoot {
// Append path part
path = append(path, pathPart)
}
collection := make([]interface{}, len(v.arr))
for j, kv := range v.arr {
next := n.param
switch kv.typ {
case valueTypeObject:
if next != nil {
ref, err := traverseModel(crs, kv, path, next, reqParams, strconv.Itoa(j))
if err != nil {
return "", err
}
collection[j] = ref
}
case valueTypeArray:
if next != nil {
ref, err := traverseCollection(crs, kv, path, next, reqParams, strconv.Itoa(j))
if err != nil {
return "", err
}
collection[j] = ref
}
default:
if next != nil {
return "", fmt.Errorf("unexpected primitive value for element %d at %s", j, pathStr(path))
}
collection[j] = kv
}
}
// Create rid
p := make([]interface{}, len(n.params))
for k, pp := range n.params {
switch pp.typ {
case paramTypeURL:
p[k] = reqParams[pp.name]
case paramTypePath:
p[k] = path[pp.idx]
}
}
rid := fmt.Sprintf(n.pattern, p...)
crs[rid] = cachedResource{
typ: resourceTypeCollection,
collection: collection,
}
return res.Ref(rid), nil
}
func pathStr(path []string) string {
if len(path) == 0 {
return "endpoint root"
}
return strings.Join(path, ".")
}
| 21.118738 | 152 | 0.612844 |
77d7b261ad1febba3308206e114ebff010e09836 | 6,061 | rs | Rust | src/lib.rs | y-fujii/nanore | e9ee360de11c49109a45829cb85d4c21db270e22 | [
"MIT"
] | null | null | null | src/lib.rs | y-fujii/nanore | e9ee360de11c49109a45829cb85d4c21db270e22 | [
"MIT"
] | null | null | null | src/lib.rs | y-fujii/nanore | e9ee360de11c49109a45829cb85d4c21db270e22 | [
"MIT"
] | null | null | null | // (c) Yasuhiro Fujii <http://mimosa-pudica.net>, under MIT License.
use std::*;
pub enum RegEx<'a, T, U: Copy = ()> {
Eps,
Atom( Box<dyn 'a + Fn( usize, &T ) -> bool> ),
Alt( Box<RegEx<'a, T, U>>, Box<RegEx<'a, T, U>> ),
Seq( Box<RegEx<'a, T, U>>, Box<RegEx<'a, T, U>>, usize ),
Repeat( Box<RegEx<'a, T, U>>, usize ),
Weight( isize ),
Mark( U ),
}
impl<'a, T, U: Copy> ops::Add for Box<RegEx<'a, T, U>> {
type Output = Box<RegEx<'a, T, U>>;
fn add( self, other: Self ) -> Self::Output {
Box::new( RegEx::Alt( self, other ) )
}
}
impl<'a, T, U: Copy> ops::Mul for Box<RegEx<'a, T, U>> {
type Output = Box<RegEx<'a, T, U>>;
fn mul( self, other: Self ) -> Self::Output {
Box::new( RegEx::Seq( self, other, usize::MAX ) )
}
}
pub fn eps<'a, T, U: Copy>() -> Box<RegEx<'a, T, U>> {
Box::new( RegEx::Eps )
}
pub fn atom<'a, T, U: Copy, F: 'a + Fn( usize, &T ) -> bool>( f: F ) -> Box<RegEx<'a, T, U>> {
Box::new( RegEx::Atom( Box::new( f ) ) )
}
pub fn rep<'a, T, U: Copy>( e0: Box<RegEx<'a, T, U>> ) -> Box<RegEx<'a, T, U>> {
Box::new( RegEx::Repeat( e0, usize::MAX ) )
}
pub fn weight<'a, T, U: Copy>( w: isize ) -> Box<RegEx<'a, T, U>> {
Box::new( RegEx::Weight( w ) )
}
pub fn mark<'a, T, U: Copy>( m: U ) -> Box<RegEx<'a, T, U>> {
Box::new( RegEx::Mark( m ) )
}
pub fn opt<'a, T, U: Copy>( e0: Box<RegEx<'a, T, U>> ) -> Box<RegEx<'a, T, U>> {
eps() + e0
}
pub fn any<'a, T, U: Copy>() -> Box<RegEx<'a, T, U>> {
atom( move |_, _| true )
}
pub fn val<'a, T: 'a + PartialEq, U: Copy>( v0: T ) -> Box<RegEx<'a, T, U>> {
atom( move |_, v| *v == v0 )
}
pub struct RegExRoot<'a, T, U: Copy = ()> {
regex: Box<RegEx<'a, T, U>>,
nstate: usize,
}
impl<'a, T, U: Copy> RegExRoot<'a, T, U> {
pub fn new( mut e: Box<RegEx<'a, T, U>> ) -> RegExRoot<'a, T, U> {
let n = Self::renumber( &mut e, 0 );
RegExRoot{
regex: e,
nstate: n,
}
}
fn renumber( e: &mut RegEx<'a, T, U>, i: usize ) -> usize {
match *e {
RegEx::Eps => i,
RegEx::Atom( _ ) => i,
RegEx::Alt( ref mut e0, ref mut e1 ) => {
Self::renumber( e1, Self::renumber( e0, i ) )
}
RegEx::Seq( ref mut e0, ref mut e1, ref mut s ) => {
*s = Self::renumber( e0, i );
Self::renumber( e1, *s + 1 )
}
RegEx::Repeat( ref mut e0, ref mut s ) => {
*s = i;
Self::renumber( e0, i + 1 )
}
RegEx::Weight( _ ) => i,
RegEx::Mark( _ ) => i,
}
}
}
struct Path<T>( usize, T, Option<rc::Rc<Path<T>>> );
#[derive( Clone )]
struct State<T>( isize, Option<rc::Rc<Path<T>>> );
#[derive( Clone )]
pub struct Matcher<'a, T, U: Copy = ()> {
root: &'a RegExRoot<'a, T, U>,
index: usize,
s0: State<U>,
states: Vec<State<U>>,
s1: State<U>,
}
impl<'a, T, U: Copy> Matcher<'a, T, U> {
pub fn new( root: &'a RegExRoot<'a, T, U> ) -> Matcher<'a, T, U> {
let mut this = Matcher{
root: root,
index: 0,
s0: State( 0, None ),
states: vec![ State( isize::MAX, None ); root.nstate ],
s1: State( isize::MAX, None ),
};
this.s1 = this.propagate( &root.regex, State( 0, None ) );
this
}
pub fn feed( &mut self, v: &T ) {
let s0 = mem::replace( &mut self.s0, State( isize::MAX, None ) );
let s1 = self.shift( &self.root.regex, v, s0 );
self.index += 1;
let s2 = self.propagate( &self.root.regex, State( isize::MAX, None ) );
self.s1 = Self::choice( s1, s2 );
}
pub fn feed_iter<'b, Iter: IntoIterator<Item = &'b T>>( &mut self, iter: Iter ) where 'a: 'b {
for v in iter {
self.feed( v );
}
}
pub fn is_match( &self ) -> bool {
self.s1.0 != isize::MAX
}
pub fn is_alive( &self ) -> bool {
self.s0.0 != isize::MAX ||
self.s1.0 != isize::MAX ||
self.states.iter().any( |s| s.0 != isize::MAX )
}
pub fn path( &self ) -> Vec<(usize, U)> {
let mut result = Vec::new();
let mut it = self.s1.1.clone();
while let Some( e ) = it {
result.push( (e.0, e.1) );
it = e.2.clone();
}
result.reverse();
result
}
fn choice( s0: State<U>, s1: State<U> ) -> State<U> {
if s1.0 < s0.0 { s1 } else { s0 }
}
fn choice_inplace( s0: &mut State<U>, s1: State<U> ) {
if s1.0 < s0.0 {
*s0 = s1;
}
}
// handle epsilon transition.
fn propagate( &mut self, e: &RegEx<'a, T, U>, s0: State<U> ) -> State<U> {
match *e {
RegEx::Eps => s0,
RegEx::Atom( _ ) => State( isize::MAX, None ),
RegEx::Alt( ref e0, ref e1 ) => {
let s1 = self.propagate( e0, s0.clone() );
let s2 = self.propagate( e1, s0 );
Self::choice( s1, s2 )
}
RegEx::Seq( ref e0, ref e1, s ) => {
let s1 = self.propagate( e0, s0 );
Self::choice_inplace( &mut self.states[s], s1 );
let s2 = self.states[s].clone();
self.propagate( e1, s2 )
}
RegEx::Repeat( ref e0, s ) => {
Self::choice_inplace( &mut self.states[s], s0 );
let s1 = self.states[s].clone();
let s2 = self.propagate( e0, s1 );
Self::choice_inplace( &mut self.states[s], s2 );
self.states[s].clone()
}
RegEx::Weight( w ) => {
let dw = if s0.0 != isize::MAX { w } else { 0 };
State( s0.0 + dw, s0.1 )
}
RegEx::Mark( m ) => {
State( s0.0, Some( rc::Rc::new( Path( self.index, m, s0.1 ) ) ) )
}
}
}
// handle normal transition.
fn shift( &mut self, e: &RegEx<'a, T, U>, v: &T, s0: State<U> ) -> State<U> {
match *e {
RegEx::Eps => State( isize::MAX, None ),
RegEx::Atom( ref f ) => {
if s0.0 != isize::MAX && f( self.index, v ) {
s0
}
else {
State( isize::MAX, None )
}
}
RegEx::Alt( ref e0, ref e1 ) => {
let s1 = self.shift( e0, v, s0.clone() );
let s2 = self.shift( e1, v, s0 );
Self::choice( s1, s2 )
}
RegEx::Seq( ref e0, ref e1, s ) => {
let s1 = self.shift( e0, v, s0 );
let s2 = mem::replace( &mut self.states[s], s1 );
self.shift( e1, v, s2 )
}
RegEx::Repeat( ref e0, s ) => {
let s1 = mem::replace( &mut self.states[s], State( isize::MAX, None ) );
self.states[s] = self.shift( e0, v, s1 );
State( isize::MAX, None )
}
RegEx::Weight( _ ) => State( isize::MAX, None ),
RegEx::Mark( _ ) => State( isize::MAX, None ),
}
}
}
| 25.791489 | 95 | 0.519881 |
e5243bcaf71ccb5aaa825244f3d85a3ec0bf22aa | 1,540 | ts | TypeScript | src/services/input.ts | petli-full/awk-vscode | 849f40f8b6ad81a5472817688b702d15f916c477 | [
"MIT"
] | 2 | 2021-03-26T15:36:14.000Z | 2021-07-28T05:48:07.000Z | src/services/input.ts | petli-full/awk-vscode | 849f40f8b6ad81a5472817688b702d15f916c477 | [
"MIT"
] | 1 | 2021-07-28T05:50:13.000Z | 2021-08-09T02:03:48.000Z | src/services/input.ts | petli-full/awk-vscode | 849f40f8b6ad81a5472817688b702d15f916c477 | [
"MIT"
] | 1 | 2021-03-26T15:36:17.000Z | 2021-03-26T15:36:17.000Z | import * as vscode from 'vscode';
interface Input {
load: () => void;
reset: () => void;
ready: (text: string) => Thenable<vscode.TextEditor>;
get: () => string;
getFilename: () => string;
};
let _input = '';
let _filename = '';
const load = () => {
const doc = vscode.window.activeTextEditor?.document;
_input = (doc ? doc.getText() : '').trim();
_filename = (doc ? doc.fileName : '').trim();
};
let editor$: null | Thenable<vscode.TextEditor> = null;
let _editor: null | vscode.TextEditor = null;
const reset = () => {
_input = '';
editor$ = null;
_editor = null;
};
const ready = (text: string): Thenable<vscode.TextEditor> => {
if (editor$ === null || (_editor !== null && _editor.document.isClosed)) {
_input = text;
editor$ = vscode.workspace.openTextDocument({ language: 'plaintext', content: '' }).then(doc => {
return vscode.window.showTextDocument(doc).then(editor => {
editor.edit(builder => {
builder.insert(doc.positionAt(0), text);
}).then(() => editor);
_editor = editor;
return editor;
});
});
return editor$;
} else if (_editor === null) {
return editor$.then(() => ready(text));
}
return editor$;
};
const get = (): string => {
return _input;
};
const getFilename = (): string => {
return _filename;
};
export const input: Input = {
load,
reset,
ready,
get,
getFilename,
};
| 23.333333 | 105 | 0.54026 |
9bcfbdba03c390d467d143b80aeb1358f0fb9694 | 1,881 | js | JavaScript | ForumArchive/acc/post_34226_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 136 | 2015-01-01T17:33:35.000Z | 2022-02-26T16:38:08.000Z | ForumArchive/acc/post_34226_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 60 | 2015-06-20T00:39:16.000Z | 2021-09-02T22:55:27.000Z | ForumArchive/acc/post_34226_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 141 | 2015-04-29T09:50:11.000Z | 2022-03-18T09:20:44.000Z | [{"Owner":"JackFalcon","Date":"2017-11-26T22:09:00Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tHello_co_\n_lt_/p_gt_\n\n_lt_p_gt_\n\t _lt_em_gt_What is the simplest OR best way to_lt_/em_gt_ _lt_em_gt_get a cube to copy a footIK bone transforms (location/rotation) AND export successfully?_lt_/em_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\t When the right foot IK is posed_co_ the cube mimics the transform in Blender_co_ but on _lt_em_gt_export _lt_/em_gt_the cube has no animation.\n_lt_/p_gt_\n\n_lt_p_gt_\n\t How to get the cube to mimic the footIK transform?\n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n_lt_p_gt_\n\t NOTE_dd_ not a case of applying transforms (did that). _lt_img alt_eq__qt__dd_)_qt_ data-emoticon_eq__qt__qt_ height_eq__qt_20_qt_ src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ title_eq__qt__dd_)_qt_ width_eq__qt_20_qt_ /_gt_ \n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"JackFalcon","Date":"2017-11-27T00:30:34Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tUPDATE_dd_ think I found a solution method that exports the animation....\n_lt_/p_gt_\n\n_lt_p_gt_\n\t- parent cube bone to foot bone... while parenting to ikbone does not(?) \n_lt_/p_gt_\n\n_lt_p_gt_\n\tSOLVED_dd_ used foot bone as a copy transform (via bone parenting)_co_ not using IK_co_\n_lt_/p_gt_\n\n_lt_p_gt_\n\tand not using modifiers_co_ or mesh parenting (did not export animation).\n_lt_/p_gt_\n\n_lt_p_gt_\n\tStill curious_co_ any technical reason why that happens?\n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"}] | 1,881 | 1,881 | 0.805423 |
39ee5187e73b27be3e9e31c5b2137c0557963a1e | 2,741 | java | Java | odps-console-basic/src/test/java/com/aliyun/openservices/odps/console/commands/UseProjectCommandTest.java | aliyun/aliyun-odps-console | c67d38afd8d8cae493e806f92083e783b2b4c930 | [
"Apache-2.0"
] | 75 | 2015-12-07T07:40:09.000Z | 2022-02-05T09:37:35.000Z | odps-console-basic/src/test/java/com/aliyun/openservices/odps/console/commands/UseProjectCommandTest.java | aliyun/aliyun-odps-console | c67d38afd8d8cae493e806f92083e783b2b4c930 | [
"Apache-2.0"
] | 22 | 2016-09-01T16:25:34.000Z | 2021-12-09T22:03:38.000Z | odps-console-basic/src/test/java/com/aliyun/openservices/odps/console/commands/UseProjectCommandTest.java | aliyun/aliyun-odps-console | c67d38afd8d8cae493e806f92083e783b2b4c930 | [
"Apache-2.0"
] | 25 | 2016-06-02T05:27:51.000Z | 2021-07-14T07:31:11.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyun.openservices.odps.console.commands;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.Test;
import com.aliyun.odps.OdpsException;
import com.aliyun.openservices.odps.console.ExecutionContext;
import com.aliyun.openservices.odps.console.ODPSConsoleException;
import com.aliyun.openservices.odps.console.utils.ODPSConsoleUtils;
/**
* Created by nizheming on 15/6/19.
*/
public class UseProjectCommandTest {
@Test
public void testHttps() throws ODPSConsoleException, OdpsException, IOException {
ExecutionContext ctx = ExecutionContext.init();
Properties properties = new Properties();
properties.load(new FileInputStream(ODPSConsoleUtils.getConfigFilePath()));
String endpoint = (String) properties.get("https_end_point");
ctx.setEndpoint(endpoint);
UseProjectCommand command = UseProjectCommand.parse("use " + ctx.getProjectName(), ctx);
command.run();
String result = command.getMsg();
assertEquals(result,"WARNING: untrusted https connection:'" + endpoint + "', add https_check=true in config file to avoid this warning.");
}
@Test(expected = RuntimeException.class)
public void testHttpsNeg() throws ODPSConsoleException, OdpsException, IOException {
ExecutionContext ctx = ExecutionContext.init();
ctx.setHttpsCheck(true);
Properties properties = new Properties();
properties.load(new FileInputStream(ODPSConsoleUtils.getConfigFilePath()));
String endpoint = (String) properties.get("https_end_point");
ctx.setEndpoint(endpoint);
UseProjectCommand command = UseProjectCommand.parse("use " + ctx.getProjectName(), ctx);
command.run();
String result = command.getMsg();
assertEquals(result,"WARNING: untrusted https connection:'" + endpoint + "', add https_check=true in config file to avoid this warning.");
}
} | 41.530303 | 142 | 0.756658 |
e8da2871c87cf2076690059ef9b906d674072b5a | 846 | py | Python | setup.py | stshrive/pycense | 5bfd1b7b6b326a5592f58d621ee596c6c1d8a490 | [
"MIT"
] | null | null | null | setup.py | stshrive/pycense | 5bfd1b7b6b326a5592f58d621ee596c6c1d8a490 | [
"MIT"
] | 5 | 2018-09-15T23:40:11.000Z | 2018-10-05T22:57:13.000Z | setup.py | stshrive/pycense | 5bfd1b7b6b326a5592f58d621ee596c6c1d8a490 | [
"MIT"
] | 1 | 2018-10-04T23:43:42.000Z | 2018-10-04T23:43:42.000Z | import os
import setuptools
VERSION = "1.0.0a1+dev"
INSTALL_REQUIRES = [
'pip-licenses',
]
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research'
]
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setuptools.setup(
name='pycense',
version="0.1.0",
description='Python package license inspector.',
long_description=read('README.md'),
license='MIT',
author='Microsoft Corporation',
author_email='stshrive@microsoft.com', # TODO: not one person :)
url='https://github.com/stshrive/pycense',
zip_safe=True,
classifiers=CLASSIFIERS,
entry_points = {'console_scripts': ['pycense=pycense.__main__:__main__']},
packages=['pycense',],
install_requires=INSTALL_REQUIRES
)
| 24.171429 | 78 | 0.682033 |
85c53ce72352eb5ab455b7e5f441dcce40e527de | 1,525 | js | JavaScript | IzendaHours/Resources/js/charts.js | shaheinm/IzendaHours | a9ba1f99b07f4e0958d28ea5c963b4a82adf6482 | [
"MIT"
] | null | null | null | IzendaHours/Resources/js/charts.js | shaheinm/IzendaHours | a9ba1f99b07f4e0958d28ea5c963b4a82adf6482 | [
"MIT"
] | null | null | null | IzendaHours/Resources/js/charts.js | shaheinm/IzendaHours | a9ba1f99b07f4e0958d28ea5c963b4a82adf6482 | [
"MIT"
] | 2 | 2015-04-16T19:00:09.000Z | 2016-10-17T22:23:05.000Z | // Copyright (c) 2005-2013 Izenda, L.L.C. - ALL RIGHTS RESERVED
// Add new chart
jq$(function () {
jq$('#add_chart').dialog({
autoOpen: true,
width: 960,
height: "auto", height: 640,
modal: true,
buttons: {
"Continue": function () {
jq$(this).dialog("close");
}
},
show: {
effect: 'fade',
duration: 200,
},
hide: {
effect: 'fade',
duration: 200,
}
});
// Dialog Link
jq$('#dialog_link').click(function () {
jq$('#dialog').dialog('open');
return false;
});
jq$('#add_chart_link').click(function () {
jq$('#add_chart').dialog('open');
return false;
});
jq$('.ui-widget-overlay').live("click", function () {
//Close the dialog
jq$("#add_chart").dialog("close");
jq$("#dialog").dialog("close");
});
jq$(function () {
jq$("#v-tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
});
});
jq$(document).keydown(function (e)
{
if (e.which == 116) // key code of the F5 button
{
document.location.reload();
}
});
jq$(document).ready(function () {
// $("#myModal").modal("show");
jq$(".chart-type-selector").parent().parent().addClass("has-chart-type-selector");
jq$('a[href="#edit_title"], .h2').live("click", function (event) {
event.preventDefault();
event.stopPropagation();
jq$(this).closest("h2").find("input").removeClass("h2").focus().focusout(function () {
jq$(this).closest("h2").find("input").addClass("h2");
});
});
});
| 21.180556 | 89 | 0.552787 |
94934d1dfca33a45aef8251c83df70e450e389fb | 636 | asm | Assembly | oeis/028/A028403.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/028/A028403.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/028/A028403.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A028403: Number of types of Boolean functions of n variables under a certain group.
; 4,12,40,144,544,2112,8320,33024,131584,525312,2099200,8392704,33562624,134234112,536903680,2147549184,8590065664,34360000512,137439477760,549756862464,2199025352704,8796097216512,35184380477440,140737505132544,562949986975744,2251799880794112,9007199388958720,36028797287399424,144115188612726784,576460753377165312,2305843011361177600,9223372041149743104,36893488156009037824,147573952606856282112,590295810393065390080,2361183241503542083584,9444732965876729380864,37778931863232039616512
mov $1,2
pow $1,$0
add $1,1
bin $1,2
mul $1,4
mov $0,$1
| 63.6 | 492 | 0.866352 |
16a12c8c14d9b48388a320989435b95228d455a2 | 165 | h | C | src/KFEnums.h | DrData/ukf | 75770bbf92e7fc90ea007a9512e7b23d784ccf5c | [
"MIT"
] | null | null | null | src/KFEnums.h | DrData/ukf | 75770bbf92e7fc90ea007a9512e7b23d784ccf5c | [
"MIT"
] | 1 | 2019-04-26T02:15:22.000Z | 2019-04-26T02:15:35.000Z | src/KFEnums.h | DrData/ukf | 75770bbf92e7fc90ea007a9512e7b23d784ccf5c | [
"MIT"
] | 1 | 2019-04-26T02:09:01.000Z | 2019-04-26T02:09:01.000Z | #pragma once
namespace KF
{
// Define sensor type enumeration
enum SensorType
{
eLaser,
eRadar,
};
enum KFType
{
eKF,
eUKF,
};
} | 8.684211 | 35 | 0.551515 |
9db2705c26523b9e73483ba0de6ad0a2cb675224 | 2,051 | swift | Swift | Sources/Intermodular/Extensions/SwiftUI/KeyboardShortcut++.swift | n41l/SwiftUIX | 6840dc104acbb1c840faad7a3a1b4385d03066cf | [
"MIT"
] | 33 | 2019-06-04T21:17:27.000Z | 2019-08-01T16:00:35.000Z | Sources/Intermodular/Extensions/SwiftUI/KeyboardShortcut++.swift | n41l/SwiftUIX | 6840dc104acbb1c840faad7a3a1b4385d03066cf | [
"MIT"
] | null | null | null | Sources/Intermodular/Extensions/SwiftUI/KeyboardShortcut++.swift | n41l/SwiftUIX | 6840dc104acbb1c840faad7a3a1b4385d03066cf | [
"MIT"
] | null | null | null | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
#if os(macOS)
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension KeyboardShortcut {
public var appKitKeyEquivalent: (key: Character, modifiers: NSEvent.ModifierFlags) {
return (key.character, modifiers.appKitModifierFlags)
}
public init?(from event: NSEvent) {
guard let key = event.charactersIgnoringModifiers.map(Character.init) else {
return nil
}
self.init(KeyEquivalent(key), modifiers: EventModifiers(from: event.modifierFlags))
}
public static func ~= (lhs: KeyboardShortcut, rhs: KeyboardShortcut) -> Bool {
lhs.key ~= rhs.key && rhs.modifiers.contains(lhs.modifiers)
}
}
// MARK: - Auxiliary Implementation -
extension EventModifiers {
fileprivate var appKitModifierFlags: NSEvent.ModifierFlags {
switch self {
case .capsLock:
return .capsLock
case .shift:
return .shift
case .control:
return .control
case .option:
return .control
case .command:
return .command
case .numericPad:
return .numericPad
case .function:
return .function
default:
fatalError()
}
}
fileprivate init(from modifierFlags: NSEvent.ModifierFlags) {
self.init()
if modifierFlags.contains(.capsLock) {
insert(.capsLock)
}
if modifierFlags.contains(.shift) {
insert(.shift)
}
if modifierFlags.contains(.control) {
insert(.control)
}
if modifierFlags.contains(.command) {
insert(.command)
}
if modifierFlags.contains(.numericPad) {
insert(.numericPad)
}
if modifierFlags.contains(.function) {
insert(.function)
}
}
}
#endif
| 24.129412 | 91 | 0.569966 |
19c468bc357500232b521c27997820d2fc92dcfd | 874 | asm | Assembly | programs/oeis/317/A317538.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/317/A317538.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | programs/oeis/317/A317538.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | ; A317538: Indices m for which A317413(m) = 1.
; 1,4,6,9,12,16,19,21,24,28,30,33,37,40,43,45,48,52,54,57,60,64,67,69,73,76,78,81,85,88,91,93,96,100,102,105,108,112,115,117,120,124,126,129,133,136,139,141,145,148,150,153,156,160,163,165,169,172,174,177,181,184,187,189,192,196,198,201,204
mov $14,$0
mov $16,2
mov $18,$0
lpb $16
clr $0,14
mov $0,$14
sub $16,1
add $0,$16
sub $0,1
mov $7,$0
mov $9,2
mov $11,$0
lpb $9
clr $0,7
mov $0,$7
sub $9,1
lpb $0
add $2,$0
lpb $2
sub $2,4
add $3,3
lpe
div $0,2
mov $2,2
lpe
mov $1,$3
lpe
lpb $7
mov $7,0
sub $8,$1
lpe
mov $1,$8
add $1,5
mov $13,$11
mul $13,5
add $1,$13
mov $17,$16
lpb $17
mov $15,$1
sub $17,1
lpe
lpe
lpb $14
mov $14,0
sub $15,$1
lpe
mov $1,$15
div $1,3
mov $20,$18
mul $20,3
add $1,$20
| 15.890909 | 240 | 0.528604 |
5b54bba23d8872a6a1aa1be7ecab55af4023bde3 | 1,522 | h | C | GeometryReaders/XMLIdealGeometryESSource/interface/XMLIdealGeometryESSource.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | GeometryReaders/XMLIdealGeometryESSource/interface/XMLIdealGeometryESSource.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | GeometryReaders/XMLIdealGeometryESSource/interface/XMLIdealGeometryESSource.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef GeometryReaders_XMLIdealGeometryESSource_XMLIdealGeometryESSource_H
#define GeometryReaders_XMLIdealGeometryESSource_XMLIdealGeometryESSource_H
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/EventSetupRecordIntervalFinder.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DetectorDescription/Core/interface/DDCompactView.h"
#include "GeometryReaders/XMLIdealGeometryESSource/interface/GeometryConfiguration.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
#include <memory>
#include <string>
class XMLIdealGeometryESSource : public edm::ESProducer,
public edm::EventSetupRecordIntervalFinder
{
public:
XMLIdealGeometryESSource(const edm::ParameterSet & p);
~XMLIdealGeometryESSource() override;
std::unique_ptr<DDCompactView> produceGeom(const IdealGeometryRecord &);
std::unique_ptr<DDCompactView> produceMagField(const IdealMagneticFieldRecord &);
std::unique_ptr<DDCompactView> produce();
protected:
void setIntervalFor(const edm::eventsetup::EventSetupRecordKey &,
const edm::IOVSyncValue &,edm::ValidityInterval &) override;
private:
XMLIdealGeometryESSource(const XMLIdealGeometryESSource &) = delete;
const XMLIdealGeometryESSource & operator=(const XMLIdealGeometryESSource &) = delete;
std::string rootNodeName_;
bool userNS_;
GeometryConfiguration geoConfig_;
};
#endif
| 39.025641 | 90 | 0.799606 |
969abe60fd78b5b95139ae61841b16cb5b23f4fa | 8,553 | kt | Kotlin | app/src/main/java/com/kou/seekmake/data/retrofit/SeekMakeRepository.kt | itzkou/seekmake-android | aee05bcf921efe59b0fa263cc932a5daf3b9a3e0 | [
"MIT"
] | null | null | null | app/src/main/java/com/kou/seekmake/data/retrofit/SeekMakeRepository.kt | itzkou/seekmake-android | aee05bcf921efe59b0fa263cc932a5daf3b9a3e0 | [
"MIT"
] | null | null | null | app/src/main/java/com/kou/seekmake/data/retrofit/SeekMakeRepository.kt | itzkou/seekmake-android | aee05bcf921efe59b0fa263cc932a5daf3b9a3e0 | [
"MIT"
] | null | null | null | package com.kou.seekmake.data.retrofit
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.JsonSyntaxException
import com.kou.seekmake.models.SeekMake.*
import okhttp3.MultipartBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
class SeekMakeRepository {
fun signUp(api: SeekMakeApi, userSeek: UserSeek): LiveData<SignUpResponse> {
val apiresp = MutableLiveData<SignUpResponse>()
api.signUp(userSeek).enqueue(object : Callback<SignUpResponse> {
override fun onFailure(call: Call<SignUpResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(SignUpResponse(null, "0"))
else if (t is JsonSyntaxException)
apiresp.postValue(SignUpResponse(null, "2"))
}
override fun onResponse(call: Call<SignUpResponse>, response: Response<SignUpResponse>) {
when {
response.code() == 200 -> apiresp.postValue(response.body())
response.code() == 422 -> {
apiresp.postValue(SignUpResponse(null, "1"))
}
}
}
})
return apiresp
}
fun signIn(api: SeekMakeApi, userSeek: UserSeek): LiveData<LoginResponse> {
val apiresp = MutableLiveData<LoginResponse>()
api.signIn(userSeek).enqueue(object : Callback<LoginResponse> {
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(LoginResponse(null, "0"))
}
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
when {
response.code() == 200 -> apiresp.postValue(response.body())
response.code() == 401 -> apiresp.postValue(LoginResponse(null, "1"))
response.code() == 422 -> apiresp.postValue(LoginResponse(null, "2"))
}
}
})
return apiresp
}
fun getClient(api: SeekMakeApi, id: String): LiveData<ClientResponse> {
val apiresp = MutableLiveData<ClientResponse>()
api.getClient(id).enqueue(object : Callback<ClientResponse> {
override fun onFailure(call: Call<ClientResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(ClientResponse(null, "0"))
}
override fun onResponse(call: Call<ClientResponse>, response: Response<ClientResponse>) {
if (response.isSuccessful)
apiresp.postValue(response.body())
}
})
return apiresp
}
fun pwdReset(api: SeekMakeApi, userSeek: UserSeek): LiveData<PassResetResponse> {
val apiresp = MutableLiveData<PassResetResponse>()
api.resetPwd(userSeek).enqueue(object : Callback<PassResetResponse> {
override fun onFailure(call: Call<PassResetResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(PassResetResponse("0", null))
}
override fun onResponse(call: Call<PassResetResponse>, response: Response<PassResetResponse>) {
if (response.isSuccessful)
apiresp.postValue(response.body())
}
})
return apiresp
}
fun updateProfile(api: SeekMakeApi, id: String, userSeek: UserSeek): LiveData<UpdateProfileResponse> {
val apiresp = MutableLiveData<UpdateProfileResponse>()
api.updateProfile(id, userSeek).enqueue(object : Callback<UpdateProfileResponse> {
override fun onFailure(call: Call<UpdateProfileResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(UpdateProfileResponse(null, "0"))
}
//TODO don't forget to make sure that inputs are validate in order to get code 200
override fun onResponse(call: Call<UpdateProfileResponse>, response: Response<UpdateProfileResponse>) {
when {
response.code() == 200 -> apiresp.postValue(response.body())
response.code() == 401 -> apiresp.postValue(UpdateProfileResponse(null, "1"))
}
}
})
return apiresp
}
fun updatePwd(api: SeekMakeApi, id: String, pwdRequest: PwdRequest): LiveData<PwdUpdateResponse> {
val apiresp = MutableLiveData<PwdUpdateResponse>()
api.updatePwd(id, pwdRequest).enqueue(object : Callback<PwdUpdateResponse> {
override fun onFailure(call: Call<PwdUpdateResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(PwdUpdateResponse(null, "0"))
}
override fun onResponse(call: Call<PwdUpdateResponse>, response: Response<PwdUpdateResponse>) {
when {
response.code() == 200 -> apiresp.postValue(response.body())
//validation error
response.code() == 400 -> apiresp.postValue(PwdUpdateResponse(null, "1"))
// old pwd is not correct
response.code() == 422 -> apiresp.postValue(PwdUpdateResponse(null, "2"))
}
}
})
return apiresp
}
fun uploadFile(api: SeekMakeApi, file: MultipartBody.Part): LiveData<FileResponse> {
val apiresp = MutableLiveData<FileResponse>()
api.uploadFile(file).enqueue(object : Callback<FileResponse> {
override fun onFailure(call: Call<FileResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(FileResponse("0"))
}
override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
if (response.isSuccessful)
apiresp.postValue(response.body())
}
})
return apiresp
}
fun submitOrder(api: SeekMakeApi, token: String, order: Order): LiveData<OrderResponse> {
val apiresp = MutableLiveData<OrderResponse>()
api.submitOrder("Bearer $token", order).enqueue(object : Callback<OrderResponse> {
override fun onFailure(call: Call<OrderResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(OrderResponse(null, "0"))
}
override fun onResponse(call: Call<OrderResponse>, response: Response<OrderResponse>) {
if (response.code() == 200)
apiresp.postValue(response.body())
else {
val jObjError = JSONObject(response.errorBody()!!.string())
Log.d("vijr", jObjError.getJSONObject("data").toString())
}
}
})
return apiresp
}
fun getDemands(api: SeekMakeApi, token: String, id: String): LiveData<DemandsResponse> {
val apiresp = MutableLiveData<DemandsResponse>()
api.getDemands("Bearer $token", id).enqueue(object : Callback<DemandsResponse> {
override fun onFailure(call: Call<DemandsResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(DemandsResponse(null, "0"))
}
override fun onResponse(call: Call<DemandsResponse>, response: Response<DemandsResponse>) {
if (response.code() == 200)
apiresp.postValue(response.body())
}
})
return apiresp
}
fun updateDemand(api: SeekMakeApi, token: String, id: String, status: OrderStatus): LiveData<UpdateDemandResponse> {
val apiresp = MutableLiveData<UpdateDemandResponse>()
api.updateDemand("Bearer $token", id, status = status).enqueue(object : Callback<UpdateDemandResponse> {
override fun onFailure(call: Call<UpdateDemandResponse>, t: Throwable) {
if (t is IOException)
apiresp.postValue(UpdateDemandResponse(null, "0"))
}
override fun onResponse(call: Call<UpdateDemandResponse>, response: Response<UpdateDemandResponse>) {
if (response.code() == 200)
apiresp.postValue(response.body())
}
})
return apiresp
}
}
| 38.527027 | 120 | 0.589968 |
170e74cacb0a2413004a5d16eb1164f178c172eb | 2,594 | h | C | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/D3D11/Vertex.h | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/D3D11/Vertex.h | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/D3D11/Vertex.h | Jaraffe-github/Old_Engines | 0586d383af99cfcf076b18dace49e779a55b88e8 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
namespace JF
{
namespace Vertex
{
enum class VertexType
{
Position,
PosColor,
PosNormalTex,
PosNormalTexTan,
};
struct BasicVertex
{
BasicVertex(){}
};
struct Position : BasicVertex
{
Position() : BasicVertex() {}
Position(XMFLOAT3 pos)
: BasicVertex(), Pos(pos) {}
Position(float px, float py, float pz)
: BasicVertex(), Pos(px, py, pz) {}
XMFLOAT3 Pos;
};
// PosColor 24Byte Struct
struct PosColor : BasicVertex
{
PosColor() : BasicVertex(){}
PosColor(XMFLOAT3 pos, XMFLOAT4 color)
: BasicVertex(), Pos(pos), Color(color){}
PosColor(float px, float py, float pz,
float cr, float cg, float cb, float ca)
: BasicVertex(), Pos(px, py, pz), Color(cr, cg, cb, ca) {}
XMFLOAT3 Pos;
XMFLOAT4 Color;
};
// Basic 32Byte Struct
struct PosNormalTex : BasicVertex
{
PosNormalTex() : BasicVertex() {}
PosNormalTex(XMFLOAT3 pos, XMFLOAT3 normal, XMFLOAT2 tex)
: BasicVertex(),
Pos(pos), Normal(normal), Tex(tex) {}
PosNormalTex(XMFLOAT3& pos, XMFLOAT3& normal, XMFLOAT2& tex)
: BasicVertex(),
Pos(pos), Normal(normal), Tex(tex) {}
PosNormalTex(
float px, float py, float pz,
float nx, float ny, float nz,
float u, float v)
: BasicVertex(),
Pos(px, py, pz), Normal(nx, ny, nz), Tex(u, v) {}
XMFLOAT3 Pos;
XMFLOAT3 Normal;
XMFLOAT2 Tex;
};
// Basic 48Byte Struct
struct PosNormalTexTan : BasicVertex
{
PosNormalTexTan() : BasicVertex() {}
PosNormalTexTan(XMFLOAT3 pos, XMFLOAT3 normal, XMFLOAT2 tex, XMFLOAT4 tan)
: BasicVertex(),
Pos(pos), Normal(normal), Tex(tex), Tan(tan) {}
PosNormalTexTan(XMFLOAT3& pos, XMFLOAT3& normal, XMFLOAT2& tex, XMFLOAT4& tan)
: BasicVertex(),
Pos(pos), Normal(normal), Tex(tex), Tan(tan) {}
PosNormalTexTan(
float px, float py, float pz,
float nx, float ny, float nz,
float u, float v,
float tx, float ty, float tz, float tw)
: BasicVertex(),
Pos(px, py, pz), Normal(nx, ny, nz), Tex(u, v), Tan(tx, ty, tz, tw) {}
XMFLOAT3 Pos;
XMFLOAT3 Normal;
XMFLOAT2 Tex;
XMFLOAT4 Tan;
};
}
class InputLayoutDesc
{
public:
static const D3D11_INPUT_ELEMENT_DESC Position[1];
static const D3D11_INPUT_ELEMENT_DESC PosColor[2];
static const D3D11_INPUT_ELEMENT_DESC PosNormalTex[3];
static const D3D11_INPUT_ELEMENT_DESC PosNormalTexTan[4];
};
class InputLayouts
{
public:
static void InitAll(ID3D11Device* device);
static void DestroyAll();
static ID3D11InputLayout* Position;
static ID3D11InputLayout* PosColor;
static ID3D11InputLayout* PosNormalTex;
static ID3D11InputLayout* PosNormalTexTan;
};
} | 22.955752 | 80 | 0.684657 |
331719a2a5a244761348d8660d5c741b1f74d90f | 2,921 | py | Python | tests/test1.py | pedroramaciotti/Cloudtropy | bce1cc1cd6c5217ac20cf5a98491d10c6a8905b2 | [
"MIT"
] | null | null | null | tests/test1.py | pedroramaciotti/Cloudtropy | bce1cc1cd6c5217ac20cf5a98491d10c6a8905b2 | [
"MIT"
] | null | null | null | tests/test1.py | pedroramaciotti/Cloudtropy | bce1cc1cd6c5217ac20cf5a98491d10c6a8905b2 | [
"MIT"
] | 1 | 2021-03-10T14:04:04.000Z | 2021-03-10T14:04:04.000Z | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
# from scipy.stats import entropy
import sys
sys.path.append('../')
import cloudtropy
# data
gen_dim = 2
gen_N = 300
lims = (-2,6)
scale = 0.2
X = np.random.uniform(low=lims[0],high=lims[1],size=(10000,2)) # background
X = np.concatenate([X,scale*np.random.randn(gen_N,gen_dim)+np.array([0,0])] )
X = np.concatenate([X,scale*np.random.randn(gen_N,gen_dim)+np.array([4,0])] )
X = np.concatenate([X,scale*np.random.randn(gen_N,gen_dim)+np.array([0,4])] )
X = np.concatenate([X,scale*np.random.randn(gen_N,gen_dim)+np.array([4,4])] )
# input parameters
N_grid = 80
delta_c = 0.35
# grid,pmf = cloudtropy.pmf(X,N=N_grid,delta_c=delta_c,lims=[(-2,6),(-2,6)])
grid,pmf = cloudtropy.pmf(X,d=0.1,delta_c=delta_c,lims=[(-2,6),(-2,6)])
entropy = cloudtropy.entropy(X,base=2,N=N_grid,delta_c=delta_c,lims=[(-3,7),(-3,7)])
print(cloudtropy.entropy(X,base=2,d=0.1,delta_c=delta_c,lims=[(-3,7),(-3,7)]))
############## All in one
fig = plt.figure(figsize=(14,3))
#
ax1 = fig.add_subplot(1,4,1)
# levels = np.linspace(0,flat_pmf.max(),40)
ax1.scatter(X[:,0], X[:,1],s=1,alpha=0.1,color='k')
ax1.set_xlabel('x'),ax1.set_ylabel('y')
ax1.set_xlim(lims),ax1.set_xlim(lims)
ax1.axis('equal')
#
ax2 = fig.add_subplot(1,3,2,projection='3d')
ax2.plot_surface(grid[0], grid[1], pmf,cmap='coolwarm', edgecolor='none',shade='interp')
ax2.set_xlabel('x'),ax2.set_ylabel('y')#,ax.set_zlabel('PMF',rotation=90)
ax2.view_init(elev=60, azim=-45)
#
ax3 = fig.add_subplot(1,3,3)
cs = ax3.contourf(grid[0], grid[1], pmf, levels=np.linspace(0,pmf.max(),40), cmap='Purples_r')
ax3.set_xlabel('x'),ax3.set_ylabel('y')
ax3.set_title('Entropy = %.3f'%entropy)
ax3.set_xlim(lims),ax3.set_xlim(lims),
ax3.axis('equal')
cbar = fig.colorbar(cs)
#
plt.tight_layout()
# plt.savefig('all.pdf')
plt.savefig('all.png',dpi=400)
############## Separate
fig = plt.figure(figsize=(4,3))
#
ax1 = fig.add_subplot(1,1,1)
# levels = np.linspace(0,flat_pmf.max(),40)
ax1.scatter(X[:,0], X[:,1],s=1,alpha=0.1,color='k')
ax1.set_xlabel('x'),ax1.set_ylabel('y')
ax1.set_xlim(lims),ax1.set_xlim(lims)
ax1.axis('equal')
plt.savefig('scatter.png',dpi=400)
#
fig = plt.figure(figsize=(4,3))
#
ax2 = fig.add_subplot(1,1,1,projection='3d')
ax2.plot_surface(grid[0], grid[1], pmf,cmap='coolwarm', edgecolor='none',shade='interp')
ax2.set_xlabel('x'),ax2.set_ylabel('y')#,ax.set_zlabel('PMF',rotation=90)
ax2.view_init(elev=60, azim=-45)
plt.savefig('surf.png',dpi=400)
#
fig = plt.figure(figsize=(4,3))
#
ax3 = fig.add_subplot(1,1,1)
cs = ax3.contourf(grid[0], grid[1], pmf, levels=np.linspace(0,pmf.max(),40), cmap='Purples_r')
# ax3.set_xlabel('x'),ax3.set_ylabel('y')
# ax3.set_title('Entropy = %.3f'%entropy)
ax3.set_xlim(lims),ax3.set_xlim(lims),
ax3.axis('equal')
cbar = fig.colorbar(cs)
#
plt.tight_layout()
# plt.savefig('all.pdf')
plt.savefig('contour_simple.png',dpi=400)
| 27.819048 | 94 | 0.680589 |
0defed50f029759823c8afb6f3a7a77f7d333c78 | 65 | kt | Kotlin | kotest-core/src/jvmMain/kotlin/io/kotlintest/aliases.kt | xiaodongw/kotest | 94e9fe43199c5d6e0dfca8bdf8b2f09a2ff036bd | [
"Apache-2.0"
] | null | null | null | kotest-core/src/jvmMain/kotlin/io/kotlintest/aliases.kt | xiaodongw/kotest | 94e9fe43199c5d6e0dfca8bdf8b2f09a2ff036bd | [
"Apache-2.0"
] | null | null | null | kotest-core/src/jvmMain/kotlin/io/kotlintest/aliases.kt | xiaodongw/kotest | 94e9fe43199c5d6e0dfca8bdf8b2f09a2ff036bd | [
"Apache-2.0"
] | null | null | null | package io.kotlintest
typealias Spec = io.kotest.core.spec.Spec
| 16.25 | 41 | 0.8 |
feeec2795332733b680736bb62058568a3f880b9 | 1,088 | html | HTML | app/views/pages/catalogo/_item_182.html | pulibrary/cicognara-rails | d47e8868b35dd4db5f3a28b623735d3be519b71d | [
"Apache-2.0"
] | 3 | 2017-02-22T20:03:52.000Z | 2019-05-24T21:57:59.000Z | app/views/pages/catalogo/_item_182.html | pulibrary/cicognara-rails | d47e8868b35dd4db5f3a28b623735d3be519b71d | [
"Apache-2.0"
] | 343 | 2016-04-26T15:12:00.000Z | 2022-03-21T16:29:22.000Z | app/views/pages/catalogo/_item_182.html | pulibrary/cicognara-rails | d47e8868b35dd4db5f3a28b623735d3be519b71d | [
"Apache-2.0"
] | 2 | 2016-04-26T14:56:50.000Z | 2016-04-26T22:03:09.000Z | <section xmlns="http://www.w3.org/1999/xhtml" class="catalogo-item" id="182">
<span class="catalogo-item-label">182.</span>
<span class="catalogo-bibl">
<span class="catalogo-author">PILES (de)</span>,
<span class="catalogo-title"><a class="catalog-link" href="/catalog/182"> Diverses coversatios sur la peinture,</a></span>
<span class="catalogo-pubPlace">Paris</span>
<span class="catalogo-date">1677.</span> In fine a questo libro sono unite
Figures d’accademie pour apprendre a dessiner, gravées par Sebastien le Clerc, 1673. Sono 31
tavole.</span>
<div class="catalogo-note">Le quali tengonsi in pregio dagli amatori.</div><div id="catalogo-note-text-182" class="catalogo-note-search-results truncate-line-clamp">Le quali tengonsi in pregio dagli amatori.</div><a id="catalogo-note-text-toggle-182" class="catalogo-note-search-results-toggle" href="#"><i class="bi bi-caret-down"/><span>Show More</span></a>
</section> | 98.909091 | 380 | 0.630515 |
5bec423783e44b30a76f0e6f11e19788897c5536 | 8,774 | c | C | INFLO-PRO/Arada/external/locomate-2.0-mips_2.0.0.7/src/can-utils/isotpsniffer.c | OSADP/INFLO | 19964445fe79a1f9334516fa0f51fa9dfc735f6c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | INFLO-PRO/Arada/external/locomate-2.0-mips_2.0.0.7/src/can-utils/isotpsniffer.c | OSADP/INFLO | 19964445fe79a1f9334516fa0f51fa9dfc735f6c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | INFLO-PRO/Arada/external/locomate-2.0-mips_2.0.0.7/src/can-utils/isotpsniffer.c | OSADP/INFLO | 19964445fe79a1f9334516fa0f51fa9dfc735f6c | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-02-02T18:12:32.000Z | 2020-11-04T04:35:58.000Z | /*
* $Id: isotpsniffer.c 898 2009-01-13 09:32:45Z hartkopp $
*/
/*
* isotpsniffer.c - dump ISO15765-2 datagrams using PF_CAN isotp protocol
*
* Copyright (c) 2008 Volkswagen Group Electronic Research
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Volkswagen nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, provided that this notice is retained in full, this
* software may be distributed under the terms of the GNU General
* Public License ("GPL") version 2, in which case the provisions of the
* GPL apply INSTEAD OF those given above.
*
* The provided data structures and external interfaces from this code
* are not restricted to be used by modules with a GPL compatible license.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* Send feedback to <socketcan-users@lists.berlios.de>
*
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <time.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <linux/can/isotp.h>
#include "terminal.h"
#define NO_CAN_ID 0xFFFFFFFFU
#define FORMAT_HEX 1
#define FORMAT_ASCII 2
#define FORMAT_DEFAULT (FORMAT_ASCII | FORMAT_HEX)
void print_usage(char *prg)
{
fprintf(stderr, "\nUsage: %s [options] <CAN interface>\n", prg);
fprintf(stderr, "Options: -s <can_id> (source can_id. Use 8 digits for extended IDs)\n");
fprintf(stderr, " -d <can_id> (destination can_id. Use 8 digits for extended IDs)\n");
fprintf(stderr, " -x <addr> (extended addressing mode.)\n");
fprintf(stderr, " -c (color mode)\n");
fprintf(stderr, " -t <type> (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
fprintf(stderr, " -f <format> (1 = HEX, 2 = ASCII, 3 = HEX & ASCII - default: %d)\n", FORMAT_DEFAULT);
fprintf(stderr, " -h <len> (head: print only first <len> bytes)\n");
fprintf(stderr, "\nCAN IDs and addresses are given and expected in hexadecimal values.\n");
fprintf(stderr, "\n");
}
void printbuf(unsigned char *buffer, int nbytes, int color, int timestamp,
int format, struct timeval *tv, struct timeval *last_tv,
canid_t src, int socket, char *candevice, int head)
{
int i;
if (color == 1)
printf("%s", FGRED);
if (color == 2)
printf("%s", FGBLUE);
if (timestamp) {
ioctl(socket, SIOCGSTAMP, tv);
switch (timestamp) {
case 'a': /* absolute with timestamp */
printf("(%ld.%06ld) ", tv->tv_sec, tv->tv_usec);
break;
case 'A': /* absolute with date */
{
struct tm tm;
char timestring[25];
tm = *localtime(&tv->tv_sec);
strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
printf("(%s.%06ld) ", timestring, tv->tv_usec);
}
break;
case 'd': /* delta */
case 'z': /* starting with zero */
{
struct timeval diff;
if (last_tv->tv_sec == 0) /* first init */
*last_tv = *tv;
diff.tv_sec = tv->tv_sec - last_tv->tv_sec;
diff.tv_usec = tv->tv_usec - last_tv->tv_usec;
if (diff.tv_usec < 0)
diff.tv_sec--, diff.tv_usec += 1000000;
if (diff.tv_sec < 0)
diff.tv_sec = diff.tv_usec = 0;
printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
if (timestamp == 'd')
*last_tv = *tv; /* update for delta calculation */
}
break;
default: /* no timestamp output */
break;
}
}
/* the source socket gets pdu data from the detination id */
printf(" %s %03X [%d] ", candevice, src & CAN_EFF_MASK, nbytes);
if (format & FORMAT_HEX) {
for (i=0; i<nbytes; i++) {
printf("%02X ", buffer[i]);
if (head && i+1 >= head) {
printf("... ");
break;
}
}
if (format & FORMAT_ASCII)
printf(" - ");
}
if (format & FORMAT_ASCII) {
printf("'");
for (i=0; i<nbytes; i++) {
if ((buffer[i] > 0x1F) && (buffer[i] < 0x7F))
printf("%c", buffer[i]);
else
printf(".");
if (head && i+1 >= head)
break;
}
printf("'");
if (head && i+1 >= head)
printf(" ... ");
}
if (color)
printf("%s", ATTRESET);
printf("\n");
fflush(stdout);
}
int main(int argc, char **argv)
{
fd_set rdfs;
int s, t;
struct sockaddr_can addr;
struct ifreq ifr;
static struct can_isotp_options opts;
int opt, quit = 0;
int color = 0;
int head = 0;
int timestamp = 0;
int format = FORMAT_DEFAULT;
canid_t src = NO_CAN_ID;
canid_t dst = NO_CAN_ID;
extern int optind, opterr, optopt;
static struct timeval tv, last_tv;
unsigned char buffer[4096];
int nbytes;
while ((opt = getopt(argc, argv, "s:d:x:h:ct:f:?")) != -1) {
switch (opt) {
case 's':
src = strtoul(optarg, (char **)NULL, 16);
if (strlen(optarg) > 7)
src |= CAN_EFF_FLAG;
break;
case 'd':
dst = strtoul(optarg, (char **)NULL, 16);
if (strlen(optarg) > 7)
dst |= CAN_EFF_FLAG;
break;
case 'x':
opts.flags |= CAN_ISOTP_EXTEND_ADDR;
opts.ext_address = strtoul(optarg, (char **)NULL, 16) & 0xFF;
break;
case 'f':
format = (atoi(optarg) & (FORMAT_ASCII | FORMAT_HEX));
break;
case 'h':
head = atoi(optarg);
break;
case 'c':
color = 1;
break;
case 't':
timestamp = optarg[0];
if ((timestamp != 'a') && (timestamp != 'A') &&
(timestamp != 'd') && (timestamp != 'z')) {
printf("%s: unknown timestamp mode '%c' - ignored\n",
basename(argv[0]), optarg[0]);
timestamp = 0;
}
break;
case '?':
print_usage(basename(argv[0]));
exit(0);
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
print_usage(basename(argv[0]));
exit(1);
break;
}
}
if ((argc - optind) != 1 || src == NO_CAN_ID || dst == NO_CAN_ID) {
print_usage(basename(argv[0]));
exit(1);
}
if ((s = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP)) < 0) {
perror("socket");
exit(1);
}
if ((t = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP)) < 0) {
perror("socket");
exit(1);
}
opts.flags |= CAN_ISOTP_LISTEN_MODE;
setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts));
setsockopt(t, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts));
addr.can_family = AF_CAN;
strcpy(ifr.ifr_name, argv[optind]);
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_ifindex = ifr.ifr_ifindex;
addr.can_addr.tp.tx_id = dst;
addr.can_addr.tp.rx_id = src;
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
close(s);
exit(1);
}
addr.can_addr.tp.tx_id = src;
addr.can_addr.tp.rx_id = dst;
if (bind(t, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
close(s);
exit(1);
}
while (!quit) {
FD_ZERO(&rdfs);
FD_SET(s, &rdfs);
FD_SET(t, &rdfs);
FD_SET(0, &rdfs);
if ((nbytes = select(t+1, &rdfs, NULL, NULL, NULL)) < 0) {
perror("select");
continue;
}
if (FD_ISSET(0, &rdfs)) {
getchar();
quit = 1;
printf("quit due to keyboard input.\n");
}
if (FD_ISSET(s, &rdfs)) {
nbytes = read(s, buffer, 4096);
if (nbytes < 0) {
perror("read socket s");
return -1;
}
if (nbytes > 4095)
return -1;
printbuf(buffer, nbytes, color?1:0, timestamp, format,
&tv, &last_tv, src, s, ifr.ifr_name, head);
}
if (FD_ISSET(t, &rdfs)) {
nbytes = read(t, buffer, 4096);
if (nbytes < 0) {
perror("read socket t");
return -1;
}
if (nbytes > 4095)
return -1;
printbuf(buffer, nbytes, color?2:0, timestamp, format,
&tv, &last_tv, dst, t, ifr.ifr_name, head);
}
}
close(s);
return 0;
}
| 25.805882 | 111 | 0.634374 |
139d599e8721a3b64c4118415493dd41224b7325 | 2,935 | kt | Kotlin | app/src/main/java/com/yaroslavgamayunov/stockviewer/repository/StockApiRepository.kt | EtsTest-AndroidApps/StockViewer | 9f177cc718767bfaea3d6154f75821829dd5355b | [
"MIT"
] | 47 | 2021-07-22T15:43:50.000Z | 2022-01-19T13:01:23.000Z | app/src/main/java/com/yaroslavgamayunov/stockviewer/repository/StockApiRepository.kt | EtsTest-AndroidApps/StockViewer | 9f177cc718767bfaea3d6154f75821829dd5355b | [
"MIT"
] | null | null | null | app/src/main/java/com/yaroslavgamayunov/stockviewer/repository/StockApiRepository.kt | EtsTest-AndroidApps/StockViewer | 9f177cc718767bfaea3d6154f75821829dd5355b | [
"MIT"
] | 8 | 2021-07-21T12:25:29.000Z | 2022-02-11T00:44:52.000Z | package com.yaroslavgamayunov.stockviewer.repository
import com.yaroslavgamayunov.stockviewer.network.FinHubApiService
import com.yaroslavgamayunov.stockviewer.network.IexCloudApiService
import com.yaroslavgamayunov.stockviewer.utils.CallResult
import com.yaroslavgamayunov.stockviewer.utils.safeApiCall
import com.yaroslavgamayunov.stockviewer.vo.CompanyInfo
import com.yaroslavgamayunov.stockviewer.vo.HistoricalCandleData
import com.yaroslavgamayunov.stockviewer.vo.NewsItem
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
class StockApiRepository @Inject constructor(
private val iexCloudApiService: IexCloudApiService,
private val finHubApiService: FinHubApiService
) {
suspend fun getHistoricalData(
ticker: String,
duration: StockDataDuration
): CallResult<HistoricalCandleData> {
return safeApiCall {
finHubApiService.getHistoricalData(
ticker,
duration.resolution,
duration.startTime,
duration.endTime
)
}
}
suspend fun getNews(
ticker: String,
startTime: Long,
endTime: Long
): CallResult<List<NewsItem>> {
val startDate = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date(startTime))
val endDate = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date(endTime))
return safeApiCall {
finHubApiService.getNews(ticker, startDate, endDate)
}
}
suspend fun getCompanyInfo(ticker: String): CallResult<CompanyInfo> {
return safeApiCall {
iexCloudApiService.getCompanyInfo(ticker)
}
}
}
sealed class StockDataDuration {
val endTime: Long
get() {
val calendar = Calendar.getInstance()
return calendar.time.time.div(1000)
}
val startTime: Long
get() {
val calendar = Calendar.getInstance()
when (this) {
is All -> return 0
is Day -> calendar.add(Calendar.DAY_OF_YEAR, -1)
is HalfYear -> calendar.add(Calendar.MONTH, -6)
is Month -> calendar.add(Calendar.MONTH, -1)
is Week -> calendar.add(Calendar.WEEK_OF_YEAR, -1)
is Year -> calendar.add(Calendar.YEAR, -1)
}
return calendar.time.time.div(1000)
}
val resolution: String
get() {
return when (this) {
is All -> "W"
is Day -> "30"
is HalfYear -> "D"
is Month -> "D"
is Week -> "60"
is Year -> "D"
}
}
object Day : StockDataDuration()
object Week : StockDataDuration()
object Month : StockDataDuration()
object HalfYear : StockDataDuration()
object Year : StockDataDuration()
object All : StockDataDuration()
} | 31.223404 | 89 | 0.619421 |
98514289e13a57eae7c461c4912553020d0945d1 | 4,934 | kt | Kotlin | app/src/main/java/com/jobs/assignment/presentation/ui/list/ListFragment.kt | SanushRadalage/ComposeSamples | 46a48e46b5c1dd96477319639db9d13a9275524a | [
"MIT"
] | null | null | null | app/src/main/java/com/jobs/assignment/presentation/ui/list/ListFragment.kt | SanushRadalage/ComposeSamples | 46a48e46b5c1dd96477319639db9d13a9275524a | [
"MIT"
] | null | null | null | app/src/main/java/com/jobs/assignment/presentation/ui/list/ListFragment.kt | SanushRadalage/ComposeSamples | 46a48e46b5c1dd96477319639db9d13a9275524a | [
"MIT"
] | null | null | null | package com.jobs.assignment.presentation.ui.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.widget.Toolbar
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.findNavController
import com.google.android.material.snackbar.Snackbar
import com.jobs.assignment.R
import com.jobs.assignment.domain.model.Job
import com.jobs.assignment.presentation.BaseApplication
import com.jobs.assignment.presentation.components.LoadingJobShimmer
import com.jobs.assignment.util.snack
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import javax.inject.Inject
@AndroidEntryPoint
class ListFragment : Fragment(), StateHandler {
@Inject
lateinit var application: BaseApplication
private lateinit var toolBar: Toolbar
private val viewModel: ListViewModel by viewModels()
@ExperimentalCoroutinesApi
@ExperimentalFoundationApi
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
val jobs = viewModel.jobs.value
val loading = viewModel.loading.value
Column {
Box(
modifier = Modifier
.fillMaxSize()
) {
if (loading) {
LoadingJobShimmer(imageHeight = 250.dp)
} else {
LazyColumn {
val grouped = jobs.groupBy { it.stickyDate }
grouped.forEach { (initial, jobs) ->
stickyHeader {
Text(
initial!!,
Modifier
.fillMaxWidth()
.background(Color.White)
.padding(8.dp),
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
}
items(jobs) { job ->
CardView(job = job, onClick = {
val bundle = Bundle()
bundle.putString("Id", job.id!!)
findNavController().navigate(
R.id.action_listFragment_to_itemFragment,
bundle
)
})
}
}
}
}
}
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.stateHandler = this
toolBar = requireActivity().findViewById(R.id.mainToolBar)
toolBar.navigationIcon = null
toolBar.title = getString(R.string.jobs)
backCallBack()
}
private fun backCallBack() {
val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
requireActivity().finish()
}
}
requireActivity().onBackPressedDispatcher.addCallback(this as LifecycleOwner, callback)
}
override fun onSuccess(job: Job) {
TODO("since using lazy loading success callBack is not needed")
}
override fun onFailure() {
requireView().snack(
getString(R.string.error),
R.string.ok,
Snackbar.LENGTH_LONG,
R.color.white,
R.color.red
) {
this.setAction(getString(R.string.ok)) {
this.dismiss()
}
}
}
} | 36.548148 | 95 | 0.530199 |
9bd21b0a0645626b2270758effb332d3ec926934 | 2,395 | js | JavaScript | api/controllers/expenseController.js | SebastianDochia/budget-app | 7b03c3bf03866f30756eaa0dbf7669fc74767aac | [
"MIT"
] | null | null | null | api/controllers/expenseController.js | SebastianDochia/budget-app | 7b03c3bf03866f30756eaa0dbf7669fc74767aac | [
"MIT"
] | null | null | null | api/controllers/expenseController.js | SebastianDochia/budget-app | 7b03c3bf03866f30756eaa0dbf7669fc74767aac | [
"MIT"
] | null | null | null | 'use strict';
const firebase = require('../db');
const Expense = require('../models/expense');
const firestore = firebase.firestore();
const addExpense = async (req, res, next) => {
try {
const data = req.body;
await firestore.collection('expenses').doc().set(data);
res.send('Expense saved successfuly');
} catch (error) {
res.status(400).send(error.message);
}
}
const getAllExpenses = async (req, res, next) => {
try {
const expenses = await firestore.collection('expenses');
const data = await expenses.get();
const expensesArray = [];
if(data.empty) {
res.status(404).send('No expense found');
}else {
data.forEach(doc => {
const expense = new Expense(
doc.id,
doc.data().body.name,
doc.data().body.value,
doc.data().body.date,
doc.data().body.category,
);
expensesArray.push(expense);
});
res.send(expensesArray);
}
} catch (error) {
res.status(400).send(error.message);
}
}
const getExpense = async (req, res, next) => {
try {
const id = req.params.id;
const expense = await firestore.collection('expense').doc(id);
const data = await expense.get();
if(!data.exists) {
res.status(404).send('Expense with the given ID not found');
}else {
res.send(data.data());
}
} catch (error) {
res.status(400).send(error.message);
}
}
const updateExpense = async (req, res, next) => {
try {
const id = req.params.id;
const data = req.body;
const expense = await firestore.collection('expenses').doc(id);
await expense.update(data);
res.send('Expense updated successfuly');
} catch (error) {
res.status(400).send(error.message);
}
}
const deleteExpense = async (req, res, next) => {
try {
const id = req.params.id;
await firestore.collection('expenses').doc(id).delete();
res.send('Expense deleted successfuly');
} catch (error) {
res.status(400).send(error.message);
}
}
module.exports = {
addExpense,
getAllExpenses,
getExpense,
updateExpense,
deleteExpense,
} | 28.176471 | 72 | 0.54238 |
91c34433df5535bce8da3570c85766d60d298a4c | 54 | sql | SQL | chapter_004/src/main/java/ru/job4j/sql/filters_second/4.sql | Massimilian/Vasily-Maslov | c741c19831fcb9eabd6d83ba0450e931925f48de | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/sql/filters_second/4.sql | Massimilian/Vasily-Maslov | c741c19831fcb9eabd6d83ba0450e931925f48de | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/sql/filters_second/4.sql | Massimilian/Vasily-Maslov | c741c19831fcb9eabd6d83ba0450e931925f48de | [
"Apache-2.0"
] | 1 | 2018-07-14T14:13:05.000Z | 2018-07-14T14:13:05.000Z | select * from product order by price desc limit 1;
| 27 | 52 | 0.722222 |
d27f6b0628307b99dfacd7085c3cd8f26eb84355 | 541 | php | PHP | app/Models/Language.php | Darktroy/old_mine | 7ea6cd1564a9d011314d9b86dc5cf7782a5e7d78 | [
"MIT"
] | null | null | null | app/Models/Language.php | Darktroy/old_mine | 7ea6cd1564a9d011314d9b86dc5cf7782a5e7d78 | [
"MIT"
] | null | null | null | app/Models/Language.php | Darktroy/old_mine | 7ea6cd1564a9d011314d9b86dc5cf7782a5e7d78 | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
//
protected $table = 'change_maker_languages';
protected $fillable = ['maker_id','lang_name','level'];
public static function storeLanguages($request,$user_id)
{
// $data = $request
foreach ($request->lang as $lang) {
// dd($lang);
$_this = new self;
$lang['maker_id'] = $user_id;
$_this->create($lang);
}
// dd($request->lang);
}
}
| 21.64 | 60 | 0.560074 |
92efa1bd85eeef6ea491db31d27dbb968aee2fae | 447 | kt | Kotlin | idea/idea-completion/testData/basic/common/boldOrGrayed/TwoReceivers.kt | masfian77/kotlin | fe855d09d847dac8e79b2620033c3a953fdf686a | [
"ECL-2.0",
"Apache-2.0"
] | 71 | 2020-10-12T14:18:06.000Z | 2022-02-25T07:57:06.000Z | idea/idea-completion/testData/basic/common/boldOrGrayed/TwoReceivers.kt | masfian77/kotlin | fe855d09d847dac8e79b2620033c3a953fdf686a | [
"ECL-2.0",
"Apache-2.0"
] | 76 | 2020-11-13T12:30:25.000Z | 2021-09-17T15:32:57.000Z | idea/idea-completion/testData/basic/common/boldOrGrayed/TwoReceivers.kt | masfian77/kotlin | fe855d09d847dac8e79b2620033c3a953fdf686a | [
"ECL-2.0",
"Apache-2.0"
] | 36 | 2020-10-12T14:04:32.000Z | 2022-01-29T20:35:30.000Z | // FIR_COMPARISON
interface Base {
fun inBase()
}
interface I1 : Base {
fun inI1()
}
interface I2 : I1 {
fun inI2()
}
fun foo(i1: I1, i2: I2) {
with(i1) {
with(i2) {
<caret>
}
}
}
// EXIST: { lookupString: "inI1", attributes: "bold" }
// EXIST: { lookupString: "inI2", attributes: "bold" }
// EXIST: { lookupString: "inBase", attributes: "" }
// EXIST: { lookupString: "equals", attributes: "" }
| 17.88 | 54 | 0.548098 |
cb5ad11dfe0eb5fad65464c1d6d54e76704fafa8 | 130,208 | html | HTML | RFC-docs/html-inline-errata/rfc3165.html | matcdac/IETF_RFCs | c73caa411e90949c468478d1b3fb094260e4506e | [
"ADSL"
] | null | null | null | RFC-docs/html-inline-errata/rfc3165.html | matcdac/IETF_RFCs | c73caa411e90949c468478d1b3fb094260e4506e | [
"ADSL"
] | null | null | null | RFC-docs/html-inline-errata/rfc3165.html | matcdac/IETF_RFCs | c73caa411e90949c468478d1b3fb094260e4506e | [
"ADSL"
] | 1 | 2021-12-09T08:28:12.000Z | 2021-12-09T08:28:12.000Z | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://dublincore.org/documents/2008/08/04/dc-html/">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index,follow" />
<link rel="icon" href="./css/images/rfc.png" type="image/png" />
<link rel="shortcut icon" href="./css/images/rfc.png" type="image/png" />
<title>rfc3165</title>
<link rel="stylesheet" type="text/css" href="./css/errata-base.css"/>
<link rel="stylesheet" type="text/css" href="./css/errata-color.css" title="Default: Basic Colors"/>
<link rel="alternative stylesheet" type="text/css" href="./css/errata-monochrome.css" title="Monochrome"/>
<link rel="alternative stylesheet" type="text/css" href="./css/errata-printer.css" title="Printer"/>
<script src="./css/errata.js"></script>
</head>
<body>
<div class='Verified-headnote-styling'>
<span style="font-weight: bold;">This is a purely informative rendering of an RFC that includes verified errata. This rendering may not be used as a reference.</span>
<br/>
<br/>
The following 'Verified' errata have been incorporated in this document:
<a href='#btn_330'>EID 330</a>
</div>
<pre>
Network Working Group D. Levi
Request for Comments: 3165 Nortel Networks
Obsoletes: 2592 J. Schoenwaelder
Category: Standards Track TU Braunschweig
August 2001
Definitions of Managed Objects for the
Delegation of Management Scripts
Status of this Memo
This document specifies an Internet standards track protocol for the
Internet community, and requests discussion and suggestions for
improvements. Please refer to the current edition of the "Internet
Official Protocol Standards" (STD 1) for the standardization state
and status of this protocol. Distribution of this memo is unlimited.
Copyright Notice
Copyright (C) The Internet Society (2001). All Rights Reserved.
Abstract
This memo defines a portion of the Management Information Base (MIB)
for use with network management protocols in the Internet community.
In particular, it describes a set of managed objects that allow the
delegation of management scripts to distributed managers.
Table of Contents
1 Introduction ................................................. 3
2 The SNMP Management Framework ................................ 3
3 Overview ..................................................... 4
3.1 Terms ...................................................... 5
4 Requirements and Design Issues ............................... 6
4.1 Script Languages ........................................... 6
4.2 Script Transfer ............................................ 7
4.3 Script Execution ........................................... 8
5 Structure of the MIB ......................................... 9
5.1 Language Group ............................................. 9
5.2 Script Group ............................................... 10
5.3 Code Group ................................................. 11
5.4 Launch Group ............................................... 11
5.5 Run Group .................................................. 11
6 Definitions .................................................. 12
7 Usage Examples ............................................... 49
7.1 Pushing a Script via SNMP .................................. 49
7.2 Pulling a Script from a URL ................................ 50
7.3 Modifying an Existing Script ............................... 50
7.4 Removing an Existing Script ................................ 51
7.5 Creating a Launch Button ................................... 51
7.6 Launching a Script ......................................... 52
7.7 Suspending a Running Script ................................ 52
7.8 Resuming a Suspended Script ................................ 53
7.9 Terminating a Running Script ............................... 53
7.10 Removing a Terminated Script .............................. 54
7.11 Removing a Launch Button .................................. 54
8 VACM Configuration Examples .................................. 54
8.1 Sandbox for Guests ......................................... 55
8.2 Sharing Scripts ............................................ 55
8.3 Emergency Scripts .......................................... 56
9 IANA Considerations .......................................... 57
10 Security Considerations ..................................... 57
11 Intellectual Property ....................................... 59
12 Changes from RFC 2592 ....................................... 59
13 Acknowledgments ............................................. 61
14 References .................................................. 61
15 Editors' Addresses .......................................... 63
16 Full Copyright Statement .................................... 64
1. Introduction
This memo defines a portion of the Management Information Base (MIB)
for use with network management protocols in the Internet community.
In particular, it describes a set of managed objects that allow the
delegation of management scripts to distributed managers.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
document are to be interpreted as described in RFC 2119 [RFC2119].
2. The SNMP Management Framework
The SNMP Management Framework presently consists of five major
components:
o An overall architecture, described in RFC 2571 [RFC2571].
o Mechanisms for describing and naming objects and events for the
purpose of management. The first version of this Structure of
Management Information (SMI) is called SMIv1 and described in STD
16, RFC 1155 [RFC1155], STD 16, RFC 1212 [RFC1212] and RFC 1215
[RFC1215]. The second version, called SMIv2, is described in STD
58, RFC 2578 [RFC2578], STD 58, RFC 2579 [RFC2579] and STD 58, RFC
2580 [RFC2580].
o Message protocols for transferring management information. The
first version of the SNMP message protocol is called SNMPv1 and
described in STD 15, RFC 1157 [RFC1157]. A second version of the
SNMP message protocol, which is not an Internet standards track
protocol, is called SNMPv2c and described in RFC 1901 [RFC1901]
and RFC 1906 [RFC1906]. The third version of the message protocol
is called SNMPv3 and described in RFC 1906 [RFC1906], RFC 2572
[RFC2572] and RFC 2574 [RFC2574].
o Protocol operations for accessing management information. The
first set of protocol operations and associated PDU formats is
described in STD 15, RFC 1157 [RFC1157]. A second set of protocol
operations and associated PDU formats is described in RFC 1905
[RFC1905].
o A set of fundamental applications described in RFC 2573 [RFC2573]
and the view-based access control mechanism described in RFC 2575
[RFC2575].
A more detailed introduction to the current SNMP Management Framework
can be found in RFC 2570 [RFC2570].
Managed objects are accessed via a virtual information store, termed
the Management Information Base or MIB. Objects in the MIB are
defined using the mechanisms defined in the SMI.
This memo specifies a MIB module that is compliant to the SMIv2. A
MIB conforming to the SMIv1 can be produced through the appropriate
translations. The resulting translated MIB must be semantically
equivalent, except where objects or events are omitted because no
translation is possible (use of Counter64). Some machine readable
information in SMIv2 will be converted into textual descriptions in
SMIv1 during the translation process. However, this loss of machine
readable information is not considered to change the semantics of the
MIB.
3. Overview
The Script MIB module defined in this memo can be used to delegate
management functions to distributed managers. Management functions
are defined as management scripts written in a management scripting
language. This MIB makes no assumptions about the language itself
and even allows distribution of compiled native code, if an
implementation is able to execute native code under the control of
this MIB.
The Script MIB defines a standard interface for the delegation of
management functions based on the Internet management framework. In
particular, it provides the following capabilities:
1. Capabilities to transfer management scripts to a distributed
manager.
2. Capabilities for initiating, suspending, resuming and terminating
management scripts.
3. Capabilities to transfer arguments for management scripts.
4. Capabilities to monitor and control running management scripts.
5. Capabilities to transfer the results produced by running
management scripts.
This memo does not address any additional topics like the generation
of notifications or how to address remote agents from a Script MIB
implementation.
3.1. Terms
This section defines the terms used throughout this memo.
o A `distributed manager' is a processing entity which is capable of
performing network management functions. For the scope of this
memo, a distributed manager is assumed to implement the Script
MIB.
o A `higher-level manager', or just `manager', is a processing
entity or human who initiates and controls the operations
performed by one or more distributed managers.
o A `management script' is a set of instructions written in an
executable language which implements a management function.
o A `management scripting language' is a language used to write
management scripts. The term scripting language does not imply
that the language must have the characteristics of scripting
languages (e.g., string orientation, interpretation, weak typing).
The MIB defined in this memo also allows to control management
scripts written in arbitrary compiled system programming
languages.
o A `distributed manager' can be decomposed into an `SNMP entity'
which implements the Script MIB defined in this memo and the `
runtime system' that executes scripts. The Script MIB sees the
runtime system as the managed resource which is controlled by the
MIB.
The runtime system can act as an SNMP application, according to
the SNMP architecture defined in RFC 2571 [RFC2571]. For example,
a runtime system which sends SNMP requests to other SNMP entities
will act as a command generator application. The SNMP
applications in the runtime system may use the same SNMP engine
which also serves the command responder application used to
implement the Script MIB, but they are not required to do so.
o A `launch button' is the conceptual button used to start the
execution of a management script. It assigns control parameters
to a management script. In particular, it defines the ownership
of the scripts started from a launch button. The ownership can be
used by the language runtime system to enforce security profiles
on a running management script.
4. Requirements and Design Issues
This section discusses some general requirements that have influenced
the design of the Script MIB.
o The Script MIB must not make any assumptions about specific
languages or runtime systems.
o The Script MIB must provide mechanisms that help to avoid new
management problems (e.g., script version problems).
o The Script MIB must provide SNMP interfaces to all functions
required to delegate management scripts. However, other protocols
might be used in addition if they provide a significant
improvement in terms of convenience for implementation or
performance.
o The Script MIB must be organized so that access can be controlled
effectively by using view-based access control [RFC2575].
The following sections discuss some design issues in more detail.
4.1. Script Languages
The Script MIB defined in this memo makes no assumption about the
script language. This MIB can therefore be used in combination with
different languages (such as Tcl or Java) and/or different versions
of the same language. No assumptions are made about the format in
which management scripts are transferred.
The Script MIB provides access to information about the language
versions supported by a Script MIB implementation so that a manager
can learn about the capabilities provided by an implementation.
Languages and language versions are identified as follows:
1. The language is identified by an object identifier. Object
identifier for well-known languages will be registered by the
Internet Assigned Numbers Authority (IANA). Enterprise specific
languages can also be registered in the enterprise specific OID
subtree.
2. A particular version of a language is identified by a language
version number. The combination of a language object identifier
and a language version is in most cases sufficient to decide
whether a script can be executed or not.
3. Different implementations of the same language version might have
differences due to ambiguities in the language definition or
additional language features provided by an implementor. An
additional object identifier value is provided which identifies
the organization which provides the implementation of a language.
This might be used by scripts that require a particular
implementation of a language.
4. Finally, there might be different versions of a language
implementation. A version number for the language implementation
is provided so that the manager can also distinguish between
different implementations from the same organization of a
particular language version.
The version numbers can either be used by a manager to select the
language version required to execute a particular script or to select
a script that fits the language versions supported by a particular
Script MIB implementation.
An additional table lists language extensions that provide features
not provided by the core language. Language extensions are usually
required to turn a general purpose language into a management
language. In many cases, language extensions will come in the form
of libraries that provide capabilities like sending SNMP requests to
remote SNMP agents or accessing the local MIB instrumentation. Every
extension is associated with a language and carries its own version
numbers.
4.2. Script Transfer
There are two different ways to transfer management scripts to a
distributed manager. The first approach requires that the manager
pushes the script to the distributed manager. This is therefore
called the `push model'. The second approach is the `pull model'
where the manager tells the distributed manager the location of the
script and the distributed manager retrieves the script itself.
The MIB defined in this memo supports both models. The `push model'
is realized by a table which allows a manager to write scripts by
sending a sequence of SNMP set requests. The script can be split
into several fragments in order to deal with SNMP message size
limitations.
The `pull model' is realized by the use of Uniform Resource Locators
(URLs) [RFC2396] that point to the script source. The manager writes
the URL which points to the script source to the distributed manager
by sending an SNMP set request. The distributed manager is then
responsible for retrieving the document using the protocol specified
in the URL. This allows the use of protocols like FTP [RFC959] or
HTTP [RFC2616] to transfer large management scripts efficiently.
The Script MIB also allows management scripts that are hard-wired
into the Script MIB implementation. Built-in scripts can either be
implemented in a language runtime system, or they can be built
natively into the Script MIB implementation. The implementation of
the `push model' or the `pull model' is not required.
Scripts can be stored in non-volatile storage. This allows a
distributed manager to restart scripts if it is restarted (off-line
restart). A manager is not required to push scripts back into the
distributed manager after a restart if the script is backed up in
non-volatile storage.
Every script is identified by an administratively assigned name.
This name may be used to derive the name which is used to access the
script in non-volatile storage. This mapping is implementation
specific. However, the mapping must ensure that the Script MIB
implementation can handle scripts with the same administrative name
owned by different managers. One way to achieve this is to use the
script owner in addition to the script name in order to derive the
internal name used to refer to a particular script in non-volatile
storage.
4.3. Script Execution
The Script MIB permits execution of several instances of the same or
different management scripts. Script arguments are passed as OCTET
STRING values. Scripts return a single result value which is also an
OCTET STRING value. The semantic interpretation of result values is
left to the invoking manager or other management scripts. A script
invoker must understand the format and semantics of both the
arguments and the results of the scripts that it invokes.
Scripts can also export complex results through a MIB interface.
This allows a management application to access and use script results
in the same manner as it processes any other MIB data. However, the
Script MIB does not provide any special support for the
implementation of MIBs through scripts.
Runtime errors terminate active scripts. An exit code and a human
readable error message is left in the MIB. A notification containing
the exit code, the error message and a timestamp is generated when a
script terminates with an error exit code.
Script arguments and results do not have any size limitations other
than the limits imposed by the SMI and the SNMP protocol. However,
implementations of this MIB might have further restrictions. A
script designer might therefore choose to return the results via
other mechanisms if the script results can be very large. One
possibility is to return a URL as a script result which points to the
file containing the script output.
Executing scripts have a status object attached which allows script
execution to be suspended, resumed, or aborted. The precise
semantics of the suspend and resume operations are language and
runtime system dependent. Some runtime systems may choose to not
implement the suspend/resume operations.
A history of finished scripts is kept in the MIB. A script invoker
can collect results at a later point in time (offline operation).
Control objects can be used to control how entries in the history are
aged out if the table fills up.
5. Structure of the MIB
This section presents the structure of the MIB. The objects are
arranged into the following groups:
o language group (smLangTable, smExtsnTable)
o script group (smScriptTable)
o script code group (smCodeTable)
o script launch group (smLaunchTable)
o running script group (smRunTable)
5.1. Language Group
The smLanguageGroup is used to provide information about the
languages and the language extensions supported by a Script MIB
implementation. This group includes two tables. The smLangTable
lists all languages supported by a Script MIB implementation and the
smExtsnTable lists the extensions that are available for a given
language.
5.2. Script Group
The smScriptGroup consists of a single table, called the
smScriptTable. The smScriptTable lists all scripts known to a Script
MIB implementation. The smScriptTable contains objects that allow
the following operations:
o download scripts from a URL (pull model)
o read scripts from local non-volatile storage
o store scripts in local non-volatile storage
o delete scripts from local non-volatile storage
o list permanent scripts (that can not be changed or removed)
o read and modify the script status (enabled, disabled, editing)
A status object called smScriptOperStatus allows a manager to obtain
the current status of a script. It is also used to provide an error
indication if an attempt to invoke one of the operations listed above
fails. The status change of a script can be requested by modifying
the associated smScriptAdminStatus object.
The source of a script is defined by the smScriptSource object. This
object may contain a URL pointing to a remote location which provides
access to the management script. The script source is read from the
smCodeTable (described below) or from non-volatile storage if the
smScriptSource object contains an empty URL. The smScriptStorageType
object is used to distinguish between scripts read from non-volatile
storage and scripts read from the smCodeTable.
Scripts are automatically loaded once the smScriptAdminStatus object
is set to `enabled'. Loading a script includes retrieving the script
(probably from a remote location), compiling the script for languages
that require a compilation step, and making the code available to the
runtime system. The smScriptOperStatus object is used to indicate
the status of the loading process. This object will start in the
state `retrieving', switch to the state `compiling' and finally reach
the state `enabled'. Errors during the retrieval or compilation
phase will result in an error state such as `compilationFailed'.
5.3. Code Group
The smCodeGroup consists of a single table, called the smCodeTable,
which provides the ability to transfer and modify scripts via SNMP
set requests. In particular, the smCodeTable allows the following
operations:
o download scripts via SNMP (push model)
o modify scripts via SNMP (editing)
The smCodeTable lists the code of a script. A script can be
fragmented over multiple rows of the smCodeTable in order to handle
SNMP message size limitations. Modifications of the smCodeTable are
only possible if the associated smScriptOperStatus object has the
value `editing'. The Script MIB implementation reloads the modified
script code once the smScriptOperStatus changes to `enabled' again.
The implementation of the smCodeGroup is optional.
5.4. Launch Group
The smLaunchGroup contains a single table, the smLaunchTable. An
entry in the smLaunchTable represents a launch button which can be
used to start a script. The smLaunchTable allows the following
operations:
o associate a script with an owner used during script execution
o provide arguments and parameters for script invocation
o invoke scripts with a single set operation
The smLaunchTable describes scripts and their parameters that are
ready to be launched. An entry in the smLaunchTable attaches an
argument to a script and control values which, for example, define
the maximum number of times that a script invoked from a particular
row in the smLaunchTable may be running concurrently.
An entry in the smLaunchTable also defines the owner which will be
used to associate permissions with the script execution.
5.5. Run Group
The smRunGroup contains a single table, called the smRunTable, which
lists all scripts that are currently running or have terminated
recently. The smRunTable contains objects that allow the following
operations:
o retrieve status information from running scripts
o control running scripts (suspend, resume, abort)
o retrieve results from recently terminated scripts
o control the remaining maximum lifetime of a running script
o control how long script results are accessible
Every row in the smRunTable contains the argument passed during
script invocation, the result produced by the script and the script
exit code. The smRunTable also provides information about the
current run state as well as start and end time-stamps. There are
three writable objects in the smRunTable. The smRunLifeTime object
defines the maximum time a running script may run before it is
terminated by the Script MIB implementation. The smRunExpireTime
object defines the time that a completed script can stay in the
smRunTable before it is aged out. The smRunControl object allows
running scripts to be suspended, resumed, or aborted.
6. Definitions
DISMAN-SCRIPT-MIB DEFINITIONS ::= BEGIN
IMPORTS
MODULE-IDENTITY, OBJECT-TYPE, NOTIFICATION-TYPE,
Integer32, Unsigned32, mib-2
FROM SNMPv2-SMI
RowStatus, TimeInterval, DateAndTime, StorageType, DisplayString
FROM SNMPv2-TC
MODULE-COMPLIANCE, OBJECT-GROUP, NOTIFICATION-GROUP
FROM SNMPv2-CONF
SnmpAdminString
FROM SNMP-FRAMEWORK-MIB;
scriptMIB MODULE-IDENTITY
LAST-UPDATED "200108210000Z"
ORGANIZATION "IETF Distributed Management Working Group"
CONTACT-INFO
"WG EMail: disman@dorothy.bmc.com
Subscribe: disman-request@dorothy.bmc.com
Chair: Randy Presuhn
BMC Software, Inc.
Postal: Office 1-3141
2141 North First Street
San Jose, California 95131
USA
EMail: rpresuhn@bmc.com
Phone: +1 408 546-1006
Editor: David B. Levi
Nortel Networks
Postal: 4401 Great America Parkway
Santa Clara, CA 95052-8185
USA
EMail: dlevi@nortelnetworks.com
Phone: +1 423 686 0432
Editor: Juergen Schoenwaelder
TU Braunschweig
Postal: Bueltenweg 74/75
38106 Braunschweig
Germany
EMail: schoenw@ibr.cs.tu-bs.de
Phone: +49 531 391-3283"
DESCRIPTION
"This MIB module defines a set of objects that allow to
delegate management scripts to distributed managers."
REVISION "200108210000Z"
DESCRIPTION
"Revised version, published as RFC 3165.
This revision introduces several new objects: smScriptError,
smScriptLastChange, smLaunchError, smLaunchLastChange,
smLaunchRowExpireTime, smRunResultTime, and smRunErrorTime.
The following existing objects were updated: the maximum
value of smRunLifeTime now disables the timer, an
autostart value was added to the smLaunchAdminStatus
object, and a new expired state was added to the
smLaunchOperStatus object.
A new smScriptException notification has been added to
support runtime error notifications.
Created new conformance and compliance statements that
take care of the new objects and notifications.
Clarifications have been added in several places to remove
ambiguities or contradictions that were discovered and
reported by implementors."
REVISION "199902221800Z"
DESCRIPTION
"Initial version, published as RFC 2592."
::= { mib-2 64 }
--
-- The groups defined within this MIB module:
--
smObjects OBJECT IDENTIFIER ::= { scriptMIB 1 }
smNotifications OBJECT IDENTIFIER ::= { scriptMIB 2 }
smConformance OBJECT IDENTIFIER ::= { scriptMIB 3 }
--
-- Script language and language extensions.
--
-- This group defines tables which list the languages and the
-- language extensions supported by a Script MIB implementation.
-- Languages are uniquely identified by object identifier values.
--
smLangTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmLangEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table lists supported script languages."
::= { smObjects 1 }
smLangEntry OBJECT-TYPE
SYNTAX SmLangEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular language."
INDEX { smLangIndex }
::= { smLangTable 1 }
SmLangEntry ::= SEQUENCE {
smLangIndex Integer32,
smLangLanguage OBJECT IDENTIFIER,
smLangVersion SnmpAdminString,
smLangVendor OBJECT IDENTIFIER,
smLangRevision SnmpAdminString,
smLangDescr SnmpAdminString
}
smLangIndex OBJECT-TYPE
<span class="Verified-inline-styling" id='inline-330'> SYNTAX Integer32 (0..2147483647) <button id="btn_330" target="expand_330" onclick='hideFunction("expand_330")'>Expand</button>
</span id__locate=330>
<div class="nodeCloseClass" id='expand_330'><div class='Verified-endnote-styling' id='eid330'>
<pre>
<b><i><a href='https://www.rfc-editor.org/errata/eid330'>EID 330</a> (Verified) is as follows:</i></b>
<b>Section:</b> 6
<b>Original Text:</b>
SYNTAX Integer32 (1..2147483647)
<b>Corrected Text:</b>
SYNTAX Integer32 (0..2147483647)
</pre>
<b>Notes:</b><br/>
</div>
</div> MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The locally arbitrary, but unique identifier associated
with this language entry.
The value is expected to remain constant at least from one
re-initialization of the entity's network management system
to the next re-initialization.
Note that the data type and the range of this object must
be consistent with the definition of smScriptLanguage."
::= { smLangEntry 1 }
smLangLanguage OBJECT-TYPE
SYNTAX OBJECT IDENTIFIER
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The globally unique identification of the language."
::= { smLangEntry 2 }
smLangVersion OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The version number of the language. The zero-length string
shall be used if the language does not have a version
number.
It is suggested that the version number consist of one or
more decimal numbers separated by dots, where the first
number is called the major version number."
::= { smLangEntry 3 }
smLangVendor OBJECT-TYPE
SYNTAX OBJECT IDENTIFIER
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"An object identifier which identifies the vendor who
provides the implementation of the language. This object
identifier SHALL point to the object identifier directly
below the enterprise object identifier {1 3 6 1 4 1}
allocated for the vendor. The value must be the object
identifier {0 0} if the vendor is not known."
::= { smLangEntry 4 }
smLangRevision OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The version number of the language implementation.
The value of this object must be an empty string if
version number of the implementation is unknown.
It is suggested that the value consist of one or more
decimal numbers separated by dots, where the first
number is called the major version number."
::= { smLangEntry 5 }
smLangDescr OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"A textual description of the language."
::= { smLangEntry 6 }
smExtsnTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmExtsnEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table lists supported language extensions."
::= { smObjects 2 }
smExtsnEntry OBJECT-TYPE
SYNTAX SmExtsnEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular language extension."
INDEX { smLangIndex, smExtsnIndex }
::= { smExtsnTable 1 }
SmExtsnEntry ::= SEQUENCE {
smExtsnIndex Integer32,
smExtsnExtension OBJECT IDENTIFIER,
smExtsnVersion SnmpAdminString,
smExtsnVendor OBJECT IDENTIFIER,
smExtsnRevision SnmpAdminString,
smExtsnDescr SnmpAdminString
}
smExtsnIndex OBJECT-TYPE
SYNTAX Integer32 (1..2147483647)
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The locally arbitrary, but unique identifier associated
with this language extension entry.
The value is expected to remain constant at least from one
re-initialization of the entity's network management system
to the next re-initialization."
::= { smExtsnEntry 1}
smExtsnExtension OBJECT-TYPE
SYNTAX OBJECT IDENTIFIER
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The globally unique identification of the language
extension."
::= { smExtsnEntry 2 }
smExtsnVersion OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The version number of the language extension.
It is suggested that the version number consist of one or
more decimal numbers separated by dots, where the first
number is called the major version number."
::= { smExtsnEntry 3 }
smExtsnVendor OBJECT-TYPE
SYNTAX OBJECT IDENTIFIER
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"An object identifier which identifies the vendor who
provides the implementation of the extension. The
object identifier value should point to the OID node
directly below the enterprise OID {1 3 6 1 4 1}
allocated for the vendor. The value must by the object
identifier {0 0} if the vendor is not known."
::= { smExtsnEntry 4 }
smExtsnRevision OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The version number of the extension implementation.
The value of this object must be an empty string if
version number of the implementation is unknown.
It is suggested that the value consist of one or more
decimal numbers separated by dots, where the first
number is called the major version number."
::= { smExtsnEntry 5 }
smExtsnDescr OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"A textual description of the language extension."
::= { smExtsnEntry 6 }
--
-- Scripts known by the Script MIB implementation.
--
-- This group defines a table which lists all known scripts.
-- Scripts can be added and removed through manipulation of the
-- smScriptTable.
--
smScriptObjects OBJECT IDENTIFIER ::= { smObjects 3 }
smScriptTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmScriptEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table lists and describes locally known scripts."
::= { smScriptObjects 1 }
smScriptEntry OBJECT-TYPE
SYNTAX SmScriptEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular script. Every script that
is stored in non-volatile memory is required to appear in
this script table."
INDEX { smScriptOwner, smScriptName }
::= { smScriptTable 1 }
SmScriptEntry ::= SEQUENCE {
smScriptOwner SnmpAdminString,
smScriptName SnmpAdminString,
smScriptDescr SnmpAdminString,
smScriptLanguage Integer32,
smScriptSource DisplayString,
smScriptAdminStatus INTEGER,
smScriptOperStatus INTEGER,
smScriptStorageType StorageType,
smScriptRowStatus RowStatus,
smScriptError SnmpAdminString,
smScriptLastChange DateAndTime
}
smScriptOwner OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The manager who owns this row in the smScriptTable."
::= { smScriptEntry 1 }
smScriptName OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (1..32))
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The locally-unique, administratively assigned name for this
script. This object allows an smScriptOwner to have multiple
entries in the smScriptTable.
This value of this object may be used to derive the name
(e.g. a file name) which is used by the Script MIB
implementation to access the script in non-volatile
storage. The details of this mapping are implementation
specific. However, the mapping needs to ensure that scripts
created by different owners with the same script name do not
map to the same name in non-volatile storage."
::= { smScriptEntry 2 }
smScriptDescr OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"A description of the purpose of the script."
::= { smScriptEntry 3 }
smScriptLanguage OBJECT-TYPE
SYNTAX Integer32 (0..2147483647)
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object type identifies an entry in the
smLangTable which is used to execute this script.
The special value 0 may be used by hard-wired scripts
that can not be modified and that are executed by
internal functions.
Set requests to change this object are invalid if the
value of smScriptOperStatus is `enabled' or `compiling'
and will result in an inconsistentValue error.
Note that the data type and the range of this object must
be consistent with the definition of smLangIndex."
::= { smScriptEntry 4 }
smScriptSource OBJECT-TYPE
SYNTAX DisplayString
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"This object either contains a reference to the script
source or an empty string. A reference must be given
in the form of a Uniform Resource Locator (URL) as
defined in RFC 2396. The allowed character sets and the
encoding rules defined in RFC 2396 section 2 apply.
When the smScriptAdminStatus object is set to `enabled',
the Script MIB implementation will `pull' the script
source from the URL contained in this object if the URL
is not empty.
An empty URL indicates that the script source is loaded
from local storage. The script is read from the smCodeTable
if the value of smScriptStorageType is volatile. Otherwise,
the script is read from non-volatile storage.
Note: This document does not mandate implementation of any
specific URL scheme. An attempt to load a script from a
nonsupported URL scheme will cause the smScriptOperStatus
to report an `unknownProtocol' error.
Set requests to change this object are invalid if the
value of smScriptOperStatus is `enabled', `editing',
`retrieving' or `compiling' and will result in an
inconsistentValue error."
DEFVAL { ''H }
::= { smScriptEntry 5 }
smScriptAdminStatus OBJECT-TYPE
SYNTAX INTEGER {
enabled(1),
disabled(2),
editing(3)
}
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object indicates the desired status of
the script. See the definition of smScriptOperStatus for
a description of the values.
When the smScriptAdminStatus object is set to `enabled' and
the smScriptOperStatus is `disabled' or one of the error
states, the Script MIB implementation will `pull' the script
source from the URL contained in the smScriptSource object
if the URL is not empty."
DEFVAL { disabled }
::= { smScriptEntry 6 }
smScriptOperStatus OBJECT-TYPE
SYNTAX INTEGER {
enabled(1),
disabled(2),
editing(3),
retrieving(4),
compiling(5),
noSuchScript(6),
accessDenied(7),
wrongLanguage(8),
wrongVersion(9),
compilationFailed(10),
noResourcesLeft(11),
unknownProtocol(12),
protocolFailure(13),
genericError(14)
}
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The actual status of the script in the runtime system. The
value of this object is only meaningful when the value of
the smScriptRowStatus object is `active'.
The smScriptOperStatus object may have the following values:
- `enabled' indicates that the script is available and can
be started by a launch table entry.
- `disabled' indicates that the script can not be used.
- `editing' indicates that the script can be modified in the
smCodeTable.
- `retrieving' indicates that the script is currently being
loaded from non-volatile storage or a remote system.
- `compiling' indicates that the script is currently being
compiled by the runtime system.
- `noSuchScript' indicates that the script does not exist
at the smScriptSource.
- `accessDenied' indicates that the script can not be loaded
from the smScriptSource due to a lack of permissions.
- `wrongLanguage' indicates that the script can not be
loaded from the smScriptSource because of a language
mismatch.
- `wrongVersion' indicates that the script can not be loaded
from the smScriptSource because of a language version
mismatch.
- `compilationFailed' indicates that the compilation failed.
- `noResourcesLeft' indicates that the runtime system does
not have enough resources to load the script.
- `unknownProtocol' indicates that the script could not be
loaded from the smScriptSource because the requested
protocol is not supported.
- `protocolFailure' indicates that the script could not be
loaded from the smScriptSource because of a protocol
failure.
- `genericError' indicates that the script could not be
loaded due to an error condition not listed above.
The `retrieving' and `compiling' states are transient states
which will either lead to one of the error states or the
`enabled' state. The `disabled' and `editing' states are
administrative states which are only reached by explicit
management operations.
All launch table entries that refer to this script table
entry shall have an smLaunchOperStatus value of `disabled'
when the value of this object is not `enabled'."
DEFVAL { disabled }
::= { smScriptEntry 7 }
smScriptStorageType OBJECT-TYPE
SYNTAX StorageType
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"This object defines whether this row and the script
controlled by this row are kept in volatile storage and
lost upon reboot or if this row is backed up by
non-volatile or permanent storage.
The storage type of this row always complies with the value
of this entry if the value of the corresponding RowStatus
object is `active'.
However, the storage type of the script controlled by this
row may be different, if the value of this entry is
`non-volatile'. The script controlled by this row is written
into local non-volatile storage if the following condition
becomes true:
(a) the URL contained in the smScriptSource object is empty
and
(b) the smScriptStorageType is `nonVolatile'
and
(c) the smScriptOperStatus is `enabled'
Setting this object to `volatile' removes a script from
non-volatile storage if the script controlled by this row
has been in non-volatile storage before. Attempts to set
this object to permanent will always fail with an
inconsistentValue error.
The value of smScriptStorageType is only meaningful if the
value of the corresponding RowStatus object is `active'.
If smScriptStorageType has the value permanent(4), then all
objects whose MAX-ACCESS value is read-create must be
writable, with the exception of the smScriptStorageType and
smScriptRowStatus objects, which shall be read-only."
DEFVAL { volatile }
::= { smScriptEntry 8 }
smScriptRowStatus OBJECT-TYPE
SYNTAX RowStatus
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"A control that allows entries to be added and removed from
this table.
Changing the smScriptRowStatus from `active' to
`notInService' will remove the associated script from the
runtime system.
Deleting conceptual rows from this table may affect the
deletion of other resources associated with this row. For
example, a script stored in non-volatile storage may be
removed from non-volatile storage.
An entry may not exist in the `active' state unless all
required objects in the entry have appropriate values. Rows
that are not complete or not in service are not known by the
script runtime system.
Attempts to `destroy' a row or to set a row `notInService'
while the smScriptOperStatus is `enabled' will result in an
inconsistentValue error.
Attempts to `destroy' a row or to set a row `notInService'
where the value of the smScriptStorageType object is
`permanent' or `readOnly' will result in an
inconsistentValue error.
The value of this object has no effect on whether other
objects in this conceptual row can be modified."
::= { smScriptEntry 9 }
smScriptError OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"This object contains a descriptive error message if the
transition into the operational status `enabled' failed.
Implementations must reset the error message to a
zero-length string when a new attempt to change the
script status to `enabled' is started."
DEFVAL { ''H }
::= { smScriptEntry 10 }
smScriptLastChange OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when this script table entry was last
modified. The value '0000000000000000'H is returned if
the script table entry has not yet been modified.
Note that the resetting of smScriptError is not considered
a change of the script table entry."
DEFVAL { '0000000000000000'H }
::= { smScriptEntry 11 }
--
-- Access to script code via SNMP
--
-- The smCodeTable allows script code to be read and modified
-- via SNMP.
--
smCodeTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmCodeEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table contains the script code for scripts that are
written via SNMP write operations."
::= { smScriptObjects 2 }
smCodeEntry OBJECT-TYPE
SYNTAX SmCodeEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular fragment of a script."
INDEX { smScriptOwner, smScriptName, smCodeIndex }
::= { smCodeTable 1 }
SmCodeEntry ::= SEQUENCE {
smCodeIndex Unsigned32,
smCodeText OCTET STRING,
smCodeRowStatus RowStatus
}
smCodeIndex OBJECT-TYPE
SYNTAX Unsigned32 (1..4294967295)
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The index value identifying this code fragment."
::= { smCodeEntry 1 }
smCodeText OBJECT-TYPE
SYNTAX OCTET STRING (SIZE (1..1024))
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The code that makes up a fragment of a script. The format
of this code fragment depends on the script language which
is identified by the associated smScriptLanguage object."
::= { smCodeEntry 2 }
smCodeRowStatus OBJECT-TYPE
SYNTAX RowStatus
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"A control that allows entries to be added and removed from
this table.
The value of this object has no effect on whether other
objects in this conceptual row can be modified."
::= { smCodeEntry 3 }
--
-- Script execution.
--
-- This group defines tables which allow script execution to be
-- initiated, suspended, resumed, and terminated. It also provides
-- a mechanism for keeping a history of recent script executions
-- and their results.
--
smRunObjects OBJECT IDENTIFIER ::= { smObjects 4 }
smLaunchTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmLaunchEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table lists and describes scripts that are ready
to be executed together with their parameters."
::= { smRunObjects 1 }
smLaunchEntry OBJECT-TYPE
SYNTAX SmLaunchEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular executable script."
INDEX { smLaunchOwner, smLaunchName }
::= { smLaunchTable 1 }
SmLaunchEntry ::= SEQUENCE {
smLaunchOwner SnmpAdminString,
smLaunchName SnmpAdminString,
smLaunchScriptOwner SnmpAdminString,
smLaunchScriptName SnmpAdminString,
smLaunchArgument OCTET STRING,
smLaunchMaxRunning Unsigned32,
smLaunchMaxCompleted Unsigned32,
smLaunchLifeTime TimeInterval,
smLaunchExpireTime TimeInterval,
smLaunchStart Integer32,
smLaunchControl INTEGER,
smLaunchAdminStatus INTEGER,
smLaunchOperStatus INTEGER,
smLaunchRunIndexNext Integer32,
smLaunchStorageType StorageType,
smLaunchRowStatus RowStatus,
smLaunchError SnmpAdminString,
smLaunchLastChange DateAndTime,
smLaunchRowExpireTime TimeInterval
}
smLaunchOwner OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The manager who owns this row in the smLaunchTable. Every
instance of a running script started from a particular entry
in the smLaunchTable (i.e. entries in the smRunTable) will
be owned by the same smLaunchOwner used to index the entry
in the smLaunchTable. This owner is not necessarily the same
as the owner of the script itself (smLaunchScriptOwner)."
::= { smLaunchEntry 1 }
smLaunchName OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (1..32))
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The locally-unique, administratively assigned name for this
launch table entry. This object allows an smLaunchOwner to
have multiple entries in the smLaunchTable. The smLaunchName
is an arbitrary name that must be different from any other
smLaunchTable entries with the same smLaunchOwner but can be
the same as other entries in the smLaunchTable with
different smLaunchOwner values. Note that the value of
smLaunchName is not related in any way to the name of the
script being launched."
::= { smLaunchEntry 2 }
smLaunchScriptOwner OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object in combination with the value of
smLaunchScriptName identifies the script that can be
launched from this smLaunchTable entry. Attempts to write
this object will fail with an inconsistentValue error if
the value of smLaunchOperStatus is `enabled'."
::= { smLaunchEntry 3 }
smLaunchScriptName OBJECT-TYPE
SYNTAX SnmpAdminString (SIZE (0..32))
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object in combination with the value of
the smLaunchScriptOwner identifies the script that can be
launched from this smLaunchTable entry. The zero-length
string may be used to point to a non-existing script.
Attempts to write this object will fail with an
inconsistentValue error if the value of smLaunchOperStatus
is `enabled'."
DEFVAL { ''H }
::= { smLaunchEntry 4 }
smLaunchArgument OBJECT-TYPE
SYNTAX OCTET STRING
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The argument supplied to the script. When a script is
invoked, the value of this object is used to initialize
the smRunArgument object."
DEFVAL { ''H }
::= { smLaunchEntry 5 }
smLaunchMaxRunning OBJECT-TYPE
SYNTAX Unsigned32 (1..4294967295)
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The maximum number of concurrently running scripts that may
be invoked from this entry in the smLaunchTable. Lowering
the current value of this object does not affect any scripts
that are already executing."
DEFVAL { 1 }
::= { smLaunchEntry 6 }
smLaunchMaxCompleted OBJECT-TYPE
SYNTAX Unsigned32 (1..4294967295)
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The maximum number of finished scripts invoked from this
entry in the smLaunchTable allowed to be retained in the
smRunTable. Whenever the value of this object is changed
and whenever a script terminates, entries in the smRunTable
are deleted if necessary until the number of completed
scripts is smaller than the value of this object. Scripts
whose smRunEndTime value indicates the oldest completion
time are deleted first."
DEFVAL { 1 }
::= { smLaunchEntry 7 }
smLaunchLifeTime OBJECT-TYPE
SYNTAX TimeInterval
UNITS "centi-seconds"
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The default maximum amount of time a script launched
from this entry may run. The value of this object is used
to initialize the smRunLifeTime object when a script is
launched. Changing the value of an smLaunchLifeTime
instance does not affect scripts previously launched from
this entry."
DEFVAL { 360000 }
::= { smLaunchEntry 8 }
smLaunchExpireTime OBJECT-TYPE
SYNTAX TimeInterval
UNITS "centi-seconds"
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The default maximum amount of time information about a
script launched from this entry is kept in the smRunTable
after the script has completed execution. The value of
this object is used to initialize the smRunExpireTime
object when a script is launched. Changing the value of an
smLaunchExpireTime instance does not affect scripts
previously launched from this entry."
DEFVAL { 360000 }
::= { smLaunchEntry 9 }
smLaunchStart OBJECT-TYPE
SYNTAX Integer32 (0..2147483647)
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"This object is used to start the execution of scripts.
When retrieved, the value will be the value of smRunIndex
for the last script that started execution by manipulating
this object. The value will be zero if no script started
execution yet.
A script is started by setting this object to an unused
smRunIndex value. A new row in the smRunTable will be
created which is indexed by the value supplied by the
set-request in addition to the value of smLaunchOwner and
smLaunchName. An unused value can be obtained by reading
the smLaunchRunIndexNext object.
Setting this object to the special value 0 will start
the script with a self-generated smRunIndex value. The
consequence is that the script invoker has no reliable
way to determine the smRunIndex value for this script
invocation and that the invoker has therefore no way
to obtain the results from this script invocation. The
special value 0 is however useful for scheduled script
invocations.
If this object is set, the following checks must be
performed:
1) The value of the smLaunchOperStatus object in this
entry of the smLaunchTable must be `enabled'.
2) The values of smLaunchScriptOwner and
smLaunchScriptName of this row must identify an
existing entry in the smScriptTable.
3) The value of smScriptOperStatus of this entry must
be `enabled'.
4) The principal performing the set operation must have
read access to the script. This must be checked by
calling the isAccessAllowed abstract service interface
defined in RFC 2271 on the row in the smScriptTable
identified by smLaunchScriptOwner and smLaunchScriptName.
The isAccessAllowed abstract service interface must be
called on all columnar objects in the smScriptTable with
a MAX-ACCESS value different than `not-accessible'. The
test fails as soon as a call indicates that access is
not allowed.
5) If the value provided by the set operation is not 0,
a check must be made that the value is currently not
in use. Otherwise, if the value provided by the set
operation is 0, a suitable unused value must be
generated.
6) The number of currently executing scripts invoked
from this smLaunchTable entry must be less than
smLaunchMaxRunning.
Attempts to start a script will fail with an
inconsistentValue error if one of the checks described
above fails.
Otherwise, if all checks have been passed, a new entry
in the smRunTable will be created indexed by smLaunchOwner,
smLaunchName and the new value for smRunIndex. The value
of smLaunchArgument will be copied into smRunArgument,
the value of smLaunchLifeTime will be copied to
smRunLifeTime, and the value of smLaunchExpireTime
will be copied to smRunExpireTime.
The smRunStartTime will be set to the current time and
the smRunState will be set to `initializing' before the
script execution is initiated in the appropriate runtime
system.
Note that the data type and the range of this object must
be consistent with the smRunIndex object. Since this
object might be written from the scheduling MIB, the
data type Integer32 rather than Unsigned32 is used."
DEFVAL { 0 }
::= { smLaunchEntry 10 }
smLaunchControl OBJECT-TYPE
SYNTAX INTEGER {
abort(1),
suspend(2),
resume(3),
nop(4)
}
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"This object is used to request a state change for all
running scripts in the smRunTable that were started from
this row in the smLaunchTable.
Setting this object to abort(1), suspend(2) or resume(3)
will set the smRunControl object of all applicable rows
in the smRunTable to abort(1), suspend(2) or resume(3)
respectively. The phrase `applicable rows' means the set of
rows which were created from this entry in the smLaunchTable
and whose value of smRunState allows the corresponding
state change as described in the definition of the
smRunControl object. Setting this object to nop(4) has no
effect.
Attempts to set this object lead to an inconsistentValue
error only if all implicated sets on all the applicable
rows lead to inconsistentValue errors. It is not allowed
to return an inconsistentValue error if at least one state
change on one of the applicable rows was successful."
DEFVAL { nop }
::= { smLaunchEntry 11 }
smLaunchAdminStatus OBJECT-TYPE
SYNTAX INTEGER {
enabled(1),
disabled(2),
autostart(3)
}
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object indicates the desired status of
this launch table entry. The values enabled(1) and
autostart(3) both indicate that the launch table entry
should transition into the operational enabled(1) state as
soon as the associated script table entry is enabled(1).
The value autostart(3) further indicates that the script
is started automatically by conceptually writing the
value 0 into the associated smLaunchStart object during
the transition from the `disabled' into the `enabled'
operational state. This is useful for scripts that are
to be launched on system start-up."
DEFVAL { disabled }
::= { smLaunchEntry 12 }
smLaunchOperStatus OBJECT-TYPE
SYNTAX INTEGER {
enabled(1),
disabled(2),
expired(3)
}
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The value of this object indicates the actual status of
this launch table entry. The smLaunchOperStatus object
may have the following values:
- `enabled' indicates that the launch table entry is
available and can be used to start scripts.
- `disabled' indicates that the launch table entry can
not be used to start scripts.
- `expired' indicates that the launch table entry can
not be used to start scripts and will disappear as
soon as all smRunTable entries associated with this
launch table entry have disappeared.
The value `enabled' requires that the smLaunchRowStatus
object is active. The value `disabled' requires that there
are no entries in the smRunTable associated with this
smLaunchTable entry."
DEFVAL { disabled }
::= { smLaunchEntry 13 }
smLaunchRunIndexNext OBJECT-TYPE
SYNTAX Integer32 (1..2147483647)
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"This variable is used for creating rows in the smRunTable.
The value of this variable is a currently unused value
for smRunIndex, which can be written into the smLaunchStart
object associated with this row to launch a script.
The value returned when reading this variable must be unique
for the smLaunchOwner and smLaunchName associated with this
row. Subsequent attempts to read this variable must return
different values.
This variable will return the special value 0 if no new rows
can be created.
Note that the data type and the range of this object must be
consistent with the definition of smRunIndex."
::= { smLaunchEntry 14 }
smLaunchStorageType OBJECT-TYPE
SYNTAX StorageType
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"This object defines if this row is kept in volatile storage
and lost upon reboot or if this row is backed up by stable
storage.
The value of smLaunchStorageType is only meaningful if the
value of the corresponding RowStatus object is active.
If smLaunchStorageType has the value permanent(4), then all
objects whose MAX-ACCESS value is read-create must be
writable, with the exception of the smLaunchStorageType and
smLaunchRowStatus objects, which shall be read-only."
DEFVAL { volatile }
::= { smLaunchEntry 15 }
smLaunchRowStatus OBJECT-TYPE
SYNTAX RowStatus
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"A control that allows entries to be added and removed from
this table.
Attempts to `destroy' a row or to set a row `notInService'
while the smLaunchOperStatus is `enabled' will result in
an inconsistentValue error.
Attempts to `destroy' a row or to set a row `notInService'
where the value of the smLaunchStorageType object is
`permanent' or `readOnly' will result in an
inconsistentValue error.
The value of this object has no effect on whether other
objects in this conceptual row can be modified."
::= { smLaunchEntry 16 }
smLaunchError OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"This object contains a descriptive error message if an
attempt to launch a script fails. Implementations must reset
the error message to a zero-length string when a new attempt
to launch a script is started."
DEFVAL { ''H }
::= { smLaunchEntry 17 }
smLaunchLastChange OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when this launch table entry was last
modified. The value '0000000000000000'H is returned if
the launch table entry has not yet been modified.
Note that a change of smLaunchStart, smLaunchControl,
smLaunchRunIndexNext, smLaunchRowExpireTime, or the
resetting of smLaunchError is not considered a change
of this launch table entry."
DEFVAL { '0000000000000000'H }
::= { smLaunchEntry 18 }
smLaunchRowExpireTime OBJECT-TYPE
SYNTAX TimeInterval
UNITS "centi-seconds"
MAX-ACCESS read-create
STATUS current
DESCRIPTION
"The value of this object specifies how long this row remains
in the `enabled' or `disabled' operational state. The value
reported by this object ticks backwards. When the value
reaches 0, it stops ticking backward and the row is
deleted if there are no smRunTable entries associated with
this smLaunchTable entry. Otherwise, the smLaunchOperStatus
changes to `expired' and the row deletion is deferred
until there are no smRunTable entries associated with this
smLaunchTable entry.
The smLaunchRowExpireTime will not tick backwards if it is
set to its maximum value (2147483647). In other words,
setting this object to its maximum value turns the timer
off.
The value of this object may be set in order to increase
or reduce the remaining time that the launch table entry
may be used. Setting the value to 0 will cause an immediate
row deletion or transition into the `expired' operational
state.
It is not possible to set this object while the operational
status is `expired'. Attempts to modify this object while
the operational status is `expired' leads to an
inconsistentValue error.
Note that the timer ticks backwards independent of the
operational state of the launch table entry."
DEFVAL { 2147483647 }
::= { smLaunchEntry 19 }
smRunTable OBJECT-TYPE
SYNTAX SEQUENCE OF SmRunEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"This table lists and describes scripts that are currently
running or have been running in the past."
::= { smRunObjects 2 }
smRunEntry OBJECT-TYPE
SYNTAX SmRunEntry
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"An entry describing a particular running or finished
script."
INDEX { smLaunchOwner, smLaunchName, smRunIndex }
::= { smRunTable 1 }
SmRunEntry ::= SEQUENCE {
smRunIndex Integer32,
smRunArgument OCTET STRING,
smRunStartTime DateAndTime,
smRunEndTime DateAndTime,
smRunLifeTime TimeInterval,
smRunExpireTime TimeInterval,
smRunExitCode INTEGER,
smRunResult OCTET STRING,
smRunControl INTEGER,
smRunState INTEGER,
smRunError SnmpAdminString,
smRunResultTime DateAndTime,
smRunErrorTime DateAndTime
}
smRunIndex OBJECT-TYPE
SYNTAX Integer32 (1..2147483647)
MAX-ACCESS not-accessible
STATUS current
DESCRIPTION
"The locally arbitrary, but unique identifier associated
with this running or finished script. This value must be
unique for all rows in the smRunTable with the same
smLaunchOwner and smLaunchName.
Note that the data type and the range of this object must
be consistent with the definition of smLaunchRunIndexNext
and smLaunchStart."
::= { smRunEntry 1 }
smRunArgument OBJECT-TYPE
SYNTAX OCTET STRING
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The argument supplied to the script when it started."
DEFVAL { ''H }
::= { smRunEntry 2 }
smRunStartTime OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when the execution started. The value
'0000000000000000'H is returned if the script has not
started yet."
DEFVAL { '0000000000000000'H }
::= { smRunEntry 3 }
smRunEndTime OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when the execution terminated. The value
'0000000000000000'H is returned if the script has not
terminated yet."
DEFVAL { '0000000000000000'H }
::= { smRunEntry 4 }
smRunLifeTime OBJECT-TYPE
SYNTAX TimeInterval
UNITS "centi-seconds"
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"This object specifies how long the script can execute.
This object returns the remaining time that the script
may run. The object is initialized with the value of the
associated smLaunchLifeTime object and ticks backwards.
The script is aborted immediately when the value reaches 0.
The value of this object may be set in order to increase or
reduce the remaining time that the script may run. Setting
this value to 0 will abort script execution immediately,
and, if the value of smRunExpireTime is also 0, will remove
this entry from the smRunTable once it has terminated.
If smRunLifeTime is set to its maximum value (2147483647),
either by a set operation or by its initialization from the
smLaunchLifeTime object, then it will not tick backwards.
A running script with a maximum smRunLifeTime value will
thus never be terminated with a `lifeTimeExceeded' exit
code.
The value of smRunLifeTime reflects the real-time execution
time as seen by the outside world. The value of this object
will always be 0 for a script that finished execution, that
is smRunState has the value `terminated'.
The value of smRunLifeTime does not change while a script
is suspended, that is smRunState has the value `suspended'.
Note that this does not affect set operations. It is legal
to modify smRunLifeTime via set operations while a script
is suspended."
::= { smRunEntry 5 }
smRunExpireTime OBJECT-TYPE
SYNTAX TimeInterval
UNITS "centi-seconds"
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"The value of this object specifies how long this row can
exist in the smRunTable after the script has terminated.
This object returns the remaining time that the row may
exist before it is aged out. The object is initialized with
the value of the associated smLaunchExpireTime object and
ticks backwards. The entry in the smRunTable is destroyed
when the value reaches 0 and the smRunState has the value
`terminated'.
The value of this object may be set in order to increase or
reduce the remaining time that the row may exist. Setting
the value to 0 will destroy this entry as soon as the
smRunState has the value `terminated'."
::= { smRunEntry 6 }
smRunExitCode OBJECT-TYPE
SYNTAX INTEGER {
noError(1),
halted(2),
lifeTimeExceeded(3),
noResourcesLeft(4),
languageError(5),
runtimeError(6),
invalidArgument(7),
securityViolation(8),
genericError(9)
}
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The value of this object indicates the reason why a
script finished execution. The smRunExitCode code may have
one of the following values:
- `noError', which indicates that the script completed
successfully without errors;
- `halted', which indicates that the script was halted
by a request from an authorized manager;
- `lifeTimeExceeded', which indicates that the script
exited because a time limit was exceeded;
- `noResourcesLeft', which indicates that the script
exited because it ran out of resources (e.g. memory);
- `languageError', which indicates that the script exited
because of a language error (e.g. a syntax error in an
interpreted language);
- `runtimeError', which indicates that the script exited
due to a runtime error (e.g. a division by zero);
- `invalidArgument', which indicates that the script could
not be run because of invalid script arguments;
- `securityViolation', which indicates that the script
exited due to a security violation;
- `genericError', which indicates that the script exited
for an unspecified reason.
If the script has not yet begun running, or is currently
running, the value will be `noError'."
DEFVAL { noError }
::= { smRunEntry 7 }
smRunResult OBJECT-TYPE
SYNTAX OCTET STRING
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The result value produced by the running script. Note that
the result may change while the script is executing."
DEFVAL { ''H }
::= { smRunEntry 8 }
smRunControl OBJECT-TYPE
SYNTAX INTEGER {
abort(1),
suspend(2),
resume(3),
nop(4)
}
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"The value of this object indicates the desired status of the
script execution defined by this row.
Setting this object to `abort' will abort execution if the
value of smRunState is `initializing', `executing',
`suspending', `suspended' or `resuming'. Setting this object
to `abort' when the value of smRunState is `aborting' or
`terminated', or if the implementation can determine that
the attempt to abort the execution would fail, will result
in an inconsistentValue error.
Setting this object to `suspend' will suspend execution
if the value of smRunState is `executing'. Setting this
object to `suspend' will cause an inconsistentValue error
if the value of smRunState is not `executing' or if the
implementation can determine that the attempt to suspend
the execution would fail.
Setting this object to `resume' will resume execution
if the value of smRunState is `suspending' or
`suspended'. Setting this object to `resume' will cause an
inconsistentValue error if the value of smRunState is
not `suspended' or if the implementation can determine
that the attempt to resume the execution would fail.
Setting this object to nop(4) has no effect."
DEFVAL { nop }
::= { smRunEntry 9 }
smRunState OBJECT-TYPE
SYNTAX INTEGER {
initializing(1),
executing(2),
suspending(3),
suspended(4),
resuming(5),
aborting(6),
terminated(7)
}
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The value of this object indicates the script's execution
state. If the script has been invoked but has not yet
begun execution, the value will be `initializing'. If the
script is running, the value will be `executing'.
A running script which received a request to suspend
execution first transitions into a temporary `suspending'
state. The temporary `suspending' state changes to
`suspended' when the script has actually been suspended. The
temporary `suspending' state changes back to `executing' if
the attempt to suspend the running script fails.
A suspended script which received a request to resume
execution first transitions into a temporary `resuming'
state. The temporary `resuming' state changes to `running'
when the script has actually been resumed. The temporary
`resuming' state changes back to `suspended' if the attempt
to resume the suspended script fails.
A script which received a request to abort execution but
which is still running first transitions into a temporary
`aborting' state.
A script which has finished its execution is `terminated'."
::= { smRunEntry 10 }
smRunError OBJECT-TYPE
SYNTAX SnmpAdminString
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"This object contains a descriptive error message if the
script startup or execution raised an abnormal condition.
An implementation must store a descriptive error message
in this object if the script exits with the smRunExitCode
`genericError'."
DEFVAL { ''H }
::= { smRunEntry 11 }
smRunResultTime OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when the smRunResult was last updated.
The value '0000000000000000'H is returned if smRunResult
has not yet been updated after the creation of this
smRunTable entry."
DEFVAL { '0000000000000000'H }
::= { smRunEntry 12 }
smRunErrorTime OBJECT-TYPE
SYNTAX DateAndTime
MAX-ACCESS read-only
STATUS current
DESCRIPTION
"The date and time when the smRunError was last updated.
The value '0000000000000000'H is returned if smRunError
has not yet been updated after the creation of this
smRunTable entry."
DEFVAL { '0000000000000000'H }
::= { smRunEntry 13 }
--
-- Notifications. The definition of smTraps makes notification
-- registrations reversible (see STD 58, RFC 2578).
--
smTraps OBJECT IDENTIFIER ::= { smNotifications 0 }
smScriptAbort NOTIFICATION-TYPE
OBJECTS { smRunExitCode, smRunEndTime, smRunError }
STATUS current
DESCRIPTION
"This notification is generated whenever a running script
terminates with an smRunExitCode unequal to `noError'."
::= { smTraps 1 }
smScriptResult NOTIFICATION-TYPE
OBJECTS { smRunResult }
STATUS current
DESCRIPTION
"This notification can be used by scripts to notify other
management applications about results produced by the
script.
This notification is not automatically generated by the
Script MIB implementation. It is the responsibility of
the executing script to emit this notification where it
is appropriate to do so."
::= { smTraps 2 }
smScriptException NOTIFICATION-TYPE
OBJECTS { smRunError }
STATUS current
DESCRIPTION
"This notification can be used by scripts to notify other
management applications about script errors.
This notification is not automatically generated by the
Script MIB implementation. It is the responsibility of
the executing script or the runtime system to emit this
notification where it is appropriate to do so."
::= { smTraps 3 }
-- conformance information
smCompliances OBJECT IDENTIFIER ::= { smConformance 1 }
smGroups OBJECT IDENTIFIER ::= { smConformance 2 }
-- compliance statements
smCompliance2 MODULE-COMPLIANCE
STATUS current
DESCRIPTION
"The compliance statement for SNMP entities which implement
the Script MIB."
MODULE -- this module
MANDATORY-GROUPS {
smLanguageGroup, smScriptGroup2, smLaunchGroup2,
smRunGroup2, smNotificationsGroup2
}
GROUP smCodeGroup
DESCRIPTION
"The smCodeGroup is mandatory only for those implementations
that support the downloading of scripts via SNMP."
OBJECT smScriptSource
MIN-ACCESS read-only
DESCRIPTION
"The smScriptSource object is read-only for implementations
that are not able to download script code from a URL."
OBJECT smCodeText
DESCRIPTION
"A compliant implementation need only support write access to
the smCodeText object only during row creation."
OBJECT smLaunchArgument
DESCRIPTION
"A compliant implementation has to support a minimum size
for smLaunchArgument of 255 octets."
OBJECT smRunArgument
DESCRIPTION
"A compliant implementation has to support a minimum size
for smRunArgument of 255 octets."
OBJECT smRunResult
DESCRIPTION
"A compliant implementation has to support a minimum size
for smRunResult of 255 octets."
OBJECT smRunState
DESCRIPTION
"A compliant implementation does not have to support script
suspension and the smRunState `suspended'. Such an
implementation will change into the `suspending' state
when the smRunControl is set to `suspend' and remain in this
state until smRunControl is set to `resume' or the script
terminates."
::= { smCompliances 2 }
smLanguageGroup OBJECT-GROUP
OBJECTS {
smLangLanguage, smLangVersion,
smLangVendor, smLangRevision,
smLangDescr, smExtsnExtension,
smExtsnVersion, smExtsnVendor,
smExtsnRevision, smExtsnDescr
}
STATUS current
DESCRIPTION
"A collection of objects providing information about the
capabilities of the scripting engine."
::= { smGroups 1 }
smScriptGroup2 OBJECT-GROUP
OBJECTS {
smScriptDescr, smScriptLanguage,
smScriptSource, smScriptAdminStatus,
smScriptOperStatus, smScriptStorageType,
smScriptRowStatus, smScriptError,
smScriptLastChange
}
STATUS current
DESCRIPTION
"A collection of objects providing information about
installed scripts."
::= { smGroups 7 }
smCodeGroup OBJECT-GROUP
OBJECTS {
smCodeText, smCodeRowStatus
}
STATUS current
DESCRIPTION
"A collection of objects used to download or modify scripts
by using SNMP set requests."
::= { smGroups 3 }
smLaunchGroup2 OBJECT-GROUP
OBJECTS {
smLaunchScriptOwner, smLaunchScriptName,
smLaunchArgument, smLaunchMaxRunning,
smLaunchMaxCompleted, smLaunchLifeTime,
smLaunchExpireTime, smLaunchStart,
smLaunchControl, smLaunchAdminStatus,
smLaunchOperStatus, smLaunchRunIndexNext,
smLaunchStorageType, smLaunchRowStatus,
smLaunchError, smLaunchLastChange,
smLaunchRowExpireTime
}
STATUS current
DESCRIPTION
"A collection of objects providing information about scripts
that can be launched."
::= { smGroups 8 }
smRunGroup2 OBJECT-GROUP
OBJECTS {
smRunArgument, smRunStartTime,
smRunEndTime, smRunLifeTime,
smRunExpireTime, smRunExitCode,
smRunResult, smRunState,
smRunControl, smRunError,
smRunResultTime, smRunErrorTime
}
STATUS current
DESCRIPTION
"A collection of objects providing information about running
scripts."
::= { smGroups 9 }
smNotificationsGroup2 NOTIFICATION-GROUP
NOTIFICATIONS {
smScriptAbort,
smScriptResult,
smScriptException
}
STATUS current
DESCRIPTION
"The notifications emitted by the Script MIB."
::= { smGroups 10 }
--
-- Deprecated compliance and conformance group definitions
-- from RFC 2592.
--
smCompliance MODULE-COMPLIANCE
STATUS deprecated
DESCRIPTION
"The compliance statement for SNMP entities which implement
the Script MIB."
MODULE -- this module
MANDATORY-GROUPS {
smLanguageGroup, smScriptGroup, smLaunchGroup, smRunGroup
}
GROUP smCodeGroup
DESCRIPTION
"The smCodeGroup is mandatory only for those implementations
that support the downloading of scripts via SNMP."
OBJECT smScriptSource
MIN-ACCESS read-only
DESCRIPTION
"The smScriptSource object is read-only for implementations
that are not able to download script code from a URL."
OBJECT smCodeText
DESCRIPTION
"A compliant implementation need only support write access
to the smCodeText object during row creation."
OBJECT smLaunchArgument
DESCRIPTION
"A compliant implementation has to support a minimum size
for smLaunchArgument of 255 octets."
OBJECT smRunArgument
DESCRIPTION
"A compliant implementation has to support a minimum size
for smRunArgument of 255 octets."
OBJECT smRunResult
DESCRIPTION
"A compliant implementation has to support a minimum size
for smRunResult of 255 octets."
OBJECT smRunState
DESCRIPTION
"A compliant implementation does not have to support script
suspension and the smRunState `suspended'. Such an
implementation will change into the `suspending' state
when the smRunControl is set to `suspend' and remain in this
state until smRunControl is set to `resume' or the script
terminates."
::= { smCompliances 1 }
smScriptGroup OBJECT-GROUP
OBJECTS {
smScriptDescr, smScriptLanguage,
smScriptSource, smScriptAdminStatus,
smScriptOperStatus, smScriptStorageType,
smScriptRowStatus
}
STATUS deprecated
DESCRIPTION
"A collection of objects providing information about
installed scripts."
::= { smGroups 2 }
smLaunchGroup OBJECT-GROUP
OBJECTS {
smLaunchScriptOwner, smLaunchScriptName,
smLaunchArgument, smLaunchMaxRunning,
smLaunchMaxCompleted, smLaunchLifeTime,
smLaunchExpireTime, smLaunchStart,
smLaunchControl, smLaunchAdminStatus,
smLaunchOperStatus, smLaunchRunIndexNext,
smLaunchStorageType, smLaunchRowStatus
}
STATUS deprecated
DESCRIPTION
"A collection of objects providing information about scripts
that can be launched."
::= { smGroups 4 }
smRunGroup OBJECT-GROUP
OBJECTS {
smRunArgument, smRunStartTime,
smRunEndTime, smRunLifeTime,
smRunExpireTime, smRunExitCode,
smRunResult, smRunState,
smRunControl, smRunError
}
STATUS deprecated
DESCRIPTION
"A collection of objects providing information about running
scripts."
::= { smGroups 5 }
smNotificationsGroup NOTIFICATION-GROUP
NOTIFICATIONS {
smScriptAbort,
smScriptResult
}
STATUS deprecated
DESCRIPTION
"The notifications emitted by the Script MIB."
::= { smGroups 6 }
END
7. Usage Examples
This section presents some examples that explain how a manager can
use the Script MIB defined in this memo. The purpose of these
examples is to explain the steps that are normally used to delegate
management scripts.
7.1. Pushing a Script via SNMP
This example explains the steps performed by a manager to push a
script into a distributed manager.
1. The manager first checks the smLangTable and the smExtsnTable in
order to select the appropriate script or language.
2. The manager creates a row in the smScriptTable by issuing an SNMP
set-request. The smScriptRowStatus object is set to
`createAndWait' and the smScriptSource object is set to an empty
string. The smScriptLanguage object is set to the language in
which the script was written. The smScriptStorageType object is
set to `volatile' to indicate that the script will be loaded via
the smCodeTable. The smScriptOwner is set to a string which
identifies the principal who owns the new row. The smScriptName
defines the administratively assigned unique name for the script.
3. The manager sets the smScriptRowStatus object to `active' and the
smScriptAdminStatus object to `editing'.
4. The manager pushes the script to the distributed manager by
issuing a couple of SNMP set-requests to fill the smCodeTable.
5. Once the whole script has been transferred, the manager sends a
set-request to set the smScriptAdminStatus object to `enabled'.
The Script MIB implementation now makes the script accessible to
the runtime system. This might include the compilation of the
script if the language requires a compilation step.
6. The manager polls the smScriptOperStatus object until the value is
either `enabled' or one of the error status codes. The script can
only be used if the value of smScriptOperStatus is `enabled'.
7. If the manager wants to store the script in local non-volatile
storage, it should send a set-request which changes the
smScriptStorageType object to `nonVolatile'.
7.2. Pulling a Script from a URL
This example explains the steps performed by a manager to cause a
distributed manager to pull a script from a URL.
1. The manager first checks the smLangTable and the smExtsnTable in
order to select the appropriate script or language.
2. The manager creates a row in the smScriptTable by issuing an SNMP
set-request. The smScriptRowStatus object is set to
`createAndWait' and the smScriptSource object is set to the URL
which points to the script source. The smScriptLanguage object is
set to the language in which the script was written. The
smScriptOwner is set to a string which identifies the principal
who owns the new row. The smScriptName defines the
administratively assigned unique name for the script.
3. The manager sets the smScriptRowStatus object to `active'.
4. The manager sends a set-request to set the smScriptAdminStatus
object to `enabled'. The Script MIB implementation now makes the
script accessible to the runtime system. This causes a retrieval
operation to pull the script from the URL stored in
smScriptSource. This retrieval operation might be followed by a
compile operation if the language requires a compilation step.
5. The manager polls the smScriptOperStatus object until the value is
either `enabled' or one of the error status codes. The script can
only be used if the value of smScriptOperStatus is `enabled'.
6. If the manager wants to store the script in local non-volatile
storage, it should send a set-request which changes the
smScriptStorageType object to `nonVolatile'.
7.3. Modifying an Existing Script
This section explains how a manager can modify a script by sending
SNMP set-requests.
1. First, the script is de-activated by setting the
smScriptAdminStatus to `disabled'.
2. The manager polls the smScriptOperStatus object until the value is
`disabled'.
3. The manager sets smScriptSource to an empty string and
smScriptAdminStatus to `editing'. This makes the script source
available in the smCodeTable.
4. The manager polls the smScriptOperStatus object until the value is
`editing'.
5. The manager sends SNMP set-requests to modify the script in the
smCodeTable.
6. The manager sends a set-request to set the smScriptAdminStatus
object to `enabled'. The Script MIB implementation now makes the
script accessible to the runtime system. This might include the
compilation of the script if the language requires a compilation
step.
7. The manager polls the smScriptOperStatus object until the value is
either `enabled' or one of the error status codes. The script can
only be used if the value of smScriptOperStatus is `enabled'.
7.4. Removing an Existing Script
This section explains how a manager can remove a script from a
distributed manager.
1. First, the manager sets the smScriptAdminStatus to `disabled'.
This will ensure that no new scripts can be started while running
scripts finish their execution.
2. The manager polls the smScriptOperStatus object until the value is
`disabled'.
3. The manager sends an SNMP set-request to change the
smScriptRowStatus object to `destroy'. This will remove the row
and all associated resources from the Script MIB implementation.
7.5. Creating a Launch Button
This section explains how a manager can create a launch button for
starting a script.
1. The manager, who is identified by an smLaunchOwner value, first
chooses a name for the new row in the smLaunchTable. The manager
sends an SNMP set-request to set the smLaunchRowStatus object for
this smLaunchOwner and smLaunchName to `createAndWait'.
2. The manager fills the new smLaunchTable row with all required
parameters. The smLaunchScriptOwner and smLaunchScriptName values
point to the script that should be started from this launch
button.
3. The manager sets the smLaunchRowStatus object to `active'.
4. The manager sends a set-request to change smLaunchAdminStatus to
`enabled' once the new smLaunchTable row is complete.
5. The manager polls the smLaunchOperStatus object until the value is
`enabled'.
7.6. Launching a Script
This section explains the suggested way to launch a script from a
given launch button.
1. The manager first retrieves the value of smLaunchRunIndexNext from
the launch button selected to start the script.
2. The manager sends an SNMP set-request to set the smLaunchStart
object to the value obtained in step 1. This will launch the
script if all necessary pre-conditions are satisfied (see the
definition of smLaunchStart for more details). The manager can
also provide the smLaunchArgument in the same set-request that is
used to start the script. Upon successful start, a new row will
be created in the smRunTable indexed by smLaunchOwner,
smLaunchName and the value written to smLaunchStart.
3. The manager polls the smRunState object until the value is either
`executing' (the default case), `suspended' or `terminated'.
The first step is not required. A manager can also try to guess an
unused value for smRunIndex if the manager wants to start the script
in a single transaction. A manager can also use the special value 0
if it does not care about the smRunIndex.
7.7. Suspending a Running Script
This section explains how a manager can suspend a running script.
1. The manager sets the smRunControl object of the running script or
the smLaunchControl object of the launch button used to start the
running script to `suspend'. Setting smLaunchControl will suspend
all running scripts started from the launch button while
smRunControl will only suspend the running script associated with
the smRunControl instance.
2. The manager polls the smRunState object until the value is either
`suspended', `executing', or `terminated'. If the value is
`suspended', then the suspend operation was successful. If the
value is `executing', then the attempt to suspend the script
failed. The value `terminated' can be received in cases where the
suspend operation failed and the running script terminated between
the polls.
Note that the set operation in the first step can lead to an
inconsistentValue error which indicates that the suspend operation
failed (e.g., because the runtime system does not support
suspend/resume). There is no need to poll smRunState in this case.
7.8. Resuming a Suspended Script
This section explains how a manager can resume a suspended script.
1. The manager sets the smRunControl object of the running script or
the smLaunchControl object of the launch button used to start the
running script to `resume'. Setting smLaunchControl will resume
all running scripts started from the launch button while
smRunControl will only resume the running script associated with
the smRunControl instance.
2. The manager polls the smRunState object until the value is either
`suspended', `executing', or `terminated'. If the value is
`executing', then the resume operation was successful. If the
value is `suspended', then the attempt to resume the script
failed. The value `terminated' can be received in cases where the
resume operation was successful and the running script terminated
between the polls.
Note that the set operation in the first step can lead to an
inconsistentValue error which indicates that the resume operation
failed (e.g., because the runtime system does not support
suspend/resume). There is no need to poll smRunState in this case.
7.9. Terminating a Running Script
This section explains two ways to terminate a running script. The
first approach is as follows:
1. The manager sets the smRunControl object of the running script or
the smLaunchControl object of the launch button used to start the
running script to `abort'. Setting smLaunchControl will abort all
running scripts started from the launch button while smRunControl
will only abort the running script associated with the
smRunControl instance.
2. The manager polls the smRunState object until the value is
`terminated'.
The second way to terminate a script is to set the smRunLifeTime to
zero which causes the runtime system to terminate the script with a
`lifeTimeExceeded' exit code:
1. The manager changes the value of smRunLifeTime to 0. This causes
the Script MIB implementation to abort the script because the
remaining life time has expired.
2. The manager polls the smRunState object until the value is
`terminated'.
Note that changing the smRunLifeTime value can also be used to
increase the permitted lifetime of a running script. For example, a
manager can choose to set smRunLifeTime to a small fixed time
interval and increase the value periodically. This strategy has the
nice effect that scripts terminate automatically if the manager loses
contact with the Script MIB engine.
7.10. Removing a Terminated Script
This section explains how a manager can remove a terminated script.
1. The manager changes the smRunExpireTime to 0. This causes the
Script MIB implementation to destroy the smRunTable entry of the
terminated script.
7.11. Removing a Launch Button
This section explains how a manager can remove a launch button from a
distributed manager.
1. First, the manager sets the smLaunchAdminStatus to `disabled'.
This will ensure that no new scripts can be started from this
launch button while running scripts finish their execution.
2. The manager polls the smLaunchOperStatus object until the value is
`disabled'.
3. The manager sends an SNMP set-request to change the
smLaunchRowStatus object to `destroy'. This will remove the row
and all associated resources from the Script MIB implementation.
8. VACM Configuration Examples
This section shows how the view-based access control model defined in
RFC 2575 [RFC2575] can be configured to control access to the Script
MIB.
8.1. Sandbox for Guests
The first example demonstrates how to configure VACM to give the
members of the VACM group "guest" limited access to the Script MIB.
The MIB views defined below give the members of the "guest" group a
sandbox where they can install and start their own scripts, but not
access any other scripts maintained by the Script MIB implementation.
vacmAccessReadView."guest"."".usm.authNoPriv = "guestReadView"
vacmAccessWriteView."guest"."".usm.authNoPriv = "guestWriteView"
The guestReadView grants read access to the smLangTable, the
smExtsnTable and to all the table entries owned by "guest":
guestReadView:
smLangTable (included)
smExtsnTable (included)
smScriptObjects.*.*.*."guest" (included)
smRunObjects.*.*.*."guest" (included)
The guestWriteView grants write access to all the table entries owned
by "guest":
guestWriteView:
smScriptObjects.*.*.*."guest" (included)
smRunObjects.*.*.*."guest" (included)
8.2. Sharing Scripts
This example demonstrates how VACM can be used to share a repository
of scripts between the members of the "senior" and the members of the
"junior" VACM group:
vacmAccessReadView."junior"."".usm.authNoPriv = "juniorReadView"
vacmAccessWriteView."junior"."".usm.authNoPriv = "juniorWriteView"
juniorReadView:
smLangTable (included)
smExtsnTable (included)
smScriptObjects.*.*.*."junior" (included)
smRunObjects.*.*.*."junior" (included)
smScriptObjects.*.*.*."utils" (included)
juniorWriteView:
smScriptObjects.*.*.*."junior" (included)
smRunObjects.*.*.*."junior" (included)
The definitions above allow the members of the "junior" VACM group to
start the scripts owned by "utils" in addition to the script the
members of the "junior" VACM group installed themselves. This is
accomplished by giving the members of "junior" read access to scripts
in "utils". This allows members of "junior" to create entries in the
smLaunchTable which refer to scripts in "utils", and to launch those
scripts using these entries in the smLaunchTable.
vacmAccessReadView."senior"."".usm.authNoPriv = "seniorReadView"
vacmAccessWriteView."senior"."".usm.authNoPriv = "seniorWriteView"
seniorReadView:
smLangTable (included)
smExtsnTable (included)
smScriptObjects.*.*.*."senior" (included)
smRunObjects.*.*.*."senior" (included)
smScriptObjects.*.*.*."utils" (included)
seniorWriteView:
smScriptObjects.*.*.*."senior" (included)
smRunObjects.*.*.*."senior" (included)
smScriptObjects.*.*.*."utils" (included)
The definitions for the members of the "senior" VACM group allow to
start the scripts owned by "utils" in addition to the script the
members of the "senior" VACM group installed themself. The third
write access rule in the seniorWriteView also grants the permission
to install scripts owned by "utils". The members of the "senior"
VACM group therefore have the permissions to install and modify
scripts that can be called by the members of the "junior" VACM group.
8.3. Emergency Scripts
This example demonstrates how VACM can be used to allow the members
of the "junior" VACM group to launch scripts that are executed with
the permissions associated with the "emergency" owner. This works by
adding the following rules to the juniorReadView and the
juniorWriteView:
juniorReadView:
smScriptObjects.*.*.*."emergency" (included)
smRunObjects.*.*.*."emergency" (included)
juniorWriteView
smLaunchStart."emergency" (included)
smLaunchArgument."emergency" (included)
The rules added to the juniorReadView grant read access to the
scripts, the launch buttons and the results owned by "emergency".
The rules added to the juniorWriteView grant write permissions to the
smLaunchStart and smLaunchArgument variables owned by "emergency".
Members of the "junior" VACM group can therefore start scripts that
will execute under the owner "emergency".
seniorReadView:
smScriptObjects.*.*.*."emergency" (included)
smRunObjects.*.*.*."emergency" (included)
seniorWriteView:
smScriptObjects.*.*.*."emergency" (included)
smRunObjects.*.*.*."emergency" (included)
The rules added to the seniorReadView and the seniorWriteView will
give the members of the "senior" VACM group the rights to install
emergency scripts and to configure appropriate launch buttons.
9. IANA Considerations
The Internet Assigned Numbers Authority (IANA) is responsible for
maintaining a MIB module (IANA-LANGUAGE-MIB) which provides OID
registrations for well-known languages. The IANA language registry
is intended to reduce interoperability problems by providing a single
list of well-known languages. However, it is of course still
possible to register languages in private OID spaces. Registering
languages in private OID spaces is especially attractive if a
language is used for experimentation or if a language is only used in
environments where the distribution of MIB modules with the language
registration does not cause any maintenance problems.
Any additions or changes to the list of languages registered via IANA
require Designated Expert Review as defined in the IANA guidelines
[RFC2434]. The Designated Expert will be selected by the IESG Area
Director for the IETF Operations and Management Area.
10. Security Considerations
There are a number of management objects defined in this MIB that
have a MAX-ACCESS clause of read-write and/or read-create. Such
objects may be considered sensitive or vulnerable in some network
environments. The support for SET operations in a non-secure
environment without proper protection can have a negative effect on
network operations.
SNMPv1 by itself is not a secure environment. Even if the network
itself is secure (for example by using IPSec), even then, there is no
control as to who on the secure network is allowed to access and
GET/SET (read/change/create/delete) the objects in this MIB.
It is recommended that the implementers consider the security
features as provided by the SNMPv3 framework. Specifically, the use
of the User-based Security Model RFC 2574 [RFC2574] and the View-
based Access Control Model RFC 2575 [RFC2575] is recommended.
It is then a customer/user responsibility to ensure that the SNMP
entity giving access to an instance of this MIB, is properly
configured to give access to the objects only to those principals
(users) that have legitimate rights to indeed GET or SET
(change/create/delete) them.
This MIB provides the ability to distribute applications written in
an arbitrary language to remote systems in a network. The security
features of the languages available in a particular implementation
should be taken into consideration when deploying an implementation
of this MIB.
To facilitate the provisioning of access control by a security
administrator using the View-Based Access Control Model (VACM)
defined in RFC 2575 [RFC2575] for tables in which multiple users may
need to independently create or modify entries, the initial index is
used as an "owner index". Such an initial index has a syntax of
SnmpAdminString, and can thus be trivially mapped to a securityName
or groupName as defined in VACM, in accordance with a security
policy.
All entries in related tables belonging to a particular user will
have the same value for this initial index. For a given user's
entries in a particular table, the object identifiers for the
information in these entries will have the same subidentifiers
(except for the "column" subidentifier) up to the end of the encoded
owner index. To configure VACM to permit access to this portion of
the table, one would create vacmViewTreeFamilyTable entries with the
value of vacmViewTreeFamilySubtree including the owner index portion,
and vacmViewTreeFamilyMask "wildcarding" the column subidentifier.
More elaborate configurations are possible.
The VACM access control mechanism described above provides control
over SNMP access to Script MIB objects. There are a number of other
access control issues that are outside of the scope of this MIB. For
example, access control on URLs, especially those that use the file
scheme, must be realized by the underlying operating system. A
mapping of the owner index value to a local operating system security
user identity should be used by an implementation of this MIB to
control access to operating system resources when resolving URLs or
executing scripts.
11. Intellectual Property
The IETF takes no position regarding the validity or scope of any
intellectual property or other rights that might be claimed to
pertain to the implementation or use of the technology described in
this document or the extent to which any license under such rights
might or might not be available; neither does it represent that it
has made any effort to identify any such rights. Information on the
IETF's procedures with respect to rights in standards-track and
standards-related documentation can be found in BCP-11. Copies of
claims of rights made available for publication and any assurances of
licenses to be made available, or the result of an attempt made to
obtain a general license or permission for the use of such
proprietary rights by implementors or users of this specification can
be obtained from the IETF Secretariat.
The IETF invites any interested party to bring to its attention any
copyrights, patents or patent applications, or other proprietary
rights which may cover technology that may be required to practice
this standard. Please address the information to the IETF Executive
Director.
12. Changes from RFC 2592
The following list documents major changes from the previous version
of this document, published as RFC 2592:
- Updated the boilerplate and the references.
- Added revision clauses to the module identity macro.
- Various typos have been fixed.
- Added SIZE restriction to smScriptName which is consistent with
smLaunchScriptName. Added DEFVAL and some clarifying text on the
usage of a zero-length string to smLaunchScriptName.
- Clarified under which conditions changes to smScriptLanguage are
invalid.
- Added new smScriptError and smLaunchError objects.
- Setting smRunLifeTime to its maximum value now disables the timer
so that scripts can run forever.
- Added the `autostart' value to the smLaunchAdminStatus object
which allows to launch scripts during the disable->enabled
transition of smLaunchOperStatus.
- Added an additional step to the "creating a launch button"
procedure which sets the smLaunchRowStatus to active.
- Added a final polling step in the procedure to launch a script.
- Added a final polling step in the procedure to terminate a running
script.
- Removed the requirement that smRunError is a zero-length string
while the smRunExitCode has the value `noError'.
- Added new smScriptLastChange, smLaunchLastChange, smRunResultTime,
and smRunErrorTime objects.
- Added some additional boilerplate text to the security
considerations section.
- Added a new smLaunchRowExpireTime object and a new `expired' state
to the smLaunchOperStatus object.
- Clarified that the smRunState object reports the actual state if
attempts to suspend or resume scripts fail.
- Clarified the conditions under which set operations to
smLaunchControl and smRunControl can lead to inconsistentValue
errors.
- Added procedures for suspending/resuming/removing running scripts
to section 7.
- Added text to the smScriptStorageType description to better
highlight the difference between the storage type of the script
row entry and the script itself.
- Updated the smCompliances statement to not require write access to
the smCodeText object after row creation.
- Deprecated smCompliance, smScriptGroup, smLaunchGroup, smRunGroup,
smNotificationsGroup and created smCompliance2, smScriptGroup2,
smLaunchGroup2, smRunGroup2 and smNotificationsGroup2 that take
care of the new objects and notifications.
13. Acknowledgments
This document was produced by the IETF Distributed Management
(DISMAN) working group.
14. References
[RFC2571] Harrington, D., Presuhn, R. and B. Wijnen, "An
Architecture for Describing SNMP Management Frameworks",
RFC 2571, April 1999.
[RFC1155] Rose, M. and K. McCloghrie, "Structure and Identification
of Management Information for TCP/IP-based Internets", STD
16, RFC 1155, May 1990.
[RFC1212] Rose, M. and K. McCloghrie, "Concise MIB Definitions", STD
16, RFC 1212, March 1991.
[RFC1215] Rose, M., "A Convention for Defining Traps for use with
the SNMP", RFC 1215, March 1991.
[RFC2578] McCloghrie, K., Perkins, D., Schoenwaelder, J., Case, J.,
Rose, M. and S. Waldbusser, "Structure of Management
Information Version 2 (SMIv2)", STD 58, RFC 2578, April
1999.
[RFC2579] McCloghrie, K., Perkins, D., Schoenwaelder, J., Case, J.,
Rose, M. and S. Waldbusser, "Textual Conventions for
SMIv2", STD 58, RFC 2579, April 1999.
[RFC2580] McCloghrie, K., Perkins, D., Schoenwaelder, J., Case, J.,
Rose, M. and S. Waldbusser, "Conformance Statements for
SMIv2", STD 58, RFC 2580, April 1999.
[RFC1157] Case, J., Fedor, M., Schoffstall, M. and J. Davin, "Simple
Network Management Protocol", STD 15, RFC 1157, May 1990.
[RFC1901] Case, J., McCloghrie, K., Rose, M. and S. Waldbusser,
"Introduction to Community-based SNMPv2", RFC 1901,
January 1996.
[RFC1906] Case, J., McCloghrie, K., Rose, M. and S. Waldbusser,
"Transport Mappings for Version 2 of the Simple Network
Management Protocol (SNMPv2)", RFC 1906, January 1996.
[RFC2572] Case, J., Harrington D., Presuhn R. and B. Wijnen,
"Message Processing and Dispatching for the Simple Network
Management Protocol (SNMP)", RFC 2572, April 1999.
[RFC2574] Blumenthal, U. and B. Wijnen, "User-based Security Model
(USM) for version 3 of the Simple Network Management
Protocol (SNMPv3)", RFC 2574, April 1999.
[RFC1905] Case, J., McCloghrie, K., Rose, M. and S. Waldbusser,
"Protocol Operations for Version 2 of the Simple Network
Management Protocol (SNMPv2)", RFC 1905, January 1996.
[RFC2573] Levi, D., Meyer, P. and B. Stewart, "SNMPv3 Applications",
RFC 2573, April 1999.
[RFC2575] Wijnen, B., Presuhn, R. and K. McCloghrie, "View-based
Access Control Model (VACM) for the Simple Network
Management Protocol (SNMP)", RFC 2575, April 1999.
[RFC2570] Case, J., Mundy, R., Partain, D. and B. Stewart,
"Introduction to Version 3 of the Internet-standard
Network Management Framework", RFC 2570, April 1999.
[RFC2028] Hovey, R. and S. Bradner, "The Organizations Involved in
the IETF Standards Process", BCP 11, RFC 2028, October
1996.
[RFC2396] Berners-Lee, T., Fielding, R. and L. Masinter, " Uniform
Resource Identifiers (URI): Generic Syntax", RFC 2396,
August 1998.
[RFC959] Postel, J. and J. Reynolds, "File Transfer Protocol", STD
9, RFC 959, October 1985.
[RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H.,
Masinter, L., Leach, P. and T. Berners-Lee, "Hypertext
Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999.
[RFC2434] Narten, T. and H. Alvestrand, "Guidelines for Writing an
IANA Considerations Section in RFCs", BCP 26, RFC 2434,
October 1998.
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
Requirement Levels", BCP 14, RFC 2119, March 1997.
15. Editors' Addresses
David B. Levi
Nortel Networks
4401 Great America Parkway
Santa Clara, CA 95052-8185
USA
Phone: +1 423 686 0432
EMail: dlevi@nortelnetworks.com
Juergen Schoenwaelder
TU Braunschweig
Bueltenweg 74/75
38106 Braunschweig
Germany
Phone: +49 531 391-3283
EMail: schoenw@ibr.cs.tu-bs.de
16. Full Copyright Statement
Copyright (C) The Internet Society (2001). All Rights Reserved.
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.
The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
Acknowledgement
Funding for the RFC Editor function is currently provided by the
Internet Society.
</re>
</body>
</html>
| 42.663172 | 199 | 0.661204 |
369fa64ebc77cae1df42bea6460e705c18ab2ee7 | 2,988 | rs | Rust | src/chess/moves/rook.rs | bloatoo/zchess | e7cacb4e36d4646b6ef086c1e634a8c314223744 | [
"MIT"
] | 2 | 2021-12-28T22:41:51.000Z | 2021-12-29T10:02:33.000Z | src/chess/moves/rook.rs | bloatoo/zchess | e7cacb4e36d4646b6ef086c1e634a8c314223744 | [
"MIT"
] | null | null | null | src/chess/moves/rook.rs | bloatoo/zchess | e7cacb4e36d4646b6ef086c1e634a8c314223744 | [
"MIT"
] | null | null | null | use crate::chess::utils::calculate_squares_to_edge;
use crate::chess::{board::Edge, Board, Move, Piece};
pub const ROOK_MOVES: &[Move] = &[
Move {
x: 8,
y: 0,
constraints: &[],
},
Move {
x: 0,
y: 8,
constraints: &[],
},
];
pub fn generate_rook_moves(board: &Board, sq: usize, piece: &Piece) -> Vec<usize> {
let mut moves = vec![];
for mv in ROOK_MOVES.iter() {
if mv.x == 0 {
let top_edge = calculate_squares_to_edge(Edge::Top, sq);
let mut valid = true;
for i in 1..=top_edge {
if !valid {
continue;
}
let final_sq = sq + i as usize * 8;
match board.piece_at(final_sq) {
Some(p) => {
if p.side() != piece.side() {
moves.push(final_sq);
}
valid = false;
}
None => moves.push(final_sq),
};
}
let bottom_edge = calculate_squares_to_edge(Edge::Bottom, sq);
let mut valid = true;
for i in 1..=bottom_edge {
if !valid {
continue;
}
let final_sq = sq - i * 8;
match board.piece_at(final_sq) {
Some(p) => {
if p.side() != piece.side() {
moves.push(final_sq);
}
valid = false;
}
None => moves.push(final_sq),
}
}
} else {
let right_edge = calculate_squares_to_edge(Edge::Right, sq);
let mut valid = true;
for i in 1..=right_edge {
if !valid {
continue;
}
let final_sq = sq + i;
match board.piece_at(final_sq) {
Some(p) => {
if p.side() != piece.side() {
moves.push(final_sq);
}
valid = false;
}
None => moves.push(final_sq),
}
}
let left_edge = calculate_squares_to_edge(Edge::Left, sq);
let mut valid = true;
for i in 1..=left_edge {
if !valid {
continue;
}
let final_sq = sq - i;
match board.piece_at(final_sq) {
Some(p) => {
if p.side() != piece.side() {
moves.push(final_sq);
}
valid = false;
}
None => moves.push(final_sq),
}
}
}
}
moves
}
| 27.925234 | 83 | 0.358434 |
404cb8362bcfdd803cb1b26c1c5bdcf7eb8586c2 | 1,977 | kt | Kotlin | kotlin/src/test/kotlin/nonamedb/test/specs/unit/storage/engines/MemoryEngineSpec.kt | sndnv/nonamedb | e229ea19df94a89ddd135cf9e2b5bce5f1aa0f6f | [
"Apache-2.0"
] | 1 | 2019-04-21T05:29:54.000Z | 2019-04-21T05:29:54.000Z | kotlin/src/test/kotlin/nonamedb/test/specs/unit/storage/engines/MemoryEngineSpec.kt | sndnv/nonamedb | e229ea19df94a89ddd135cf9e2b5bce5f1aa0f6f | [
"Apache-2.0"
] | null | null | null | kotlin/src/test/kotlin/nonamedb/test/specs/unit/storage/engines/MemoryEngineSpec.kt | sndnv/nonamedb | e229ea19df94a89ddd135cf9e2b5bce5f1aa0f6f | [
"Apache-2.0"
] | null | null | null | package nonamedb.test.specs.unit.storage.engines
import io.kotlintest.*
import io.kotlintest.specs.StringSpec
import nonamedb.storage.Done
import nonamedb.storage.engines.MemoryEngine
class MemoryEngineSpec : StringSpec(){
init {
val timeout = 5.seconds
val testKey = "some key"
val testValue = "some value".toByteArray()
val updatedTestValue = "some updated value".toByteArray()
val testEngine = MemoryEngine()
"should fail to retrieve missing data" {
val result = testEngine.get(testKey)
eventually(timeout) {
result.getCompleted() shouldBe null
}
}
"should successfully add data" {
val result = testEngine.put(testKey, testValue)
eventually(timeout) {
result.getCompleted() shouldBe Done
}
}
"should successfully retrieve data" {
val result = testEngine.get(testKey)
eventually(timeout) {
result.getCompleted() shouldBe testValue
}
}
"should successfully update data" {
val result = testEngine.put(testKey, updatedTestValue)
eventually(timeout) {
result.getCompleted() shouldBe Done
}
}
"should successfully retrieve updated data" {
val result = testEngine.get(testKey)
eventually(timeout) {
result.getCompleted() shouldBe updatedTestValue
}
}
"should successfully remove data" {
val result = testEngine.put(testKey, "".toByteArray())
eventually(timeout) {
result.getCompleted() shouldBe Done
}
}
"should fail to retrieve removed data" {
val result = testEngine.get(testKey)
eventually(timeout) {
result.getCompleted() shouldBe null
}
}
}
}
| 29.954545 | 66 | 0.56955 |
150d2f00044ad50acb6790dd788d4befcfcf0564 | 931 | kt | Kotlin | library/src/material/java/androidx/appcompat/app/RialtoViewInflater.kt | ubuntudroid/Rialto | cd86cc260aa84e03816ab0566fdd3892bdaf489f | [
"Apache-2.0"
] | 256 | 2018-11-30T10:59:15.000Z | 2020-08-03T07:25:12.000Z | library/src/material/java/androidx/appcompat/app/RialtoViewInflater.kt | ubuntudroid/Rialto | cd86cc260aa84e03816ab0566fdd3892bdaf489f | [
"Apache-2.0"
] | 6 | 2018-12-08T17:12:02.000Z | 2020-09-29T10:42:44.000Z | library/src/material/java/androidx/appcompat/app/RialtoViewInflater.kt | ubuntudroid/Rialto | cd86cc260aa84e03816ab0566fdd3892bdaf489f | [
"Apache-2.0"
] | 11 | 2018-12-02T18:55:10.000Z | 2020-02-08T17:51:52.000Z | package androidx.appcompat.app
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import com.google.android.material.button.MaterialButton
import com.stylingandroid.rialto.androidx.widget.RialtoEditText
import com.stylingandroid.rialto.androidx.widget.RialtoTextView
internal class RialtoViewInflater : AppCompatViewInflater() {
override fun createTextView(context: Context, attrs: AttributeSet?): AppCompatTextView {
return RialtoTextView(context, attrs)
}
override fun createEditText(context: Context, attrs: AttributeSet?): AppCompatEditText {
return RialtoEditText(context, attrs)
}
override fun createButton(context: Context, attrs: AttributeSet): AppCompatButton {
return MaterialButton(context, attrs)
}
}
| 34.481481 | 92 | 0.801289 |
d58f4ed9860a0002dad107290ab7f007322216a7 | 4,443 | swift | Swift | Sources/SwiftInspectorCommands/InitializerCommand.swift | thedrick/SwiftInspector | 71018af70ec680c0f55927a7452b2a6a6c2fe39f | [
"MIT"
] | null | null | null | Sources/SwiftInspectorCommands/InitializerCommand.swift | thedrick/SwiftInspector | 71018af70ec680c0f55927a7452b2a6a6c2fe39f | [
"MIT"
] | null | null | null | Sources/SwiftInspectorCommands/InitializerCommand.swift | thedrick/SwiftInspector | 71018af70ec680c0f55927a7452b2a6a6c2fe39f | [
"MIT"
] | null | null | null | // Created by Francisco Diaz on 3/27/20.
//
// Copyright (c) 2020 Francisco Diaz
//
// Distributed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import ArgumentParser
import Foundation
import SwiftInspectorCore
final class InitializerCommand: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "initializer",
abstract: "Finds information about the initializers of the specified type"
)
@Option(help: "The absolute path to the file to inspect")
var path: String
@Option(help: "The name of the type whose initializer information we'll be looking for")
var name: String
@Flag(name: .shortAndLong, default: true, inversion: .prefixedEnableDisable, help: typeOnlyHelp)
var typeOnly: Bool
@Option(parsing: .upToNextOption, help: argumentNameHelp)
var parameterName: [String]
/// Runs the command
func run() throws {
let cachedSyntaxTree = CachedSyntaxTree()
let analyzer = InitializerAnalyzer(name: name, cachedSyntaxTree: cachedSyntaxTree)
let fileURL = URL(fileURLWithPath: path)
let initializerStatements = try analyzer.analyze(fileURL: fileURL)
let outputArray = initializerStatements.filter(shouldReturnParameters).map { outputString(from: $0) }
let output = outputArray.joined(separator: "\n")
print(output)
}
/// Validates if the arguments of this command are valid
func validate() throws {
guard !name.isEmpty else {
throw InspectorError.emptyArgument(argumentName: "--name")
}
guard !path.isEmpty else {
throw InspectorError.emptyArgument(argumentName: "--path")
}
let pathURL = URL(fileURLWithPath: path)
guard FileManager.default.isSwiftFile(at: pathURL) else {
throw InspectorError.invalidArgument(argumentName: "--path", value: path)
}
}
private func outputString(from statement: InitializerStatement) -> String {
if typeOnly {
return statement.parameters.map { $0.typeNames.joined(separator: " ") }.joined(separator: " ")
} else {
return statement.parameters.map { "\($0.name),\($0.typeNames.joined(separator: ","))" }.joined(separator: " ")
}
}
/// Filters the provided `InitializerStatement` given the user-provided `argumentName`
///
/// - Returns: `true` if the provided initializer statement should be used as output, `false` otherwise
private func shouldReturnParameters(from statement: InitializerStatement) -> Bool {
guard !parameterName.isEmpty else {
return true
}
let parameterNames = statement.parameters.map { $0.name }
return parameterNames.sorted().elementsEqual(parameterName.sorted())
}
}
private var typeOnlyHelp = ArgumentHelp("The granularity of the output",
discussion: """
Outputs a list of the type names by default. If disabled it outputs the name of the parameter and the name of the type (e.g. 'foo,Int bar,String')
""")
private var argumentNameHelp = ArgumentHelp("A list of parameter names to filter initializers for",
discussion: """
When this value is provided, the command will only return the initializers that contain the list of parameters provided and will filter out everything else
""")
| 41.915094 | 195 | 0.698402 |
1a342e6b5cd39c48ab80118ead23965a563e728f | 1,097 | rs | Rust | quic/s2n-quic-core/src/transmission/mode.rs | sthagen/aws-s2n-quic | 3096e046adee004fe1cab835b4e0066977ab0c10 | [
"Apache-2.0"
] | 1 | 2022-02-28T16:53:06.000Z | 2022-02-28T16:53:06.000Z | quic/s2n-quic-core/src/transmission/mode.rs | sthagen/aws-s2n-quic | 3096e046adee004fe1cab835b4e0066977ab0c10 | [
"Apache-2.0"
] | null | null | null | quic/s2n-quic-core/src/transmission/mode.rs | sthagen/aws-s2n-quic | 3096e046adee004fe1cab835b4e0066977ab0c10 | [
"Apache-2.0"
] | null | null | null | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Mode {
/// Loss recovery probing to detect lost packets
LossRecoveryProbing,
/// Maximum transmission unit probing to determine the path MTU
MtuProbing,
/// Path validation to verify peer address reachability
PathValidationOnly,
/// Normal transmission
Normal,
}
impl Mode {
/// Is the transmission a probe for loss recovery
pub fn is_loss_recovery_probing(&self) -> bool {
matches!(self, Mode::LossRecoveryProbing)
}
/// Is the transmission a probe for path maximum transmission unit discovery
pub fn is_mtu_probing(&self) -> bool {
matches!(self, Mode::MtuProbing)
}
/// Is the transmission a probe for path validation
pub fn is_path_validation(&self) -> bool {
matches!(self, Mode::PathValidationOnly)
}
/// Is this transmission not a probe
pub fn is_normal(&self) -> bool {
matches!(self, Mode::Normal)
}
}
| 29.648649 | 80 | 0.672744 |
167028314029adf2d4372d4ab2a9e2d37b67f9f1 | 871 | h | C | Code/RDGeneral/RDThreads.h | Mike575/rdkit | 373a89021e478f878c6011a201e3fb8f4a122093 | [
"PostgreSQL"
] | 1 | 2019-01-23T06:02:24.000Z | 2019-01-23T06:02:24.000Z | Code/RDGeneral/RDThreads.h | Mike575/rdkit | 373a89021e478f878c6011a201e3fb8f4a122093 | [
"PostgreSQL"
] | null | null | null | Code/RDGeneral/RDThreads.h | Mike575/rdkit | 373a89021e478f878c6011a201e3fb8f4a122093 | [
"PostgreSQL"
] | null | null | null | //
// Copyright (C) 2015-2018 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/export.h>
#ifndef RDTHREADS_H_2015
#define RDTHREADS_H_2015
#include <RDGeneral/Invariant.h>
#ifdef RDK_THREADSAFE_SSS
#include <thread>
namespace RDKit {
inline unsigned int getNumThreadsToUse(int target) {
if (target >= 1) {
return static_cast<unsigned int>(target);
}
unsigned int res = std::thread::hardware_concurrency();
if (res > rdcast<unsigned int>(-target)) {
return res + target;
} else {
return 1;
}
}
}
#else
namespace RDKit {
inline unsigned int getNumThreadsToUse(int target) {
RDUNUSED_PARAM(target);
return 1;
}
}
#endif
#endif
| 19.355556 | 64 | 0.700344 |
7f1610e61fe4d126e2a9d2e38f0b4661c65c9e03 | 993 | go | Go | cmd/util/pool_test.go | pop/wash | 16e54fa159f28802fadef1d0d5632d32b07c6f86 | [
"Apache-2.0"
] | 180 | 2019-03-19T16:54:48.000Z | 2022-03-21T01:20:21.000Z | cmd/util/pool_test.go | pop/wash | 16e54fa159f28802fadef1d0d5632d32b07c6f86 | [
"Apache-2.0"
] | 413 | 2019-03-19T17:05:50.000Z | 2021-07-01T16:45:26.000Z | cmd/util/pool_test.go | pop/wash | 16e54fa159f28802fadef1d0d5632d32b07c6f86 | [
"Apache-2.0"
] | 39 | 2019-03-19T16:55:47.000Z | 2022-01-28T10:57:23.000Z | package cmdutil
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
// Test that a pool with a single worker finishes.
func TestPool1(t *testing.T) {
p := NewPool(1)
val := 0
p.Submit(func() {
val++
p.Done()
})
p.Finish()
assert.Equal(t, 1, val)
}
// Test that a pool with two workers executes them concurrently and finishes.
func TestPool2(t *testing.T) {
p := NewPool(2)
var mux1, mux2 sync.Mutex
val := 0
// Start with both mutexes locked. In sequence wait on one and unlock the other so that both
// functions must run concurrently to correctly unlock them.
mux1.Lock()
mux2.Lock()
p.Submit(func() {
// Wait on 1.
mux1.Lock()
val++
// Signal 2.
mux2.Unlock()
p.Done()
})
p.Submit(func() {
// Signal 1.
mux1.Unlock()
// Wait on 2.
mux2.Lock()
val++
p.Done()
})
// At the end both mutexes are again locked.
// Wait for completion and ensure both functions have updated the value.
p.Finish()
assert.Equal(t, 2, val)
}
| 17.421053 | 93 | 0.650554 |
7191168772c96698f982661d242a1d3d4f5176b5 | 369 | ts | TypeScript | services/auth/src/index.ts | PabloSzx/lear-model-tutor | d38fccbaf0e93eedb0acef3db2391312ee043a5b | [
"MIT"
] | null | null | null | services/auth/src/index.ts | PabloSzx/lear-model-tutor | d38fccbaf0e93eedb0acef3db2391312ee043a5b | [
"MIT"
] | null | null | null | services/auth/src/index.ts | PabloSzx/lear-model-tutor | d38fccbaf0e93eedb0acef3db2391312ee043a5b | [
"MIT"
] | 1 | 2021-06-11T02:31:50.000Z | 2021-06-11T02:31:50.000Z | import Fastify from "fastify";
import { Auth0Verify } from "common";
import { buildApp } from "./app";
const app = Fastify({
logger: true,
});
(async () => {
await app.register(Auth0Verify);
const EnvelopApp = buildApp({
async prepare() {
await import("./modules");
},
});
await app.register(EnvelopApp.plugin);
app.listen(3001);
})();
| 15.375 | 40 | 0.615176 |
2687741456a098c37afc8bf69e80796b3b034052 | 19,878 | java | Java | backend/resource-microservice/src/main/java/io/vertx/armysystem/microservice/resource/impl/OrganizationServiceImpl.java | derek518/VertxSample | c62aec54820829adbd55c52d12d40028f220f0df | [
"Apache-2.0"
] | null | null | null | backend/resource-microservice/src/main/java/io/vertx/armysystem/microservice/resource/impl/OrganizationServiceImpl.java | derek518/VertxSample | c62aec54820829adbd55c52d12d40028f220f0df | [
"Apache-2.0"
] | 1 | 2021-12-14T20:41:59.000Z | 2021-12-14T20:41:59.000Z | backend/resource-microservice/src/main/java/io/vertx/armysystem/microservice/resource/impl/OrganizationServiceImpl.java | derek518/VertxSample | c62aec54820829adbd55c52d12d40028f220f0df | [
"Apache-2.0"
] | null | null | null | package io.vertx.armysystem.microservice.resource.impl;
import io.vertx.armysystem.business.common.QueryCondition;
import io.vertx.armysystem.business.common.ServiceBase;
import io.vertx.armysystem.business.common.enums.OrgSequence;
import io.vertx.armysystem.business.common.enums.OrgType;
import io.vertx.armysystem.business.common.resource.Organization;
import io.vertx.armysystem.microservice.common.functional.Functional;
import io.vertx.armysystem.microservice.common.service.MongoRepositoryWrapper;
import io.vertx.armysystem.microservice.resource.OrganizationService;
import io.vertx.armysystem.microservice.resource.api.OrganizationRouter;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.mongo.BulkOperation;
import org.mvel2.ast.Or;
import java.util.*;
import java.util.stream.Collectors;
public class OrganizationServiceImpl extends MongoRepositoryWrapper implements OrganizationService, ServiceBase {
private static final String FILTER_COLUMN_NAME = "parentIds";
private static final Logger logger = LoggerFactory.getLogger(OrganizationRouter.class);
private final Vertx vertx;
public OrganizationServiceImpl(Vertx vertx, JsonObject config) {
super(vertx, config);
this.vertx = vertx;
}
@Override
public String getServiceName() {
return "resource-organization-eb-service";
}
@Override
public String getServiceAddress() {
return "service.resource.organization";
}
@Override
public String getPermission() {
return "Organization";
}
@Override
public String getCollectionName() {
return "Organization";
}
@Override
public OrganizationService initializePersistence(Handler<AsyncResult<Void>> resultHandler) {
this.createCollection(getCollectionName())
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("name", 1), new JsonObject()))
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("displayName", 1), new JsonObject().put("unique", true)))
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("orgCode", 1), new JsonObject()))
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("parentIds", 1), new JsonObject()))
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("parentId", 1), new JsonObject()))
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("orgSequence", 1), new JsonObject()))
.otherwise(err -> null)
.setHandler(resultHandler);
return this;
}
@Override
public OrganizationService addOne(JsonObject item, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
Organization organization = new Organization(item);
logger.info("addOne " + organization);
validateParams(organization, true) // 参数检查
.compose(o -> getParentOrg(organization.getParentId(), principal))
.compose(parent -> {
Future<JsonObject> future = Future.future();
logger.info("get parent " + parent);
if (parent == null && organization.getParentId() != null) {
// parentId not found
future.fail("Not found");
} else if (!checkPermission(parent, principal)) {
future.fail("No permission");
} else {
organization.setId(UUID.randomUUID().toString());
organization.setDeactivated(false);
// 设置单位长名称
organization.setDisplayName(makeDisplayName(parent, organization));
// 设置本单位的parentIds
organization.setParentIds(getParentIds(parent));
organization.getParentIds().add(organization.getId());
// 设置单位orgCode
organization.setOrgCode(makeOrgCode(parent, organization));
JsonObject jsonObject = organization.toJson();
jsonObject.remove("childCount");
return this.insertOne(getCollectionName(), jsonObject)
.map(org -> org.put("childCount", 0));
}
return future;
}).setHandler(resultHandler);
return this;
}
@Override
public OrganizationService retrieveOne(String id, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
this.findOne(getCollectionName(), getCondition(id, principal).getQuery(), new JsonObject())
.map(option -> option.orElse(null))
.compose(item -> fillChildCount(item))
.setHandler(resultHandler);
return this;
}
@Override
public OrganizationService retrieveAll(JsonObject principal, Handler<AsyncResult<List<JsonObject>>> resultHandler) {
this.retrieveManyByCondition(new JsonObject(), principal, resultHandler);
return this;
}
@Override
public OrganizationService count(JsonObject condition, JsonObject principal, Handler<AsyncResult<Long>> resultHandler) {
QueryCondition qCondition = QueryCondition.parse(condition);
qCondition.filterByUserOrganizationV2(FILTER_COLUMN_NAME, principal);
logger.info("count condition: " + qCondition);
this.count(getCollectionName(), qCondition.getQuery())
.setHandler(resultHandler);
return this;
}
@Override
public OrganizationService retrieveManyByCondition(JsonObject condition, JsonObject principal, Handler<AsyncResult<List<JsonObject>>> resultHandler) {
QueryCondition qCondition = QueryCondition.parse(condition);
if (qCondition.getOption().getJsonObject("sort") == null) {
qCondition.getOption().put("sort", new JsonObject().put("orgCode", 1));
}
qCondition.filterByUserOrganizationV2(FILTER_COLUMN_NAME, principal);
logger.info("retrieveManyByCondition condition: " + qCondition);
this.findWithOptions(getCollectionName(), qCondition.getQuery(), qCondition.getOption())
.map(list -> list.stream()
.map(json -> new Organization(json).toJson())
.collect(Collectors.toList()))
.compose(list -> Functional.allOfFutures(list.stream()
.map(object -> fillChildCount(object))
.collect(Collectors.toList())))
.setHandler(resultHandler);
return this;
}
@Override
public OrganizationService updateOne(String id, JsonObject item, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
item.remove("id");
item.remove("parentId");
item.remove("parentIds");
item.remove("childCount");
item.remove("orgCode");
item.remove("displayName");
item.remove("deactivated");
item.remove("deactivatedAt");
logger.info("updateOne id: " + id + " to: " + item);
this.findOne(getCollectionName(), getCondition(id, principal).getQuery(), new JsonObject())
.map(option -> option.map(Organization::new).orElse(null))
.compose(organization -> {
if (organization != null) {
// 如果修改单位名称,则自动更新全名称
if (item.containsKey("name") && !organization.getName().equals(item.getString("name"))) {
item.put("displayName",
organization.getDisplayName().replace(organization.getName(), item.getString("name")));
}
if (item.containsKey("nodeCode") && organization.getNodeCode() != item.getInteger("nodeCode")) {
item.put("orgCode", makeOrgCode(organization, item.getInteger("nodeCode")));
}
return this.update(getCollectionName(), new JsonObject().put("_id", organization.getId()), item)
.map(o -> organization);
} else {
return Future.failedFuture("Not found");
}
}).compose(organization -> {
if (item.containsKey("displayName") || item.containsKey("orgCode")) {
return this.findWithOptions(getCollectionName(),
new JsonObject().put("parentIds", organization.getId()),
new JsonObject().put("limit", 10000))
.map(list -> list.stream().filter(org -> org.getString("id") != organization.getId())
.map(org -> {
JsonObject obj = new JsonObject();
if (item.containsKey("displayName") && org.containsKey("displayName")) {
obj.put("displayName",
org.getString("displayName")
.replace(organization.getDisplayName(), item.getString("displayName")));
}
if (item.containsKey("orgCode") && org.containsKey("orgCode")) {
obj.put("orgCode",
org.getString("orgCode")
.replace(organization.getOrgCode(), item.getString("orgCode")));
}
obj.put("updatedTime", new Date().getTime());
return new BulkOperation(new JsonObject()
.put("type", "update")
.put("filter", new JsonObject().put("_id", org.getString("id")))
.put("document", new JsonObject().put("$set", obj))
.put("upsert", false)
.put("multi", false));
}).collect(Collectors.toList())
)
.compose(list -> {
logger.info("before bulkwrite: " + list);
if (list == null || list.isEmpty()) {
return Future.succeededFuture();
} else {
return this.bulkWrite(getCollectionName(), list);
}
})
.compose(list ->
this.findOne(getCollectionName(), new JsonObject().put("_id", organization.getId()), new JsonObject())
.map(option -> option.orElse(null))
);
} else {
return this.findOne(getCollectionName(), new JsonObject().put("_id", organization.getId()), new JsonObject())
.map(option -> option.orElse(null));
}
})
.compose(o -> fillChildCount(o))
.setHandler(resultHandler);
return this;
}
@Override
public OrganizationService deleteOne(String id, JsonObject principal, Handler<AsyncResult<Void>> resultHandler) {
JsonObject query = getCondition(id, principal).getQuery();
logger.info("deleteOne id: " + id);
this.findOne(getCollectionName(), query, new JsonObject())
.compose(o -> fillChildCount(o.get()))
.compose(organization -> {
if (organization == null) {
return Future.failedFuture("Not found");
} else if (organization.getInteger("childCount")>0){
return Future.failedFuture("Not allowed");
} else {
return this.removeById(getCollectionName(), organization.getString("id"));
}
}).setHandler(resultHandler);
return this;
}
@Override
public OrganizationService swapPosition(String id, String otherId, JsonObject principal, Handler<AsyncResult<Void>> resultHandler) {
JsonObject query1 = getCondition(id, principal).getQuery();
JsonObject query2 = getCondition(id, principal).getQuery();
logger.info("swapPosition " + id + "<->" + otherId);
this.findOne(getCollectionName(), query1, new JsonObject())
.map(option -> option.orElse(null))
.compose(organization ->
this.findOne(getCollectionName(), query2, new JsonObject())
.map(option -> option.orElse(null))
.map(o -> new JsonObject().put("org1", organization).put("org2", o))
).compose(both -> {
if (both.getJsonObject("org1") == null || both.getJsonObject("org2") == null) {
return Future.failedFuture("Not found");
} else {
Organization org1 = new Organization(both.getJsonObject("org1"));
Organization org2 = new Organization(both.getJsonObject("org2"));
String newOrgCode1 = makeOrgCode(org1, org2.getNodeCode());
String newOrgCode2 = makeOrgCode(org2, org1.getNodeCode());
List<BulkOperation> bulkOperations = new ArrayList<>();
// 进行批量更新操作
return getUpdateCodeList(org1, newOrgCode1, org2.getNodeCode())
.compose(list -> {
bulkOperations.addAll(list);
return getUpdateCodeList(org2, newOrgCode2, org1.getNodeCode());
}).compose(list -> {
bulkOperations.addAll(list);
return this.bulkWrite(getCollectionName(), bulkOperations);
});
}
}).setHandler(ar -> {
if (ar.succeeded()) {
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture(ar.cause()));
}
});
return this;
}
@Override
public OrganizationService deactivate(String id, Boolean deactivated, JsonObject principal, Handler<AsyncResult<Void>> resultHandler) {
JsonObject query = getCondition(id, principal).getQuery();
logger.info("deactivate " + id + " to " + deactivated);
this.findOne(getCollectionName(), query, new JsonObject())
.map(option -> option.map(Organization::new).orElse(null))
.compose(organization -> {
if (organization == null) {
return Future.failedFuture("Not found");
} else if (organization.getDeactivated() == deactivated) {
return Future.succeededFuture();
} else {
JsonObject update = new JsonObject().put("deactivated", deactivated);
if (deactivated) {
update.put("deactivatedAt", new Date().getTime());
} else {
update.put("deactivatedAt", 0);
}
return this.update(getCollectionName(),
new JsonObject().put("parentIds", organization.getId()), update);
}
}).setHandler(resultHandler);
return this;
}
private Future<List<BulkOperation>> getUpdateCodeList(Organization organization, String orgCode, int nodeCode) {
return this.findWithOptions(getCollectionName(),
new JsonObject().put("parentIds", organization.getId()),
new JsonObject().put("skip", 10000))
.map(list -> list.stream().map(org -> {
JsonObject object = new JsonObject()
.put("orgCode", org.getString("orgCode").replace(organization.getOrgCode(), orgCode));
if (org.getString("id") == organization.getId()) {
object.put("nodeCode", nodeCode);
}
object.put("updatedTime", new Date().getTime());
return new BulkOperation(new JsonObject()
.put("type", "update")
.put("filter", new JsonObject().put("_id", org.getString("id")))
.put("document", new JsonObject().put("$set", object))
.put("upsert", false)
.put("multi", false));
}).collect(Collectors.toList()));
}
// 设置按单位权限过滤检索条件
private QueryCondition getCondition(String id, JsonObject principal) {
// JsonObject query = new JsonObject().put("_id", id);
JsonObject query = new JsonObject().put("$or", new JsonArray()
.add(new JsonObject().put("_id", id))
.add(new JsonObject().put("displayName", id)));
QueryCondition condition = new QueryCondition(query, new JsonObject())
.filterByUserOrganizationV1(FILTER_COLUMN_NAME, principal);
return condition;
}
private List<String> getParentIds(JsonObject obj) {
List<String> parentIds = new ArrayList<>();
if (obj != null && obj.containsKey("parentIds")) {
parentIds = obj.getJsonArray("parentIds").getList();
}
return parentIds;
}
// 自动设置单位全名称
private String makeDisplayName(JsonObject parent, Organization organization) {
if (parent != null) {
if ((parent.getInteger("orgSequence") == OrgSequence.Army.getValue() &&
organization.getOrgSequence() > OrgSequence.Army.getValue()) || !parent.containsKey("displayName")) {
return organization.getName();
} else {
return parent.getString("displayName") + organization.getName();
}
} else {
return organization.getName();
}
}
private String makeOrgCode(JsonObject parent, Organization organization) {
if (parent != null)
return parent.getString("orgCode") + String.format("%02d", organization.getNodeCode()%100);
else
return String.format("%02d", organization.getNodeCode()%100);
}
private String makeOrgCode(Organization organization, int newNodeCode) {
String newCode = organization.getOrgCode() == null ? "" : organization.getOrgCode();
if (newCode.length() < 2) {
newCode = "";
} else {
newCode = newCode.substring(0, newCode.length()-2);
}
newCode += String.format("%02d", newNodeCode%100);
return newCode;
}
// 获取单位父节点
private Future<JsonObject> getParentOrg(String parentId, JsonObject principal) {
if (parentId == null && principal.containsKey("organizationId")) {
parentId = principal.getString("organizationId");
}
if (parentId != null) {
return this.findOne(getCollectionName(), new JsonObject().put("_id", parentId), new JsonObject())
.otherwise(Optional.empty())
.map(option -> option.orElse(null));
} else {
return Future.succeededFuture();
}
}
// 检查添加单位权限
private boolean checkPermission(JsonObject parent, JsonObject principal) {
String userOrgId = principal.getString("organizationId");
if (userOrgId == null) {
return true;
} else if (parent == null || parent.getJsonArray("parentIds") == null) {
return false;
} else {
return parent.getJsonArray("parentIds").getList().contains(userOrgId);
}
}
private Future<Void> validateParams(Organization organization, Boolean forAdd) {
Future<Void> future = Future.future();
Boolean failed = false;
if (forAdd) {
failed = failed || organization.getName() == null || organization.getName().isEmpty();
failed = failed || organization.getNodeCode() == 0;
failed = failed || !(Arrays.stream(OrgSequence.values())
.anyMatch(os -> os.getValue() == organization.getOrgSequence()));
failed = failed || !(Arrays.stream(OrgType.values())
.anyMatch(ot -> ot.getName().equals(organization.getOrgType())));
} else {
failed = failed || !((organization.getOrgSequence() == 0) ||
Arrays.stream(OrgSequence.values())
.anyMatch(os -> os.getValue() == organization.getOrgSequence()));
failed = failed || !((organization.getOrgType() == null) ||
Arrays.stream(OrgType.values())
.anyMatch(ot -> ot.getName().equals(organization.getOrgType())));
}
if ((forAdd && organization.getId() != null) ||
failed) {
future.fail("Invalid parameter");
} else {
future.complete();
}
return future;
}
private Future<JsonObject> fillChildCount(JsonObject object) {
if (object != null) {
return this.count(getCollectionName(), new JsonObject().put("parentId", object.getString("id")))
.map(count -> object.put("childCount", count));
} else {
return Future.succeededFuture(null);
}
}
}
| 39.59761 | 152 | 0.625063 |
2a2da11e2fc4828a0cde601c4d49ed717b057d03 | 4,661 | java | Java | rtmap/src/com/rtmap/core/action/IndexController.java | fushenghua/rtmap_blog | fc5f5244f2a59ad3e505bdd37a83503d24d71642 | [
"Unlicense"
] | null | null | null | rtmap/src/com/rtmap/core/action/IndexController.java | fushenghua/rtmap_blog | fc5f5244f2a59ad3e505bdd37a83503d24d71642 | [
"Unlicense"
] | 1 | 2015-09-15T07:46:52.000Z | 2015-09-15T07:46:52.000Z | rtmap/src/com/rtmap/core/action/IndexController.java | fushenghua/rtmap_blog | fc5f5244f2a59ad3e505bdd37a83503d24d71642 | [
"Unlicense"
] | null | null | null | package com.rtmap.core.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.rtmap.core.entity.PageBean;
import com.rtmap.core.entity.QueryCondition;
import com.rtmap.core.entity.bo.BlogArticleBo;
import com.rtmap.core.entity.vo.AlipayEventUserVo;
import com.rtmap.core.entity.vo.BlogArticleVo;
import com.rtmap.core.service.BlogArticleService;
import com.rtmap.core.service.CodingEventService;
@Controller
public class IndexController extends BaseController {
private static Logger logger = Logger.getLogger(IndexController.class);
@Autowired
private BlogArticleService blogArticleService;
@Autowired
private CodingEventService codingEventService;
/**
* 主页
* @user jack
* 2014年8月6日
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public String index(HttpServletRequest request, QueryCondition queryCondition){
return "index";
// return blog(request, queryCondition);
}
/**
* 博客主页
* @user jack
* 2014年8月6日
*/
@RequestMapping(value = "blog", method = RequestMethod.GET)
public String blog(HttpServletRequest request, QueryCondition queryCondition){
PageBean<BlogArticleVo> articleBean = null;
try{
articleBean = blogArticleService.getArticleList(queryCondition);
}catch(Exception e){
e.printStackTrace();
}
request.setAttribute("articleList", articleBean != null ? articleBean.getDatas() : null);
request.setAttribute("pageInfo", articleBean);
logger.info("get article list size:" + articleBean.getDatas().size());
return "blog/blog";
}
/**
* 关于页面
* @user
*
*/
@RequestMapping(value = "about", method = RequestMethod.GET)
public String about(HttpServletRequest request, QueryCondition queryCondition){
return "blog/about";
}
/**
* RTMAP Blog 活动页面
* @user jack
* 2015年4月23日
*/
@RequestMapping(value = "codingEvent", method = RequestMethod.GET)
public String codingEvent(HttpServletRequest request, QueryCondition queryCondition){
try {
BlogArticleBo article = blogArticleService.getArticleById(74);
request.setAttribute("article", article);
List<AlipayEventUserVo> eventList = codingEventService.getAlipayEventList();
request.setAttribute("codingEventList", eventList);
request.setAttribute("totalMoney", eventList != null ? eventList.get(0).getTotalMoney() : 0);
} catch (Exception e) {
e.printStackTrace();
}
return "blog/codingEvent";
}
/**
* 支付宝页面
* @user jack
* 2015年4月23日
*/
@RequestMapping(value = "zhifubao", method = RequestMethod.GET)
public String zhifubao(HttpServletRequest request, QueryCondition queryCondition){
return "aliPay/index";
}
/**
* 支付宝生成二维码管理
* @user jack
* 2015年4月23日
*/
@RequestMapping(value = "alipayapi", method = RequestMethod.POST)
public String alipayapi(HttpServletRequest request, QueryCondition queryCondition){
return "aliPay/alipayapi";
}
/**
* 支付宝回调
* @user jack
* 2015年4月23日
*/
@RequestMapping(value = "alinotify", method = RequestMethod.GET)
public String alinotify(HttpServletRequest request, QueryCondition queryCondition){
return "aliPay/notify_url";
}
/**
* 留下你的想法(用户留言本)
* @user jack
* 2014年8月6日
*/
@RequestMapping(value = "blog/leaveYourMind", method = RequestMethod.GET)
public String leaveYourMind(HttpServletRequest request , QueryCondition queryCondition){
return "blog/leaveYourMind";
}
@RequestMapping(value = "json")
public String json(HttpServletRequest request, HttpServletResponse response) {
return "android/json";
}
@RequestMapping(value = "ios")
public String ios(HttpServletRequest request, HttpServletResponse response) {
return "android/ios";
}
@RequestMapping(value = "formater")
public String formater(HttpServletRequest request, HttpServletResponse response) {
return "android/jsonformater";
}
@RequestMapping(value = "layout")
public String layout(HttpServletRequest request, HttpServletResponse response) {
return "android/layout";
}
@RequestMapping(value = "note")
public String note(HttpServletRequest request, HttpServletResponse response) {
return "note/note";
}
/**
* 系统演示
* @user jack
* 2014年8月6日
*/
// @RequestMapping(value = "systemDemo", method = RequestMethod.GET)
// public String leaveYourMind(HttpServletRequest request , QueryCondition queryCondition){
// return "blog/systemDemo";
// }
}
| 28.595092 | 96 | 0.750268 |
9c441c73c53afacd8c937cc8bf74254e59ace5d6 | 65 | js | JavaScript | src/config.js | knair7/SAPCAI | ac082a58c4512aeeef17a514e5ea0af654d77082 | [
"MIT"
] | 1 | 2021-12-22T05:26:57.000Z | 2021-12-22T05:26:57.000Z | src/config.js | UsulPro/Webchat | 85e079ef8318601336f340835af7fc0f41c27332 | [
"MIT"
] | 1 | 2018-02-12T10:37:19.000Z | 2018-02-12T10:37:19.000Z | src/config.js | UsulPro/Webchat | 85e079ef8318601336f340835af7fc0f41c27332 | [
"MIT"
] | 1 | 2018-12-14T10:19:34.000Z | 2018-12-14T10:19:34.000Z | export default {
apiUrl: 'https://api.recast.ai/connect/v1',
}
| 16.25 | 45 | 0.676923 |
7433581b613967a33a367537548b58227e266647 | 565 | c | C | test_counters.c | Gopal-Dahale/xv6-public | 468430afb899fbec535202aa67bedf6c53f0c856 | [
"MIT-0"
] | 3 | 2021-06-09T05:08:43.000Z | 2021-06-29T06:42:04.000Z | test_counters.c | Gopal-Dahale/xv6-public | 468430afb899fbec535202aa67bedf6c53f0c856 | [
"MIT-0"
] | null | null | null | test_counters.c | Gopal-Dahale/xv6-public | 468430afb899fbec535202aa67bedf6c53f0c856 | [
"MIT-0"
] | null | null | null | #include "types.h"
#include "stat.h"
#include "user.h"
#include "uspinlock.h"
int main()
{
int ret;
int i;
// Initialize locks and counters
ucounter_init();
uspinlock_init();
ret = fork();
//both parent and child increment the same counter 10000 times each
for (i = 0; i < 10000; i++)
{
uspinlock_acquire(0);
ucounter_set(0, ucounter_get(0) + 1);
uspinlock_release(0);
}
if (ret == 0)
{
exit();
}
else
{
wait();
printf(1, "%d\n", ucounter_get(0));
//ideally this value should be 20000
exit();
}
}
| 15.694444 | 69 | 0.59115 |
0ee10fa68de4de1804c29cac7d89ea5ea5b613ca | 175 | ts | TypeScript | src/app/data/model/cutting-fish.spec.ts | ajessikafernandes/estancia-restaurant | aec222557857d6757d94c5474fc7b90830d2c8eb | [
"MIT"
] | 1 | 2021-05-22T23:58:42.000Z | 2021-05-22T23:58:42.000Z | src/app/data/model/cutting-fish.spec.ts | ajessikafernandes/estancia-restaurant | aec222557857d6757d94c5474fc7b90830d2c8eb | [
"MIT"
] | null | null | null | src/app/data/model/cutting-fish.spec.ts | ajessikafernandes/estancia-restaurant | aec222557857d6757d94c5474fc7b90830d2c8eb | [
"MIT"
] | null | null | null | import { CuttingFish } from './cutting-fish';
describe('CuttingFish', () => {
it('should create an instance', () => {
expect(new CuttingFish()).toBeTruthy();
});
});
| 21.875 | 45 | 0.6 |
b6529f603c5da791b72540da54ed09872f0d75fd | 115 | rb | Ruby | test/ruby/hooks/on_worker_boot.rb | afxcn/unit | a336928e1027af92d0c9bb2ccb369a3f9b53abae | [
"Apache-2.0"
] | 2,633 | 2017-09-06T16:10:12.000Z | 2022-03-24T07:18:45.000Z | test/ruby/hooks/on_worker_boot.rb | afxcn/unit | a336928e1027af92d0c9bb2ccb369a3f9b53abae | [
"Apache-2.0"
] | 637 | 2017-09-06T23:43:11.000Z | 2022-03-31T19:28:46.000Z | test/ruby/hooks/on_worker_boot.rb | afxcn/unit | a336928e1027af92d0c9bb2ccb369a3f9b53abae | [
"Apache-2.0"
] | 365 | 2017-09-06T22:39:55.000Z | 2022-03-29T13:06:38.000Z | require 'securerandom'
on_worker_boot do
File.write("./cookie_worker_boot.#{SecureRandom.hex}", "booted")
end
| 19.166667 | 68 | 0.747826 |
163cb1f31edd68ddeb04262d9340a46c1ae5fcee | 3,812 | c | C | C_EXAMPLES/ESEMPI_DEL_LIBRO/cap16/cap16_heapsort.c | lsoffi/EsperienzeDiLaboratorioDiCalcolo201920 | 7a2a821b37cc8dfca527e9afb639a86a8e6c759b | [
"MIT"
] | 1 | 2019-10-18T10:03:58.000Z | 2019-10-18T10:03:58.000Z | C_EXAMPLES/ESEMPI_DEL_LIBRO/cap16/cap16_heapsort.c | lsoffi/EsperienzeDiLaboratorioDiCalcolo201920 | 7a2a821b37cc8dfca527e9afb639a86a8e6c759b | [
"MIT"
] | null | null | null | C_EXAMPLES/ESEMPI_DEL_LIBRO/cap16/cap16_heapsort.c | lsoffi/EsperienzeDiLaboratorioDiCalcolo201920 | 7a2a821b37cc8dfca527e9afb639a86a8e6c759b | [
"MIT"
] | null | null | null | /*
cap16_heapsort.c: Heapsort algorithm for data ordering.
Copyright (C) 2006 Federico Ricci-Tersenghi (Federico.Ricci@roma1.infn.it)
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.
This program has been extracted from "Programmazione Scientifica",
Pearson Education ed. (2006), by Barone, Marinari, Organtini and
Ricci-Tersenghi. ISBN 8871922425.
*/
/* by FRT */
#include <stdio.h>
#include <stdlib.h>
struct dataStruct {
float *data;
int size, numData;
};
void error(char *);
void readFile(char *, struct dataStruct *);
void heapify(int, struct dataStruct *);
void buildHeap(struct dataStruct *);
void heapSort(struct dataStruct *);
/* non possiamo usare il nome 'heapsort' perche' gia` esiste
una funzione con questo nome dichiarata dentro <stdlib.h> */
int main(int argc, char *argv[]) {
char *filename;
struct dataStruct heap;
int i;
if (argc != 2) {
fprintf(stderr, "usage: %s <filename> \n", argv[0]);
exit(1);
}
filename = argv[1];
readFile(filename, &heap);
heapSort(&heap);
for (i = 1; i <= heap.numData; i++) {
printf("%f\n", heap.data[i]);
}
return EXIT_SUCCESS;
}
void error(char *string) {
fprintf(stderr, "ERROR: %s\n", string);
exit(EXIT_FAILURE);
}
void readFile(char *filename, struct dataStruct *pHeap) {
FILE *inputFile;
if ((inputFile = fopen(filename, "r")) == NULL)
error("Opening the file");
pHeap->size = 2;
pHeap->data = (float*)malloc(pHeap->size * sizeof(float));
pHeap->numData = 1;
/* gli indici devono partire da 1 invece che da 0 */
while (fscanf(inputFile, "%f", pHeap->data + pHeap->numData) != EOF) {
pHeap->numData++;
if (pHeap->numData == pHeap->size) {
pHeap->size *= 2;
pHeap->data = (float*)realloc(pHeap->data,
pHeap->size * sizeof(float));
}
}
pHeap->numData--;
/* altrimenti numData varrebbe 1 piu` del numero di dati nell'heap */
fclose(inputFile);
}
void heapify(int index, struct dataStruct *pHeap) {
int left, right, max;
float tmp;
left = 2 * index;
if (left <= pHeap->numData) {
/* verifico la priorita` del figlio di sinistra */
if (pHeap->data[left] > pHeap->data[index]) {
max = left;
} else {
max = index;
}
/* e poi di quello di destra */
right = left + 1;
if (right <= pHeap->numData &&
pHeap->data[right] > pHeap->data[max]) {
max = right;
}
/* se necessario faccio lo scambio dei dati di 2 nodi */
if (max != index) {
tmp = pHeap->data[index];
pHeap->data[index] = pHeap->data[max];
pHeap->data[max] = tmp;
/* e richiamo heapify ricorsivamente */
heapify(max, pHeap);
}
}
}
void buildHeap(struct dataStruct *pHeap) {
int i;
for (i = (int)(pHeap->numData / 2); i > 0; i--) {
heapify(i, pHeap);
}
}
void heapSort(struct dataStruct *pHeap) {
int keepNumData;
float tmp;
buildHeap(pHeap);
keepNumData = pHeap->numData;
while (pHeap->numData > 1) {
tmp = pHeap->data[1];
pHeap->data[1] = pHeap->data[pHeap->numData];
pHeap->data[pHeap->numData] = tmp;
pHeap->numData--;
heapify(1, pHeap);
}
pHeap->numData = keepNumData;
}
| 27.824818 | 81 | 0.650315 |
7ae375b8e187bc5179298e4bdc0a00fbb1f87995 | 464 | rs | Rust | kani-compiler/src/codegen_cprover_gotoc/codegen/mod.rs | celinval/kani-dev | 677bacdb9ad7ce74dd20bbf6ba3cc6b87a6d7d16 | [
"Apache-2.0",
"MIT"
] | 111 | 2022-01-27T17:58:27.000Z | 2022-03-30T02:59:48.000Z | kani-compiler/src/codegen_cprover_gotoc/codegen/mod.rs | celinval/kani-dev | 677bacdb9ad7ce74dd20bbf6ba3cc6b87a6d7d16 | [
"Apache-2.0",
"MIT"
] | 228 | 2022-01-25T19:55:02.000Z | 2022-03-31T17:32:09.000Z | kani-compiler/src/codegen_cprover_gotoc/codegen/mod.rs | celinval/kani-dev | 677bacdb9ad7ce74dd20bbf6ba3cc6b87a6d7d16 | [
"Apache-2.0",
"MIT"
] | 7 | 2022-01-27T21:20:56.000Z | 2022-03-29T02:27:28.000Z | // Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! This module does that actual translation of MIR constructs to goto constructs.
//! Each subfile is named for the MIR construct it translates.
mod assert;
mod block;
mod function;
mod intrinsic;
mod operand;
mod place;
mod rvalue;
mod span;
mod statement;
mod static_var;
// Visible for all codegen module.
pub(super) mod typ;
pub use assert::PropertyClass;
pub use typ::TypeExt;
| 20.173913 | 82 | 0.760776 |
ff7efb71e1e9742b5fa86086f195aa61321efb46 | 33,108 | sql | SQL | zjxm.sql | kingweiang/zjxm | c8b3d11dc324107e465d84cb87b0ff8f3c788d93 | [
"BSD-2-Clause"
] | null | null | null | zjxm.sql | kingweiang/zjxm | c8b3d11dc324107e465d84cb87b0ff8f3c788d93 | [
"BSD-2-Clause"
] | null | null | null | zjxm.sql | kingweiang/zjxm | c8b3d11dc324107e465d84cb87b0ff8f3c788d93 | [
"BSD-2-Clause"
] | null | null | null | /*
Navicat MySQL Data Transfer
Source Server : 111
Source Server Version : 50709
Source Host : localhost:3306
Source Database : zjxm
Target Server Type : MYSQL
Target Server Version : 50709
File Encoding : 65001
Date: 2017-05-23 09:17:18
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for p_admin
-- ----------------------------
DROP TABLE IF EXISTS `p_admin`;
CREATE TABLE `p_admin` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`username` varchar(30) NOT NULL COMMENT '用户名',
`password` char(32) NOT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='管理用户表';
-- ----------------------------
-- Records of p_admin
-- ----------------------------
INSERT INTO `p_admin` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3');
INSERT INTO `p_admin` VALUES ('2', 'root', 'root');
INSERT INTO `p_admin` VALUES ('3', 'goods', 'e10adc3949ba59abbe56e057f20f883e');
INSERT INTO `p_admin` VALUES ('4', '111', '698d51a19d8a121ce581499d7b701668');
INSERT INTO `p_admin` VALUES ('5', '222', 'bcbe3365e6ac95ea2c0343a2395834dd');
-- ----------------------------
-- Table structure for p_admin_role
-- ----------------------------
DROP TABLE IF EXISTS `p_admin_role`;
CREATE TABLE `p_admin_role` (
`admin_id` mediumint(8) unsigned NOT NULL COMMENT '管理ID',
`role_id` mediumint(8) unsigned NOT NULL COMMENT '角色ID',
KEY `admin_id` (`admin_id`),
KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='管理角色关系表';
-- ----------------------------
-- Records of p_admin_role
-- ----------------------------
INSERT INTO `p_admin_role` VALUES ('5', '1');
INSERT INTO `p_admin_role` VALUES ('5', '2');
-- ----------------------------
-- Table structure for p_attribute
-- ----------------------------
DROP TABLE IF EXISTS `p_attribute`;
CREATE TABLE `p_attribute` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`attr_name` varchar(30) NOT NULL COMMENT '属性名称',
`attr_type` enum('唯一','可选') NOT NULL COMMENT '属性类型',
`attr_option_values` varchar(300) NOT NULL DEFAULT '' COMMENT '属性可选值',
`type_id` mediumint(8) unsigned NOT NULL COMMENT '类型Id',
PRIMARY KEY (`id`),
KEY `type_id` (`type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='属性表';
-- ----------------------------
-- Records of p_attribute
-- ----------------------------
INSERT INTO `p_attribute` VALUES ('1', '颜色', '可选', '白色,银色,黑色,玫瑰金', '1');
INSERT INTO `p_attribute` VALUES ('2', '尺寸', '可选', '4.8寸,5寸,5.5寸,6寸', '1');
INSERT INTO `p_attribute` VALUES ('5', '手机内存', '可选', '1GB,2GB,4GB', '1');
INSERT INTO `p_attribute` VALUES ('6', '生产日期', '唯一', '', '1');
-- ----------------------------
-- Table structure for p_brand
-- ----------------------------
DROP TABLE IF EXISTS `p_brand`;
CREATE TABLE `p_brand` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`brand_name` varchar(150) NOT NULL COMMENT '品牌名称',
`site_url` varchar(150) NOT NULL DEFAULT '' COMMENT '官网地址',
`logo` varchar(150) NOT NULL DEFAULT '' COMMENT '品牌logo图片',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='品牌';
-- ----------------------------
-- Records of p_brand
-- ----------------------------
INSERT INTO `p_brand` VALUES ('2', '11', '11', 'Brand/2017-05-10/5912d557b2746.jpg');
-- ----------------------------
-- Table structure for p_category
-- ----------------------------
DROP TABLE IF EXISTS `p_category`;
CREATE TABLE `p_category` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`cat_name` varchar(30) NOT NULL COMMENT '分类名称',
`parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '上级分类ID,0为顶级分类',
`is_floor` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否楼层推荐',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COMMENT='分类表';
-- ----------------------------
-- Records of p_category
-- ----------------------------
INSERT INTO `p_category` VALUES ('1', '家用电器', '0', '是');
INSERT INTO `p_category` VALUES ('2', '手机、数码、京东通信', '0', '是');
INSERT INTO `p_category` VALUES ('3', '电脑、办公', '0', '否');
INSERT INTO `p_category` VALUES ('4', '家居、家具、家装、厨具', '0', '否');
INSERT INTO `p_category` VALUES ('5', '男装、女装、内衣、珠宝', '0', '否');
INSERT INTO `p_category` VALUES ('6', '个护化妆', '0', '否');
INSERT INTO `p_category` VALUES ('8', '运动户外', '0', '否');
INSERT INTO `p_category` VALUES ('9', '汽车、汽车用品', '0', '否');
INSERT INTO `p_category` VALUES ('10', '母婴、玩具乐器', '0', '否');
INSERT INTO `p_category` VALUES ('11', '食品、酒类、生鲜、特产', '0', '否');
INSERT INTO `p_category` VALUES ('12', '营养保健', '0', '否');
INSERT INTO `p_category` VALUES ('13', '图书、音像、电子书', '0', '否');
INSERT INTO `p_category` VALUES ('14', '彩票、旅行、充值、票务', '0', '否');
INSERT INTO `p_category` VALUES ('15', '理财、众筹、白条、保险', '0', '否');
INSERT INTO `p_category` VALUES ('16', '大家电', '1', '是');
INSERT INTO `p_category` VALUES ('17', '生活电器', '1', '是');
INSERT INTO `p_category` VALUES ('18', '厨房电器', '1', '否');
INSERT INTO `p_category` VALUES ('19', '个护健康', '1', '是');
INSERT INTO `p_category` VALUES ('20', '五金家装', '1', '是');
INSERT INTO `p_category` VALUES ('21', 'iphone', '2', '是');
INSERT INTO `p_category` VALUES ('22', '冰箱', '16', '是');
INSERT INTO `p_category` VALUES ('23', '空调', '16', '否');
INSERT INTO `p_category` VALUES ('24', '变频空调', '23', '否');
-- ----------------------------
-- Table structure for p_goods
-- ----------------------------
DROP TABLE IF EXISTS `p_goods`;
CREATE TABLE `p_goods` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`goods_name` varchar(150) NOT NULL COMMENT '商品名称',
`market_price` decimal(10,2) NOT NULL COMMENT '市场价格',
`shop_price` decimal(10,2) NOT NULL COMMENT '本店价格',
`goods_desc` longtext COMMENT '商品描述',
`is_on_sale` enum('是','否') NOT NULL DEFAULT '是' COMMENT '是否上架',
`is_delete` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否放到回收站',
`addtime` datetime NOT NULL COMMENT '添加时间',
`logo` varchar(150) NOT NULL DEFAULT '' COMMENT '原图',
`sm_logo` varchar(150) NOT NULL DEFAULT '' COMMENT '小图',
`mid_logo` varchar(150) NOT NULL DEFAULT '' COMMENT '中图',
`big_logo` varchar(150) NOT NULL DEFAULT '' COMMENT '大图',
`mbig_logo` varchar(150) NOT NULL DEFAULT '' COMMENT '更大图',
`brand_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '品牌ID',
`cate_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '主分类ID',
`type_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '类型ID',
`promote_price` decimal(10,2) DEFAULT '0.00' COMMENT '促销价格',
`promote_start_date` datetime DEFAULT '0000-00-00 00:00:00' COMMENT '添加时间',
`promote_end_date` datetime DEFAULT '0000-00-00 00:00:00' COMMENT '结束时间',
`is_new` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否新品',
`is_hot` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否热卖',
`is_best` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否精品',
`sort_num` tinyint(3) unsigned NOT NULL DEFAULT '100' COMMENT '排序的数字',
`is_floor` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否楼层推荐',
PRIMARY KEY (`id`),
KEY `shop_price` (`shop_price`),
KEY `addtime` (`addtime`),
KEY `is_on_sale` (`is_on_sale`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COMMENT='商品';
-- ----------------------------
-- Records of p_goods
-- ----------------------------
INSERT INTO `p_goods` VALUES ('2', '钱币1', '100.00', '80.00', '<p>1111</p>', '是', '否', '2017-04-18 11:21:47', 'Goods/2017-04-18/58f5864ae9844.png', 'Goods/2017-04-18/sm_58f5864ae9844.png', 'Goods/2017-04-18/mid_58f5864ae9844.png', 'Goods/2017-04-18/big_58f5864ae9844.png', 'Goods/2017-04-18/mbig_58f5864ae9844.png', '0', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('3', '钱币2', '1300.00', '1200.00', '<p>范德萨发生11111</p>', '是', '否', '2017-04-19 11:10:39', 'Goods/2017-04-19/58f6da8777a2c.jpg', 'Goods/2017-04-19/sm_58f6da8777a2c.jpg', 'Goods/2017-04-19/mid_58f6da8777a2c.jpg', 'Goods/2017-04-19/big_58f6da8777a2c.jpg', 'Goods/2017-04-19/mbig_58f6da8777a2c.jpg', '2', '0', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('5', '发的发', '11221.00', '1213.00', '<p>范德萨发生</p>', '是', '否', '2017-04-19 17:19:22', 'Goods/2017-04-19/58f72b9a1b5e6.jpg', 'Goods/2017-04-19/thumb_3_58f72b9a1b5e6.jpg', 'Goods/2017-04-19/thumb_2_58f72b9a1b5e6.jpg', 'Goods/2017-04-19/thumb_1_58f72b9a1b5e6.jpg', 'Goods/2017-04-19/thumb_0_58f72b9a1b5e6.jpg', '0', '0', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('6', '111', '11111.00', '11111111.00', '<p>111111111111</p>', '是', '否', '2017-04-20 10:48:11', 'Goods/2017-04-20/58f8216a8837f.jpg', 'Goods/2017-04-20/thumb_3_58f8216a8837f.jpg', 'Goods/2017-04-20/thumb_2_58f8216a8837f.jpg', 'Goods/2017-04-20/thumb_1_58f8216a8837f.jpg', 'Goods/2017-04-20/thumb_0_58f8216a8837f.jpg', '2', '17', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '是');
INSERT INTO `p_goods` VALUES ('7', '111', '111.00', '110.00', '<p>123123</p>', '是', '否', '2017-04-21 10:08:39', 'Goods/2017-04-21/58f969a676455.jpg', 'Goods/2017-04-21/thumb_3_58f969a676455.jpg', 'Goods/2017-04-21/thumb_2_58f969a676455.jpg', 'Goods/2017-04-21/thumb_1_58f969a676455.jpg', 'Goods/2017-04-21/thumb_0_58f969a676455.jpg', '2', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('8', '放水电费是', '100.00', '99.00', '', '是', '否', '2017-04-24 16:22:16', 'Goods/2017-04-24/58fdb5b780407.jpg', 'Goods/2017-04-24/thumb_3_58fdb5b780407.jpg', 'Goods/2017-04-24/thumb_2_58fdb5b780407.jpg', 'Goods/2017-04-24/thumb_1_58fdb5b780407.jpg', 'Goods/2017-04-24/thumb_0_58fdb5b780407.jpg', '2', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('9', '范德萨发', '100.00', '99.00', '', '是', '否', '2017-04-24 16:23:18', 'Goods/2017-04-24/58fdb5f579fe2.jpg', 'Goods/2017-04-24/thumb_3_58fdb5f579fe2.jpg', 'Goods/2017-04-24/thumb_2_58fdb5f579fe2.jpg', 'Goods/2017-04-24/thumb_1_58fdb5f579fe2.jpg', 'Goods/2017-04-24/thumb_0_58fdb5f579fe2.jpg', '2', '17', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '是');
INSERT INTO `p_goods` VALUES ('10', '11', '1.00', '1.00', '', '是', '否', '2017-04-24 17:09:34', 'Goods/2017-04-24/58fdc0cd2d563.jpg', 'Goods/2017-04-24/thumb_3_58fdc0cd2d563.jpg', 'Goods/2017-04-24/thumb_2_58fdc0cd2d563.jpg', 'Goods/2017-04-24/thumb_1_58fdc0cd2d563.jpg', 'Goods/2017-04-24/thumb_0_58fdc0cd2d563.jpg', '2', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('11', '111', '111.00', '11.00', '', '是', '否', '2017-04-24 17:17:03', 'Goods/2017-04-24/58fdc28e8fd47.jpg', 'Goods/2017-04-24/thumb_3_58fdc28e8fd47.jpg', 'Goods/2017-04-24/thumb_2_58fdc28e8fd47.jpg', 'Goods/2017-04-24/thumb_1_58fdc28e8fd47.jpg', 'Goods/2017-04-24/thumb_0_58fdc28e8fd47.jpg', '2', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '100', '否');
INSERT INTO `p_goods` VALUES ('13', '科龙空调', '1111.00', '111.00', '<p>范德萨发</p>', '是', '否', '2017-04-26 09:23:49', 'Goods/2017-05-12/59157e3d568e5.jpg', 'Goods/2017-05-12/sm_59157e3d568e5.jpg', 'Goods/2017-05-12/mid_59157e3d568e5.jpg', 'Goods/2017-05-12/big_59157e3d568e5.jpg', 'Goods/2017-05-12/mbig_59157e3d568e5.jpg', '2', '1', '0', '0.00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '否', '否', '否', '120', '是');
INSERT INTO `p_goods` VALUES ('14', '12121', '1111.00', '1111.00', '<p>发顺丰</p>', '是', '否', '2017-04-26 09:28:05', 'Goods/2017-05-12/59157e207ea9a.jpg', 'Goods/2017-05-12/sm_59157e207ea9a.jpg', 'Goods/2017-05-12/mid_59157e207ea9a.jpg', 'Goods/2017-05-12/big_59157e207ea9a.jpg', 'Goods/2017-05-12/mbig_59157e207ea9a.jpg', '2', '1', '0', '99.00', '2017-05-10 00:00:00', '2017-05-10 23:59:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('15', '范德萨发', '100.00', '100.00', '<p>范德萨发</p>', '是', '否', '2017-04-26 09:40:16', 'Goods/2017-05-12/5915560aaae39.jpg', 'Goods/2017-05-12/sm_5915560aaae39.jpg', 'Goods/2017-05-12/mid_5915560aaae39.jpg', 'Goods/2017-05-12/big_5915560aaae39.jpg', 'Goods/2017-05-12/mbig_5915560aaae39.jpg', '2', '16', '1', '999.00', '2017-05-10 09:18:00', '2017-05-11 00:00:00', '是', '否', '否', '99', '是');
INSERT INTO `p_goods` VALUES ('16', '11', '1.00', '1.00', '<p>啊啊啊啊</p>', '是', '否', '2017-05-23 00:00:00', '', '', '', '', '', '2', '1', '1', '1.00', '2017-05-23 00:00:00', '2017-05-31 00:00:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('17', '111', '111.00', '111.00', '', '是', '否', '2017-05-12 22:22:30', 'Goods/2017-05-12/5915c525d125c.jpg', 'Goods/2017-05-12/thumb_3_5915c525d125c.jpg', 'Goods/2017-05-12/thumb_2_5915c525d125c.jpg', 'Goods/2017-05-12/thumb_1_5915c525d125c.jpg', 'Goods/2017-05-12/thumb_0_5915c525d125c.jpg', '2', '1', '0', '11.00', '2017-05-12 00:00:00', '2017-05-12 22:22:00', '否', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('18', '111', '111.00', '111.00', '<p>11111</p>', '是', '否', '2017-05-12 22:24:33', 'Goods/2017-05-12/5915c5a1749d7.jpg', 'Goods/2017-05-12/thumb_3_5915c5a1749d7.jpg', 'Goods/2017-05-12/thumb_2_5915c5a1749d7.jpg', 'Goods/2017-05-12/thumb_1_5915c5a1749d7.jpg', 'Goods/2017-05-12/thumb_0_5915c5a1749d7.jpg', '2', '1', '2', '111.00', '2017-05-12 22:24:00', '2017-05-12 22:24:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('19', 'fafds', '11.00', '11.00', '', '是', '否', '2017-05-12 22:35:02', 'Goods/2017-05-12/5915c8165a290.jpg', 'Goods/2017-05-12/thumb_3_5915c8165a290.jpg', 'Goods/2017-05-12/thumb_2_5915c8165a290.jpg', 'Goods/2017-05-12/thumb_1_5915c8165a290.jpg', 'Goods/2017-05-12/thumb_0_5915c8165a290.jpg', '2', '1', '0', '111.00', '2017-05-12 22:34:00', '2017-05-12 22:34:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('20', '111', '111.00', '111.00', '', '是', '否', '2017-05-12 22:35:41', 'Goods/2017-05-12/5915c83dafa16.jpg', 'Goods/2017-05-12/thumb_3_5915c83dafa16.jpg', 'Goods/2017-05-12/thumb_2_5915c83dafa16.jpg', 'Goods/2017-05-12/thumb_1_5915c83dafa16.jpg', 'Goods/2017-05-12/thumb_0_5915c83dafa16.jpg', '2', '1', '0', '111.00', '2017-05-12 22:35:00', '2017-05-12 22:35:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('21', '1111', '111.00', '111.00', '', '是', '否', '2017-05-12 22:36:20', 'Goods/2017-05-12/5915c864755f4.jpg', 'Goods/2017-05-12/thumb_3_5915c864755f4.jpg', 'Goods/2017-05-12/thumb_2_5915c864755f4.jpg', 'Goods/2017-05-12/thumb_1_5915c864755f4.jpg', 'Goods/2017-05-12/thumb_0_5915c864755f4.jpg', '2', '1', '0', '111.00', '2017-05-12 22:36:00', '2017-05-12 22:36:00', '否', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('22', 'qqq', '11.00', '111.00', '', '是', '否', '2017-05-12 22:37:12', 'Goods/2017-05-12/5915c898ad14e.jpg', 'Goods/2017-05-12/thumb_3_5915c898ad14e.jpg', 'Goods/2017-05-12/thumb_2_5915c898ad14e.jpg', 'Goods/2017-05-12/thumb_1_5915c898ad14e.jpg', 'Goods/2017-05-12/thumb_0_5915c898ad14e.jpg', '2', '16', '0', '111.00', '2017-05-12 22:37:00', '2017-05-12 22:37:00', '是', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('23', '到底是广东省', '111.00', '11.00', '', '是', '否', '2017-05-12 22:47:56', 'Goods/2017-05-12/5915cb1c458a0.jpg', 'Goods/2017-05-12/thumb_3_5915cb1c458a0.jpg', 'Goods/2017-05-12/thumb_2_5915cb1c458a0.jpg', 'Goods/2017-05-12/thumb_1_5915cb1c458a0.jpg', 'Goods/2017-05-12/thumb_0_5915cb1c458a0.jpg', '2', '1', '0', '111.00', '2017-05-12 22:47:00', '2017-05-31 00:00:00', '否', '是', '是', '100', '是');
INSERT INTO `p_goods` VALUES ('24', '风刀霜剑覅啥', '11.00', '111.00', '<p>发的萨芬撒女的发生大沙发<img src=\"http://zjxm.com/Public/umeditor1_2_2-utf8-php/php/upload/20170515/14948169835180.jpg\" alt=\"14948169835180.jpg\" /></p>', '是', '否', '2017-05-15 10:57:08', 'Goods/2017-05-15/59191903e1f12.jpg', 'Goods/2017-05-15/thumb_3_59191903e1f12.jpg', 'Goods/2017-05-15/thumb_2_59191903e1f12.jpg', 'Goods/2017-05-15/thumb_1_59191903e1f12.jpg', 'Goods/2017-05-15/thumb_0_59191903e1f12.jpg', '2', '1', '1', '111.00', '2017-05-15 10:56:00', '2017-05-15 10:56:00', '是', '是', '是', '100', '是');
-- ----------------------------
-- Table structure for p_goods_attr
-- ----------------------------
DROP TABLE IF EXISTS `p_goods_attr`;
CREATE TABLE `p_goods_attr` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`attr_value` varchar(15) NOT NULL DEFAULT '' COMMENT '属性的值',
`attr_id` mediumint(8) unsigned NOT NULL COMMENT '属性Id',
`goods_id` mediumint(8) unsigned NOT NULL COMMENT '商品Id',
PRIMARY KEY (`id`),
KEY `attr_id` (`attr_id`),
KEY `goods_id` (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COMMENT='商品属性表';
-- ----------------------------
-- Records of p_goods_attr
-- ----------------------------
INSERT INTO `p_goods_attr` VALUES ('1', '白色', '1', '14');
INSERT INTO `p_goods_attr` VALUES ('2', '银色', '1', '14');
INSERT INTO `p_goods_attr` VALUES ('3', '黑色', '1', '14');
INSERT INTO `p_goods_attr` VALUES ('4', '5寸', '2', '14');
INSERT INTO `p_goods_attr` VALUES ('5', '银色', '1', '15');
INSERT INTO `p_goods_attr` VALUES ('6', '4.8寸', '2', '15');
INSERT INTO `p_goods_attr` VALUES ('7', '1GB', '5', '15');
INSERT INTO `p_goods_attr` VALUES ('8', '白色', '1', '15');
INSERT INTO `p_goods_attr` VALUES ('9', '5寸', '2', '15');
INSERT INTO `p_goods_attr` VALUES ('10', '4GB', '5', '15');
INSERT INTO `p_goods_attr` VALUES ('11', '2GB', '5', '15');
INSERT INTO `p_goods_attr` VALUES ('12', '5.5寸', '2', '15');
INSERT INTO `p_goods_attr` VALUES ('13', '黑色', '1', '15');
INSERT INTO `p_goods_attr` VALUES ('14', '白色', '1', '24');
INSERT INTO `p_goods_attr` VALUES ('15', '银色', '1', '24');
INSERT INTO `p_goods_attr` VALUES ('16', '黑色', '1', '24');
INSERT INTO `p_goods_attr` VALUES ('17', '4.8寸', '2', '24');
INSERT INTO `p_goods_attr` VALUES ('18', '5寸', '2', '24');
INSERT INTO `p_goods_attr` VALUES ('19', '5.5寸', '2', '24');
INSERT INTO `p_goods_attr` VALUES ('20', '2GB', '5', '24');
INSERT INTO `p_goods_attr` VALUES ('21', '1GB', '5', '24');
INSERT INTO `p_goods_attr` VALUES ('22', '4GB', '5', '24');
INSERT INTO `p_goods_attr` VALUES ('23', '发发的撒法萨芬', '6', '15');
-- ----------------------------
-- Table structure for p_goods_cate
-- ----------------------------
DROP TABLE IF EXISTS `p_goods_cate`;
CREATE TABLE `p_goods_cate` (
`cate_id` mediumint(8) unsigned NOT NULL COMMENT '分类ID',
`goods_id` mediumint(8) unsigned NOT NULL COMMENT '商品ID',
KEY `goods_id` (`goods_id`),
KEY `cate_id` (`cate_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品扩展分类表';
-- ----------------------------
-- Records of p_goods_cate
-- ----------------------------
INSERT INTO `p_goods_cate` VALUES ('1', '11');
INSERT INTO `p_goods_cate` VALUES ('2', '11');
INSERT INTO `p_goods_cate` VALUES ('3', '11');
INSERT INTO `p_goods_cate` VALUES ('4', '11');
INSERT INTO `p_goods_cate` VALUES ('5', '11');
INSERT INTO `p_goods_cate` VALUES ('6', '11');
INSERT INTO `p_goods_cate` VALUES ('18', '14');
INSERT INTO `p_goods_cate` VALUES ('16', '13');
INSERT INTO `p_goods_cate` VALUES ('22', '22');
INSERT INTO `p_goods_cate` VALUES ('22', '23');
INSERT INTO `p_goods_cate` VALUES ('22', '2');
INSERT INTO `p_goods_cate` VALUES ('16', '24');
INSERT INTO `p_goods_cate` VALUES ('23', '15');
INSERT INTO `p_goods_cate` VALUES ('24', '15');
INSERT INTO `p_goods_cate` VALUES ('17', '15');
INSERT INTO `p_goods_cate` VALUES ('19', '15');
-- ----------------------------
-- Table structure for p_goods_number
-- ----------------------------
DROP TABLE IF EXISTS `p_goods_number`;
CREATE TABLE `p_goods_number` (
`goods_id` mediumint(8) unsigned NOT NULL COMMENT '商品Id',
`goods_number` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '商品库存量',
`goods_attr_id` varchar(150) NOT NULL DEFAULT '' COMMENT '商品属性id',
KEY `goods_id` (`goods_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品库存表';
-- ----------------------------
-- Records of p_goods_number
-- ----------------------------
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,6,10');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,7,9');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,11,12');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '6,8,10');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '7,8,9');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '8,9,10');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '9,11,13');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '6,10,13');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,6,10');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,7,9');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '5,11,12');
INSERT INTO `p_goods_number` VALUES ('15', '1111', '6,8,10');
-- ----------------------------
-- Table structure for p_goods_pic
-- ----------------------------
DROP TABLE IF EXISTS `p_goods_pic`;
CREATE TABLE `p_goods_pic` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`pic` varchar(150) NOT NULL COMMENT '原图',
`sm_pic` varchar(150) NOT NULL COMMENT '小图',
`mid_pic` varchar(150) NOT NULL COMMENT '中图',
`big_pic` varchar(150) NOT NULL COMMENT '大图',
`goods_id` mediumint(8) unsigned NOT NULL COMMENT '商品Id',
PRIMARY KEY (`id`),
KEY `goods_id` (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='商品相册';
-- ----------------------------
-- Records of p_goods_pic
-- ----------------------------
INSERT INTO `p_goods_pic` VALUES ('1', 'Goods/2017-05-15/59191904e3d95.jpg', 'Goods/2017-05-15/thumb_2_59191904e3d95.jpg', 'Goods/2017-05-15/thumb_1_59191904e3d95.jpg', 'Goods/2017-05-15/thumb_0_59191904e3d95.jpg', '24');
INSERT INTO `p_goods_pic` VALUES ('2', 'Goods/2017-05-15/591919051ec08.jpg', 'Goods/2017-05-15/thumb_2_591919051ec08.jpg', 'Goods/2017-05-15/thumb_1_591919051ec08.jpg', 'Goods/2017-05-15/thumb_0_591919051ec08.jpg', '24');
INSERT INTO `p_goods_pic` VALUES ('3', 'Goods/2017-05-15/591919053d052.jpg', 'Goods/2017-05-15/thumb_2_591919053d052.jpg', 'Goods/2017-05-15/thumb_1_591919053d052.jpg', 'Goods/2017-05-15/thumb_0_591919053d052.jpg', '24');
INSERT INTO `p_goods_pic` VALUES ('4', 'Goods/2017-05-15/591958043c26c.jpg', 'Goods/2017-05-15/thumb_2_591958043c26c.jpg', 'Goods/2017-05-15/thumb_1_591958043c26c.jpg', 'Goods/2017-05-15/thumb_0_591958043c26c.jpg', '18');
INSERT INTO `p_goods_pic` VALUES ('5', 'Goods/2017-05-15/59195804678c6.jpg', 'Goods/2017-05-15/thumb_2_59195804678c6.jpg', 'Goods/2017-05-15/thumb_1_59195804678c6.jpg', 'Goods/2017-05-15/thumb_0_59195804678c6.jpg', '18');
INSERT INTO `p_goods_pic` VALUES ('6', 'Goods/2017-05-15/5919580485ed2.jpg', 'Goods/2017-05-15/thumb_2_5919580485ed2.jpg', 'Goods/2017-05-15/thumb_1_5919580485ed2.jpg', 'Goods/2017-05-15/thumb_0_5919580485ed2.jpg', '18');
INSERT INTO `p_goods_pic` VALUES ('7', 'Goods/2017-05-15/59195804aba1a.jpg', 'Goods/2017-05-15/thumb_2_59195804aba1a.jpg', 'Goods/2017-05-15/thumb_1_59195804aba1a.jpg', 'Goods/2017-05-15/thumb_0_59195804aba1a.jpg', '18');
INSERT INTO `p_goods_pic` VALUES ('8', 'Goods/2017-05-15/59195822641f6.jpg', 'Goods/2017-05-15/thumb_2_59195822641f6.jpg', 'Goods/2017-05-15/thumb_1_59195822641f6.jpg', 'Goods/2017-05-15/thumb_0_59195822641f6.jpg', '15');
INSERT INTO `p_goods_pic` VALUES ('9', 'Goods/2017-05-15/59195822978e7.jpg', 'Goods/2017-05-15/thumb_2_59195822978e7.jpg', 'Goods/2017-05-15/thumb_1_59195822978e7.jpg', 'Goods/2017-05-15/thumb_0_59195822978e7.jpg', '15');
INSERT INTO `p_goods_pic` VALUES ('10', 'Goods/2017-05-15/59195822c1c39.jpg', 'Goods/2017-05-15/thumb_2_59195822c1c39.jpg', 'Goods/2017-05-15/thumb_1_59195822c1c39.jpg', 'Goods/2017-05-15/thumb_0_59195822c1c39.jpg', '15');
INSERT INTO `p_goods_pic` VALUES ('11', 'Goods/2017-05-15/59195822f30ea.jpg', 'Goods/2017-05-15/thumb_2_59195822f30ea.jpg', 'Goods/2017-05-15/thumb_1_59195822f30ea.jpg', 'Goods/2017-05-15/thumb_0_59195822f30ea.jpg', '15');
-- ----------------------------
-- Table structure for p_member
-- ----------------------------
DROP TABLE IF EXISTS `p_member`;
CREATE TABLE `p_member` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`username` varchar(30) NOT NULL COMMENT '用户名',
`password` char(32) NOT NULL COMMENT '密码',
`face` varchar(150) NOT NULL DEFAULT '' COMMENT '用户头像',
`jifen` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '会员积分',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员用户表';
-- ----------------------------
-- Records of p_member
-- ----------------------------
-- ----------------------------
-- Table structure for p_member_level
-- ----------------------------
DROP TABLE IF EXISTS `p_member_level`;
CREATE TABLE `p_member_level` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`level_name` varchar(50) NOT NULL COMMENT '级别名称',
`jifen_bottom` mediumint(8) unsigned NOT NULL COMMENT '积分下限',
`jifen_top` mediumint(8) unsigned NOT NULL COMMENT '积分上限',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='会员级别';
-- ----------------------------
-- Records of p_member_level
-- ----------------------------
INSERT INTO `p_member_level` VALUES ('1', '一级会员', '0', '5000');
INSERT INTO `p_member_level` VALUES ('2', '二级会员', '5001', '10000');
INSERT INTO `p_member_level` VALUES ('3', '三级会员', '10001', '20000');
-- ----------------------------
-- Table structure for p_member_price
-- ----------------------------
DROP TABLE IF EXISTS `p_member_price`;
CREATE TABLE `p_member_price` (
`price` decimal(10,2) NOT NULL COMMENT '会员价格',
`level_id` mediumint(8) unsigned NOT NULL COMMENT '级别ID',
`goods_id` mediumint(8) unsigned NOT NULL COMMENT '商品ID',
KEY `level_id` (`level_id`),
KEY `goods_id` (`goods_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='会员级别价格表';
-- ----------------------------
-- Records of p_member_price
-- ----------------------------
INSERT INTO `p_member_price` VALUES ('101.00', '1', '7');
INSERT INTO `p_member_price` VALUES ('102.00', '2', '7');
INSERT INTO `p_member_price` VALUES ('103.00', '3', '7');
INSERT INTO `p_member_price` VALUES ('111.00', '1', '14');
INSERT INTO `p_member_price` VALUES ('111.00', '2', '14');
INSERT INTO `p_member_price` VALUES ('111.00', '3', '14');
INSERT INTO `p_member_price` VALUES ('1000.00', '1', '13');
INSERT INTO `p_member_price` VALUES ('100.00', '2', '13');
INSERT INTO `p_member_price` VALUES ('100.00', '3', '13');
INSERT INTO `p_member_price` VALUES ('111.00', '1', '24');
INSERT INTO `p_member_price` VALUES ('11.00', '2', '24');
INSERT INTO `p_member_price` VALUES ('111.00', '3', '24');
INSERT INTO `p_member_price` VALUES ('111.00', '1', '24');
INSERT INTO `p_member_price` VALUES ('11.00', '2', '24');
INSERT INTO `p_member_price` VALUES ('111.00', '3', '24');
INSERT INTO `p_member_price` VALUES ('11.00', '1', '18');
INSERT INTO `p_member_price` VALUES ('11.00', '2', '18');
INSERT INTO `p_member_price` VALUES ('11.00', '3', '18');
INSERT INTO `p_member_price` VALUES ('22.00', '1', '15');
INSERT INTO `p_member_price` VALUES ('222.00', '2', '15');
INSERT INTO `p_member_price` VALUES ('333.00', '3', '15');
-- ----------------------------
-- Table structure for p_privilege
-- ----------------------------
DROP TABLE IF EXISTS `p_privilege`;
CREATE TABLE `p_privilege` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`pri_name` varchar(30) NOT NULL COMMENT '权限名称',
`module_name` varchar(30) NOT NULL DEFAULT '' COMMENT '模块名称',
`controller_name` varchar(30) NOT NULL DEFAULT '' COMMENT '控制器名称',
`action_name` varchar(30) NOT NULL DEFAULT '' COMMENT '方法名称',
`parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '上级权限Id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8 COMMENT='权限表';
-- ----------------------------
-- Records of p_privilege
-- ----------------------------
INSERT INTO `p_privilege` VALUES ('1', '商品模块', '', '', '', '0');
INSERT INTO `p_privilege` VALUES ('2', '商品列表', 'Admin', 'Goods', 'lst', '1');
INSERT INTO `p_privilege` VALUES ('3', '添加商品', 'Admin', 'Goods', 'add', '2');
INSERT INTO `p_privilege` VALUES ('4', '修改商品', 'Admin', 'Goods', 'edit', '2');
INSERT INTO `p_privilege` VALUES ('5', '删除商品', 'Admin', 'Goods', 'delete', '2');
INSERT INTO `p_privilege` VALUES ('6', '分类列表', 'Admin', 'Category', 'lst', '1');
INSERT INTO `p_privilege` VALUES ('7', '添加分类', 'Admin', 'Category', 'add', '6');
INSERT INTO `p_privilege` VALUES ('8', '修改分类', 'Admin', 'Category', 'edit', '6');
INSERT INTO `p_privilege` VALUES ('9', '删除分类', 'Admin', 'Category', 'delete', '6');
INSERT INTO `p_privilege` VALUES ('10', 'RBAC', '', '', '', '0');
INSERT INTO `p_privilege` VALUES ('11', '权限列表', 'Admin', 'Privilege', 'lst', '10');
INSERT INTO `p_privilege` VALUES ('12', '添加权限', 'Privilege', 'Admin', 'add', '11');
INSERT INTO `p_privilege` VALUES ('13', '修改权限', 'Admin', 'Privilege', 'edit', '11');
INSERT INTO `p_privilege` VALUES ('14', '删除权限', 'Admin', 'Privilege', 'delete', '11');
INSERT INTO `p_privilege` VALUES ('15', '角色列表', 'Admin', 'Role', 'lst', '10');
INSERT INTO `p_privilege` VALUES ('16', '添加角色', 'Admin', 'Role', 'add', '15');
INSERT INTO `p_privilege` VALUES ('17', '修改角色', 'Admin', 'Role', 'edit', '15');
INSERT INTO `p_privilege` VALUES ('18', '删除角色', 'Admin', 'Role', 'delete', '15');
INSERT INTO `p_privilege` VALUES ('19', '管理员列表', 'Admin', 'Admin', 'lst', '10');
INSERT INTO `p_privilege` VALUES ('20', '添加管理员', 'Admin', 'Admin', 'add', '19');
INSERT INTO `p_privilege` VALUES ('21', '修改管理员', 'Admin', 'Admin', 'edit', '19');
INSERT INTO `p_privilege` VALUES ('22', '删除管理员', 'Admin', 'Admin', 'delete', '19');
INSERT INTO `p_privilege` VALUES ('23', '类型列表', 'Admin', 'Type', 'lst', '1');
INSERT INTO `p_privilege` VALUES ('24', '添加类型', 'Admin', 'Type', 'add', '23');
INSERT INTO `p_privilege` VALUES ('25', '修改类型', 'Admin', 'Type', 'edit', '23');
INSERT INTO `p_privilege` VALUES ('26', '删除类型', 'Admin', 'Type', 'delete', '23');
INSERT INTO `p_privilege` VALUES ('27', '属性列表', 'Admin', 'Attribute', 'lst', '23');
INSERT INTO `p_privilege` VALUES ('28', '添加属性', 'Admin', 'Attribute', 'add', '27');
INSERT INTO `p_privilege` VALUES ('29', '修改属性', 'Admin', 'Attribute', 'edit', '27');
INSERT INTO `p_privilege` VALUES ('30', '删除属性', 'Admin', 'Attribute', 'delete', '27');
INSERT INTO `p_privilege` VALUES ('31', 'ajax删除商品属性', 'Admin', 'Goods', 'ajaxDelGoodsAttr', '4');
INSERT INTO `p_privilege` VALUES ('32', 'ajax删除商品相册图片', 'Admin', 'Goods', 'ajaxDelImage', '4');
INSERT INTO `p_privilege` VALUES ('33', '会员管理', '', '', '', '0');
INSERT INTO `p_privilege` VALUES ('34', '会员级别列表', 'Admin', 'MemberLevel', 'lst', '33');
INSERT INTO `p_privilege` VALUES ('35', '添加会员级别', 'Admin', 'MemberLevel', 'add', '34');
INSERT INTO `p_privilege` VALUES ('36', '修改会员级别', 'Admin', 'MemberLevel', 'edit', '34');
INSERT INTO `p_privilege` VALUES ('37', '删除会员级别', 'Admin', 'MemberLevel', 'delete', '34');
INSERT INTO `p_privilege` VALUES ('38', '品牌列表', 'Admin', 'Brand', 'lst', '1');
-- ----------------------------
-- Table structure for p_role
-- ----------------------------
DROP TABLE IF EXISTS `p_role`;
CREATE TABLE `p_role` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`role_name` varchar(30) NOT NULL COMMENT '角色名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='角色权限关系表';
-- ----------------------------
-- Records of p_role
-- ----------------------------
INSERT INTO `p_role` VALUES ('1', '商品管理员');
INSERT INTO `p_role` VALUES ('2', '商品管理员1');
-- ----------------------------
-- Table structure for p_role_pri
-- ----------------------------
DROP TABLE IF EXISTS `p_role_pri`;
CREATE TABLE `p_role_pri` (
`pri_id` mediumint(8) unsigned NOT NULL COMMENT '权限ID',
`role_id` mediumint(8) unsigned NOT NULL COMMENT '角色ID',
KEY `pri_id` (`pri_id`),
KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色权限关系表';
-- ----------------------------
-- Records of p_role_pri
-- ----------------------------
INSERT INTO `p_role_pri` VALUES ('1', '1');
INSERT INTO `p_role_pri` VALUES ('2', '1');
INSERT INTO `p_role_pri` VALUES ('3', '1');
INSERT INTO `p_role_pri` VALUES ('4', '1');
INSERT INTO `p_role_pri` VALUES ('31', '1');
INSERT INTO `p_role_pri` VALUES ('32', '1');
INSERT INTO `p_role_pri` VALUES ('5', '1');
INSERT INTO `p_role_pri` VALUES ('1', '2');
INSERT INTO `p_role_pri` VALUES ('2', '2');
INSERT INTO `p_role_pri` VALUES ('3', '2');
INSERT INTO `p_role_pri` VALUES ('4', '2');
INSERT INTO `p_role_pri` VALUES ('31', '2');
INSERT INTO `p_role_pri` VALUES ('32', '2');
INSERT INTO `p_role_pri` VALUES ('5', '2');
-- ----------------------------
-- Table structure for p_type
-- ----------------------------
DROP TABLE IF EXISTS `p_type`;
CREATE TABLE `p_type` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
`type_name` varchar(30) NOT NULL COMMENT '类型名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='类型表';
-- ----------------------------
-- Records of p_type
-- ----------------------------
INSERT INTO `p_type` VALUES ('1', '手机');
INSERT INTO `p_type` VALUES ('2', '内存');
INSERT INTO `p_type` VALUES ('4', '服装');
| 64.664063 | 568 | 0.624683 |
5c3c7545a1ad243a4ba9a2a802bf39a887b24c3d | 289 | h | C | ios/ReactNativeCountries.h | danceconvention/react-native-countries | 8bf5fb14cd96ed436f0810f2cb803da8adf001d2 | [
"MIT"
] | 16 | 2019-01-13T21:43:52.000Z | 2022-01-29T12:10:56.000Z | ios/ReactNativeCountries.h | danceconvention/react-native-countries | 8bf5fb14cd96ed436f0810f2cb803da8adf001d2 | [
"MIT"
] | 2 | 2020-01-16T23:10:16.000Z | 2020-01-20T08:09:43.000Z | ios/ReactNativeCountries.h | danceconvention/react-native-countries | 8bf5fb14cd96ed436f0810f2cb803da8adf001d2 | [
"MIT"
] | 4 | 2019-10-02T07:12:46.000Z | 2021-06-12T21:55:04.000Z | //
// ReactNativeCountries.h
// ReactNativeCountries
//
// Created by Talut TASGIRAN on 24.12.2018.
//
#if __has_include("RCTBridgeModule.h")
#import "RCTBridgeModule.h"
#else
#import <React/RCTBridgeModule.h>
#endif
@interface ReactNativeCountries : NSObject <RCTBridgeModule>
@end
| 17 | 60 | 0.750865 |
5f3a11ff0a84e6d64226bcaf918e020ff37958f6 | 504 | ts | TypeScript | dist/lib/createClassName.d.ts | DmitriVanGuard/svelte-preprocess-cssmodules | 3b24f22c1bed4ebfb1fd18e22c3588917b917a33 | [
"MIT"
] | null | null | null | dist/lib/createClassName.d.ts | DmitriVanGuard/svelte-preprocess-cssmodules | 3b24f22c1bed4ebfb1fd18e22c3588917b917a33 | [
"MIT"
] | null | null | null | dist/lib/createClassName.d.ts | DmitriVanGuard/svelte-preprocess-cssmodules | 3b24f22c1bed4ebfb1fd18e22c3588917b917a33 | [
"MIT"
] | null | null | null | import { PluginOptions } from '../types';
/**
* Create the interpolated name
* @param filename tthe resource filename
* @param markup Markup content
* @param style Stylesheet content
* @param className the className
* @param pluginOptions preprocess-cssmodules options
* @return the interpolated name
*/
declare function createCssModulesClassName(filename: string, markup: string, style: string, className: string, pluginOptions: PluginOptions): string;
export default createCssModulesClassName;
| 38.769231 | 149 | 0.78373 |
d6a9963aab9f173b583fd272ba1457e76c00cd6e | 5,074 | swift | Swift | EmbeddedSocial/Sources/Modules/Activity/Entities/ActivityViewModels.swift | LDaneliukas/EmbeddedSocial-iOS-SDK | c1de4c64b9d744020d10bde8411db03968f24965 | [
"MIT"
] | 10 | 2019-07-05T19:35:10.000Z | 2021-07-12T18:02:33.000Z | EmbeddedSocial/Sources/Modules/Activity/Entities/ActivityViewModels.swift | LDaneliukas/EmbeddedSocial-iOS-SDK | c1de4c64b9d744020d10bde8411db03968f24965 | [
"MIT"
] | 365 | 2017-09-29T07:31:05.000Z | 2018-10-18T16:27:48.000Z | EmbeddedSocial/Sources/Modules/Activity/Entities/ActivityViewModels.swift | LDaneliukas/EmbeddedSocial-iOS-SDK | c1de4c64b9d744020d10bde8411db03968f24965 | [
"MIT"
] | 8 | 2019-08-07T07:13:30.000Z | 2021-11-10T10:11:30.000Z | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import UIKit
protocol ActivityItemViewModel {
var cellID: String { get set }
var cellClass: UITableViewCell.Type { get set }
}
struct PendingRequestViewModel: ActivityItemViewModel {
var cellID: String
var cellClass: UITableViewCell.Type
let profileImagePlaceholder = AppConfiguration.shared.theme.assets.userPhotoPlaceholder
let profileImage: String?
let profileName: String?
}
struct ActivityViewModel: ActivityItemViewModel {
var cellID: String
var cellClass: UITableViewCell.Type
let iconImage: Asset?
let profileImagePlaceholder = AppConfiguration.shared.theme.assets.userPhotoPlaceholder
let profileImage: String?
let postImagePlaceholder: Asset?
let postText: String
let postTime: String
let postImage: String?
}
class ActivityItemViewModelBuilder {
static func build(from item: ActivityItem) -> ActivityItemViewModel {
switch item {
case let .pendingRequest(model):
return RequestItemViewModelBuilder.build(from: model)
case let .myActivity(model):
return MyActivityItemViewModelBuilder.build(from: model)
case let .othersActivity(model):
return OthersActivityItemViewModelBuilder.build(from: model)
}
}
static func assetForActivity(_ model: ActivityView) -> Asset? {
var result: Asset?
if let activityType = model.activityType {
switch activityType {
case .comment:
result = Asset.esDecorComment
case .following:
result = Asset.esDecorFollow
case .like:
result = Asset.esDecorLike
default:
result = nil
}
}
return result
}
}
class RequestItemViewModelBuilder {
static func build(from model: User) -> ActivityItemViewModel {
let cellID = FollowRequestCell.reuseID
let cellClass = FollowRequestCell.self
let profileImage = model.photo?.getHandle()
let profileName = model.fullName
return PendingRequestViewModel(cellID: cellID,
cellClass: cellClass,
profileImage: profileImage,
profileName: profileName)
}
}
class MyActivityItemViewModelBuilder {
static func build(from model: ActivityView) -> ActivityItemViewModel {
let cellID = ActivityCell.reuseID
let cellClass = ActivityCell.self
let profileImage = model.actorUsers?.first?.photoUrl
var postImage = model.actedOnContent?.blobUrl
if postImage != nil {
postImage! += Constants.ImageResize.pixels100
}
let postImagePlaceholder: Asset? = (model.actedOnContent?.contentType == .topic) ? Asset.placeholderPostNoimage : nil
let postText = ActivityTextRender.shared.renderMyActivity(model: model) ?? ""
let timeAgoText = model.createdTimeAgo() ?? ""
let activityIcon = ActivityItemViewModelBuilder.assetForActivity(model)
return ActivityViewModel(cellID: cellID,
cellClass: cellClass,
iconImage: activityIcon,
profileImage: profileImage,
postImagePlaceholder: postImagePlaceholder,
postText: postText,
postTime: timeAgoText,
postImage: postImage)
}
}
class OthersActivityItemViewModelBuilder {
static func build(from model: ActivityView) -> ActivityItemViewModel {
let cellID = ActivityCell.reuseID
let cellClass = ActivityCell.self
let profileImage = model.actorUsers?.first?.photoUrl
var postImage = model.actedOnContent?.blobUrl
if postImage != nil {
postImage! += Constants.ImageResize.pixels100
}
let postImagePlaceholder: Asset? = (model.actedOnContent?.contentType == .topic) ? Asset.placeholderPostNoimage : nil
let postText = ActivityTextRender.shared.renderOthersActivity(model: model) ?? ""
let timeAgoText = model.createdTimeAgo() ?? ""
let activityIcon = ActivityItemViewModelBuilder.assetForActivity(model)
return ActivityViewModel(cellID: cellID,
cellClass: cellClass,
iconImage: activityIcon,
profileImage: profileImage,
postImagePlaceholder: postImagePlaceholder,
postText: postText,
postTime: timeAgoText,
postImage: postImage)
}
}
| 36.503597 | 125 | 0.60268 |
007fb8d55bde628d5dee90865f5de781caca55fd | 10,042 | kt | Kotlin | src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/PushImageService.kt | Kinway050/bk-ci | 86fa21d345d9c06b3f6857ba38d8d8d0d96ca7e3 | [
"MIT"
] | 1,939 | 2019-05-29T05:15:45.000Z | 2022-03-29T11:49:16.000Z | src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/PushImageService.kt | Kinway050/bk-ci | 86fa21d345d9c06b3f6857ba38d8d8d0d96ca7e3 | [
"MIT"
] | 3,608 | 2019-06-05T07:55:23.000Z | 2022-03-31T15:03:41.000Z | src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/PushImageService.kt | Kinway050/bk-ci | 86fa21d345d9c06b3f6857ba38d8d8d0d96ca7e3 | [
"MIT"
] | 561 | 2019-05-29T07:15:10.000Z | 2022-03-29T09:32:15.000Z | /*
* Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.devops.image.service
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.dockerjava.api.model.AuthConfig
import com.github.dockerjava.core.DefaultDockerClientConfig
import com.github.dockerjava.core.DockerClientBuilder
import com.github.dockerjava.core.command.PullImageResultCallback
import com.github.dockerjava.core.command.PushImageResultCallback
import com.tencent.devops.common.api.util.SecurityUtil
import com.tencent.devops.common.api.util.timestamp
import com.tencent.devops.common.client.Client
import com.tencent.devops.common.redis.RedisOperation
import com.tencent.devops.image.config.DockerConfig
import com.tencent.devops.image.pojo.PushImageParam
import com.tencent.devops.image.pojo.PushImageTask
import com.tencent.devops.image.pojo.enums.TaskStatus
import com.tencent.devops.image.utils.CommonUtils
import com.tencent.devops.common.log.utils.BuildLogPrinter
import com.tencent.devops.ticket.pojo.enums.CredentialType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.util.UUID
import java.util.concurrent.Executors
@Service@Suppress("ALL")
class PushImageService @Autowired constructor(
private val client: Client,
private val dockerConfig: DockerConfig,
private val redisOperation: RedisOperation,
private val objectMapper: ObjectMapper,
private val buildLogPrinter: BuildLogPrinter
) {
companion object {
private val logger = LoggerFactory.getLogger(PushImageService::class.java)
private val executorService = Executors.newFixedThreadPool(20)
}
private val dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost(dockerConfig.dockerHost)
.withDockerConfig(dockerConfig.dockerConfig)
.withApiVersion(dockerConfig.apiVersion)
.withRegistryUrl(dockerConfig.imagePrefix)
.withRegistryUsername(dockerConfig.registryUsername)
.withRegistryPassword(SecurityUtil.decrypt(dockerConfig.registryPassword!!))
.build()
private val dockerClient = DockerClientBuilder.getInstance(dockerClientConfig).build()
fun pushImage(pushImageParam: PushImageParam): PushImageTask? {
val taskId = UUID.randomUUID().toString()
val now = LocalDateTime.now()
val task = PushImageTask(
taskId = taskId,
projectId = pushImageParam.projectId,
operator = pushImageParam.userId,
createdTime = now.timestamp(),
updatedTime = now.timestamp(),
taskStatus = TaskStatus.RUNNING.name,
taskMessage = ""
)
setRedisTask(taskId, task)
executorService.execute { syncPushImage(pushImageParam, task) }
return task
}
private fun buildImageTaskKey(taskId: String): String {
return "image.pushImageTask_$taskId"
}
fun getPushImageTask(taskId: String): PushImageTask? {
val task = redisOperation.get(buildImageTaskKey(taskId)) ?: return null
try {
return objectMapper.readValue(task, PushImageTask::class.java)
} catch (t: Throwable) {
logger.warn("covert imageTask failed, task: $task", t)
}
return null
}
private fun setRedisTask(taskId: String, task: PushImageTask) {
redisOperation.set(buildImageTaskKey(taskId), objectMapper.writeValueAsString(task), 3600)
}
private fun syncPushImage(pushImageParam: PushImageParam, task: PushImageTask) {
logger.info("[${pushImageParam.buildId}]|push image, taskId:" +
" ${task.taskId}, pushImageParam: ${pushImageParam.outStr()}")
val fromImage =
"${dockerConfig.imagePrefix}/paas/${pushImageParam.projectId}/" +
"${pushImageParam.srcImageName}:${pushImageParam.srcImageTag}"
logger.info("源镜像:$fromImage")
val toImageRepo = "${pushImageParam.repoAddress}/${pushImageParam.namespace}/${pushImageParam.targetImageName}"
try {
pullImage(fromImage)
logger.info("[${pushImageParam.buildId}]|Pull image success, image name and tag: $fromImage")
dockerClient.tagImageCmd(fromImage, toImageRepo, pushImageParam.targetImageTag).exec()
logger.info("[${pushImageParam.buildId}]|Tag image success, image name and tag: " +
"$toImageRepo:${pushImageParam.targetImageTag}")
buildLogPrinter.addLine(
buildId = pushImageParam.buildId,
message = "目标镜像:$toImageRepo:${pushImageParam.targetImageTag}",
tag = pushImageParam.buildId,
executeCount = pushImageParam.executeCount ?: 1
)
pushImageToRepo(pushImageParam)
logger.info("[${pushImageParam.buildId}]|Push image success, image name and tag:" +
" $toImageRepo:${pushImageParam.targetImageTag}")
task.apply {
taskStatus = TaskStatus.SUCCESS.name
updatedTime = LocalDateTime.now().timestamp()
}
setRedisTask(task.taskId, task)
} catch (e: Throwable) {
logger.error("[${pushImageParam.buildId}]|push image error", e)
task.apply {
taskStatus = TaskStatus.FAILED.name
updatedTime = LocalDateTime.now().timestamp()
taskMessage = e.message!!
}
setRedisTask(task.taskId, task)
} finally {
try {
dockerClient.removeImageCmd(fromImage).exec()
logger.info("[${pushImageParam.buildId}]|Remove local source image success: $fromImage")
} catch (e: Throwable) {
logger.error("[${pushImageParam.buildId}]|Docker rmi failed, msg: ${e.message}")
}
try {
dockerClient.removeImageCmd("$toImageRepo:${pushImageParam.targetImageTag}").exec()
logger.info("[${pushImageParam.buildId}]|Remove local source image success: " +
"$toImageRepo:${pushImageParam.targetImageTag}")
} catch (e: Throwable) {
logger.error("[${pushImageParam.buildId}]|Docker rmi failed, msg: ${e.message}")
}
}
}
private fun pullImage(image: String) {
val authConfig = AuthConfig()
.withUsername(dockerConfig.registryUsername)
.withPassword(SecurityUtil.decrypt(dockerConfig.registryPassword!!))
.withRegistryAddress(dockerConfig.registryUrl)
dockerClient.pullImageCmd(image).withAuthConfig(authConfig).exec(PullImageResultCallback()).awaitCompletion()
}
private fun pushImageToRepo(pushImageParam: PushImageParam) {
var userName: String? = null
var password: String? = null
val ticketId = pushImageParam.ticketId
if (null != ticketId) {
val ticketsMap =
CommonUtils.getCredential(client, pushImageParam.projectId, ticketId, CredentialType.USERNAME_PASSWORD)
userName = ticketsMap["v1"] as String
password = ticketsMap["v2"] as String
}
val image =
"${pushImageParam.repoAddress}/${pushImageParam.namespace}/" +
"${pushImageParam.targetImageName}:${pushImageParam.targetImageTag}"
val builder = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost(dockerConfig.dockerHost)
.withDockerConfig(dockerConfig.dockerConfig)
.withApiVersion(dockerConfig.apiVersion)
.withRegistryUrl(pushImageParam.repoAddress)
if (null != userName) {
builder.withRegistryUsername(userName)
}
if (null != password) {
builder.withRegistryPassword(password)
}
val dockerClientConfig = builder.build()
val dockerClient = DockerClientBuilder.getInstance(dockerClientConfig).build()
try {
val authConfig = AuthConfig()
.withUsername(userName)
.withPassword(password)
.withRegistryAddress(pushImageParam.repoAddress)
dockerClient.pushImageCmd(image).withAuthConfig(authConfig).exec(PushImageResultCallback())
.awaitCompletion()
} finally {
try {
dockerClient.close()
} catch (e: Exception) {
logger.error("[${pushImageParam.buildId}]| dockerClient close error:", e)
}
}
}
}
| 45.853881 | 119 | 0.674268 |
f054faecd1c3afb1400bddfe418fe3516e6092a0 | 4,489 | js | JavaScript | packages/wp-story-editor/src/api/test/media.js | igordanchenko/web-stories-wp | 2d71fc965a317b06b280ed65448d705d1d892eb7 | [
"Apache-2.0"
] | 24 | 2022-01-21T22:55:25.000Z | 2022-03-18T08:12:39.000Z | packages/wp-story-editor/src/api/test/media.js | igordanchenko/web-stories-wp | 2d71fc965a317b06b280ed65448d705d1d892eb7 | [
"Apache-2.0"
] | 796 | 2022-01-21T20:38:25.000Z | 2022-03-31T21:51:54.000Z | packages/wp-story-editor/src/api/test/media.js | igordanchenko/web-stories-wp | 2d71fc965a317b06b280ed65448d705d1d892eb7 | [
"Apache-2.0"
] | 8 | 2022-02-08T12:51:11.000Z | 2022-03-23T17:51:05.000Z | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
/**
* External dependencies
*/
import { bindToCallbacks } from '@web-stories-wp/wp-utils';
/**
* Internal dependencies
*/
import * as apiCallbacks from '..';
import { flattenFormData } from '../utils';
import { GET_MEDIA_RESPONSE_HEADER, GET_MEDIA_RESPONSE_BODY } from './_utils';
jest.mock('@wordpress/api-fetch');
describe('Media API Callbacks', () => {
beforeEach(() => {
jest.clearAllMocks();
});
const MEDIA_PATH = `/web-stories/v1/media/`;
it('getMedia with cacheBust:true should call api with &cache_bust=true', () => {
apiFetch.mockReturnValue(
Promise.resolve({
body: GET_MEDIA_RESPONSE_BODY,
headers: GET_MEDIA_RESPONSE_HEADER,
})
);
const { getMedia } = bindToCallbacks(apiCallbacks, {
api: { media: MEDIA_PATH },
});
getMedia({
mediaType: '',
searchTerm: '',
pagingNum: 1,
cacheBust: true,
});
expect(apiFetch).toHaveBeenCalledWith(
expect.objectContaining({
path: expect.stringMatching('&cache_bust=true'),
})
);
});
it('updateMedia maps arguments to expected format', () => {
apiFetch.mockReturnValue(Promise.resolve(GET_MEDIA_RESPONSE_BODY[0]));
const { updateMedia } = bindToCallbacks(apiCallbacks, {
api: { media: MEDIA_PATH },
});
const mediaId = 1;
const mockData = {
baseColor: '#123456',
blurHash: 'asdafd-dsfgh',
isMuted: false,
mediaSource: 'source-video',
optimizedId: 12,
mutedId: 13,
altText: 'New Alt Text',
storyId: 11,
posterId: 14,
};
const expectedWpKeysMapping = {
meta: {
web_stories_base_color: mockData.baseColor,
web_stories_blurhash: mockData.blurHash,
web_stories_optimized_id: mockData.optimizedId,
web_stories_muted_id: mockData.mutedId,
web_stories_poster_id: mockData.posterId,
},
web_stories_is_muted: mockData.isMuted,
web_stories_media_source: mockData.mediaSource,
post: mockData.storyId,
featured_media: mockData.posterId,
alt_text: mockData.altText,
};
updateMedia(mediaId, mockData);
expect(apiFetch).toHaveBeenCalledWith(
expect.objectContaining({
path: MEDIA_PATH + `${mediaId}/`,
method: 'POST',
data: expectedWpKeysMapping,
})
);
});
it('uploadMedia maps arguments to expected format', () => {
apiFetch.mockReturnValue(Promise.resolve(GET_MEDIA_RESPONSE_BODY[0]));
const { uploadMedia } = bindToCallbacks(apiCallbacks, {
api: { media: MEDIA_PATH },
});
const file = new File([''], 'filename');
const mockData = {
originalId: 11,
templateId: 12,
isMuted: false,
mediaSource: 'source-video',
trimData: { data: 'trimData' },
baseColor: '#123456',
blurHash: 'asdafd-dsfgh',
};
const expectedWpKeysMapping = {
web_stories_media_source: mockData.mediaSource,
web_stories_is_muted: mockData.isMuted,
post: mockData.templateId,
original_id: mockData.originalId,
web_stories_trim_data: mockData.trimData,
web_stories_base_color: mockData.baseColor,
web_stories_blurhash: mockData.blurHash,
};
const expectedDataArgument = new window.FormData();
expectedDataArgument.append(
'file',
file,
// eslint-disable-next-line jest/no-conditional-in-test
file.name || file.type.replace('/', '.')
);
Object.entries(expectedWpKeysMapping).forEach(([key, value]) =>
flattenFormData(expectedDataArgument, key, value)
);
uploadMedia(file, mockData);
expect(apiFetch).toHaveBeenCalledWith(
expect.objectContaining({
path: MEDIA_PATH,
method: 'POST',
body: expectedDataArgument,
})
);
});
});
| 28.05625 | 82 | 0.652261 |
9671d678b496b5bd1714a0e06a8fe25b3fbd9372 | 2,769 | php | PHP | app/Http/Controllers/LabelsResourceController.php | austin-dudzik/spark | 4f2014121473ffe1a1f5929636b85272ff2ef421 | [
"MIT"
] | null | null | null | app/Http/Controllers/LabelsResourceController.php | austin-dudzik/spark | 4f2014121473ffe1a1f5929636b85272ff2ef421 | [
"MIT"
] | null | null | null | app/Http/Controllers/LabelsResourceController.php | austin-dudzik/spark | 4f2014121473ffe1a1f5929636b85272ff2ef421 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use App\Traits\ViewSorter;
use App\Models\Label;
use App\Models\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LabelsResourceController extends Controller
{
use ViewSorter;
/**
* Display a list of all labels
*
*/
public function index()
{
// Return labels view
return view('labels', [
'labels' => Label::query()->
with(['tasks'])->
where('user_id', '=', Auth::id())->
get()
]);
}
/**
* Store a new label in the database
*
* @param Request $request
*/
public function store(Request $request)
{
// Validate the request
$fields = $request->validateWithBag('new_label', [
'name' => 'required',
'color' => 'required',
]);
// Assign the user ID to the request
$fields['user_id'] = Auth::id();
// Create the label
Label::query()->create($fields);
// Redirect back
return redirect()->back();
}
/**
* Display the specified label
*
* @param Label $label
*/
public function show(Label $label)
{
// Return the single label view
return view('label-single', [
'label' => Label::query()->
where('user_id', '=', Auth::id())->
where('id', '=', $label->id)->
first(),
'tasks' => Task::query()->
where('user_id', '=', Auth::id())->
where('label_id', '=', $label->id)->
whereNull('completed')->
orderBy($this->getSorters()->sort_by, $this->getSorters()->order_by)->
get(),
]);
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param Label $label
*/
public function update(Request $request, Label $label)
{
// Validate the request
$fields = $request->validateWithBag('edit_label_' . $label->id, [
'name' => 'required',
'color' => 'required',
]);
// Update the label
Label::query()->find($label->id)->update($fields);
// Redirect to index with success
return redirect()->back();
}
/**
* Remove the specified label from storage.
*
* @param Label $label
*/
public function destroy(Label $label)
{
// Find and delete existing label
Label::query()->find($label->id)->delete();
// Remove label from tasks
Task::query()->
where('label_id', '=', $label->id)->
update(['label_id' => null]);
// Redirect to index
return redirect()->back();
}
}
| 23.87069 | 82 | 0.506681 |
85bc51703c4a5daaf7e1a2b4105aaadec3f2acf7 | 1,238 | js | JavaScript | packages/app/src/containers/ServiceAntenneEdit/mutations.js | SocialGouv/emjpm | 935ad9a80af4e6481edc433dba11b7f4e2d37c77 | [
"Apache-2.0"
] | 16 | 2019-06-12T13:22:02.000Z | 2022-02-28T03:14:14.000Z | packages/app/src/containers/ServiceAntenneEdit/mutations.js | SocialGouv/emjpm | 935ad9a80af4e6481edc433dba11b7f4e2d37c77 | [
"Apache-2.0"
] | 1,568 | 2019-02-04T09:18:35.000Z | 2022-03-28T18:54:22.000Z | packages/app/src/containers/ServiceAntenneEdit/mutations.js | SocialGouv/emjpm | 935ad9a80af4e6481edc433dba11b7f4e2d37c77 | [
"Apache-2.0"
] | 9 | 2019-02-15T17:20:12.000Z | 2021-05-19T08:54:56.000Z | import gql from "graphql-tag";
export const EDIT_ANTENNE = gql`
mutation editAntenne(
$antenne_id: Int
$user_id: Int
$name: String
$mesures_max: Int
$contact_phone: String
$contact_lastname: String
$contact_firstname: String
$contact_email: String
$code_postal: String
$departement_code: String
$adresse: String
$ville: String
$latitude: Float
$longitude: Float
) {
update_service_antenne(
where: { id: { _eq: $antenne_id } }
_set: {
name: $name
mesures_max: $mesures_max
contact_phone: $contact_phone
contact_lastname: $contact_lastname
contact_firstname: $contact_firstname
contact_email: $contact_email
code_postal: $code_postal
departement_code: $departement_code
adresse: $adresse
ville: $ville
latitude: $latitude
longitude: $longitude
}
) {
returning {
ville
adresse
code_postal
departement_code
latitude
longitude
contact_email
contact_firstname
contact_lastname
contact_phone
id
mesures_max
name
service_id
}
}
}
`;
| 22.107143 | 45 | 0.601777 |
a17ff841d70dc876059b3590bbe2359c33235ec6 | 4,076 | kt | Kotlin | gallery/src/main/java/com/worldsnas/gallery/adapter/ImageViewerAdapter.kt | worldsnas/AIO | c7d084d2cf2c4f9486337fe347d5d6b8b5806e0a | [
"Apache-2.0"
] | 58 | 2019-07-05T06:49:17.000Z | 2021-11-29T00:35:36.000Z | gallery/src/main/java/com/worldsnas/gallery/adapter/ImageViewerAdapter.kt | seyedjafariy/AIO | c7d084d2cf2c4f9486337fe347d5d6b8b5806e0a | [
"Apache-2.0"
] | 1 | 2019-06-24T17:55:19.000Z | 2019-06-24T17:55:19.000Z | gallery/src/main/java/com/worldsnas/gallery/adapter/ImageViewerAdapter.kt | seyedjafariy/AIO | c7d084d2cf2c4f9486337fe347d5d6b8b5806e0a | [
"Apache-2.0"
] | 12 | 2019-07-04T15:09:37.000Z | 2021-07-27T14:17:23.000Z | package com.worldsnas.gallery.adapter
import android.content.Context
import android.graphics.drawable.Animatable
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.imagepipeline.image.ImageInfo
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.worldsnas.gallery.drawee.ZoomableDraweeView
import me.relex.photodraweeview.OnScaleChangeListener
import java.util.*
/*
* Created by troy379 on 07.12.16.
*/
class ImageViewerAdapter(
private val context: Context, private val dataSet: List<String>,
private val imageRequestBuilder: ImageRequestBuilder?,
private val hierarchyBuilder: GenericDraweeHierarchyBuilder?,
private val isZoomingAllowed: Boolean
) : RecyclingPagerAdapter<ImageViewerAdapter.ImageViewHolder>() {
private val holders: HashSet<ImageViewHolder> = HashSet()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
val drawee = ZoomableDraweeView(context)
drawee.isEnabled = isZoomingAllowed
val holder = ImageViewHolder(drawee)
holders.add(holder)
return holder
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
holder.bind(position)
}
override val itemCount: Int = dataSet.size
fun isScaled(index: Int): Boolean {
for (holder in holders) {
if (holder.position == index) {
return holder.isScaled
}
}
return false
}
fun resetScale(index: Int) {
for (holder in holders) {
if (holder.position == index) {
holder.resetScale()
break
}
}
}
fun getUrl(position: Int): String {
return dataSet[position]
}
private fun getDraweeControllerListener(drawee: ZoomableDraweeView): BaseControllerListener<ImageInfo> {
return object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
if (imageInfo == null) {
return
}
drawee.update(imageInfo.width, imageInfo.height)
}
}
}
inner class ImageViewHolder(itemView: View) : ViewHolder(itemView), OnScaleChangeListener {
var position = -1
private val drawee: ZoomableDraweeView = itemView as ZoomableDraweeView
var isScaled: Boolean = false
fun bind(position: Int) {
this.position = position
tryToSetHierarchy()
setController(dataSet[position])
drawee.setOnScaleChangeListener(this)
}
override fun onScaleChange(scaleFactor: Float, focusX: Float, focusY: Float) {
isScaled = drawee.scale > 1.0f
}
fun resetScale() {
drawee.setScale(1.0f, true)
}
private fun tryToSetHierarchy() {
if (hierarchyBuilder != null) {
hierarchyBuilder.actualImageScaleType = ScalingUtils.ScaleType.FIT_CENTER
drawee.hierarchy = hierarchyBuilder.build()
}
}
private fun setController(url: String) {
val controllerBuilder = Fresco.newDraweeControllerBuilder()
controllerBuilder.setUri(url)
controllerBuilder.oldController = drawee.controller
controllerBuilder.controllerListener = getDraweeControllerListener(drawee)
if (imageRequestBuilder != null) {
imageRequestBuilder.setSource(Uri.parse(url))
controllerBuilder.imageRequest = imageRequestBuilder.build()
}
drawee.controller = controllerBuilder.build()
}
}
}
| 32.870968 | 108 | 0.659961 |
087760c8fe2e402c7962071306b00683c64d544a | 1,870 | swift | Swift | Rocket.Chat/API/Requests/UserInfoRequest.swift | ichat-intelizign/iOSIchatOldCode | e6d303a68644d90cda43ef69beb8d4619ea5a9d6 | [
"MIT"
] | null | null | null | Rocket.Chat/API/Requests/UserInfoRequest.swift | ichat-intelizign/iOSIchatOldCode | e6d303a68644d90cda43ef69beb8d4619ea5a9d6 | [
"MIT"
] | null | null | null | Rocket.Chat/API/Requests/UserInfoRequest.swift | ichat-intelizign/iOSIchatOldCode | e6d303a68644d90cda43ef69beb8d4619ea5a9d6 | [
"MIT"
] | null | null | null | //
// UserInfoRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/19/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
// DOCS: https://rocket.chat/docs/developer-guides/rest-api/users/info
import SwiftyJSON
typealias UserInfoResult = APIResult<UserInfoRequest>
class UserInfoRequest: APIRequest {
let path = "/api/v1/users.info"
let query: String?
let userId: String?
let username: String?
init(userId: String) {
self.userId = userId
self.username = nil
self.query = "userId=\(userId)"
}
init(username: String) {
self.username = username
self.userId = nil
self.query = "username=\(username)"
}
}
extension APIResult where T == UserInfoRequest {
var user: JSON? {
return raw?["user"]
}
var id: String? {
return user?["_id"].string
}
var type: String? {
return user?["type"].string
}
var name: String? {
return user?["name"].string
}
var username: String? {
return user?["username"].string
}
var phone: String? {
return user?["phone"].string
}
var location: String? {
return user?["location"].string
}
var utcOffset: Double? {
return user?["utcOffset"].double
}
var lastLogin: String? {
return user?["lastLogin"].string
}
var emails: JSON {
return (user!["emails"])
}
}
class EmailClass {
var address: String
var verified: Bool
init(address: String, verified: Bool) {
self.address = address
self.verified = verified
}
func toJSON() -> [String:Any] {
var dictionary: [String : Any] = [:]
dictionary["address"] = self.address
dictionary["verified"] = self.verified
return dictionary
}
}
| 21.25 | 71 | 0.575936 |
2f11dc1af2a03ebe590b1c5caf66b115a1e6e2ee | 803 | php | PHP | app/Models/Chat.php | Group5-HCMUS/Back-end-Php | a20f6755bd0df942dbce9cdd76cd76231b39c2c0 | [
"MIT"
] | null | null | null | app/Models/Chat.php | Group5-HCMUS/Back-end-Php | a20f6755bd0df942dbce9cdd76cd76231b39c2c0 | [
"MIT"
] | 1 | 2021-02-02T16:24:50.000Z | 2021-02-02T16:24:50.000Z | app/Models/Chat.php | Group5-HCMUS/Back-end-Php | a20f6755bd0df942dbce9cdd76cd76231b39c2c0 | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Illuminate\Support\Arr;
use Laravel\Scout\Searchable;
class Chat extends Model
{
use Searchable;
protected $table = 'chats';
/**
* @return array
*/
public function toSearchableArray()
{
return Arr::only(Arr::dot($this->toArray()), [
'id',
'user.full_name',
'user.email',
'user.phone_number',
]);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function sender()
{
return $this->belongsTo(User::class, 'sender_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function receiver()
{
return $this->belongsTo(User::class, 'receiver_id');
}
}
| 18.674419 | 64 | 0.562889 |
e3bc83dc4e73ac7d2bd9123447cf917d8998cad2 | 14,036 | kt | Kotlin | stately-collections/src/commonTest/kotlin/co/touchlab/stately/collections/SharedLinkedListTest.kt | rafaeltoledo/Stately | 2091d59fc30a10b06b11f9550f18aac4e2df0953 | [
"Apache-2.0"
] | null | null | null | stately-collections/src/commonTest/kotlin/co/touchlab/stately/collections/SharedLinkedListTest.kt | rafaeltoledo/Stately | 2091d59fc30a10b06b11f9550f18aac4e2df0953 | [
"Apache-2.0"
] | null | null | null | stately-collections/src/commonTest/kotlin/co/touchlab/stately/collections/SharedLinkedListTest.kt | rafaeltoledo/Stately | 2091d59fc30a10b06b11f9550f18aac4e2df0953 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 Touchlab, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.touchlab.stately.collections
import co.touchlab.stately.concurrency.value
import co.touchlab.stately.freeze
import co.touchlab.stately.isNativeFrozen
import co.touchlab.testhelp.concurrency.ThreadOperations
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class LinkedListTest {
private fun checkList(ll: SharedLinkedList<ListData>, vararg strings: String): Boolean {
for (i in 0 until strings.size) {
if (ll.get(i).s != strings[i])
return false
}
return true
}
@Test
fun testInitFrozen() {
assertTrue(SharedLinkedList<ListData>().isNativeFrozen())
}
@Test
fun add() {
val ll = makeTen()
assertEquals(10, ll.size)
}
@Test
fun addIndex() {
val ll = SharedLinkedList<ListData>()
assertFails { ll.add(1, ListData("Item 1")) }
assertEquals(0, ll.size)
ll.add(0, ListData("Item 0"))
assertEquals(1, ll.size)
for (i in 1 until 4) {
ll.add(i, ListData("Item $i"))
}
assertEquals(4, ll.size)
checkList(ll, "Item 0", "Item 1", "Item 2", "Item 3")
ll.add(0, ListData("Before"))
checkList(ll, "Before", "Item 0", "Item 1", "Item 2", "Item 3")
ll.add(2, ListData("Middle"))
checkList(ll, "Before", "Item 0", "Middle", "Item 1", "Item 2", "Item 3")
ll.clear()
checkList(ll)
ll.add(0, ListData("Asdf"))
checkList(ll, "Asdf")
}
@Test
fun addAllIndex() {
val ll = SharedLinkedList<ListData>()
val elements = listOf(ListData("Item 0"), ListData("Item 1"))
assertFails { ll.addAll(1, elements) }
ll.addAll(0, elements)
checkList(ll, "Item 0", "Item 1")
ll.addAll(1, listOf(ListData("Item a"), ListData("Item b")))
checkList(ll, "Item 0", "Item a", "Item b", "Item 1")
}
@Test
fun addAll() {
val ll = SharedLinkedList<ListData>()
val elements = listOf(ListData("Item 0"), ListData("Item 1"))
ll.addAll(elements)
checkList(ll, "Item 0", "Item 1")
ll.addAll(listOf(ListData("Item a"), ListData("Item b")))
checkList(ll, "Item 0", "Item 1", "Item a", "Item b")
}
@Test
fun clear() {
val ll = makeTen()
assertEquals(10, ll.size)
ll.clear()
assertEquals(0, ll.size)
}
@Test
fun contains() {
val ll = makeTen()
assertTrue(ll.contains(ListData("Item 2")))
assertTrue(ll.contains(ListData("Item 7")))
assertFalse(ll.contains(ListData("Item 10")))
}
@Test
fun containsAll() {
val ll = makeTen()
assertTrue(ll.containsAll(listOf(ListData("Item 2"), ListData("Item 5"), ListData("Item 0"), ListData("Item 9"))))
assertFalse(ll.containsAll(listOf(ListData("Item 2"), ListData("Item 5"), ListData("Item 0"), ListData("Item 10"))))
}
@Test
fun get() {
val ll = makeTen()
assertEquals(ListData("Item 2"), ll.get(2))
}
@Test
fun indexOf() {
val ll = makeTen()
assertEquals(3, ll.indexOf(ListData("Item 3")))
assertEquals(0, ll.indexOf(ListData("Item 0")))
assertEquals(-1, ll.indexOf(ListData("Item 10")))
ll.clear()
assertEquals(-1, ll.indexOf(ListData("Item 3")))
}
@Test
fun isEmpty() {
val ll = makeTen()
assertFalse(ll.isEmpty())
ll.clear()
assertTrue(ll.isEmpty())
}
@Test
fun remove() {
val ll = makeTen()
assertTrue(ll.remove(ListData("Item 4")))
assertTrue(ll.remove(ListData("Item 8")))
assertFalse(ll.remove(ListData("Item 8")))
assertFalse(ll.remove(ListData("Item 88")))
assertEquals(8, ll.size)
checkList(ll, "Item 0", "Item 1", "Item 2", "Item 3", "Item 5", "Item 6", "Item 7", "Item 9")
}
@Test
fun removeAll() {
val ll = makeTen()
assertTrue(ll.removeAll(listOf(ListData("Item 4"), ListData("Item 8"))))
assertFalse(ll.removeAll(listOf(ListData("Item 4"), ListData("Item 8"))))
assertFalse(ll.removeAll(listOf(ListData("Item 5"), ListData("Item 10"))))
assertEquals(7, ll.size)
checkList(ll, "Item 0", "Item 1", "Item 2", "Item 3", "Item 6", "Item 7", "Item 9")
}
@Test
fun removeAt() {
val ll = makeTen()
assertEquals(ll.removeAt(8), ListData("Item 8"))
assertEquals(9, ll.size)
assertEquals(ll.removeAt(4), ListData("Item 4"))
assertEquals(8, ll.size)
assertEquals(ll.removeAt(4), ListData("Item 5"))
assertEquals(7, ll.size)
checkList(ll, "Item 0", "Item 1", "Item 2", "Item 3", "Item 6", "Item 7", "Item 9")
}
@Test
fun set() {
val ll = makeTen()
assertEquals(ListData("Item 2"), ll.get(2))
ll.set(2, ListData("Heyo"))
assertEquals(ListData("Heyo"), ll.get(2))
}
@Test
fun size() {
val ll = makeTen()
assertEquals(10, ll.size)
for (i in 0 until 10) {
ll.removeAt(0)
assertEquals(9 - i, ll.size)
}
}
@Test
fun internalNodeAt() {
val ll = makeTen()
assertEquals(ll.internalNodeAt(5).nodeValue.s, "Item 5")
assertFails {
ll.internalNodeAt(10)
}
val empty = SharedLinkedList<ListData>()
assertFails {
empty.internalNodeAt(0)
}
}
@Test
fun nodeAdd() {
val ll = makeTen()
ll.internalNodeAt(2).add(ListData("asdf"))
assertEquals(ll.size, 11)
assertEquals(ll.internalNodeAt(2).nodeValue.s, "asdf")
assertEquals(ll.internalNodeAt(3).nodeValue.s, "Item 2")
ll.internalNodeAt(0).add(ListData("a"))
ll.internalNodeAt(0).add(ListData("b"))
assertEquals(ll.size, 13)
assertEquals(ll.internalNodeAt(0).nodeValue.s, "b")
assertEquals(ll.internalNodeAt(1).nodeValue.s, "a")
ll.internalNodeAt(12).add(ListData("c"))
ll.internalNodeAt(13).add(ListData("d"))
assertEquals(ll.size, 15)
assertEquals(ll.internalNodeAt(12).nodeValue.s, "c")
assertEquals(ll.internalNodeAt(13).nodeValue.s, "d")
}
@Test
fun nodeRemove() {
val ll = makeTen()
ll.internalNodeAt(5).remove()
assertEquals(9, ll.size)
ll.internalNodeAt(0).remove()
assertEquals(8, ll.size)
assertFails {
ll.internalNodeAt(8).remove()
}
val node = ll.internalNodeAt(7)
assertEquals("Item 9", node.nodeValue.s)
node.remove()
assertEquals(7, ll.size)
assertEquals("Item 8", ll.internalNodeAt(6).nodeValue.s)
var loopCount = 20
while (ll.size > 0) {
ll.internalNodeAt(0).remove()
if (loopCount-- == 0) {
throw IllegalStateException("Something went wrong. Give up.")
}
}
ll.add(ListData("Asdf 0"))
ll.internalNodeAt(0).add(ListData("Asdf -1"))
}
@Test
fun nodeRemovePermanent() {
val ll = makeTen()
val node = ll.internalNodeAt(5)
node.remove(permanent = false)
assertEquals(9, ll.size)
assertFalse(node.isRemoved)
val node2 = ll.internalNodeAt(5)
node2.remove(permanent = true)
assertEquals(8, ll.size)
assertTrue(node2.isRemoved)
}
@Test
fun mtNodeAdd() {
val LOOPS = 1_000
val DOOPS = 100
val ll = SharedLinkedList<ListData>().freeze()
val nodeList = mutableListOf<AbstractSharedLinkedList.Node<ListData>>()
for (i in 0 until LOOPS) {
nodeList.add(ll.addNode(ListData("a $i")))
}
nodeList.freeze()
val ops = ThreadOperations { }
for (i in 0 until LOOPS) {
ops.exe {
val node = nodeList.get(i)
for (j in 0 until DOOPS) {
node.add(ListData("a $i sub $j"))
}
node.remove()
}
}
ops.run(8)
assertEquals(DOOPS * LOOPS, ll.size)
var loopCount = 0
var doopCount = 0
/*var debugPrint = 0
println("total size ${ll.size}")
var handCount = 0
ll.forEach { handCount++ }
println("hand size ${handCount}")
ll.forEach {
if(debugPrint < 2500)
println(it)
debugPrint++
}*/
ll.iterator().forEach {
assertEquals(ListData("a $loopCount sub $doopCount"), it)
doopCount++
if (doopCount == DOOPS) {
doopCount = 0
loopCount++
}
}
}
/**
* Test multiple threads removing and occasionally adding nodes concurrently.
*/
@Test
fun mtNodeRemove() {
val LOOPS = 20_000
val ll = SharedLinkedList<ListData>().freeze()
val nodeList = mutableListOf<AbstractSharedLinkedList.Node<ListData>>()
for (i in 0 until LOOPS) {
nodeList.add(ll.addNode(ListData("a $i")))
}
nodeList.freeze()
val ops = ThreadOperations { }
for (i in 0 until LOOPS) {
ops.exe {
val node = nodeList.get(i)
if (i % 100 == 0)
node.add(ListData("Filler $i"))
node.remove()
}
}
ops.run(8)
assertEquals(LOOPS / 100, ll.size)
}
/**
* Tests that set is stable on nodes in multiple threads. Less critical
* now that we update values in place (used to replace the node).
*/
@Test
fun mtNodeSet() {
val LOOPS = 80
val ll = SharedLinkedList<ListData>().freeze()
val nodeList = mutableListOf<AbstractSharedLinkedList.Node<ListData>>()
for (i in 0 until LOOPS) {
nodeList.add(ll.addNode(ListData("a $i")))
}
nodeList.freeze()
val ops = ThreadOperations { }
for (i in 0 until LOOPS) {
ops.exe { nodeList.get(i).set(ListData("b $i")) }
ops.test { assertEquals(ll.get(i), ListData("b $i")) }
}
ops.run(8, true)
assertEquals(LOOPS, ll.size)
}
/**
* Multithreaded add.
*/
@Test
fun mtAdd() {
val ops = ThreadOperations { SharedLinkedList<ListData>() }
val LOOPS = 50
for (wcount in 0 until LOOPS) {
ops.exe { ll ->
ll.add(ListData("$wcount 1"))
ll.add(ListData("$wcount 2"))
ll.add(ListData("$wcount 3"))
}
}
val ll = ops.run(threads = 5, randomize = true)
assertEquals(LOOPS * 3, ll.size)
}
/**
* Basic threading test.
*/
@Test
fun testBasicThreads() {
val LOOPS = 2500
val ops = ThreadOperations { SharedLinkedList<TestData>() }
val ll = SharedLinkedList<TestData>().freeze()
for (i in 0 until LOOPS) {
ops.exe { ll.add(TestData("Value: $i")) }
ops.test { ll.contains(TestData("Value: $i")) }
}
ops.run(30, true)
/* val workers = Array(8) { createWorker() }
var count = 0
workers.forEach {
val valCount = count++
it.runBackground {
for(i in 0 until 1000){
ll.add(TestData("c: $valCount, i: $i"))
}
//TODO: Figure out some threaded stress tests. The following
//was acting as intended but failing when trying to remove the same node
*//*val countDownEnd = 100 * valCount
var countDownStart = countDownEnd +
ll.nodeIterator().forEach {
countDown--
if(countDown >= 0 && countDown % 10 == 0)
{
try {
it.remove()
} catch (e: Exception) {
collisionCount.increment()
}
}
}*//*
}
}
workers.forEach { it.requestTermination() }*/
assertEquals(LOOPS, ll.size)
}
@Test
fun concurrentModificationExceptionIterator() {
concurRun(false) {
it.size
}
concurRun(false) {
it.indexOf(MapData("val 5"))
}
concurRun(true) {
it.removeAt(7)
}
concurRun(true) {
it.add(MapData("arst"))
}
concurRun(true) {
it.set(8, MapData("arst"))
}
}
private fun concurRun(shouldFail: Boolean, block: (ll: SharedLinkedList<MapData>) -> Unit) {
val ll = SharedLinkedList<MapData>()
for (i in 0 until 10) {
ll.add(MapData("val $i"))
}
val nodeIter = ll.nodeIterator()
block(ll)
if (shouldFail) {
assertFails { nodeIter.next() }
} else {
assertEquals(nodeIter.next().nodeValue.s, "val 0")
}
val iter = ll.iterator()
block(ll)
if (shouldFail) {
assertFails { iter.next() }
} else {
assertEquals(iter.next().s, "val 0")
}
}
/**
* Removed nodes should fail on any mutation related operations or being re-added
*/
@Test
fun testRemovedNode() {
val ll = SharedLinkedList<ListData>().freeze()
val node = ll.addNode(ListData("hey 22"))
node.remove()
assertFails { node.remove() }
assertFails { node.readd() }
assertFails { node.add(ListData("asdf")) }
assertFails { node.set(ListData("rre")) }
assertFails { ll.internalAdd(node) }
}
/**
* Unlikely we'll get to max int edits on a list, but not exactly impossible either.
* The version is only used for iterator and concurrent mutability issues
*/
@Test
fun versionRollover(){
val ll = makeTen()
assertTrue(ll.version.value > 0)
ll.version.value = Int.MAX_VALUE - 4
for (i in 0 until 4){
ll.add(ListData("a $i"))
}
assertEquals(0, ll.version.value)
}
@Test
fun defaultZeroPool(){
assertEquals(SharedLinkedList<ListData>().nodePool.pool.size, 0)
assertEquals(CopyOnIterateLinkedList<ListData>().nodePool.pool.size, 0)
}
private fun makeTen(): SharedLinkedList<ListData> {
val ll = SharedLinkedList<ListData>()
for (i in 0 until 10) {
ll.add(ListData("Item $i"))
}
return ll
}
}
data class ListData(val s: String)
data class TestData(val s: String) | 23.749577 | 120 | 0.599031 |
6f2ef73c368f2d643e55977e78ee6a43d4b11403 | 512 | swift | Swift | SpherumiOS/Spherum/Models/Api/PresignMediaFileURL.swift | SquoES/iOSPointCloudIntegration | 353dd74f8e103310291ec8f9f7702aa21c221987 | [
"MIT"
] | null | null | null | SpherumiOS/Spherum/Models/Api/PresignMediaFileURL.swift | SquoES/iOSPointCloudIntegration | 353dd74f8e103310291ec8f9f7702aa21c221987 | [
"MIT"
] | null | null | null | SpherumiOS/Spherum/Models/Api/PresignMediaFileURL.swift | SquoES/iOSPointCloudIntegration | 353dd74f8e103310291ec8f9f7702aa21c221987 | [
"MIT"
] | null | null | null | struct PresignMediaFileURL {
private let content: [String: Any]
init(content: [String: Any]) {
self.content = content
}
private var sourceFields: [String: Any] {
content["source_fields"] as! [String: Any]
}
var id: Int {
content["id"] as! Int
}
var requestURL: URL {
(sourceFields["url"] as! String).url!
}
var requestFields: [String: String] {
sourceFields["fields"] as! [String: String]
}
}
| 19.692308 | 51 | 0.537109 |
dfc241b546ce6fc34d95c9501a42c70cbfe19b81 | 621 | ts | TypeScript | src/types.ts | optionfactory/category-heatmap | f36d5901db0539b3904d4a5e6e4f9557d3f9d962 | [
"Apache-2.0"
] | null | null | null | src/types.ts | optionfactory/category-heatmap | f36d5901db0539b3904d4a5e6e4f9557d3f9d962 | [
"Apache-2.0"
] | null | null | null | src/types.ts | optionfactory/category-heatmap | f36d5901db0539b3904d4a5e6e4f9557d3f9d962 | [
"Apache-2.0"
] | null | null | null | import { ColorScale } from 'plotly.js';
export interface HeatmapOptions {
xAxisField: string;
xSorterType: 'text' | 'number' | 'version';
yAxisField: string;
ySorterType: 'text' | 'number' | 'version';
valuesField: string;
showInPercentage: boolean;
colorscale: ColorScale;
nullValuesAsZero: boolean;
zeroValuesAsNull: boolean;
}
export const defaults: HeatmapOptions = {
xAxisField: 'version',
xSorterType: 'text',
yAxisField: 'status',
ySorterType: 'text',
valuesField: 'Value',
showInPercentage: false,
colorscale: 'Portland',
nullValuesAsZero: false,
zeroValuesAsNull: false,
};
| 23.884615 | 45 | 0.714976 |
bb5aaaa0d3fef3dd42668c8ddbae4e10b7bd7081 | 1,111 | html | HTML | Quizify-FrontEnd/src/app/quizify/components/login/login.component.html | vingu121/Quizify_final | 3d943c4c1e5fe4c369f794715747049adf633e90 | [
"Apache-2.0"
] | null | null | null | Quizify-FrontEnd/src/app/quizify/components/login/login.component.html | vingu121/Quizify_final | 3d943c4c1e5fe4c369f794715747049adf633e90 | [
"Apache-2.0"
] | null | null | null | Quizify-FrontEnd/src/app/quizify/components/login/login.component.html | vingu121/Quizify_final | 3d943c4c1e5fe4c369f794715747049adf633e90 | [
"Apache-2.0"
] | null | null | null | <app-header></app-header>
<div class="container">
<!-- <div class="pics"> -->
<mat-card >
<h2>Login</h2>
<form [formGroup]="user" (ngSubmit)="login()">
<mat-form-field appearance="outline" class="id">
<mat-label>Username</mat-label>
<input matInput placeholder="Enter your username" type="text" class="name"
formControlName="name" required [(ngModel)]="name" />
<mat-hint></mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" class="password" >
<mat-label>Password</mat-label>
<input matInput placeholder="Password" type="password"
formControlName="password" required [(ngModel)]="password"/>
<mat-hint></mat-hint>
</mat-form-field>
<!-- <div mat-card-action > -->
<button mat-raised-button class = "btn" color="" type="submit" [disabled]="!user.valid" (click) = "login()">Login</button>
<!-- </div> -->
</form>
</mat-card>
<p>Not An Existing User .. ?</p>
<form>
<button mat-raised-button class="btn1" [routerLink]="[ '/register' ]" color="">Register</button>
</form>
<!-- </div> -->
</div>
| 30.027027 | 125 | 0.60216 |
7f205813f587d05efa32bc687d44a6c607134491 | 6,857 | go | Go | api/v1alpha1/zz_generated.deepcopy.go | JamesLaverack/minecraft-operator | dc2d1bf5eb3bc6002917a487b176eb53144a4380 | [
"Apache-2.0"
] | 4 | 2022-01-24T07:43:12.000Z | 2022-02-02T22:54:18.000Z | api/v1alpha1/zz_generated.deepcopy.go | JamesLaverack/minecraft-operator | dc2d1bf5eb3bc6002917a487b176eb53144a4380 | [
"Apache-2.0"
] | 15 | 2022-02-06T05:24:00.000Z | 2022-03-31T01:07:47.000Z | api/v1alpha1/zz_generated.deepcopy.go | JamesLaverack/minecraft-operator | dc2d1bf5eb3bc6002917a487b176eb53144a4380 | [
"Apache-2.0"
] | null | null | null | //go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha1
import (
"k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MinecraftServer) DeepCopyInto(out *MinecraftServer) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
out.Status = in.Status
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MinecraftServer.
func (in *MinecraftServer) DeepCopy() *MinecraftServer {
if in == nil {
return nil
}
out := new(MinecraftServer)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MinecraftServer) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MinecraftServerList) DeepCopyInto(out *MinecraftServerList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]MinecraftServer, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MinecraftServerList.
func (in *MinecraftServerList) DeepCopy() *MinecraftServerList {
if in == nil {
return nil
}
out := new(MinecraftServerList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MinecraftServerList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MinecraftServerSpec) DeepCopyInto(out *MinecraftServerSpec) {
*out = *in
if in.AllowList != nil {
in, out := &in.AllowList, &out.AllowList
*out = make([]Player, len(*in))
copy(*out, *in)
}
if in.OpsList != nil {
in, out := &in.OpsList, &out.OpsList
*out = make([]Player, len(*in))
copy(*out, *in)
}
if in.World != nil {
in, out := &in.World, &out.World
*out = new(WorldSpec)
(*in).DeepCopyInto(*out)
}
if in.VanillaTweaks != nil {
in, out := &in.VanillaTweaks, &out.VanillaTweaks
*out = new(VanillaTweaks)
(*in).DeepCopyInto(*out)
}
if in.Monitoring != nil {
in, out := &in.Monitoring, &out.Monitoring
*out = new(MonitoringSpec)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MinecraftServerSpec.
func (in *MinecraftServerSpec) DeepCopy() *MinecraftServerSpec {
if in == nil {
return nil
}
out := new(MinecraftServerSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MinecraftServerStatus) DeepCopyInto(out *MinecraftServerStatus) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MinecraftServerStatus.
func (in *MinecraftServerStatus) DeepCopy() *MinecraftServerStatus {
if in == nil {
return nil
}
out := new(MinecraftServerStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MonitoringSpec) DeepCopyInto(out *MonitoringSpec) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringSpec.
func (in *MonitoringSpec) DeepCopy() *MonitoringSpec {
if in == nil {
return nil
}
out := new(MonitoringSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Player) DeepCopyInto(out *Player) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Player.
func (in *Player) DeepCopy() *Player {
if in == nil {
return nil
}
out := new(Player)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VanillaTweaks) DeepCopyInto(out *VanillaTweaks) {
*out = *in
if in.Survival != nil {
in, out := &in.Survival, &out.Survival
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Mobs != nil {
in, out := &in.Mobs, &out.Mobs
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Teleportation != nil {
in, out := &in.Teleportation, &out.Teleportation
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Utilities != nil {
in, out := &in.Utilities, &out.Utilities
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Hermitcraft != nil {
in, out := &in.Hermitcraft, &out.Hermitcraft
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Experimental != nil {
in, out := &in.Experimental, &out.Experimental
*out = make([]string, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VanillaTweaks.
func (in *VanillaTweaks) DeepCopy() *VanillaTweaks {
if in == nil {
return nil
}
out := new(VanillaTweaks)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorldSpec) DeepCopyInto(out *WorldSpec) {
*out = *in
if in.PersistentVolumeClaim != nil {
in, out := &in.PersistentVolumeClaim, &out.PersistentVolumeClaim
*out = new(v1.PersistentVolumeClaimVolumeSource)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorldSpec.
func (in *WorldSpec) DeepCopy() *WorldSpec {
if in == nil {
return nil
}
out := new(WorldSpec)
in.DeepCopyInto(out)
return out
}
| 28.334711 | 114 | 0.708181 |
fb3f23f5016f62fe3a0bf6a3287072efb85bdede | 2,498 | h | C | src/core/models/inputs/utxo_input.h | bernardoaraujor/iota.c | 482e0806a4f5933307f82371772e5476a47190af | [
"Apache-2.0"
] | null | null | null | src/core/models/inputs/utxo_input.h | bernardoaraujor/iota.c | 482e0806a4f5933307f82371772e5476a47190af | [
"Apache-2.0"
] | null | null | null | src/core/models/inputs/utxo_input.h | bernardoaraujor/iota.c | 482e0806a4f5933307f82371772e5476a47190af | [
"Apache-2.0"
] | null | null | null | #ifndef __CORE_MODELS_INPUTS_UTXO_INPUT_H__
#define __CORE_MODELS_INPUTS_UTXO_INPUT_H__
#include <stdint.h>
#include "core/types.h"
#include "utarray.h"
#define TRANSACTION_ID_BYTES 32
typedef struct {
input_t type; // Set to value 0 to denote a UTXO Input.
byte_t tx_id[TRANSACTION_ID_BYTES]; // The transaction reference from which the UTXO comes from.
uint64_t output_index; // The index of the output on the referenced transaction to consume.
} utxo_input_t;
typedef UT_array utxo_inputs_t;
/**
* @brief loops utxo input list
*
*/
#define UTXO_INPUTS_FOREACH(utxo_ins, elm) \
for (elm = (utxo_input_t *)utarray_front(utxo_ins); elm != NULL; elm = (utxo_input_t *)utarray_next(utxo_ins, elm))
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Prints an utxo input element.
*
* @param[in] utxo An utxo input object.
*/
void utxo_input_print(utxo_input_t *utxo);
/**
* @brief Allocates an utxo input list object.
*
* @return utxo_inputs_t* a pointer to utxo_inputs_t object
*/
utxo_inputs_t *utxo_inputs_new();
/**
* @brief Appends an utxo input element to the list.
*
* @param[in] utxo_ins The utxo input list
* @param[in] utxo An utxo input element to be appended to the list.
*/
static void utxo_inputs_push(utxo_inputs_t *utxo_ins, utxo_input_t const *const utxo) {
utarray_push_back(utxo_ins, utxo);
}
/**
* @brief Removes an utxo input element from tail.
*
* @param[in] utxo_ins The utxo input list
*/
static void utxo_inputs_pop(utxo_inputs_t *utxo_ins) { utarray_pop_back(utxo_ins); }
/**
* @brief Gets utxo input size
*
* @param[in] utxo_ins An utxo_inputs_t object
* @return size_t
*/
static size_t utxo_inputs_len(utxo_inputs_t *utxo_ins) { return utarray_len(utxo_ins); }
/**
* @brief Gets an utxo input element from list by given index.
*
* @param[in] utxo_ins An utxo input list object
* @param[in] index The index of the element
* @return utxo_input_t*
*/
static utxo_input_t *utxo_inputs_at(utxo_inputs_t *utxo_ins, size_t index) {
// return NULL if not found.
return (utxo_input_t *)utarray_eltptr(utxo_ins, index);
}
/**
* @brief Frees an utxo input list.
*
* @param[in] utxo_ins An utxo input list object.
*/
static void utxo_inputs_free(utxo_inputs_t *utxo_ins) { utarray_free(utxo_ins); }
/**
* @brief Prints an utxo input list.
*
* @param[in] utxo_ins An utxo input list object.
*/
void utxo_inputs_print(utxo_inputs_t *utxo_ins);
#ifdef __cplusplus
}
#endif
#endif | 25.232323 | 117 | 0.720977 |
21dd8aac1d024af36da34b8f9dd1472fa2550abf | 19,106 | html | HTML | react/sectionlist.html | SKsakibul125/symmetrical-system | cb21d7a76d4821cc66dee6d41d12c1e0ef3a7335 | [
"Unlicense"
] | 7 | 2021-08-20T00:30:13.000Z | 2022-02-17T17:28:46.000Z | react/sectionlist.html | SKsakibul125/symmetrical-system | cb21d7a76d4821cc66dee6d41d12c1e0ef3a7335 | [
"Unlicense"
] | 15 | 2021-07-30T18:48:20.000Z | 2022-03-26T12:42:22.000Z | react/sectionlist.html | SKsakibul125/symmetrical-system | cb21d7a76d4821cc66dee6d41d12c1e0ef3a7335 | [
"Unlicense"
] | 3 | 2021-08-31T00:50:25.000Z | 2022-01-25T16:38:20.000Z | <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>SectionList</title>
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
</head>
<body>
<header id="title-block-header">
<h1 class="title">SectionList</h1>
</header>
<p>import Tabs from ‘<span class="citation" data-cites="theme/Tabs">@theme/Tabs</span>’; import TabItem from ‘<span class="citation" data-cites="theme/TabItem">@theme/TabItem</span>’; import constants from ‘<span class="citation" data-cites="site/core/TabsConstants">@site/core/TabsConstants</span>’;</p>
<p>A performant interface for rendering sectioned lists, supporting the most handy features:</p>
<ul>
<li>Fully cross-platform.</li>
<li>Configurable viewability callbacks.</li>
<li>List header support.</li>
<li>List footer support.</li>
<li>Item separator support.</li>
<li>Section header support.</li>
<li>Section separator support.</li>
<li>Heterogeneous data and item rendering support.</li>
<li>Pull to Refresh.</li>
<li>Scroll loading.</li>
</ul>
<p>If you don’t need section support and want a simpler interface, use <a href="flatlist.md"><code><FlatList></code></a>.</p>
<h2 id="example">Example</h2>
<p><Tabs groupId="syntax" defaultValue={constants.defaultSyntax} values={constants.syntax}> <TabItem value="functional"></p>
<p>```SnackPlayer name=SectionList%20Example import React from “react”; import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar } from “react-native”;</p>
<p>const DATA = [ { title: “Main dishes”, data: [“Pizza”, “Burger”, “Risotto”] }, { title: “Sides”, data: [“French Fries”, “Onion Rings”, “Fried Shrimps”] }, { title: “Drinks”, data: [“Water”, “Coke”, “Beer”] }, { title: “Desserts”, data: [“Cheese Cake”, “Ice Cream”] }];</p>
<p>const Item = ({ title }) => ( <View style={styles.item}> <Text style={styles.title}>{title}</Text> </View> );</p>
<p>const App = () => ( <SafeAreaView style={styles.container}> <SectionList sections={DATA} keyExtractor={(item, index) => item + index} renderItem={({ item }) => <Item title={item} />} renderSectionHeader={({ section: { title } }) => ( <Text style={styles.header}>{title}</Text> )} /> </SafeAreaView> );</p>
<p>const styles = StyleSheet.create({ container: { flex: 1, paddingTop: StatusBar.currentHeight, marginHorizontal: 16 }, item: { backgroundColor: “#f9c2ff”, padding: 20, marginVertical: 8 }, header: { fontSize: 32, backgroundColor: “#fff” }, title: { fontSize: 24 } });</p>
<p>export default App; ```</p>
<p></TabItem> <TabItem value="classical"></p>
<p>```SnackPlayer name=SectionList%20Example import React, { Component } from “react”; import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar } from “react-native”;</p>
<p>const DATA = [ { title: “Main dishes”, data: [“Pizza”, “Burger”, “Risotto”] }, { title: “Sides”, data: [“French Fries”, “Onion Rings”, “Fried Shrimps”] }, { title: “Drinks”, data: [“Water”, “Coke”, “Beer”] }, { title: “Desserts”, data: [“Cheese Cake”, “Ice Cream”] }];</p>
<p>const Item = ({ title }) => ( <View style={styles.item}> <Text style={styles.title}>{title}</Text> </View> );</p>
<p>class App extends Component { render() { return ( <SafeAreaView style={styles.container}> <SectionList sections={DATA} keyExtractor={(item, index) => item + index} renderItem={({ item }) => <Item title={item} />} renderSectionHeader={({ section: { title } }) => ( <Text style={styles.header}>{title}</Text> )} /> </SafeAreaView> ); } }</p>
<p>const styles = StyleSheet.create({ container: { flex: 1, paddingTop: StatusBar.currentHeight, marginHorizontal: 16 }, item: { backgroundColor: “#f9c2ff”, padding: 20, marginVertical: 8 }, header: { fontSize: 32, backgroundColor: “#fff” }, title: { fontSize: 24 } });</p>
<p>export default App; ```</p>
<p></TabItem> </Tabs></p>
<p>This is a convenience wrapper around <a href="virtualizedlist.md"><code><VirtualizedList></code></a>, and thus inherits its props (as well as those of <a href="scrollview.md"><code><ScrollView></code></a>) that aren’t explicitly listed here, along with the following caveats:</p>
<ul>
<li>Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.</li>
<li>This is a <code>PureComponent</code> which means that it will not re-render if <code>props</code> remain shallow-equal. Make sure that everything your <code>renderItem</code> function depends on is passed as a prop (e.g. <code>extraData</code>) that is not <code>===</code> after updates, otherwise your UI may not update on changes. This includes the <code>data</code> prop and parent component state.</li>
<li>In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it’s possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.</li>
<li>By default, the list looks for a <code>key</code> prop on each item and uses that for the React key. Alternatively, you can provide a custom <code>keyExtractor</code> prop.</li>
</ul>
<hr />
<h1 id="reference">Reference</h1>
<h2 id="props">Props</h2>
<h3 id="scrollview-props"><a href="scrollview.md#props">ScrollView Props</a></h3>
<p>Inherits <a href="scrollview.md#props">ScrollView Props</a>.</p>
<hr />
###
<div class="label required basic">
Required
</div>
<p><strong><code>renderItem</code></strong></p>
<p>Default renderer for every item in every section. Can be over-ridden on a per-section basis. Should return a React element.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>function</td>
</tr>
</tbody>
</table>
<p>The render function will be passed an object with the following keys:</p>
<ul>
<li>‘item’ (object) - the item object as specified in this section’s <code>data</code> key</li>
<li>‘index’ (number) - Item’s index within the section.</li>
<li>‘section’ (object) - The full section object as specified in <code>sections</code>.</li>
<li>‘separators’ (object) - An object with the following keys:
<ul>
<li>‘highlight’ (function) - <code>() => void</code></li>
<li>‘unhighlight’ (function) - <code>() => void</code></li>
<li>‘updateProps’ (function) - <code>(select, newProps) => void</code>
<ul>
<li>‘select’ (enum) - possible values are ‘leading’, ‘trailing’</li>
<li>‘newProps’ (object)</li>
</ul></li>
</ul></li>
</ul>
<hr />
###
<div class="label required basic">
Required
</div>
<p><strong><code>sections</code></strong></p>
<p>The actual data to render, akin to the <code>data</code> prop in <a href="flatlist.md"><code>FlatList</code></a>.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>array of <a href="sectionlist.md#section">Section</a>s</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="extradata"><code>extraData</code></h3>
<p>A marker property for telling the list to re-render (since it implements <code>PureComponent</code>). If any of your <code>renderItem</code>, Header, Footer, etc. functions depend on anything outside of the <code>data</code> prop, stick it here and treat it immutably.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>any</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="initialnumtorender"><code>initialNumToRender</code></h3>
<p>How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>number</td>
<td><code>10</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="inverted"><code>inverted</code></h3>
<p>Reverses the direction of scroll. Uses scale transforms of -1.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>boolean</td>
<td><code>false</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="itemseparatorcomponent"><code>ItemSeparatorComponent</code></h3>
<p>Rendered in between each item, but not at the top or bottom. By default, <code>highlighted</code>, <code>section</code>, and <code>[leading/trailing][Item/Section]</code> props are provided. <code>renderItem</code> provides <code>separators.highlight</code>/<code>unhighlight</code> which will update the <code>highlighted</code> prop, but you can also add custom props with <code>separators.updateProps</code>.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>component, element</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="keyextractor"><code>keyExtractor</code></h3>
<p>Used to extract a unique key for a given item at the specified index. Key is used for caching and as the React key to track item re-ordering. The default extractor checks <code>item.key</code>, then falls back to using the index, like React does. Note that this sets keys for each item, but each overall section still needs its own key.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(item: object, index: number) => string</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="listemptycomponent"><code>ListEmptyComponent</code></h3>
<p>Rendered when the list is empty. Can be a React Component (e.g. <code>SomeComponent</code>), or a React element (e.g. <code><SomeComponent /></code>).</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>component, element</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="listfootercomponent"><code>ListFooterComponent</code></h3>
<p>Rendered at the very end of the list. Can be a React Component (e.g. <code>SomeComponent</code>), or a React element (e.g. <code><SomeComponent /></code>).</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>component, element</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="listheadercomponent"><code>ListHeaderComponent</code></h3>
<p>Rendered at the very beginning of the list. Can be a React Component (e.g. <code>SomeComponent</code>), or a React element (e.g. <code><SomeComponent /></code>).</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>component, element</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="onendreached"><code>onEndReached</code></h3>
<p>Called once when the scroll position gets within <code>onEndReachedThreshold</code> of the rendered content.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(info: { distanceFromEnd: number }) => void</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="onendreachedthreshold"><code>onEndReachedThreshold</code></h3>
<p>How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the <code>onEndReached</code> callback. Thus a value of 0.5 will trigger <code>onEndReached</code> when the end of the content is within half the visible length of the list.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>number</td>
<td><code>2</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="onrefresh"><code>onRefresh</code></h3>
<p>If provided, a standard RefreshControl will be added for “Pull to Refresh” functionality. Make sure to also set the <code>refreshing</code> prop correctly. To offset the RefreshControl from the top (e.g. by 100 pts), use <code>progressViewOffset={100}</code>.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>function</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="onviewableitemschanged"><code>onViewableItemsChanged</code></h3>
<p>Called when the viewability of rows changes, as defined by the <code>viewabilityConfig</code> prop.</p>
<table>
<colgroup>
<col style="width: 100%" />
</colgroup>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(callback: { changed: array of <a href="viewtoken">ViewToken</a>s, viewableItems: array of <a href="viewtoken">ViewToken</a>s }) => void</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="refreshing"><code>refreshing</code></h3>
<p>Set this true while waiting for new data from a refresh.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>boolean</td>
<td><code>false</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="removeclippedsubviews"><code>removeClippedSubviews</code></h3>
<blockquote>
<p>Note: may have bugs (missing content) in some circumstances - use at your own risk.</p>
</blockquote>
<p>This may improve scroll performance for large lists.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>boolean</td>
<td><code>false</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="rendersectionfooter"><code>renderSectionFooter</code></h3>
<p>Rendered at the bottom of each section.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(info: { section: <a href="sectionlist#section">Section</a> }) => element, <code>null</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="rendersectionheader"><code>renderSectionHeader</code></h3>
<p>Rendered at the top of each section. These stick to the top of the <code>ScrollView</code> by default on iOS. See <code>stickySectionHeadersEnabled</code>.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(info: { section: <a href="sectionlist#section">Section</a> }) => element, <code>null</code></td>
</tr>
</tbody>
</table>
<hr />
<h3 id="sectionseparatorcomponent"><code>SectionSeparatorComponent</code></h3>
<p>Rendered at the top and bottom of each section (note this is different from <code>ItemSeparatorComponent</code> which is only rendered between items). These are intended to separate sections from the headers above and below and typically have the same highlight response as <code>ItemSeparatorComponent</code>. Also receives <code>highlighted</code>, <code>[leading/trailing][Item/Section]</code>, and any custom props from <code>separators.updateProps</code>.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>component, element</td>
</tr>
</tbody>
</table>
<hr />
<h3 id="stickysectionheadersenabled"><code>stickySectionHeadersEnabled</code></h3>
<p>Makes section headers stick to the top of the screen until the next one pushes it off. Only enabled by default on iOS because that is the platform standard there.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
<th>Default</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
| boolean | <code>false</code>
<div class="label android">
Android
</div>
<hr/>
<code>true</code>
<div data-classname="label ios">
iOS
</div>
<p>|</p>
<h2 id="methods">Methods</h2>
### <code>flashScrollIndicators()</code>
<div class="label ios">
iOS
</div>
<pre class="jsx"><code>flashScrollIndicators();</code></pre>
<p>Displays the scroll indicators momentarily.</p>
<hr />
<h3 id="recordinteraction"><code>recordInteraction()</code></h3>
<pre class="jsx"><code>recordInteraction();</code></pre>
<p>Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. if <code>waitForInteractions</code> is true and the user has not scrolled. This is typically called by taps on items or by navigation actions.</p>
<hr />
<h3 id="scrolltolocation"><code>scrollToLocation()</code></h3>
<pre class="jsx"><code>scrollToLocation(params);</code></pre>
<p>Scrolls to the item at the specified <code>sectionIndex</code> and <code>itemIndex</code> (within the section) positioned in the viewable area such that <code>viewPosition</code> 0 places it at the top (and may be covered by a sticky header), 1 at the bottom, and 0.5 centered in the middle.</p>
<blockquote>
<p>Note: Cannot scroll to locations outside the render window without specifying the <code>getItemLayout</code> or <code>onScrollToIndexFailed</code> prop.</p>
</blockquote>
<p><strong>Parameters:</strong></p>
<table>
<thead>
<tr class="header">
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
| params
<div class="label basic required">
Required
</div>
<p>| object |</p>
<p>Valid <code>params</code> keys are:</p>
<ul>
<li>‘animated’ (boolean) - Whether the list should do an animation while scrolling. Defaults to <code>true</code>.</li>
<li>‘itemIndex’ (number) - Index within section for the item to scroll to. Required.</li>
<li>‘sectionIndex’ (number) - Index for section that contains the item to scroll to. Required.</li>
<li>‘viewOffset’ (number) - A fixed number of pixels to offset the final target position, e.g. to compensate for sticky headers.</li>
<li>‘viewPosition’ (number) - A value of <code>0</code> places the item specified by index at the top, <code>1</code> at the bottom, and <code>0.5</code> centered in the middle.</li>
</ul>
<h2 id="type-definitions">Type Definitions</h2>
<h3 id="section">Section</h3>
<p>An object that identifies the data to be rendered for a given section.</p>
<table>
<thead>
<tr class="header">
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>any</td>
</tr>
</tbody>
</table>
<p><strong>Properties:</strong></p>
<table>
<thead>
<tr class="header">
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
| data
<div class="label basic required">
Required
</div>
<p>| array | The data for rendering items in this section. Array of objects, much like <a href="flatlist#data"><code>FlatList</code>’s data prop</a>. | | key | string | Optional key to keep track of section re-ordering. If you don’t plan on re-ordering sections, the array index will be used by default. | | renderItem | function | Optionally define an arbitrary item renderer for this section, overriding the default <a href="sectionlist#renderitem"><code>renderItem</code></a> for the list. | | ItemSeparatorComponent | component, element | Optionally define an arbitrary item separator for this section, overriding the default <a href="sectionlist#itemseparatorcomponent"><code>ItemSeparatorComponent</code></a> for the list. | | keyExtractor | function | Optionally define an arbitrary key extractor for this section, overriding the default <a href="sectionlist#keyextractor"><code>keyExtractor</code></a>. |</p>
</body>
</html>
| 39.312757 | 916 | 0.694808 |
70dc725ccf32e9d60106d386ebd957e8de6b19cd | 2,342 | c | C | Array/wuchao/other/7-16 c实现string函数/StringUtils.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 39 | 2020-05-31T06:14:39.000Z | 2021-01-09T11:06:39.000Z | Array/wuchao/other/7-16 c实现string函数/StringUtils.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 7 | 2020-06-02T11:04:14.000Z | 2020-06-11T14:11:58.000Z | Array/wuchao/other/7-16 c实现string函数/StringUtils.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 20 | 2020-05-31T06:21:57.000Z | 2020-10-01T04:48:38.000Z | //
// Created by 吴超 on 2020/7/16.
//
#include <stdlib.h>
#include <stdio.h>
/**
* C语言实现strcpy(字符串复制)、strcat(字符串链接)、strstr(字符串包含)、strchr(字符出现位置)、memcpy(拷贝)
*/
char *strcpy(char *source);
char *strcat(char *dest, char *source);
int strstr(char *dest, char *source);
int strchr(char *source, char target);
void* memcpy(char *dest, char* source, size_t size);
size_t stringLen(char *source);
char *strcpy(char *source) {
char *dest = malloc(stringLen(source) * sizeof(char));
int i = 0;
while (source[i] != '\0') {
dest[i] = source[i];
i++;
}
return dest;
}
char *strcat(char *dest, char *source) {
int destLen = stringLen(dest);
int sourceLen = stringLen(source);
char *result = malloc((destLen + sourceLen) * sizeof(char));
int i = 0;
while (i < destLen) {
result[i] = dest[i];
i++;
}
int j = 0;
while (j < sourceLen) {
result[i] = source[j];
i++;
j++;
}
return result;
}
int strstr(char *dest, char *source){
int i = 0;
int j = 0;
int destLen = stringLen(dest);
int sourceLen = stringLen(source);
if(sourceLen>destLen) return -1;
while(i<destLen){
if(dest[i]==source[j]){
i++;
j++;
if(j==sourceLen){
return i-sourceLen;
}
continue;
} else {
i++;
j=0;
}
}
return -1;
}
int strchr(char *source, char target){
int i = 0;
while(source[i]!='\0'){
if(source[i]==target){
return i;
}
i++;
}
}
void* memcpy(char *dest, char* source, size_t size){
int i =0;
int destLen = stringLen(dest);
int sourceLen = stringLen(source);
while(i<size&&i<sourceLen){
dest[i] = source[i];
i++;
}
if(i<destLen){
dest[i] = '\0';
}
return dest;
}
size_t stringLen(char *source) {
int i = 0;
while (source[i++] != '\0') {
}
return i-1;
}
int main() {
char *a = "asdfwer";
char *b = strcpy(a);
printf("copy:%s\n", b);
printf("strcat:%s\n", strcat(a, "hello"));
printf("strstr:%d\n", strstr("helloword","helloworld"));
printf("strchr:%d\n", strchr("helloword",'l'));
printf("memcpy:%s\n", memcpy(malloc(sizeof(char)),"helloworld",5));
}
| 20.54386 | 75 | 0.521349 |
2a606ec966f9c6ffd02986f770872de48ddff63c | 2,891 | java | Java | SimpleGame/world/Callout.java | aristocrates/javagames | 2ddd263c335dd01d9840c5b64c91925dfd2e574d | [
"BSD-2-Clause"
] | 1 | 2019-06-03T18:38:12.000Z | 2019-06-03T18:38:12.000Z | SimpleGame/world/Callout.java | aristocrates/javagames | 2ddd263c335dd01d9840c5b64c91925dfd2e574d | [
"BSD-2-Clause"
] | null | null | null | SimpleGame/world/Callout.java | aristocrates/javagames | 2ddd263c335dd01d9840c5b64c91925dfd2e574d | [
"BSD-2-Clause"
] | null | null | null | package world;
import java.awt.*;
import java.awt.image.*;
import otherStuff.*;
/**
* Write a description of class Callout here.
*
* @author Aristocrates, barbecue chef / j̶a̶r̶g̶o̶n̶ ̶s̶p̶o̶u̶t̶i̶n̶g̶ ̶m̶a̶n̶i̶a̶c̶
* part time philosopher
* @version sin(π/2)
*/
public class Callout extends GameComponent
{
private final String text;
private static final FontMetrics fontMetrics;
private static Font displayFont;
private GameComponent source;
private int height, width;
/**
* Constructs a somewhat "1.33:1" aspect ratio callout
*/
public Callout(GameComponent g, String text, boolean pointed)
{
this(g,text,(int)(4*Math.sqrt(getTextArea(text)/12.0)));
}
public Callout(GameComponent g, String text, int width)
{
this.width = width;
source = g;
this.text = splitString(text);
}
public void setNewSource(GameComponent g)
{
source = g;
}
public GameComponent clone()
{
return new Callout(source,text,width);
}
private static void drawLinebreakString(Graphics g,String text,int x,int y)
{
for (String line : text.split("\n"))
g.drawString(line, x, y += g.getFontMetrics().getHeight());
}
/**
* Returns the string "split" by \n characters into "lines" of width that
* will fit on the width of the callout
* Also sets the callout height
*/
private String splitString(String orig)
{
String ans = "";
String current = "";
int lineHeight = fontMetrics.getHeight();
for (String word : orig.split(" "))
{
if (fontMetrics.stringWidth(current+" ") > width)
{
ans += current + "\n";
current = "";
height += lineHeight;
}
current += word + " ";
}
if (!current.equals(""))
{
ans += current;
height += lineHeight;
}
return ans;
}
public Shape getDimensions()
{
return null;
}
public void drawMe(Graphics g)
{
}
public void update(GameEvent e)
{
//if (e.equals(GameEvent.disappear()))
}
private static int getTextArea(String text)
{
return fontMetrics.getHeight()*fontMetrics.stringWidth(text);
}
public boolean loopable()
{
return source.loopable();
}
static {
displayFont = new Font("Courier",Font.PLAIN,12);
Graphics genericGraphics = new BufferedImage(1000,1000,BufferedImage.TYPE_INT_RGB).getGraphics();
genericGraphics.setFont(displayFont);
fontMetrics = genericGraphics.getFontMetrics();
}
} | 26.045045 | 106 | 0.547907 |
cb1e6d79beeacfa592ba44e3a0da4cbf5d7ead2e | 3,281 | h | C | raspberry/nfc_deamon/SW369321/Platform/DAL/inc/phDriver.h | ccruzp/drs-netatmo | 87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f | [
"MIT"
] | 2 | 2019-11-08T12:45:38.000Z | 2019-11-09T16:31:12.000Z | raspberry/nfc_deamon/SW369321/Platform/DAL/inc/phDriver.h | ccruzp/drs-netatmo | 87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f | [
"MIT"
] | null | null | null | raspberry/nfc_deamon/SW369321/Platform/DAL/inc/phDriver.h | ccruzp/drs-netatmo | 87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f | [
"MIT"
] | 2 | 2019-11-07T21:56:59.000Z | 2019-11-08T02:20:59.000Z | /*
* Copyright (c), NXP Semiconductors Bangalore / India
*
* (C)NXP Semiconductors
* All rights are reserved. Reproduction in whole or in part is
* prohibited without the written consent of the copyright owner.
* NXP reserves the right to make changes without notice at any time.
* NXP makes no warranty, expressed, implied or statutory, including but
* not limited to any implied warranty of merchantability or fitness for any
*particular purpose, or that the use will not infringe any third party patent,
* copyright or trademark. NXP must not be liable for any loss or damage
* arising from its use.
*/
/** \file
* Generic phDriver Component of Reader Library Framework.
* $Author$
* $Revision$
* $Date$
*
* History:
* RS: Generated 24. Jan 2017
*
*/
#ifndef PHDRIVER_H
#define PHDRIVER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** \defgroup phDriver Driver Abstraction Layer (DAL)
*
* \brief This component implements hardware drivers that are necessary for RdLib software modules
* @{
*/
#ifdef linux
#include <sys/types.h>
#endif
#if defined (PH_TYPEDEFS_H)
#else /*PH_TYPEDEFS_H*/
#if defined(__GNUC__ ) /* Toolchain with StdInt */
# include <stdint.h>
#elif defined(__ICCARM__)
# include "intrinsics.h"
# include <stdint.h>
#elif defined(__CC_ARM)
# include <stdint.h>
#endif
#ifdef _WIN32
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
typedef long int32_t;
#endif
/** \name Floating-Point Types
*/
/*@{*/
#ifndef __float32_t_defined
/**
* \brief 32 bit floating point
*/
typedef float float32_t;
#endif
/*@}*/
#endif /*PH_TYPEDEFS_H*/
#ifndef PH_STATUS_H
/**
* \brief phStatus_t is a signed short value, using the positive range.
*
* High byte: Category (group) Identifier.\n
* Low byte : Error Specifier.
*/
typedef uint16_t phStatus_t;
#define PH_COMP_DRIVER 0xF100U /**< DRIVER component code. */
#define PH_COMP_MASK 0xFF00U /**< Component Mask for status code and component ID. */
#define PH_COMPID_MASK 0x00FFU /**< ID Mask for component ID. */
#define PH_ERR_MASK 0x00FFU /**< Error Mask for status code. */
#define PH_COMP_GENERIC 0x0000U /**< Generic Component Code. */
#ifndef NULL
# define NULL 0
#endif
#endif
#include "phbalReg.h"
#include "phDriver_Gpio.h"
#include "phDriver_Timer.h"
/*!
\brief Generic Status codes
All functions within the phDriver use these macro values as return codes.
*/
#define PH_DRIVER_SUCCESS 0x0000U /**< Function executed successfully. */
#define PH_DRIVER_TIMEOUT 0x0001U /**< No reply received, e.g. PICC removal. */
#define PH_DRIVER_ABORTED 0x0012U /**< Used when HAL ShutDown is called. */
#define PH_DRIVER_ERROR 0x0080U /**< Invalid Parameter, buffer overflow or other configuration error. */
#define PH_DRIVER_FAILURE 0x0081U /**< Failed to perform the requested operation. */
/** @}
* end of phDriver Driver Abstraction Layer (DAL)
*/
#ifdef __cplusplus
}/*Extern C*/
#endif
#endif /* PHDRIVER_H */
| 26.893443 | 124 | 0.657422 |
0be3afb3dae0c132a420748fa1f1f5bb6ccbc5e8 | 3,738 | js | JavaScript | gulpfile.js | MediaComem/biosentiers-landing-page | cceb1d46185a481cc1c898ed8856062a8aad7056 | [
"MIT"
] | null | null | null | gulpfile.js | MediaComem/biosentiers-landing-page | cceb1d46185a481cc1c898ed8856062a8aad7056 | [
"MIT"
] | null | null | null | gulpfile.js | MediaComem/biosentiers-landing-page | cceb1d46185a481cc1c898ed8856062a8aad7056 | [
"MIT"
] | null | null | null | var gulp = require('gulp');
var less = require('gulp-less');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var header = require('gulp-header');
var cleanCSS = require('gulp-clean-css');
var proxy = require('proxy-middleware');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var url = require('url');
var pkg = require('./package.json');
// Set the banner content
var banner = ['/*!\n',
' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n',
' */\n',
''
].join('');
var config = {};
try {
config = require('./config');
} catch(err) {
// ignore
}
// Compile LESS files from /less into /css
gulp.task('less', function () {
return gulp.src('sources/less/agency.less')
.pipe(less())
.pipe(header(banner, { pkg: pkg }))
.pipe(gulp.dest('sources/css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Minify compiled CSS
gulp.task('minify-css', ['less'], function () {
return gulp.src('sources/css/agency.css')
.pipe(cleanCSS({ compatibility: 'ie8' }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Minify JS
gulp.task('minify-js', function () {
return gulp.src('sources/js/*.js')
.pipe(uglify())
.pipe(header(banner, { pkg: pkg }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('js'))
.pipe(browserSync.reload({
stream: true
}));
});
// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function () {
gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
.pipe(gulp.dest('vendor/bootstrap'));
gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
.pipe(gulp.dest('vendor/jquery'));
gulp.src([
'node_modules/font-awesome/**',
'!node_modules/font-awesome/**/*.map',
'!node_modules/font-awesome/.npmignore',
'!node_modules/font-awesome/*.txt',
'!node_modules/font-awesome/*.md',
'!node_modules/font-awesome/*.json'
])
.pipe(gulp.dest('vendor/font-awesome'));
gulp.src(['node_modules/object-fit-images/dist/*.min.js'])
.pipe(gulp.dest('vendor/object-fit-images'));
});
// Run everything
gulp.task('default', ['compile', 'copy']);
// Configure the browserSync task
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: ''
},
middleware: [
createProxy()
],
browser: process.env.BROWSER || config.browser
});
});
// Dev task with browserSync
gulp.task('dev', ['browserSync', 'compile'], function () {
gulp.watch('sources/less/*.less', ['less']);
gulp.watch('sources/css/*.css', ['minify-css']);
gulp.watch('sources/js/*.js', ['minify-js']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('*.html', browserSync.reload);
gulp.watch('js/**/*.js', browserSync.reload);
});
gulp.task('compile', ['less', 'minify-css', 'minify-js']);
gulp.task('build', ['compile'], function() {
return gulp.src(['css/**/*', 'js/**/*', 'img/**/*', 'index.html', 'vendor/**/*'], {base: '.'})
.pipe(gulp.dest('dist/'));
});
gulp.task('prod', ['build'], function() {
browserSync.init({
server: {
baseDir: 'dist'
},
middleware: [
createProxy()
]
});
});
function createProxy() {
var proxyOptions = url.parse(process.env.BACKEND_URL || config.backendUrl || 'https://biosentiers.heig-vd.ch/api');
proxyOptions.route = '/api';
return proxy(proxyOptions);
}
| 27.485294 | 117 | 0.605136 |
dab22665201a165519e48436ede801e845252ef7 | 1,939 | kt | Kotlin | paymen-channel/src/main/java/it/barusu/paymen/channel/AbstractConverter.kt | barusu-it/paymen | 8a4033387099273d1fed60dfabfa761b425f7a8d | [
"Apache-2.0"
] | null | null | null | paymen-channel/src/main/java/it/barusu/paymen/channel/AbstractConverter.kt | barusu-it/paymen | 8a4033387099273d1fed60dfabfa761b425f7a8d | [
"Apache-2.0"
] | null | null | null | paymen-channel/src/main/java/it/barusu/paymen/channel/AbstractConverter.kt | barusu-it/paymen | 8a4033387099273d1fed60dfabfa761b425f7a8d | [
"Apache-2.0"
] | null | null | null | package it.barusu.paymen.channel
import it.barusu.paymen.channel.process.*
import it.barusu.paymen.common.RequestType
import it.barusu.paymen.util.ApiException
abstract class AbstractConverter : Converter {
override fun writeTo(request: Request): String =
when (request.type) {
RequestType.TRANSACTION -> from(request as TransactionRequest)
RequestType.TRANSACTION_QUERY -> from(request as TransactionQueryRequest)
RequestType.TRANSACTION_NOTIFICATION -> from(request as TransactionNotificationRequest)
}
override fun readFrom(content: String, request: Request): Response =
when (request.type) {
RequestType.TRANSACTION -> toTransactionResponse(content, request)
RequestType.TRANSACTION_QUERY -> toTransactionQueryResponse(content, request)
RequestType.TRANSACTION_NOTIFICATION -> toTransactionNotificationResponse(content, request)
}
open fun from(request: TransactionRequest): String =
throw ApiException(msg = "Transaction is not supported.")
open fun from(request: TransactionQueryRequest): String =
throw ApiException(msg = "Transaction query is not supported.")
open fun from(request: TransactionNotificationRequest): String =
throw ApiException(msg = "Transaction notification is not supported.")
open fun toTransactionResponse(content: String, request: Request): TransactionResponse =
throw ApiException(msg = "Transaction is not supported.")
open fun toTransactionQueryResponse(content: String, request: Request): TransactionQueryResponse =
throw ApiException(msg = "Transaction is not supported.")
open fun toTransactionNotificationResponse(content: String, request: Request): TransactionNotificationResponse =
throw ApiException(msg = "Transaction is not supported.")
} | 47.292683 | 116 | 0.71377 |
e9b8c2ce44a488f1397678a706f15f33861f3edf | 4,469 | rs | Rust | ffxiv-act-linux-host/src/net/mod.rs | CerulanLumina/ffxiv-act-linux-interface | ed7feff350e0a4303461d49f1fab278157a46b53 | [
"Apache-2.0"
] | 9 | 2019-08-21T01:07:46.000Z | 2021-06-29T19:54:54.000Z | ffxiv-act-linux-host/src/net/mod.rs | CerulanLumina/ffxiv-act-linux-interface | ed7feff350e0a4303461d49f1fab278157a46b53 | [
"Apache-2.0"
] | 9 | 2019-08-20T21:58:43.000Z | 2020-09-18T21:29:11.000Z | ffxiv-act-linux-host/src/net/mod.rs | CerulanLumina/ffxiv-act-linux-interface | ed7feff350e0a4303461d49f1fab278157a46b53 | [
"Apache-2.0"
] | null | null | null | use std::io::prelude::*;
use std::net::{TcpListener};
use std::sync::mpsc;
use std::thread;
use crate::pcap;
use pcap::{Device, Capture};
use etherparse::SlicedPacket;
use crate::NetConfig;
use std::process::Command;
pub fn start_packet_redirection(net_config: NetConfig, ffxiv: i32) -> bool {
let interface = net_config.interface;
let host_exclude = net_config.hostname_exclude;
let sender_opt = start_incoming_sync_host(net_config.bind_address);
if let Some(sender) = sender_opt {
if let Ok(device_list) = Device::list() {
let device_opt = device_list.into_iter().filter(|d| d.name == interface).next();
if device_opt.is_none() {
eprintln!("[NET] Unable to find device with name \"{}\"", interface);
return false;
}
let device = device_opt.unwrap();
println!("[NET] Attempting to capture on {}", device.name);
let cap = Capture::from_device(device).unwrap();
let cap_res = cap.open();
if cap_res.is_err() {
eprintln!("[NET] Unable to open device for network capture. Are you root?");
return false;
}
let mut cap = cap_res.unwrap();
let src_port_opt = get_src_port(ffxiv);
if src_port_opt.is_none() {
println!("[NET] FFXIV connection gone, stopping network-passthrough.");
return true;
}
let src_port = src_port_opt.unwrap();
println!("[NET] Identified FFXIV Server port as {}, capturing traffic from that port.", src_port);
cap.filter(format!("(src port {}) && (src host not {})", src_port, host_exclude).as_str()).expect("[NET] Unable to apply filters");
println!("[NET] Setup pcap for network redirection");
'capture: loop {
if let Ok(p) = cap.next() {
let data = p.data.to_vec();
let pa = SlicedPacket::from_ethernet(data.as_slice()).unwrap();
let pref = pa.payload;
if pref.len() == 0 {
continue;
} else {
if let Err(_) = sender.send(pref.to_vec()) {
break 'capture;
}
}
} else {
eprintln!("[NET] Unable to get next packet! Something may have gone wrong earlier.");
return false;
}
}
true
} else {
eprintln!("[NET] Unable to lookup devices. Are you root?");
false
}
} else {
eprintln!("[NET] Unable to start network sync host.");
false
}
}
fn start_incoming_sync_host(bind_address: String) -> Option<mpsc::Sender<Vec<u8>>> {
let (tx, rx) = mpsc::channel::<Vec<u8>>();
if let Ok(tcp) = TcpListener::bind(&bind_address) {
println!("[NET] TCP network-passthrough socket bound to {}.", bind_address);
thread::spawn(move || {
loop {
println!("[NET] Waiting for TCP client");
let (mut inc, from) = tcp.accept().expect("[NET] Unable to accept connection");
println!("[NET] TCP connection from {}", from);
// Clear prior packets
let mut iter = rx.try_iter();
while let Some(_) = iter.next() {}
// Send packets as received
'sync: for data in &rx {
if let Err(_) = inc.write(&data[..]) {
println!("[NET] Client connection ending.");
break 'sync;
}
}
}
});
Some(tx)
} else {
eprintln!("[NET] Unable to bind socket on {}. Is another process using it?", bind_address);
None
}
}
pub fn get_src_port(pid: i32) -> Option<u16> {
use regex::Regex;
let output = Command::new("lsof")
.arg("-i")
.arg("-a")
.arg("-p")
.arg(format!("{}", pid))
.output().expect("Unable to get lsof");
let lsof = String::from_utf8(output.stdout).expect("Couldn't read lsof output");
let re = Regex::new(r":(\d+) \(ESTABLISHED\)").unwrap();
re
.captures_iter(lsof.as_str())
.next()
.map(|cap| cap[1].parse::<u16>().expect("Couldn't parse port"))
}
| 34.914063 | 143 | 0.511971 |
e757ab8ea0f6be3a3b225ad848b211f183430871 | 1,682 | sql | SQL | src/main/resources/data-h2.sql | edoardo-liotta/Backend-for-Beginners-Group-project | 3024b7e92912de56503578fd4749a068cf98790f | [
"MIT"
] | null | null | null | src/main/resources/data-h2.sql | edoardo-liotta/Backend-for-Beginners-Group-project | 3024b7e92912de56503578fd4749a068cf98790f | [
"MIT"
] | null | null | null | src/main/resources/data-h2.sql | edoardo-liotta/Backend-for-Beginners-Group-project | 3024b7e92912de56503578fd4749a068cf98790f | [
"MIT"
] | null | null | null | INSERT INTO article (id, title, image, content, tag, approve) VALUES (1, 'Article Title 1', 'https://placeimg.com/640/480/tech?1','Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.','tech',false);
INSERT INTO article (id, title, image, content, tag, approve) VALUES (2 ,'Article Title 2', 'https://placeimg.com/640/480/tech?2','Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.','tech',true);
INSERT INTO article (id, title, image, content, tag, approve) VALUES (3, 'Article Title 3', 'https://placeimg.com/640/480/tech?3','Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.','tech',false);
INSERT INTO article (id, title, image, content, tag, approve) VALUES (4, 'Article Title 4', 'https://placeimg.com/640/480/tech?4','Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.','tech',false);
INSERT INTO customer (customer_id, first_name, last_name, password) VALUES ('eliotta', 'Edoardo', 'Liotta', 'edoardo'); | 336.4 | 390 | 0.763377 |
c7fc96de64f4d8112068caf481a1a1034ef75524 | 3,137 | java | Java | Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/jna/dbgmodel/datamodel/script/debug/WrapIDataModelScriptDebug.java | sigurasg/ghidra | ee268dea09d8f2632d73b0d00cdda3a377a744e1 | [
"Apache-2.0"
] | 17 | 2022-01-15T03:52:37.000Z | 2022-03-30T18:12:17.000Z | Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/jna/dbgmodel/datamodel/script/debug/WrapIDataModelScriptDebug.java | sigurasg/ghidra | ee268dea09d8f2632d73b0d00cdda3a377a744e1 | [
"Apache-2.0"
] | 9 | 2022-01-15T03:58:02.000Z | 2022-02-21T10:22:49.000Z | Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/jna/dbgmodel/datamodel/script/debug/WrapIDataModelScriptDebug.java | sigurasg/ghidra | ee268dea09d8f2632d73b0d00cdda3a377a744e1 | [
"Apache-2.0"
] | 1 | 2021-10-02T01:25:14.000Z | 2021-10-02T01:25:14.000Z | /* ###
* IP: GHIDRA
*
* 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 agent.dbgmodel.jna.dbgmodel.datamodel.script.debug;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WTypes.BSTRByReference;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import com.sun.jna.ptr.PointerByReference;
import agent.dbgmodel.jna.dbgmodel.UnknownWithUtils;
public class WrapIDataModelScriptDebug extends UnknownWithUtils implements IDataModelScriptDebug {
public static class ByReference extends WrapIDataModelScriptDebug
implements Structure.ByReference {
}
public WrapIDataModelScriptDebug() {
}
public WrapIDataModelScriptDebug(Pointer pvInstance) {
super(pvInstance);
}
@Override
public HRESULT ScriptDebugState() {
return _invokeHR(VTIndices.GET_DEBUG_STATE, getPointer());
}
@Override
public HRESULT GetDebugState() {
return _invokeHR(VTIndices.GET_DEBUG_STATE, getPointer());
}
@Override
public HRESULT GetCurrentPosition(Pointer currentPosition, Pointer positionSpanEnd,
BSTRByReference lineText) {
return _invokeHR(VTIndices.GET_CURRENT_POSITION, getPointer(), currentPosition,
positionSpanEnd, lineText);
}
@Override
public HRESULT GetStack(PointerByReference stack) {
return _invokeHR(VTIndices.GET_STACK, getPointer(), stack);
}
@Override
public HRESULT SetBreakpoint(ULONG linePosition, ULONG columnPosition,
PointerByReference breakpoint) {
return _invokeHR(VTIndices.SET_BREAKPOINT, getPointer(), linePosition, columnPosition,
breakpoint);
}
@Override
public HRESULT FindBreakpointById(ULONGLONG breakpointId, PointerByReference breakpoint) {
return _invokeHR(VTIndices.FIND_BREAKPOINT_BY_ID, getPointer(), breakpointId, breakpoint);
}
@Override
public HRESULT EnumerateBreakpoints(PointerByReference breakpointEnum) {
return _invokeHR(VTIndices.ENUMERATE_BREAKPOINTS, getPointer(), breakpointEnum);
}
@Override
public HRESULT GetEventFilter(ULONG eventFilter, BOOLByReference isBreakEnabled) {
return _invokeHR(VTIndices.GET_EVENT_FILTER, getPointer(), eventFilter, isBreakEnabled);
}
@Override
public HRESULT SetEventFilter(ULONG eventFilter, BOOL isBreakEnabled) {
return _invokeHR(VTIndices.SET_EVENT_FILTER, getPointer(), eventFilter, isBreakEnabled);
}
@Override
public HRESULT StartDebugging(Pointer debugClient) {
return _invokeHR(VTIndices.START_DEBUGGING, getPointer(), debugClient);
}
@Override
public HRESULT StopDebugging(Pointer debugClient) {
return _invokeHR(VTIndices.STOP_DEBUGGING, getPointer(), debugClient);
}
}
| 31.686869 | 98 | 0.790245 |
d81e764d04c6b1415ce486053b287a79261f5bc4 | 780 | swift | Swift | Radio/Interfaces/UI/Modules/NewsListView/NewsListView.swift | Daedren/radio-ios | f8559a43f34eefc12a6d28cffa0fa7bad015e8d5 | [
"MIT"
] | 2 | 2021-01-20T21:48:38.000Z | 2021-08-31T20:57:45.000Z | Radio/Interfaces/UI/Modules/NewsListView/NewsListView.swift | Daedren/radio-ios | f8559a43f34eefc12a6d28cffa0fa7bad015e8d5 | [
"MIT"
] | 5 | 2020-01-04T14:42:01.000Z | 2020-04-20T17:12:18.000Z | Radio/Interfaces/UI/Modules/NewsListView/NewsListView.swift | Daedren/radio-ios | f8559a43f34eefc12a6d28cffa0fa7bad015e8d5 | [
"MIT"
] | null | null | null | import SwiftUI
struct NewsListView<P: NewsListPresenter>: View {
@ObservedObject var presenter: P
var properties: NewsListProperties
init(presenter: P, properties: NewsListProperties) {
self.presenter = presenter
self.properties = properties
}
var body: some View {
NavigationView {
List(presenter.returnedValues) {
NewsEntryView(viewModel: $0)
}
// .styledList()
.navigationBarTitle(properties.titleBar)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct NewsListView_Previews: PreviewProvider {
static var previews: some View {
NewsListConfigurator().configureFake()
.preferredColorScheme(.dark)
}
}
| 26 | 56 | 0.629487 |
dd7c7dc5571c09c2ecac5442f27ce2495f8e641b | 278 | php | PHP | environment/owncloud_releases/OC60/apps/files/ajax/getstoragestats.php | gorootde/owncloud | 565f1a3d28ba36c18f640cc9ca4faf71b9ff5f27 | [
"Apache-2.0"
] | 1 | 2020-05-25T22:18:25.000Z | 2020-05-25T22:18:25.000Z | apps/owncloud/htdocs/apps/files/ajax/getstoragestats.php | ArcherCraftStore/ArcherVMPeridot | a34cc477ba078e1609de42fab258ca0c1691f999 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | null | null | null | apps/owncloud/htdocs/apps/files/ajax/getstoragestats.php | ArcherCraftStore/ArcherVMPeridot | a34cc477ba078e1609de42fab258ca0c1691f999 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | null | null | null | <?php
// only need filesystem apps
$RUNTIME_APPTYPES = array('filesystem');
$dir = '/';
if (isset($_GET['dir'])) {
$dir = $_GET['dir'];
}
OCP\JSON::checkLoggedIn();
// send back json
OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));
| 17.375 | 88 | 0.651079 |
0e82eb52d009f2ad587c8f7478aa82c78847125c | 139 | html | HTML | client/static/templates/mobile/overlay-sheet.html | rybon/Remocial | 324107c2471513c9b28729c1d5ac8a2a2c1cb034 | [
"MIT"
] | null | null | null | client/static/templates/mobile/overlay-sheet.html | rybon/Remocial | 324107c2471513c9b28729c1d5ac8a2a2c1cb034 | [
"MIT"
] | null | null | null | client/static/templates/mobile/overlay-sheet.html | rybon/Remocial | 324107c2471513c9b28729c1d5ac8a2a2c1cb034 | [
"MIT"
] | null | null | null | <div class="overlay" ng-show="isShown" overlay>
<alert-box></alert-box>
<confirm-box></confirm-box>
<prompt-box></prompt-box>
</div>
| 23.166667 | 47 | 0.661871 |
e618e2b0f0751a626f7d192bdb83b88372201cbe | 494 | asm | Assembly | programs/oeis/007/A007667.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/007/A007667.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/007/A007667.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A007667: The sum of both two and three consecutive squares.
; 5,365,35645,3492725,342251285,33537133085,3286296790925,322023548377445,31555021444198565,3092070077983081805,302991312620897818205,29690056566770003102165,2909322552230839406193845,285083920062055491803894525,27935314843529207357375469485,2737375770745800265530992114885,268234890218244896814679851789125,26284281865617254087573094483219245
seq $0,138288 ; a(n) = A054320(n) - A001078(n).
pow $0,2
div $0,80
mul $0,360
add $0,5
| 54.888889 | 343 | 0.856275 |
df947e31cb421d616ea0a0a99bb610e36a876113 | 2,148 | ts | TypeScript | wallet-server-ui-proxy/middleware/backup.ts | user411/bitcoin-s-ts | 4f5bfb586a47103e606ef8d1d4eb913f51103a29 | [
"MIT"
] | 11 | 2021-09-14T20:59:22.000Z | 2022-03-09T09:01:49.000Z | wallet-server-ui-proxy/middleware/backup.ts | user411/bitcoin-s-ts | 4f5bfb586a47103e606ef8d1d4eb913f51103a29 | [
"MIT"
] | 64 | 2021-08-30T15:24:52.000Z | 2022-03-23T14:21:21.000Z | wallet-server-ui-proxy/middleware/backup.ts | user411/bitcoin-s-ts | 4f5bfb586a47103e606ef8d1d4eb913f51103a29 | [
"MIT"
] | 4 | 2021-09-10T13:30:18.000Z | 2022-03-28T12:38:57.000Z | import fs from 'fs'
import path from 'path'
import { Request, Response } from 'express'
import * as WalletServer from 'wallet-ts/lib/index'
import { RunConfig } from '../type/run-config'
const Config = <RunConfig>require('../type/run-config')
const logger = require('../middleware/logger')
WalletServer.ConfigureServerURL(Config.walletServerUrl)
WalletServer.ConfigureAuthorizationHeader(Config.serverAuthHeader)
const filename = 'bitcoin-s-backup.zip'
exports.downloadBackup = (req: Request, res: Response) => {
// const r = req.body // don't currently care about request
logger.info('downloadBackup ' + Config.backupDirectory)
const fullPath = path.join(Config.backupDirectory, filename)
logger.info('fullPath: ' + fullPath + ' walletServerUrl: ' + Config.walletServerUrl)
// logger.info('auth header: ' + res.getHeader('Authorization'))
// Sanity check
try {
fs.accessSync(Config.backupDirectory) // Will throw error if directory does not exist
} catch (err) {
logger.error('downloadBackup backupDirectory is not accessible ' + Config.backupDirectory)
res.end() // Blob size 0 returned
}
// Use wallet-ts to create backup
WalletServer.ZipDataDir(fullPath).then(result => {
logger.info('ZipDataDir() complete')
if (result.result === null) { // success case
// Sanity check
try {
fs.accessSync(fullPath) // Will throw error if file does not exist
} catch (err) {
logger.error('downloadBackup fullPath is not accessible ' + fullPath)
res.end() // Blob size 0 returned
}
const readStream = fs.createReadStream(fullPath)
readStream.on('open', () =>
res.setHeader('Content-Type', 'application/zip; charset=utf-8'))
readStream.on('error',
(err) => { logger.error('readStream error ' + err) })
readStream.on('end', () => {
// Always delete backup zip after sending
fs.unlink(fullPath, function() {
// Nothing to do
})
})
readStream.pipe(res)
} else {
logger.error('downloadBackup ZipDataDir failed')
res.end() // Blob size 0 returned
}
})
}
| 32.059701 | 94 | 0.664339 |
55a4bf267de2c5b2fdbb751d58e6014f220e9218 | 941 | sql | SQL | ontrack-backend/src/main/resources/META-INF/db/update.24.sql | joansmith1/ontrack | ef31174d0310a35cbb011a950e1a7d81552cf216 | [
"MIT"
] | null | null | null | ontrack-backend/src/main/resources/META-INF/db/update.24.sql | joansmith1/ontrack | ef31174d0310a35cbb011a950e1a7d81552cf216 | [
"MIT"
] | null | null | null | ontrack-backend/src/main/resources/META-INF/db/update.24.sql | joansmith1/ontrack | ef31174d0310a35cbb011a950e1a7d81552cf216 | [
"MIT"
] | null | null | null | -- Build clean-up configuration
CREATE TABLE BUILD_CLEANUP (
ID INTEGER NOT NULL AUTO_INCREMENT,
BRANCH INTEGER NOT NULL,
RETENTION INTEGER NOT NULL,
CONSTRAINT PK_BUILD_CLEANUP PRIMARY KEY (ID),
CONSTRAINT UQ_BUILD_CLEANUP UNIQUE (BRANCH),
CONSTRAINT FK_BUILD_CLEANUP_BRANCH FOREIGN KEY (BRANCH) REFERENCES BRANCH (ID) ON DELETE CASCADE
);
CREATE TABLE BUILD_CLEANUP_PROMOTION (
BUILD_CLEANUP INTEGER NOT NULL,
PROMOTION_LEVEL INTEGER NOT NULL,
CONSTRAINT PK_BUILD_CLEANUP_PROMOTION PRIMARY KEY (BUILD_CLEANUP, PROMOTION_LEVEL),
CONSTRAINT FK_BUILD_CLEANUP_PROMOTION_BUILD_CLEANUP FOREIGN KEY (BUILD_CLEANUP) REFERENCES BUILD_CLEANUP (ID) ON DELETE CASCADE,
CONSTRAINT FK_BUILD_CLEANUP_PROMOTION_PROMOTION_LEVEL FOREIGN KEY (PROMOTION_LEVEL) REFERENCES (PROMOTION_LEVEL) ON DELETE CASCADE
);
-- @rollback
DROP TABLE IF EXISTS BUILD_CLEANUP;
DROP TABLE IF EXISTS BUILD_CLEANUP_PROMOTION;
-- @mysql
-- See update 26
| 36.192308 | 132 | 0.816153 |
85b0cec480ecde17c4381ae390cadcb69ed2d9d6 | 2,319 | js | JavaScript | config.js | pghayad/phase-3-syllabus-gatsby | fde1d63cace352736f7963933c310d0d0c2b4850 | [
"MIT"
] | null | null | null | config.js | pghayad/phase-3-syllabus-gatsby | fde1d63cace352736f7963933c310d0d0c2b4850 | [
"MIT"
] | null | null | null | config.js | pghayad/phase-3-syllabus-gatsby | fde1d63cace352736f7963933c310d0d0c2b4850 | [
"MIT"
] | 1 | 2021-07-29T19:24:12.000Z | 2021-07-29T19:24:12.000Z | const config = {
gatsby: {
pathPrefix: '/',
siteUrl: 'https://flatiron-phase-3.netlify.app',
gaTrackingId: null,
trailingSlash: false,
},
header: {
logo:
'https://instructure-uploads.s3.amazonaws.com/account_158020000000000001/attachments/43742/logo-primary.svg',
logoLink: 'https://flatiron-phase-3.netlify.app',
title: 'Phase 3 Javascript Resources',
githubUrl: '',
helpUrl: '',
tweetText: '',
links: [{ text: '', link: '' }],
search: {
enabled: false,
indexName: '',
algoliaAppId: process.env.GATSBY_ALGOLIA_APP_ID,
algoliaSearchKey: process.env.GATSBY_ALGOLIA_SEARCH_KEY,
algoliaAdminKey: process.env.ALGOLIA_ADMIN_KEY,
},
},
sidebar: {
forcedNavOrder: [
'/00-intro', // add trailing slash if enabled above
'/01-js-fundamentals',
'/02-dom-manipulation',
'/03-dom-exercises',
'/04-event-handling',
'/05-event-exercises',
'/06-fetch-basics',
'/07-fetch-crud',
'/08-fetch-exercises',
'/09-rails-as-an-api',
'/10-modern-javascript',
'/11-oojs',
],
openNav: [
'/00-intro', // add trailing slash if enabled above
],
links: [{ text: 'Flatiron Canvas', link: 'https://learning.flatironschool.com/' }],
frontline: false,
ignoreIndex: true,
title: 'Phase 3 Syllabus',
},
siteMetadata: {
title: 'Phase 3 Syllabus | Flatiron',
description:
'Documentation built with mdx. Built from https://github.com/hasura/gatsby-gitbook-boilerplate',
ogImage: null,
docsLocation: 'https://github.com/ihollander/phase-3-syllabus-gatsby/tree/main/content',
favicon:
'https://instructure-uploads.s3.amazonaws.com/account_158020000000000001/attachments/43718/flatiron-favicon.ico',
},
pwa: {
enabled: false, // disabling this will also remove the existing service worker.
manifest: {
name: 'Gatsby Gitbook Starter',
short_name: 'GitbookStarter',
start_url: '/',
background_color: '#6b37bf',
theme_color: '#6b37bf',
display: 'standalone',
crossOrigin: 'use-credentials',
icons: [
{
src: 'src/pwa-512.png',
sizes: `512x512`,
type: `image/png`,
},
],
},
},
};
module.exports = config;
| 29.35443 | 119 | 0.612333 |
c6d25c4f72141f03ee058e94885ee553877d91e6 | 930 | rb | Ruby | spec/controllers/admin/choices_controller_spec.rb | ianfleeton/zmey | d533ea22a6bbc051d6743aafb63beb3d69d8825c | [
"MIT"
] | null | null | null | spec/controllers/admin/choices_controller_spec.rb | ianfleeton/zmey | d533ea22a6bbc051d6743aafb63beb3d69d8825c | [
"MIT"
] | 8 | 2015-03-19T13:05:58.000Z | 2021-08-10T18:34:30.000Z | spec/controllers/admin/choices_controller_spec.rb | ianfleeton/zmey | d533ea22a6bbc051d6743aafb63beb3d69d8825c | [
"MIT"
] | null | null | null | require "rails_helper"
module Admin
RSpec.describe ChoicesController, type: :controller do
before do
logged_in_as_admin
end
describe "GET new" do
it "instantiates a new Choice" do
allow(controller).to receive(:feature_valid?)
expect(Choice).to receive(:new).and_return(double(Choice).as_null_object)
get "new"
end
it "sets @choice.feature_id to the feature_id supplied as a parameter" do
choice = Choice.new
allow(Choice).to receive(:new).and_return(choice)
get "new", params: {feature_id: 123}
expect(choice.feature_id).to eq 123
end
context "when the feature is invalid" do
it "redirects to the products page" do
allow(controller).to receive(:feature_valid?).and_return(false)
get "new"
expect(response).to redirect_to(admin_products_path)
end
end
end
end
end
| 28.181818 | 81 | 0.649462 |
707f0ce9400530dd6011d12fa7f035d8111e1ea8 | 1,026 | swift | Swift | SwiftUILocalNoti/DataService/ReminderMessageDataStore.swift | ketyung/SwiftUILocalNoti | 0a95fee3e5d7114dadd48cd116443e109af7c4b6 | [
"Unlicense"
] | 4 | 2021-04-04T23:40:43.000Z | 2022-02-02T16:58:26.000Z | SwiftUILocalNoti/DataService/ReminderMessageDataStore.swift | ketyung/SwiftUILocalNoti | 0a95fee3e5d7114dadd48cd116443e109af7c4b6 | [
"Unlicense"
] | null | null | null | SwiftUILocalNoti/DataService/ReminderMessageDataStore.swift | ketyung/SwiftUILocalNoti | 0a95fee3e5d7114dadd48cd116443e109af7c4b6 | [
"Unlicense"
] | null | null | null | //
// MessageDataStore.swift
// SwiftUILocalNoti
//
// Created by Chee Ket Yung on 15/03/2021.
//
import Foundation
typealias DS = ReminderMessageDataStore
struct ReminderMessageDataStore {
static let shared = ReminderMessageDataStore()
private let key = "com.techchee.savedReminderMessage"
func save(_ message : ReminderMessage ){
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(message) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: key)
}
}
func load() -> ReminderMessage{
let defaults = UserDefaults.standard
if let savedMessage = defaults.object(forKey: key) as? Data {
let decoder = JSONDecoder()
if let loadedMessage = try? decoder.decode(ReminderMessage.self, from: savedMessage) {
return loadedMessage
}
}
return ReminderMessage()
}
}
| 22.8 | 98 | 0.590643 |
dde2ed2c56369f4b209b0d63500c208121d334d2 | 1,562 | h | C | libdrm/tests/util/kms.h | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | libdrm/tests/util/kms.h | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | libdrm/tests/util/kms.h | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright 2008 Tungsten Graphics
* Jakob Bornecrantz <jakob@tungstengraphics.com>
* Copyright 2008 Intel Corporation
* Jesse Barnes <jesse.barnes@intel.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef UTIL_KMS_H
#define UTIL_KMS_H
const char *util_lookup_encoder_type_name(unsigned int type);
const char *util_lookup_connector_status_name(unsigned int type);
const char *util_lookup_connector_type_name(unsigned int type);
int util_open(const char *device, const char *module);
#endif /* UTIL_KMS_H */
| 43.388889 | 79 | 0.773367 |
86e47bb5e2ce2c884d0167457bd0767b8e00e018 | 5,568 | sql | SQL | ipbkostdb.sql | muhamadshb/IPB-Kost | 31f4c20539e2a364f040c5b7d702ab6e22dbad86 | [
"Apache-2.0"
] | 1 | 2021-03-06T16:55:27.000Z | 2021-03-06T16:55:27.000Z | ipbkostdb.sql | muhamadshb/IPB-Kost | 31f4c20539e2a364f040c5b7d702ab6e22dbad86 | [
"Apache-2.0"
] | null | null | null | ipbkostdb.sql | muhamadshb/IPB-Kost | 31f4c20539e2a364f040c5b7d702ab6e22dbad86 | [
"Apache-2.0"
] | 2 | 2020-07-07T04:12:32.000Z | 2020-10-20T23:34:58.000Z | -- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 10.1.16-MariaDB - mariadb.org binary distribution
-- Server OS: Win32
-- HeidiSQL Version: 9.4.0.5125
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table ipbkostdb.ci_sessions
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned NOT NULL DEFAULT '0',
`data` blob NOT NULL,
PRIMARY KEY (`id`),
KEY `ci_sessions_timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.ci_sessions: ~0 rows (approximately)
/*!40000 ALTER TABLE `ci_sessions` DISABLE KEYS */;
/*!40000 ALTER TABLE `ci_sessions` ENABLE KEYS */;
-- Dumping structure for table ipbkostdb.kategori
CREATE TABLE IF NOT EXISTS `kategori` (
`kategori_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(225) NOT NULL,
PRIMARY KEY (`kategori_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.kategori: ~3 rows (approximately)
/*!40000 ALTER TABLE `kategori` DISABLE KEYS */;
INSERT INTO `kategori` (`kategori_id`, `name`) VALUES
(1, 'Kost Pria'),
(2, 'Kost Wanita'),
(3, 'Kost Campur');
/*!40000 ALTER TABLE `kategori` ENABLE KEYS */;
-- Dumping structure for table ipbkostdb.kategorikost
CREATE TABLE IF NOT EXISTS `kategorikost` (
`kategorikost_id` int(11) NOT NULL AUTO_INCREMENT,
`kost_id` int(11) NOT NULL,
`kategori_id` int(11) NOT NULL,
PRIMARY KEY (`kategorikost_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.kategorikost: ~20 rows (approximately)
/*!40000 ALTER TABLE `kategorikost` DISABLE KEYS */;
INSERT INTO `kategorikost` (`kategorikost_id`, `kost_id`, `kategori_id`) VALUES
(1, 35, 1),
(2, 35, 1),
(3, 35, 1),
(4, 35, 1),
(5, 34, 1),
(6, 34, 3),
(7, 22, 1),
(8, 22, 3),
(9, 31, 1),
(10, 31, 3),
(11, 35, 1),
(12, 36, 1),
(13, 36, 3),
(14, 36, 1),
(15, 36, 3),
(16, 37, 1),
(17, 37, 1),
(18, 38, 3),
(19, 39, 1),
(20, 40, 2);
/*!40000 ALTER TABLE `kategorikost` ENABLE KEYS */;
-- Dumping structure for table ipbkostdb.kost
CREATE TABLE IF NOT EXISTS `kost` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(75) DEFAULT NULL,
`price` bigint(20) NOT NULL,
`latitude` varchar(100) DEFAULT NULL,
`longitude` varchar(100) DEFAULT NULL,
`address` text,
`photo` varchar(250) DEFAULT NULL,
`amenities` text,
`description` text,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.kost: ~3 rows (approximately)
/*!40000 ALTER TABLE `kost` DISABLE KEYS */;
INSERT INTO `kost` (`ID`, `name`, `price`, `latitude`, `longitude`, `address`, `photo`, `amenities`, `description`) VALUES
(37, 'Kost Pakde Sukardi', 350000, '-6.611069', '106.810910', 'Belakang restaurant taman seafood', '', 'AC, TV kabel, Telepon, Shower Panas & Dingin, Smooking Area', 'ok oce'),
(38, 'Jasmine Kos', 600000, '-6.6076999', '106.806285', 'Jl. Riau No. 38, Bogor', '', 'Wifi, Bed, Almari Pakaian, Kursi & Meja Belajar, Dapur, Parkir Motor', 'Tes tes'),
(39, 'Kost Ibu Lela', 600000, '-6.594648', '106.807431', 'Bogor Tengah', '', 'Bed, Almari Pakaian, Kursi & Meja Belajar, Parkir Motor', 'kost'),
(40, 'Kost Mas Uki', 700000, '-6.593604', '106.806881', 'Malabar', '', 'Bed, Almari Pakaian, Kursi & Meja Belajar, Parkir Motor', 'Kost');
/*!40000 ALTER TABLE `kost` ENABLE KEYS */;
-- Dumping structure for table ipbkostdb.tokens
CREATE TABLE IF NOT EXISTS `tokens` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`token` varchar(255) NOT NULL,
`user_id` int(10) NOT NULL,
`created` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.tokens: ~0 rows (approximately)
/*!40000 ALTER TABLE `tokens` DISABLE KEYS */;
INSERT INTO `tokens` (`id`, `token`, `user_id`, `created`) VALUES
(1, '10b1e0084271a40fae12dde64f20ff', 1, '2017-12-01');
/*!40000 ALTER TABLE `tokens` ENABLE KEYS */;
-- Dumping structure for table ipbkostdb.users
CREATE TABLE IF NOT EXISTS `users` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`fullname` varchar(50) DEFAULT NULL,
`username` varchar(50) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`password` text,
`role` varchar(10) DEFAULT NULL,
`last_login` varchar(100) DEFAULT NULL,
`status` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
-- Dumping data for table ipbkostdb.users: ~0 rows (approximately)
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`ID`, `fullname`, `username`, `email`, `password`, `role`, `last_login`, `status`) VALUES
(1, 'Muhamad Syihab', 'admin', 'syehab94@gmail.com', 'sha256:1000:Z66s3iNjWidJ91l+P0I1/S4k4wNpQ36y:jniC50nX92P+IytKBCkq86SxrPsGmVfc', NULL, '2017-12-01 09:33:52 AM', NULL);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| 40.941176 | 177 | 0.669899 |
22a688b908f3c37e4557079ac3b345cd31e82621 | 536 | lua | Lua | lua/duckbones/init.lua | thuanpham2311/zenbones.nvim | 6e36feccb3554a743ef0720abd13fea7bd8bc9dd | [
"MIT"
] | 166 | 2021-08-23T08:18:47.000Z | 2022-03-30T02:40:53.000Z | lua/duckbones/init.lua | thuanpham2311/zenbones.nvim | 6e36feccb3554a743ef0720abd13fea7bd8bc9dd | [
"MIT"
] | 29 | 2021-08-25T05:35:32.000Z | 2022-03-12T06:37:53.000Z | lua/duckbones/init.lua | thuanpham2311/zenbones.nvim | 6e36feccb3554a743ef0720abd13fea7bd8bc9dd | [
"MIT"
] | 10 | 2021-08-31T16:43:27.000Z | 2022-03-03T17:22:30.000Z | local lush = require "lush"
local generator = require "zenbones.specs"
local p = require("duckbones.palette").dark
local specs = generator.generate(p, "dark", generator.get_global_config("duckbones", "dark"))
return lush.extends({ specs }).with(function()
---@diagnostic disable: undefined-global
-- selene: allow(undefined_variable)
return {
Statement { specs.Statement, fg = p.blossom },
Special { fg = p.leaf },
PreProc { fg = p.sky },
}
-- selene: deny(undefined_variable)
---@diagnostic enable: undefined-global
end)
| 29.777778 | 93 | 0.710821 |
cc533564239dcc395c66b1c67f91aaf1df7426eb | 3,772 | sql | SQL | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/depcies/move_obj_to_schema_new.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 96 | 2017-12-12T09:35:34.000Z | 2022-03-29T16:56:02.000Z | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/depcies/move_obj_to_schema_new.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 81 | 2017-12-13T08:03:47.000Z | 2022-03-16T08:57:23.000Z | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/depcies/move_obj_to_schema_new.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 16 | 2018-04-23T12:11:22.000Z | 2022-01-12T08:03:11.000Z | --
-- PostgreSQL database dump
--
-- Dumped from database version 9.6.3
-- Dumped by pg_dump version 9.6.3
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: test; Type: SCHEMA; Schema: -; Owner: galiev_mr
--
CREATE SCHEMA test;
ALTER SCHEMA test OWNER TO galiev_mr;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
--CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
--COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = pg_catalog;
--
-- Name: user_code; Type: TYPE; Schema: test; Owner: galiev_mr
--
CREATE TYPE test.user_code AS (
f1 integer,
f2 text
);
ALTER TYPE test.user_code OWNER TO galiev_mr;
--
-- Name: emp_stamp(); Type: FUNCTION; Schema: test; Owner: galiev_mr
--
CREATE FUNCTION test.emp_stamp() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
-- Check that empname and salary are given
IF NEW.empname IS NULL THEN
RAISE EXCEPTION 'empname cannot be null';
END IF;
IF NEW.salary IS NULL THEN
RAISE EXCEPTION '% cannot have null salary', NEW.empname;
END IF;
-- Who works for us when they must pay for it?
IF NEW.salary < 0 THEN
RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
END IF;
-- Remember who changed the payroll when
NEW.last_date := current_timestamp;
NEW.last_user := current_user;
RETURN NEW;
END;
$$;
ALTER FUNCTION test.emp_stamp() OWNER TO galiev_mr;
--
-- Name: increment(integer); Type: FUNCTION; Schema: test; Owner: galiev_mr
--
CREATE FUNCTION test.increment(i integer) RETURNS integer
LANGUAGE plpgsql
AS $$
BEGIN
RETURN i + 1;
END;
$$;
ALTER FUNCTION test.increment(i integer) OWNER TO galiev_mr;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: emp; Type: TABLE; Schema: test; Owner: galiev_mr
--
CREATE TABLE test.emp (
id integer NOT NULL,
empname text,
salary integer,
last_date timestamp without time zone,
last_user text,
code test.user_code
);
ALTER TABLE test.emp OWNER TO galiev_mr;
--
-- Name: emp_id_seq; Type: SEQUENCE; Schema: test; Owner: galiev_mr
--
CREATE SEQUENCE test.emp_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE test.emp_id_seq OWNER TO galiev_mr;
--
-- Name: emp_id_seq; Type: SEQUENCE OWNED BY; Schema: test; Owner: galiev_mr
--
ALTER SEQUENCE test.emp_id_seq OWNED BY test.emp.id;
--
-- Name: emp_view; Type: VIEW; Schema: test; Owner: galiev_mr
--
CREATE VIEW test.emp_view AS
SELECT emp.empname,
emp.last_date,
increment(emp.salary) AS salary,
emp.code
FROM test.emp;
ALTER TABLE test.emp_view OWNER TO galiev_mr;
--
-- Name: emp id; Type: DEFAULT; Schema: test; Owner: galiev_mr
--
ALTER TABLE ONLY test.emp ALTER COLUMN id SET DEFAULT nextval('test.emp_id_seq'::regclass);
--
-- Name: name_ind; Type: INDEX; Schema: test; Owner: galiev_mr
--
CREATE UNIQUE INDEX name_ind ON test.emp USING btree (empname);
--
-- Name: emp notify_me; Type: RULE; Schema: test; Owner: galiev_mr
--
CREATE RULE notify_me AS
ON UPDATE TO test.emp DO
NOTIFY emp;
--
-- Name: emp emp_stamp; Type: TRIGGER; Schema: public; Owner: galiev_mr
--
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON test.emp FOR EACH ROW EXECUTE PROCEDURE test.emp_stamp();
--
-- PostgreSQL database dump complete
--
| 19.957672 | 109 | 0.681336 |
170ab76ea8a1f8e700657ff2bde2e70b5f42af03 | 1,159 | h | C | version/Core/Public/IHooks.h | K07H/ARK-Server-API | 4136c039dfefa9d1acbe94aaf14c2bd998e2f3d7 | [
"MIT"
] | 61 | 2018-03-31T16:51:44.000Z | 2022-03-19T17:09:01.000Z | version/Core/Public/IHooks.h | WETBATMAN/ARK-Server-API | f040d87a258f5185e204a49c9f49455dca0e7503 | [
"MIT"
] | 14 | 2018-02-05T19:24:13.000Z | 2022-01-08T05:02:28.000Z | version/Core/Public/IHooks.h | WETBATMAN/ARK-Server-API | f040d87a258f5185e204a49c9f49455dca0e7503 | [
"MIT"
] | 74 | 2018-01-28T10:34:42.000Z | 2022-03-26T14:38:13.000Z | #pragma once
#include <API/Base.h>
namespace ArkApi
{
class ARK_API IHooks
{
public:
virtual ~IHooks() = default;
/**
* \brief Hooks a function. Hooks are called in the reverse order.
* \param func_name Function full name
* \param detour A pointer to the detour function, which will override the target function
* \param original A pointer to the trampoline function, which will be used to call the original target function
* \return true if success, false otherwise
*/
template <typename T>
bool SetHook(const std::string& func_name, LPVOID detour, T** original)
{
return SetHookInternal(func_name, detour, reinterpret_cast<LPVOID*>(original));
}
/**
* \brief Removes a hook from a function
* \param func_name Function full name
* \param detour A pointer to the detour function
* \return true if success, false otherwise
*/
virtual bool DisableHook(const std::string& func_name, LPVOID detour) = 0;
private:
virtual bool SetHookInternal(const std::string& func_name, LPVOID detour,
LPVOID* original) = 0;
};
ARK_API IHooks& APIENTRY GetHooks();
} // namespace ArkApi
| 28.975 | 113 | 0.701467 |
0e506af1db552dba422e58d92ce4213bc2c0db52 | 293 | html | HTML | index.html | farahat80/react-weather | 30ec22d1f6c7c5974bc094c259cf007a504b1819 | [
"MIT"
] | 56 | 2017-11-07T11:20:10.000Z | 2022-03-07T15:57:11.000Z | index.html | farahat80/react-weather | 30ec22d1f6c7c5974bc094c259cf007a504b1819 | [
"MIT"
] | 63 | 2017-06-08T14:34:46.000Z | 2022-03-26T09:58:49.000Z | index.html | farahat80/react-weather | 30ec22d1f6c7c5974bc094c259cf007a504b1819 | [
"MIT"
] | 60 | 2018-03-24T12:43:19.000Z | 2022-02-21T15:59:13.000Z | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React Open Weather</title>
</head>
<body style="background-color:#666">
<div style="margin:0 auto;width:500px">
<div id="root"></div>
</div>
<script src="dist/js/main.js"></script>
</body>
</html>
| 20.928571 | 43 | 0.580205 |
a181f90a990d65ba22716a78b7cdd0f20bfab382 | 13,829 | h | C | src/ace_segment/scanning/ScanningModule.h | bxparks/AceSegment | 732df1bf4e22ab214010e9e4b534b338896ffedc | [
"MIT"
] | 4 | 2021-04-19T16:47:34.000Z | 2022-02-06T03:48:17.000Z | src/ace_segment/scanning/ScanningModule.h | bxparks/AceSegment | 732df1bf4e22ab214010e9e4b534b338896ffedc | [
"MIT"
] | 9 | 2018-04-03T23:28:56.000Z | 2021-05-14T21:44:04.000Z | src/ace_segment/scanning/ScanningModule.h | bxparks/AceSegment | 732df1bf4e22ab214010e9e4b534b338896ffedc | [
"MIT"
] | 1 | 2021-08-18T22:03:51.000Z | 2021-08-18T22:03:51.000Z | /*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_SEGMENT_SCANNING_MODULE_H
#define ACE_SEGMENT_SCANNING_MODULE_H
#include <stdint.h>
#include <AceCommon.h> // incrementMod()
#include "../hw/ClockInterface.h" // ClockInterface
#include "../LedModule.h"
class ScanningModuleTest_isAnyDigitDirty;
class ScanningModuleTest_isBrightnessDirty;
namespace ace_segment {
/**
* An implementation of `LedModule` for display modules which do not have
* hardware controller chips, so they require the microcontroller to perform the
* multiplexed scanning across the digits. The matrix wiring of the segment and
* digit pins allow only a single digit to be turned on at any given time, so
* multiplexing across all the digits quickly (e.g. 60 Hz) gives the appearance
* of activating all the digits at the same time. For LED modules with a
* hardware controller (e.g. TM1637), the controller chip performs the
* multiplexing. Note that a 74HC595 Shift Register chip does *not* perform the
* multiplexing, it only provides a conversion from serial to parallel output.
*
* This class depends on one of the implementations of the `LedMatrixBase` class
* to multiplex the LED segments on the digits, and potentially one of the of
* `SimpleSpiInterface` or `HardSpiInterface` classes if a 74HC595 shift
* register chip is used.
*
* A frame is divided into fields. A field is a partial rendering of a frame.
* Normally, the one digit corresponds to one field. However if brightness
* control is enabled by setting `T_SUBFIELDS > 1`, then a single digit will be
* rendered for T_SUBFIELDS number of times so that the brightness of the digit
* will be controlled by PWM.
*
* There are 2 ways to get the expected number of frames per second:
*
* 1) Call the renderFieldNow() in an ISR, or
* 2) Call renderFieldWhenReady() polling method repeatedly from the global
* loop(), and an internal timing parameter will trigger a renderFieldNow()
* at the appropriate time.
*
* @tparam T_LM the LedMatrixBase class that provides access to LED segments
(elements) organized by digit (group)
* @tparam T_DIGITS number of LED digits
* @tparam T_SUBFIELDS number of subfields for each digit to get brightness
* control using PWM. The default is 1, but can be set to greater than 1 to
* get brightness control.
* @tparam T_CI class that provides access to Arduino clock functions (millis()
* and micros()). The default is ClockInterface.
*/
template <
typename T_LM,
uint8_t T_DIGITS,
uint8_t T_SUBFIELDS = 1,
typename T_CI = ClockInterface>
class ScanningModule : public LedModule {
public:
/**
* Constructor.
*
* @param ledMatrix instance of LedMatrixBase that understanding the wiring
* @param framesPerSecond the rate at which all digits of the LED display
* will be refreshed
* @param numDigits number of digits in the LED display
* @param patterns array of segment pattern per digit, not nullable
* @param brightnesses array of brightness for each digit (default: nullptr)
*/
explicit ScanningModule(
const T_LM& ledMatrix,
uint8_t framesPerSecond
):
LedModule(mPatterns, T_DIGITS),
mLedMatrix(ledMatrix),
mFramesPerSecond(framesPerSecond)
{}
/**
* Configure the driver with the parameters given by in the constructor.
* Normally, this should be called only once after construction. Unit tests
* will sometimes change a parameter of FakeDriver and call this a second
* time.
*/
void begin() {
LedModule::begin();
// Set up durations for the renderFieldWhenReady() polling function.
mMicrosPerField = (uint32_t) 1000000UL / getFieldsPerSecond();
mLastRenderFieldMicros = T_CI::micros();
// Initialize variables needed for multiplexing.
mCurrentDigit = 0;
mPrevDigit = T_DIGITS - 1;
mCurrentSubField = 0;
mPattern = 0;
// Set initial patterns and global brightness.
mIsDigitBrightnessDirty = false;
mLedMatrix.clear();
if (T_SUBFIELDS > 1) {
setBrightness(T_SUBFIELDS / 2); // half brightness
}
}
/** A no-op end() function for consistency with other classes. */
void end() {
LedModule::end();
}
//-----------------------------------------------------------------------
// Additional brightness control. ScanningModule allows brightness to be
// defined on a per-digit basis.
//-----------------------------------------------------------------------
/**
* Set the brightness for a given pos, leaving pattern unchanged.
* Not all implementation of `LedClass` can support brightness for each
* digit, so this is implemented at the ScanningModule class.
*
* The maximum brightness should is exactly `T_SUBFIELDS` which turns on the
* LED 100% of the time. The minimum brightness is 0, which turns OFF the
* digit. For example, if `T_SUBFIELDS==16`, the the maximum brightness is
* 16 which turns ON the digit 100% of the time. The relative brightness of
* each brightness level is in units of 1/T_SUBFIELDS.
*
* The brightness scale is *not* normalized to [0,255]. A previous version
* of this class tried to do that, but I found that this introduced
* discretization errors which made it difficult to control the brightness
* at intermediate values. For example, suppose T_SUBFIELDS=16. If we
* changed the normalized brightness value from 32 to 40, it was impossible
* to determine without actually running the program if the 2 values
* actually differed in brightness. Instead, the calling program is expected
* to keep track of the value of T_SUBFIELDS, and create an array of
* brightness values in these raw units. The side benefit of using raw
* brightness values is that it makes displayCurrentFieldModulated() easier
* to implement.
*/
void setBrightnessAt(uint8_t pos, uint8_t brightness) {
if (pos >= T_DIGITS) return;
mBrightnesses[pos] = (brightness >= T_SUBFIELDS)
? T_SUBFIELDS : brightness;
mIsDigitBrightnessDirty = true;
}
//-----------------------------------------------------------------------
// Methods related to rendering.
//-----------------------------------------------------------------------
/** Return the requested frames per second. */
uint16_t getFramesPerSecond() const { return mFramesPerSecond; }
/** Return the fields per second. */
uint16_t getFieldsPerSecond() const {
return mFramesPerSecond * getFieldsPerFrame();
}
/** Total fields per frame across all digits. */
uint16_t getFieldsPerFrame() const { return T_DIGITS * T_SUBFIELDS; }
/**
* Return micros per field. This is how often renderFieldNow() must be
* called from a timer interrupt.
*/
uint16_t getMicrosPerField() const { return mMicrosPerField; }
/**
* Display one field of a frame when the time is right. This is a polling
* method, so call this slightly more frequently than getFieldsPerSecond()
* per second.
*
* @return Returns true if renderFieldNow() was called and the field was
* rendered.
*/
bool renderFieldWhenReady() {
uint16_t now = T_CI::micros();
uint16_t elapsedMicros = now - mLastRenderFieldMicros;
if (elapsedMicros >= mMicrosPerField) {
renderFieldNow();
mLastRenderFieldMicros = now;
return true;
} else {
return false;
}
}
/**
* Render the current field immediately. If modulation is off (i.e.
* T_SUBFIELDS == 1), then the field corresponds to the single digit. If
* modulation is enabled (T_SUBFIELDS > 1), then each digit is PWM modulated
* over T_SUBFIELDS number of renderings.
*
* This method is intended to be called directly from a timer interrupt
* handler.
*/
void renderFieldNow() {
updateBrightness();
if (T_SUBFIELDS > 1) {
displayCurrentFieldModulated();
} else {
displayCurrentFieldPlain();
}
}
private:
friend class ::ScanningModuleTest_isAnyDigitDirty;
friend class ::ScanningModuleTest_isBrightnessDirty;
// disable copy-constructor and assignment operator
ScanningModule(const ScanningModule&) = delete;
ScanningModule& operator=(const ScanningModule&) = delete;
/** Display field normally without modulation. */
void displayCurrentFieldPlain() {
const uint8_t pattern = mPatterns[mCurrentDigit];
mLedMatrix.draw(mCurrentDigit, pattern);
mPrevDigit = mCurrentDigit;
ace_common::incrementMod(mCurrentDigit, T_DIGITS);
}
/** Display field using subfield modulation. */
void displayCurrentFieldModulated() {
// Calculate the maximum subfield duration for current digit.
const uint8_t brightness = mBrightnesses[mCurrentDigit];
// Implement pulse width modulation PWM, using the following boundaries:
//
// * If brightness == 0, then turn the digit OFF 100% of the time.
// * If brightness >= T_SUBFIELDS, turn the digit ON 100% of the time.
//
// The mCurrentSubField is incremented modulo T_SUBFIELDS, so will always
// be in the range of [0, T_SUBFIELDS-1]. The brightness will always be <=
// T_SUBFIELDS, with the value of T_SUBFIELDS being 100% bright. So if we
// turn on the LED when (mCurrentSubField < brightness), we get the
// desired outcome.
const uint8_t pattern = (mCurrentSubField < brightness)
? mPatterns[mCurrentDigit]
: 0;
if (pattern != mPattern || mCurrentDigit != mPrevDigit) {
mLedMatrix.draw(mCurrentDigit, pattern);
mPattern = pattern;
}
mCurrentSubField++;
mPrevDigit = mCurrentDigit;
if (mCurrentSubField >= T_SUBFIELDS) {
ace_common::incrementMod(mCurrentDigit, T_DIGITS);
mCurrentSubField = 0;
}
}
/**
* Transfer the global brightness to the per-digit brightness and update the
* appropriate flags.
*/
void updateBrightness() {
if (isBrightnessDirty()) {
for (uint8_t i = 0; i < T_DIGITS; i++) {
setBrightnessAt(i, getBrightness());
}
// Clear the global brightness dirty flag.
clearBrightnessDirty();
}
}
private:
// The ordering of the fields below partially motivated to save memory on
// 32-bit processors.
/** LedMatrixBase instance that knows how to set and unset LED segments. */
const T_LM& mLedMatrix;
/** Pattern for each digit. */
uint8_t mPatterns[T_DIGITS];
/** Brightness for each digit. Unused if T_SUBFIELDS <= 1. */
uint8_t mBrightnesses[T_DIGITS];
//-----------------------------------------------------------------------
// Variables needed by renderFieldWhenReady() to render frames and fields at
// a certain rate per second.
//-----------------------------------------------------------------------
/** Number of micros between 2 successive calls to renderFieldNow(). */
uint16_t mMicrosPerField;
/** Timestamp in micros of the last call to renderFieldNow(). */
uint16_t mLastRenderFieldMicros;
/** Number of full frames (all digits) rendered per second. */
uint8_t const mFramesPerSecond;
//-----------------------------------------------------------------------
// Variables needed to keep track of the multiplexing of the digits,
// and PWM of a single digit.
//-----------------------------------------------------------------------
/** Dirty flag for any of the digit-specific brightness. */
bool mIsDigitBrightnessDirty;
/**
* Within the renderFieldNow() method, mCurrentDigit is the current
* digit that is being drawn. It is incremented to the next digit just
* before returning from that method.
*/
uint8_t mCurrentDigit;
/**
* Within the renderFieldNow() method, the mPrevDigit is the digit
* that was displayed on the previous call to renderFieldNow(). It is
* set to the digit that was just displayed before returning. It will be
* equal to mCurrentDigit when multiple fields are drawn for the same
* digit.
*/
uint8_t mPrevDigit;
/**
* Used by displayCurrentFieldModulated() and subclasses generated by
* fast_driver.py.
*/
uint8_t mCurrentSubField;
/**
* The segment pattern that is currently displaying on the LED. Used to
* optimize the displayCurrentFieldModulated() method if the current
* pattern is the same as the previous pattern.
*/
uint8_t mPattern;
};
}
#endif
| 38.307479 | 80 | 0.663461 |
4009b06c7f2a79a55036a8541e8d8b3d6f9a817d | 19,880 | py | Python | ost/s1/grd_batch.py | KBodolai/OpenSarToolkit | 29af1df36f10f28a17b56f39ad67f0c7f530b93a | [
"MIT"
] | null | null | null | ost/s1/grd_batch.py | KBodolai/OpenSarToolkit | 29af1df36f10f28a17b56f39ad67f0c7f530b93a | [
"MIT"
] | null | null | null | ost/s1/grd_batch.py | KBodolai/OpenSarToolkit | 29af1df36f10f28a17b56f39ad67f0c7f530b93a | [
"MIT"
] | null | null | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Batch processing for GRD products
"""
import os
import json
import itertools
import logging
import pandas as pd
from pathlib import Path
from godale._concurrent import Executor
from ost import Sentinel1Scene
from ost.s1 import grd_to_ard
from ost.helpers import raster as ras
from ost.generic import ts_extent
from ost.generic import ts_ls_mask
from ost.generic import ard_to_ts
from ost.generic import timescan
from ost.generic import mosaic
logger = logging.getLogger(__name__)
def _create_processing_dict(inventory_df):
"""Function that creates a dictionary to handle GRD batch processing
This helper function takes the inventory dataframe and creates
a dictionary with the track as key, and all the files to process as
a list, whereas the list is
:param inventory_df:
:return:
"""
# initialize empty dictionary
dict_scenes = {}
# get relative orbits and loop through each
track_list = inventory_df["relativeorbit"].unique()
for track in track_list:
# get acquisition dates and loop through each
acquisition_dates = inventory_df["acquisitiondate"][
inventory_df["relativeorbit"] == track
].unique()
# loop through dates
for i, acquisition_date in enumerate(acquisition_dates):
# get the scene ids per acquisition_date and write into a list
single_id = inventory_df["identifier"][
(inventory_df["relativeorbit"] == track)
& (inventory_df["acquisitiondate"] == acquisition_date)
].tolist()
# add this list to the dictionary and associate the track number
# as dict key
dict_scenes[f"{track}_{i+1}"] = single_id
return dict_scenes
def create_processed_df(inventory_df, list_of_scenes, outfile, out_ls, error):
df = pd.DataFrame(columns=["identifier", "outfile", "out_ls", "error"])
for scene in list_of_scenes:
temp_df = pd.DataFrame()
# get scene_id
temp_df["identifier"] = inventory_df.identifier[
inventory_df.identifier == scene
].values
# fill outfiles/error
temp_df["outfile"] = outfile
temp_df["out_ls"] = out_ls
temp_df["error"] = error
# append to final df and delete temp_df for next loop
df = pd.concat([df, temp_df])
del temp_df
return df
def grd_to_ard_batch(inventory_df, config_file):
# load relevant config parameters
with open(config_file, "r") as file:
config_dict = json.load(file)
download_dir = Path(config_dict["download_dir"])
data_mount = Path(config_dict["data_mount"])
# where all frames are grouped into acquisitions
processing_dict = _create_processing_dict(inventory_df)
processing_df = pd.DataFrame(columns=["identifier", "outfile", "out_ls", "error"])
iter_list = []
for _, list_of_scenes in processing_dict.items():
# get the paths to the file
scene_paths = [
Sentinel1Scene(scene).get_path(download_dir, data_mount)
for scene in list_of_scenes
]
iter_list.append(scene_paths)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
for task in executor.as_completed(
func=grd_to_ard.grd_to_ard,
iterable=iter_list,
fargs=(
[
str(config_file),
]
),
):
list_of_scenes, outfile, out_ls, error = task.result()
# return the info of processing as dataframe
temp_df = create_processed_df(
inventory_df, list_of_scenes, outfile, out_ls, error
)
processing_df = pd.concat([processing_df, temp_df])
return processing_df
def ards_to_timeseries(inventory_df, config_file):
with open(config_file) as file:
config_dict = json.load(file)
ard = config_dict["processing"]["single_ARD"]
ard_mt = config_dict["processing"]["time-series_ARD"]
# create all extents
_create_extents(inventory_df, config_file)
# update extents in case of ls_mask
if ard["create_ls_mask"] or ard_mt["apply_ls_mask"]:
_create_mt_ls_mask(inventory_df, config_file)
# finally create time-series
_create_timeseries(inventory_df, config_file)
def _create_extents(inventory_df, config_file):
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
iter_list = []
for track in inventory_df.relativeorbit.unique():
# get the burst directory
track_dir = processing_dir / track
list_of_extents = list(track_dir.glob("*/*/*bounds.json"))
# if extent does not already exist, add to iterable
if not (track_dir / f"{track}.min_bounds.json").exists():
iter_list.append(list_of_extents)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=os.cpu_count()
)
out_dict = {"track": [], "list_of_scenes": [], "extent": []}
for task in executor.as_completed(
func=ts_extent.mt_extent,
iterable=iter_list,
fargs=(
[
str(config_file),
]
),
):
track, list_of_scenes, extent = task.result()
out_dict["track"].append(track)
out_dict["list_of_scenes"].append(list_of_scenes)
out_dict["extent"].append(extent)
return pd.DataFrame.from_dict(out_dict)
def _create_extents_old(inventory_df, config_file):
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
iter_list = []
for track in inventory_df.relativeorbit.unique():
# get the burst directory
track_dir = processing_dir / track
# get common burst extent
list_of_scenes = list(track_dir.glob("**/*img"))
list_of_scenes = [str(x) for x in list_of_scenes if "layover" not in str(x)]
# if extent does not already exist, add to iterable
if not (track_dir / f"{track}.extent.gpkg").exists():
iter_list.append(list_of_scenes)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
out_dict = {"track": [], "list_of_scenes": [], "extent": []}
for task in executor.as_completed(
func=ts_extent.mt_extent,
iterable=iter_list,
fargs=(
[
str(config_file),
]
),
):
track, list_of_scenes, extent = task.result()
out_dict["track"].append(track)
out_dict["list_of_scenes"].append(list_of_scenes)
out_dict["extent"].append(extent)
return pd.DataFrame.from_dict(out_dict)
def _create_mt_ls_mask(inventory_df, config_file):
"""Helper function to union the Layover/Shadow masks of a Time-series
This function creates a
:param inventory_df:
:param config_file:
:return:
"""
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
iter_list = []
for track in inventory_df.relativeorbit.unique():
# get the burst directory
track_dir = processing_dir / track
# get common burst extent
list_of_masks = list(track_dir.glob("*/*/*_ls_mask.json"))
# if extent does not already exist, add to iterable
if not (track_dir / f"{track}.ls_mask.json").exists():
iter_list.append(list_of_masks)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=os.cpu_count()
)
for task in executor.as_completed(func=ts_ls_mask.mt_layover, iterable=iter_list):
task.result()
def _create_mt_ls_mask_old(inventory_df, config_file):
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
iter_list = []
for track in inventory_df.relativeorbit.unique():
# get the burst directory
track_dir = processing_dir / track
# get common burst extent
list_of_scenes = list(track_dir.glob("**/*img"))
list_of_layover = [str(x) for x in list_of_scenes if "layover" in str(x)]
iter_list.append(list_of_layover)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
out_dict = {"track": [], "list_of_layover": [], "ls_mask": [], "ls_extent": []}
for task in executor.as_completed(
func=ts_ls_mask.mt_layover,
iterable=iter_list,
fargs=(
[
str(config_file),
]
),
):
track, list_of_layover, ls_mask, ls_extent = task.result()
out_dict["track"].append(track)
out_dict["list_of_layover"].append(list_of_layover)
out_dict["ls_mask"].append(list_of_layover)
out_dict["ls_extent"].append(ls_extent)
return pd.DataFrame.from_dict(out_dict)
def _create_timeseries(inventory_df, config_file):
"""Helper function to create Timeseries out of OST ARD products
Based on the inventory GeoDataFrame and the configuration file,
this function triggers the time-series processing for all bursts/tracks
within the respective project. Each product/polarisation is treated
singularly.
Based on the ARD type/configuration settings, the function uses
SNAP's Create-Stack function to unify the grid of each scene and
applies a multi-temporal speckle filter if selected.
The output are single GeoTiff files, whereas there is the possibility to
reduce the data by converting the data format into uint8 or uint16.
This is done by linearly stretching the data between -30 and +5
for backscatter, 0 and 1 for coherence, polarimetric anisotropy #
and entropy, as well 0 and 90 for polarimetric alpha channel. All
the data is cropped to the same extent based on the minimum bounds layer.
This function executes the underlying functions using the godale framework
for parallel execution. Executor type and number of parallel processes is
defined within the configuration file.
:param inventory_df:
:type GeoDataFrame
:param config_file:
:type str/Path
:return:
"""
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
iter_list = []
for track in inventory_df.relativeorbit.unique():
# get the burst directory
track_dir = processing_dir / track
for pol in ["VV", "VH", "HH", "HV"]:
# see if there is actually any imagery in thi polarisation
list_of_files = sorted(
str(file) for file in list(track_dir.glob(f"20*/*data*/*ma0*{pol}*img"))
)
if len(list_of_files) <= 1:
continue
# create list of dims if polarisation is present
list_of_dims = sorted(
str(dim) for dim in list(track_dir.glob("20*/*bs*dim"))
)
iter_list.append([list_of_dims, track, "bs", pol])
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
out_dict = {
"track": [],
"list_of_dims": [],
"out_files": [],
"out_vrt": [],
"product": [],
"error": [],
}
for task in executor.as_completed(
func=ard_to_ts.gd_ard_to_ts,
iterable=iter_list,
fargs=(
[
str(config_file),
]
),
):
track, list_of_dims, out_files, out_vrt, product, error = task.result()
out_dict["track"].append(track)
out_dict["list_of_dims"].append(list_of_dims)
out_dict["out_files"].append(out_files)
out_dict["out_vrt"].append(out_vrt)
out_dict["product"].append(product)
out_dict["error"].append(error)
return pd.DataFrame.from_dict(out_dict)
def timeseries_to_timescan(inventory_df, config_file):
# load ard parameters
with open(config_file, "r") as file:
config_dict = json.load(file)
processing_dir = Path(config_dict["processing_dir"])
ard = config_dict["processing"]["single_ARD"]
ard_mt = config_dict["processing"]["time-series_ARD"]
ard_tscan = config_dict["processing"]["time-scan_ARD"]
# get the db scaling right
to_db = ard["to_db"]
if ard["to_db"] or ard_mt["to_db"]:
to_db = True
dtype_conversion = True if ard_mt["dtype_output"] != "float32" else False
iter_list, vrt_iter_list = [], []
for track in inventory_df.relativeorbit.unique():
# get track directory
track_dir = processing_dir / track
# define and create Timescan directory
timescan_dir = track_dir / "Timescan"
timescan_dir.mkdir(parents=True, exist_ok=True)
# loop thorugh each polarization
for polar in ["VV", "VH", "HH", "HV"]:
if (timescan_dir / f".bs.{polar}.processed").exists():
logger.info(f"Timescans for track {track} already processed.")
continue
# get timeseries vrt
time_series = track_dir / "Timeseries" / f"Timeseries.bs.{polar}.vrt"
if not time_series.exists():
continue
# create a datelist for harmonics
scene_list = list(track_dir.glob(f"Timeseries/*bs.{polar}.tif"))
# create a datelist for harmonics calculation
datelist = []
for file in sorted(scene_list):
datelist.append(file.name.split(".")[1])
# define timescan prefix
timescan_prefix = timescan_dir / f"bs.{polar}"
iter_list.append(
[
time_series,
timescan_prefix,
ard_tscan["metrics"],
dtype_conversion,
to_db,
ard_tscan["remove_outliers"],
datelist,
]
)
vrt_iter_list.append(timescan_dir)
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
# run timescan creation
out_dict = {"track": [], "prefix": [], "metrics": [], "error": []}
for task in executor.as_completed(func=timescan.gd_mt_metrics, iterable=iter_list):
burst, prefix, metrics, error = task.result()
out_dict["track"].append(burst)
out_dict["prefix"].append(prefix)
out_dict["metrics"].append(metrics)
out_dict["error"].append(error)
timescan_df = pd.DataFrame.from_dict(out_dict)
# run vrt creation
for task in executor.as_completed(
func=ras.create_tscan_vrt,
iterable=vrt_iter_list,
fargs=(
[
str(config_file),
]
),
):
task.result()
return timescan_df
def mosaic_timeseries(inventory_df, config_file):
print(" -----------------------------------")
logger.info("Mosaicking Time-series layers")
print(" -----------------------------------")
# -------------------------------------
# 1 load project config
with open(config_file, "r") as ard_file:
config_dict = json.load(ard_file)
processing_dir = Path(config_dict["processing_dir"])
# create output folder
ts_dir = processing_dir / "Mosaic" / "Timeseries"
ts_dir.mkdir(parents=True, exist_ok=True)
# loop through polarisations
iter_list, vrt_iter_list = [], []
for p in ["VV", "VH", "HH", "HV"]:
tracks = inventory_df.relativeorbit.unique()
nr_of_ts = len(
list((processing_dir / f"{tracks[0]}" / "Timeseries").glob(f"*.{p}.tif"))
)
if not nr_of_ts >= 1:
continue
outfiles = []
for i in range(1, nr_of_ts + 1):
filelist = list(processing_dir.glob(f"*/Timeseries/{i:02d}.*.{p}.tif"))
filelist = [str(file) for file in filelist if "Mosaic" not in str(file)]
# create
datelist = []
for file in filelist:
datelist.append(Path(file).name.split(".")[1])
filelist = " ".join(filelist)
start, end = sorted(datelist)[0], sorted(datelist)[-1]
if start == end:
outfile = ts_dir / f"{i:02d}.{start}.bs.{p}.tif"
else:
outfile = ts_dir / f"{i:02d}.{start}-{end}.bs.{p}.tif"
check_file = outfile.parent / f".{outfile.stem}.processed"
outfiles.append(outfile)
if check_file.exists():
logger.info(f"Mosaic layer {outfile.name} already processed.")
continue
logger.info(f"Mosaicking layer {outfile.name}.")
iter_list.append([filelist, outfile, config_file])
vrt_iter_list.append([ts_dir, p, outfiles])
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
# run mosaicking
for task in executor.as_completed(func=mosaic.gd_mosaic, iterable=iter_list):
task.result()
# run mosaicking vrts
for task in executor.as_completed(
func=mosaic.create_timeseries_mosaic_vrt, iterable=vrt_iter_list
):
task.result()
def mosaic_timescan(config_file):
# load ard parameters
with open(config_file, "r") as ard_file:
config_dict = json.load(ard_file)
processing_dir = Path(config_dict["processing_dir"])
metrics = config_dict["processing"]["time-scan_ARD"]["metrics"]
if "harmonics" in metrics:
metrics.remove("harmonics")
metrics.extend(["amplitude", "phase", "residuals"])
if "percentiles" in metrics:
metrics.remove("percentiles")
metrics.extend(["p95", "p5"])
# create out directory of not existent
tscan_dir = processing_dir / "Mosaic" / "Timescan"
tscan_dir.mkdir(parents=True, exist_ok=True)
# loop through all pontial proucts
iter_list = []
for polar, metric in itertools.product(["VV", "HH", "VH", "HV"], metrics):
# create a list of files based on polarisation and metric
filelist = list(processing_dir.glob(f"*/Timescan/*bs.{polar}.{metric}.tif"))
# break loop if there are no files
if not len(filelist) >= 2:
continue
# get number
filelist = " ".join([str(file) for file in filelist])
outfile = tscan_dir / f"bs.{polar}.{metric}.tif"
check_file = outfile.parent / f".{outfile.stem}.processed"
if check_file.exists():
logger.info(f"Mosaic layer {outfile.name} already processed.")
continue
iter_list.append([filelist, outfile, config_file])
# now we run with godale, which works also with 1 worker
executor = Executor(
executor=config_dict["executor_type"], max_workers=config_dict["max_workers"]
)
# run mosaicking
for task in executor.as_completed(func=mosaic.gd_mosaic, iterable=iter_list):
task.result()
ras.create_tscan_vrt(tscan_dir, config_file)
| 31.307087 | 88 | 0.624748 |
c6139dd399bbdb223942cf94ed2fa055cff41779 | 41,031 | lua | Lua | scripts/flax_auto.lua | Rune-Christensen/Automato-ATITD | 5b156f48294f19c6b1432664850627294aefeb54 | [
"MIT"
] | 1 | 2021-04-09T19:01:54.000Z | 2021-04-09T19:01:54.000Z | scripts/flax_auto.lua | Bemazed/Automato-ATITD | 3380bfe28128d3aead93813632c2984f12004fc1 | [
"MIT"
] | null | null | null | scripts/flax_auto.lua | Bemazed/Automato-ATITD | 3380bfe28128d3aead93813632c2984f12004fc1 | [
"MIT"
] | null | null | null | -- flax_auto.lua v1.2 -- by Jimbly, tweaked by Cegaiel and
-- KasumiGhia, revised by Tallow, revised by Tripps
--
-- Plant and harvest seeds then plant and harvest flax, repeat
-- Draws water when needed, optionally rots flax, optionally
-- stores products
--
-- Works Reliably: 2x2, 3x3, 4x4, 5x5
-- May Work (depends on your computer): 6x6, 7x7
--
dofile("ui_utils.inc");
dofile("common.inc");
dofile("settings.inc");
dofile("constants.inc");
dofile("screen_reader_common.inc");
askText = singleLine([[
flax_auto v1.0 (by Jimbly, tweaked by Cegaiel and KasumiGhia,
revised by Tallow, revised by Tripps) --
Make sure the plant flax window is pinned and on the RIGHT side of
the screen. Your Automato window should also be on the RIGHT side
of the screen. You may need to F12 at low resolutions or hide your
chat window (if it starts planting and fails to move, it probably
clicked on your chat window). Will plant grid NE of current
location. Will turn on 'Plant all crops where you stand' and 'Right
click pins/unpins a menu'. Will turn off 'Enable Hotkeys on flax'.
]]);
-- Global parameters set by prompt box.
num_loops = 5;
grid_w = 5;
grid_h = 5;
grid_direction = 1;
grid_directions = { "Northeast", "Northwest", "Southeast", "Southwest" };
grid_deltas =
{
{ {1, 0, -1, 0}, {0, -1, 0, 1} },
{ {-1, 0, 1, 0}, {0, -1, 0, 1} },
{ {1, 0, -1, 0}, {0, 1, 0, -1} },
{ {-1, 0, 1, 0}, {0, 1, 0, -1} }
};
min_seeds = 0;
is_plant = true;
seeds_per_pass = 4;
seeds_per_harvest = 1;
rot_flax = false;
water_needed = false;
water_location = {};
water_location[0] = 0;
water_location[1] = 0;
store_flax = false;
storage_location = {};
storage_location[0] = 0;
storage_location[1] = 0;
-- How many seeds are left
seeds_in_pocket = 26;
imgFlax1 = "Flax:";
imgHarvest = "HarvestThisFlax.png";
imgWeedAndWater = "WeedAndWater.png";
imgWeed = "WeedThisFlaxBed.png";
imgSeeds = "HarvestSeeds.png";
imgUseable = "UseableBy.png";
imgThisIs = "ThisIs.png";
imgUtility = "Utility.png";
imgRipOut = "RipOut.png";
imgUnpin = "UnPin.png";
imgTheSeeds = "TheSeeds.png";
imgOK = "ok.png";
imgTearDownThis = "TearDownThis.png";
imgTearDown = "TearDown.png";
imgPlantWhereChecked = "PlantAllCropsWhereYouStandChecked.png";
imgPlantWhereUnchecked = "PlantAllCropsWhereYouStandUnchecked.png";
imgHotkeysOnFlax = "EnableHotkeysOnFlax.png";
imgOptionsX = "OptionsX.png";
imgRightClickPins = "RightClickPins.png";
imgSmallX = "smallX.png";
-- Tweakable delay values
refresh_time = 300; -- Time to wait for windows to update
walk_time = 300;
-- Don't touch. These are set according to Jimbly's black magic.
walk_px_y = 340;
walk_px_x = 380;
xyCenter = {};
xyFlaxMenu = {};
-- The flax bed window
window_w = 174;
window_h = 100;
harvest_seeds_time = 1300;
FLAX = 0;
ONIONS = 1;
plantType = FLAX;
--warehouse_color = -1769769985;
--chest_color = 2036219647;
--tent_color = 1399546879;
-------------------------------------------------------------------------------
-- initGlobals()
--
-- Set up black magic values used for trying to walk a standard grid.
-------------------------------------------------------------------------------
function initGlobals()
-- Macro written with 1720 pixel wide window
srReadScreen();
xyWindowSize = srGetWindowSize();
local pixel_scale = xyWindowSize[0] / 1720;
lsPrintln("pixel_scale " .. pixel_scale);
walk_px_y = math.floor(walk_px_y * pixel_scale);
walk_px_x = math.floor(walk_px_x * pixel_scale);
local walk_x_drift = 14;
local walk_y_drift = 18;
if (lsScreenX < 1280) then
-- Have to click way off center in order to not move at high resolutions
walk_x_drift = math.floor(walk_x_drift * pixel_scale);
walk_y_drift = math.floor(walk_y_drift * pixel_scale);
else
-- Very little drift at these resolutions, clicking dead center barely moves
walk_x_drift = 1;
walk_y_drift = 1;
end
xyCenter[0] = xyWindowSize[0] / 2 - walk_x_drift;
xyCenter[1] = xyWindowSize[1] / 2 + walk_y_drift;
if plantType == FLAX then
xyFlaxMenu[0] = xyCenter[0] - 43*pixel_scale;
xyFlaxMenu[1] = xyCenter[1] + 0;
else
xyFlaxMenu[0] = xyCenter[0] - 20;
xyFlaxMenu[1] = xyCenter[1] - 10;
end
end
-------------------------------------------------------------------------------
-- checkForEnd()
--
-- Similar to checkBreak, but also looks for a clean exit.
-------------------------------------------------------------------------------
local ending = false;
function checkForEnd()
if ((lsAltHeld() and lsControlHeld()) and not ending) then
ending = true;
setStatus("");
cleanup();
error "broke out with Alt+Ctrl";
end
if (lsShiftHeld() and lsControlHeld()) then
if lsMessageBox("Break", "Are you sure you want to exit?", MB_YES + MB_NO) == MB_YES then
error "broke out with Shift+Ctrl";
end
end
if lsAltHeld() and lsShiftHeld() then
-- Pause
while lsAltHeld() or lsShiftHeld() do
statusScreen("Please release Alt+Shift", 0x808080ff, false);
end
local done = false;
while not done do
local unpaused = lsButtonText(lsScreenX - 110, lsScreenY - 60,
z, 100, 0xFFFFFFff, "Unpause");
statusScreen("Hold Alt+Shift to resume", 0xFFFFFFff, false);
done = (unpaused or (lsAltHeld() and lsShiftHeld()));
end
while lsAltHeld() or lsShiftHeld() do
statusScreen("Please release Alt+Shift", 0x808080ff, false);
end
end
end
-------------------------------------------------------------------------------
-- checkWindowSize()
--
-- Set width and height of flax window based on whether they are guilded.
-------------------------------------------------------------------------------
window_check_done_once = false;
function checkWindowSize(x, y)
if not window_check_done_once then
srReadScreen();
window_check_done_once = true;
local pos = srFindImageInRange(imgUseable, x-5, y-50, 150, 100)
if pos then
window_w = 166;
window_h = 116;
end
end
end
-------------------------------------------------------------------------------
-- promptFlaxNumbers()
--
-- Gather user-settable parameters before beginning
-------------------------------------------------------------------------------
function promptFlaxNumbers()
scale = 1.1;
local z = 0;
local is_done = nil;
local value = nil;
-- Edit box and text display
while not is_done do
-- Make sure we don't lock up with no easy way to escape!
checkBreak();
local y = 5;
lsSetCamera(0,0,lsScreenX*scale,lsScreenY*scale);
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Passes:");
num_loops = readSetting("num_loops",num_loops);
is_done, num_loops = lsEditBox("passes", 110, y, z, 50, 30, scale, scale,
0x000000ff, num_loops);
if not tonumber(num_loops) then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
num_loops = 1;
end
writeSetting("num_loops",num_loops);
y = y + 32;
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Grid size:");
grid_w = readSetting("grid_w",grid_w);
is_done, grid_w = lsEditBox("grid", 110, y, z, 50, 30, scale, scale,
0x000000ff, grid_w);
if not tonumber(grid_w) then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
grid_w = 1;
grid_h = 1;
end
grid_w = tonumber(grid_w);
grid_h = grid_w;
writeSetting("grid_w",grid_w);
y = y + 32;
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Plant to the:");
grid_direction = readSetting("grid_direction",grid_direction);
grid_direction = lsDropdown("grid_direction", 145, y, 0, 145, grid_direction, grid_directions);
writeSetting("grid_direction",grid_direction);
y = y + 32;
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Seed harvests per bed:");
seeds_per_pass = readSetting("seeds_per_pass",seeds_per_pass);
is_done, seeds_per_pass = lsEditBox("seedsper", 250, y, z, 50, 30,
scale, scale, 0x000000ff, seeds_per_pass);
seeds_per_pass = tonumber(seeds_per_pass);
if not seeds_per_pass then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
seeds_per_pass = 1;
end
writeSetting("seeds_per_pass",seeds_per_pass);
y = y + 32;
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Seeds per harvest:");
seeds_per_harvest = readSetting("seeds_per_harvest",seeds_per_harvest);
is_done, seeds_per_harvest = lsEditBox("seedsperharvest", 250, y, z, 50, 30,
scale, scale, 0x000000ff, seeds_per_harvest);
seeds_per_harvest = tonumber(seeds_per_harvest);
if not seeds_per_harvest then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
seeds_per_harvest = 1;
end
writeSetting("seeds_per_harvest",seeds_per_harvest);
y = y + 32;
rot_flax = readSetting("rot_flax",rot_flax);
rot_flax = lsCheckBox(10, y, z+10, 0xFFFFFFff, "Rot Flax", rot_flax);
writeSetting("rot_flax",rot_flax);
y = y + 32;
water_needed = readSetting("water_needed",water_needed);
water_needed = lsCheckBox(10, y, z+10, 0xFFFFFFff, "Flax requires water", water_needed);
writeSetting("water_needed",water_needed);
y = y + 32;
if rot_flax or water_needed then
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Water coords:");
water_location[0] = readSetting("water_locationX",water_location[0]);
is_done, water_location[0] = lsEditBox("water_locationX", 165, y, z, 55, 30,
scale, scale, 0x000000ff, water_location[0]);
water_location[0] = tonumber(water_location[0]);
if not water_location[0] then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
water_location[0] = 1;
end
writeSetting("water_locationX",water_location[0]);
water_location[1] = readSetting("water_locationY",water_location[1]);
is_done, water_location[1] = lsEditBox("water_locationY", 222, y, z, 55, 30,
scale, scale, 0x000000ff, water_location[1]);
water_location[1] = tonumber(water_location[1]);
if not water_location[1] then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
water_location[1] = 1;
end
writeSetting("water_locationY",water_location[1]);
y = y + 32;
end
store_flax = readSetting("store_flax",store_flax);
store_flax = lsCheckBox(10, y, z+10, 0xFFFFFFff, "Store Flax", store_flax);
writeSetting("store_flax",store_flax);
y = y + 32;
if store_flax then
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "Storage coords:");
storage_location[0] = readSetting("storage_locationX",storage_location[0]);
is_done, storage_location[0] = lsEditBox("storage_locationX", 185, y, z, 55, 30,
scale, scale, 0x000000ff, storage_location[0]);
storage_location[0] = tonumber(storage_location[0]);
if not storage_location[0] then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
storage_location[0] = 1;
end
writeSetting("storage_locationX",storage_location[0]);
storage_location[1] = readSetting("storage_locationY",storage_location[1]);
is_done, storage_location[1] = lsEditBox("storage_locationY", 242, y, z, 55, 30,
scale, scale, 0x000000ff, storage_location[1]);
storage_location[1] = tonumber(storage_location[1]);
if not storage_location[1] then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
storage_location[1] = 1;
end
writeSetting("storage_locationY",storage_location[1]);
y = y + 32 + 5;
end
if lsButtonText(10, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "OK") then
is_done = 1;
end
if lsButtonText((lsScreenX - 100) * scale, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff,
"End script") then
error "Clicked End Script button";
end
if is_done and (not num_loops or not grid_w) then
error 'Canceled';
end
lsDoFrame();
lsSleep(tick_delay);
end
min_seeds = grid_w*grid_h+1;
end
------------------------------------------------------------------------------
-- promptSeeds()
-------------------------------------------------------------------------------
function promptSeeds()
scale = 1.1;
local z = 0;
local is_done = nil;
local value = nil;
-- Edit box and text display
while not is_done do
-- Make sure we don't lock up with no easy way to escape!
checkBreak();
local y = 5;
lsSetCamera(0,0,lsScreenX*scale,lsScreenY*scale);
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "How many seeds are you");
y = y + 32;
lsPrint(5, y, z, scale, scale, 0xFFFFFFff, "starting with (minimum " .. min_seeds .. ")?");
y = y + 32;
seeds_in_pocket = readSetting("seeds_in_pocket",seeds_in_pocket);
is_done, seeds_in_pocket = lsEditBox("seeds_in_pocket", 110, y, z, 50, 30, scale, scale,
0x000000ff, seeds_in_pocket);
seeds_in_pocket = tonumber(seeds_in_pocket);
if not seeds_in_pocket then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE A NUMBER");
seeds_in_pocket = min_seeds;
elseif seeds_in_pocket < min_seeds then
is_done = nil;
lsPrint(10, y+18, z+10, 0.7, 0.7, 0xFF2020ff, "MUST BE AT LEAST " .. min_seeds);
seeds_in_pocket = min_seeds;
end
writeSetting("seeds_in_pocket",seeds_in_pocket);
y = y + 32;
y = y + 32;
lsPrintWrapped(5, y, z, lsScreenX - 10, scale, scale, 0xD0D0D0ff,
"This macro will grow seeds as needed. Any extra seeds beyond the " ..
min_seeds .. " minimum will be used before growing more seeds.");
y = y + 128;
if lsButtonText(10, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "OK") then
is_done = 1;
end
if lsButtonText((lsScreenX - 100) * scale, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff,
"End script") then
error "Clicked End Script button";
end
lsDoFrame();
lsSleep(tick_delay);
end
end
------------------------------------------------------------------------------
-- getPlantWindowPos()
-------------------------------------------------------------------------------
lastPlantPos = null;
seedImage = imgFlax1;
function getPlantWindowPos()
srReadScreen();
local plantPos = findText(seedImage);
if plantPos then
plantPos[0] = plantPos[0] + 10;
else
plantPos = lastPlantPos;
if plantPos then
safeClick(plantPos[0], plantPos[1]);
lsSleep(refresh_time);
end
end
if not plantPos then
error 'Could not find plant window';
end
lastPlantPos = plantPos;
return plantPos;
end
-------------------------------------------------------------------------------
-- getToggle()
--
-- Returns 0 or 2 alternately. Used to slightly shift position of windows
-- while collecting them.
-------------------------------------------------------------------------------
toggleBit = 0;
function getToggle()
if toggleBit == 0 then
toggleBit = 2;
else
toggleBit = 0;
end
return toggleBit;
end
-------------------------------------------------------------------------------
-- setStatus(msg)
--
-- Use this to set the current status so that the instructions remain on the
-- screen.
-------------------------------------------------------------------------------
function setStatus(message)
if not message then
message = "";
end
local color = 0xFFFFFFff;
local allow_break = true;
lsPrintWrapped(10, 80, 0, lsScreenX - 20, 0.8, 0.8, color, message);
lsPrintWrapped(10, lsScreenY-100, 0, lsScreenX - 20, 0.8, 0.8, 0xffd0d0ff,
error_status);
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100,
0xFFFFFFff, "End script") then
error(quit_message);
end
if allow_break then
lsPrint(10, 10, 0, 0.7, 0.7, 0xB0B0B0ff,
"Hold Ctrl+Alt to cleanup and end.");
lsPrint(10, 24, 0, 0.7, 0.7, 0xB0B0B0ff,
"Hold Ctrl+Shift to end this script.");
if allow_pause then
lsPrint(10, 38, 0, 0.7, 0.7, 0xB0B0B0ff,
"Hold Alt+Shift to pause this script.");
end
checkForEnd();
end
lsSleep(tick_delay);
lsDoFrame();
end
-------------------------------------------------------------------------------
-- doit()
-------------------------------------------------------------------------------
function doit()
promptFlaxNumbers();
promptSeeds();
if water_needed then
if not promptOkay("Make sure you have enough water in jugs to grow " ..
(grid_w*grid_h) .. " flax beds and make sure the plant menu is pinned.") then
error("User pressed cancel.");
end
else
if not promptOkay("Make sure the plant menu is pinned.") then
error("User pressed cancel.");
end
end
askForWindow(askText);
initGlobals();
local startPos = findCoords();
if not startPos then
error("ATITD clock not found.\Verify entire clock and borders are visible. Try moving clock slightly.");
end
local tops = findAllImages(imgThisIs);
if #tops > 0 then
error("Only the Plant menu should be pinned.");
end
getPlantWindowPos();
prepareOptions();
prepareCamera();
drawWater();
local beds_per_loop = grid_w*grid_h;
for loop_count=1, num_loops do
is_plant = (seeds_in_pocket >= min_seeds + beds_per_loop);
local planting = "false";
if is_plant then
planting = "true";
end
lsPrintln("is_plant == (" .. seeds_in_pocket .. " >= " .. min_seeds .. " + " .. beds_per_loop .. ") == " .. planting);
error_status = "";
local finalPos = plantAndPin(loop_count);
dragWindows(loop_count);
harvestAll(loop_count);
closeAllFlaxWindows();
setStatus("(" .. loop_count .. "/" .. num_loops .. ") Walking...");
if is_plant and (water_needed or rot_flax) then
lsPrintln("doit(): Walking to the water at (" .. water_location[0] .. ", " .. water_location[1] .. ")");
walk(water_location,false);
if water_needed then
drawWater();
lsSleep(150);
clickMax(); -- Sometimes drawWater() misses the max button
end
if rot_flax then
rotFlax();
end
setStatus("(" .. loop_count .. "/" .. num_loops .. ") Walking...");
end
if is_plant and store_flax then -- This should be done after rotting flax
lsPrintln("doit(): Walking to the storage location at (" .. storage_location[0] .. ", " .. storage_location[1] .. ")");
walk(storage_location,true);
storeFlax();
setStatus("(" .. loop_count .. "/" .. num_loops .. ") Walking...");
end
lsPrintln("doit(): Walking to the starting location at (" .. startPos[0] .. ", " .. startPos[1] .. ")");
walk(startPos,false);
is_plant = true;
end
lsPlaySound("Complete.wav");
end
-------------------------------------------------------------------------------
-- cleanup()
--
-- Tears out any remaining beds and unpins menus.
-------------------------------------------------------------------------------
function cleanup()
local tops = findAllImages(imgThisIs);
if #tops > 0 then
for i=1,#tops do
ripOut(tops[i]);
end
end
end
-------------------------------------------------------------------------------
-- rotFlax()
--
-- Rots flax in water. Requires you to be standing near water already.
-------------------------------------------------------------------------------
function rotFlax()
centerMouse();
local escape = "\27";
local pos = nil;
while(not pos) do
lsSleep(refresh_time);
srKeyEvent(escape);
lsSleep(refresh_time);
srReadScreen();
pos = findText("Skills...");
end
clickText(pos);
lsSleep(refresh_time);
srReadScreen();
local pos = findText("Rot flax");
if pos then
clickText(pos);
lsSleep(refresh_time);
srReadScreen();
if not clickMax() then
fatalError("Unable to find the Max button.");
end
end
end
-------------------------------------------------------------------------------
-- storeFlax()
--
-- Stores flax in a storage container such as a wharehouse, chest, or tent.
-- Requires you to be standing next to the storage container.
-- storeFlax() checks frist for a pinned menu otherwise it clicks the nearest
-- pixel of the proper color. Given the large coordinate size in Egypt,
-- positioning is not very accurate. You should only have one storage
-- container near where you are standing.
-------------------------------------------------------------------------------
function storeFlax()
setStatus("Storing flax");
local types = { "Flax (", "Rotten Flax", "Insect..." };
stash(types);
setStatus("");
end
-------------------------------------------------------------------------------
-- plantAndPin()
--
-- Walk around in a spiral, planting flax seeds and grabbing windows.
-------------------------------------------------------------------------------
function plantAndPin(loop_count)
local xyPlantFlax = getPlantWindowPos();
-- for spiral
local dxi=1;
local dt_max=grid_w;
local dt=grid_w;
-- local dx={1, 0, -1, 0};
-- local dy={0, -1, 0, 1};
local i;
local dx = {};
local dy = {};
for i=1, 4 do
dx[i] = grid_deltas[grid_direction][1][i];
dy[i] = grid_deltas[grid_direction][2][i];
end
local num_at_this_length = 3;
local x_pos = 0;
local y_pos = 0;
local success = true;
for y=1, grid_h do
for x=1, grid_w do
setStatus("(" .. loop_count .. "/" .. num_loops .. ") Planting " ..
x .. ", " .. y);
success = plantHere(xyPlantFlax, y);
if not success then
break;
end
-- Move to next position
if not ((x == grid_w) and (y == grid_h)) then
lsPrintln('walking dx=' .. dx[dxi] .. ' dy=' .. dy[dxi]);
x_pos = x_pos + dx[dxi];
y_pos = y_pos + dy[dxi];
safeClick(xyCenter[0] + walk_px_x*dx[dxi],
xyCenter[1] + walk_px_y*dy[dxi], 0);
local spot = getWaitSpot(xyFlaxMenu[0], xyFlaxMenu[1]);
lsSleep(walk_time);
waitForStasis(spot, 1500);
dt = dt - 1;
if dt == 1 then
dxi = dxi + 1;
num_at_this_length = num_at_this_length - 1;
if num_at_this_length == 0 then
dt_max = dt_max - 1;
num_at_this_length = 2;
end
if dxi == 5 then
dxi = 1;
end
dt = dt_max;
end
else
lsPrintln('skipping walking, on last leg');
end
end
checkForEnd();
if not success then
break;
end
end
local finalPos = {};
finalPos[0] = x_pos;
finalPos[1] = y_pos;
return finalPos;
end
-------------------------------------------------------------------------------
-- plantHere(xyPlantFlax)
--
-- Plant a single flax bed, get the window, pin it, then stash it.
-------------------------------------------------------------------------------
function plantHere(xyPlantFlax, y_pos)
-- Plant
lsPrintln('planting ' .. xyPlantFlax[0] .. ',' .. xyPlantFlax[1]);
local bed = clickPlant(xyPlantFlax);
if not bed then
return false;
end
-- Bring up menu
lsPrintln('menu ' .. bed[0] .. ',' .. bed[1]);
if not openAndPin(bed[0], bed[1], 3500) then
error_status = "No window came up after planting.";
seeds_in_pocket = 0;
return false;
end
-- if plantType == ONIONS then
-- lsPrintln("Onions");
-- lsSleep(200);
-- srReadScreen();
-- local waters = findAllImages("WaterThese.png");
-- for i = 1,#waters do
-- lsPrintln("Water");
-- safeClick(waters[i][0]+5, waters[i][1]+5);
-- end
-- sleepWithStatus(1000, "First Water");
-- end
-- Check for window size
checkWindowSize(bed[0], bed[1]);
-- Move window into corner
stashWindow(bed[0] + 5, bed[1], BOTTOM_RIGHT);
return true;
end
function clickPlant(xyPlantFlax)
local result = xyFlaxMenu;
local spot = getWaitSpot(xyFlaxMenu[0], xyFlaxMenu[1]);
safeClick(xyPlantFlax[0], xyPlantFlax[1], 0);
lsSleep(click_delay);
local plantSuccess = waitForChange(spot, 1500);
if not plantSuccess then
error_status = "No flax bed was placed when planting.";
result = nil;
end
seeds_in_pocket = seeds_in_pocket - 1;
return result;
end
-------------------------------------------------------------------------------
-- dragWindows(loop_count)
--
-- Move flax windows into a grid on the screen.
-------------------------------------------------------------------------------
function dragWindows(loop_count)
setStatus("(" .. loop_count .. "/" .. num_loops .. ") " ..
"Dragging Windows into Grid");
arrangeStashed();
end
-------------------------------------------------------------------------------
-- harvestAll(loop_count)
--
-- Harvest all the flax or seeds and clean up the windows afterwards.
-------------------------------------------------------------------------------
function harvestAll(loop_count)
local did_harvest = false;
local harvestLeft = 0;
local seedIndex = 1;
local seedWave = 1;
local lastTops = {};
local tops = findAllImages(imgThisIs);
local max = #tops;
while not did_harvest do
-- Monitor for Weed This/etc
lsSleep(refresh_time);
srReadScreen();
tops = findAllImages(imgThisIs);
for i=1,#tops do
safeClick(tops[i][0], tops[i][1]);
lsSleep(click_delay);
end
if is_plant then
harvestLeft = #tops;
else
harvestLeft = (#tops - seedIndex) + 1 +
(#tops * (seeds_per_pass - seedWave));
end
setStatus("(" .. loop_count .. "/" .. num_loops ..
") Harvests Left: " .. harvestLeft);
lsSleep(refresh_time);
srReadScreen();
if is_plant then
local weeds = findAllImages(imgWeed);
for i=1,#weeds do
safeClick(weeds[i][0], weeds[i][1]);
end
local waters = findAllImages(imgWeedAndWater);
for i=1,#waters do
safeClick(waters[i][0], waters[i][1]);
end
local harvests = findAllImages(imgHarvest);
for i=1,#harvests do
safeClick(harvests[i][0], harvests[i][1]);
lsSleep(refresh_time);
safeClick(harvests[i][0], harvests[i][1] - 15, 1);
end
local seeds = findAllImages(imgSeeds);
for i=1,#seeds do
local seedTop = srFindImageInRange(imgThisIs,
seeds[i][0] - 10, seeds[i][1]-window_h,
window_w, window_h, 5000);
if seedTop then
ripOut(seedTop);
end
end
else
srReadScreen();
local oks = srFindImage(imgOK,5000);
while oks do
safeClick(oks[0],oks[1]);
lsSleep(100);
oks = srFindImage(imgOK);
end
local tops = findAllImages(imgThisIs);
if #tops > 0 then
if seedIndex > #tops then
seedIndex = 1;
seedWave = seedWave + 1;
end
local seedPos = srFindImageInRange(imgSeeds,
tops[#tops - seedIndex + 1][0],
tops[#tops - seedIndex + 1][1],
160, 100);
if seedPos and seedWave <= seeds_per_pass then
local harvested = false;
local lastClick = 0;
while not harvested do
if seedPos and lsGetTimer() > lastClick + 1500 then
safeClick(seedPos[0] + 5, seedPos[1]);
lastClick = lsGetTimer();
lsSleep(100);
end
safeClick(tops[#tops - seedIndex + 1][0],
tops[#tops - seedIndex + 1][1]);
lsSleep(100);
srReadScreen();
seedPos = srFindImageInRange(imgTheSeeds,
tops[#tops - seedIndex + 1][0],
tops[#tops - seedIndex + 1][1],
160, 100);
if seedPos then
harvested = true;
else
seedPos = srFindImageInRange(imgSeeds,
tops[#tops - seedIndex + 1][0],
tops[#tops - seedIndex + 1][1],
160, 100);
end
checkForEnd();
end
seedIndex = seedIndex + 1;
seeds_in_pocket = seeds_in_pocket + seeds_per_harvest;
end
end
if seedWave > seeds_per_pass then
local seeds = findAllImages(imgThisIs);
for i=1,#seeds do
ripOut(seeds[i]);
end
end
end
if #tops <= 0 then
did_harvest = true;
end
checkForEnd();
end
-- Wait for last flax bed to disappear
sleepWithStatus(2500, "(" .. loop_count .. "/" .. num_loops ..
") ... Waiting for flax beds to disappear");
end
-------------------------------------------------------------------------------
-- walkHome(loop_count, finalPos)
--
-- Walk back to the origin (southwest corner) to start planting again.
-------------------------------------------------------------------------------
function walkHome(loop_count, finalPos)
closeAllFlaxWindows();
setStatus("(" .. loop_count .. "/" .. num_loops .. ") Walking...");
walk(finalPos,false);
-- Walk back
-- for x=1, finalPos[0] do
-- local spot = getWaitSpot(xyCenter[0] - walk_px_x, xyCenter[1]);
-- safeClick(xyCenter[0] - walk_px_x, xyCenter[1], 0);
-- lsSleep(walk_time);
-- waitForStasis(spot, 1000);
-- end
-- for x=1, -(finalPos[1]) do
-- local spot = getWaitSpot(xyCenter[0], xyCenter[1] + walk_px_y);
-- safeClick(xyCenter[0], xyCenter[1] + walk_px_y, 0);
-- lsSleep(walk_time);
-- waitForStasis(spot, 1000);
-- end
end
-------------------------------------------------------------------------------
-- ripOut(pos)
--
-- Use the Utility menu to rip out a flax bed that has gone to seed.
-- pos should be the screen position of the 'This Is' text on the window.
-------------------------------------------------------------------------------
function ripOut(pos)
setStatus("Ripping Out");
lsSleep(refresh_time);
srReadScreen();
local util_menu = srFindImageInRange(imgUtility, pos[0] - 10, pos[1] - 50,
180, 200, 5000);
if util_menu then
safeClick(util_menu[0] + 5, util_menu[1], 0);
local rip_out = waitForImage(imgRipOut, refresh_time);
if rip_out then
safeClick(rip_out[0] + 5, rip_out[1], 0);
lsSleep(refresh_time);
safeClick(pos[0], pos[1], 1); -- unpin
lsSleep(refresh_time);
else
rip_out = srFindImage(imgTearDownThis);
if rip_out then
safeClick(rip_out[0] + 5, rip_out[1], 0);
lsSleep(refresh_time);
srReadScreen();
rip_out = nil;
while not rip_out do
checkBreak();
rip_out = srFindImage(imgTearDown);
if rip_out then
safeClick(rip_out[0], rip_out[1]);
end
lsSleep(refresh_time);
srReadScreen();
end
end
safeClick(pos[0],pos[1],true);
lsSleep(refresh_time);
srReadScreen();
end
end
end
-------------------------------------------------------------------------------
-- walk(dest,abortOnError)
--
-- Walk to dest while checking for menus caused by clicking on objects.
-- Returns true if you have arrived at dest.
-- If walking around brings up a menu, the menu will be dismissed.
-- If abortOnError is true and walking around brings up a menu,
-- the function will return. If abortOnError is false, the function will
-- attempt to move around a little randomly to get around whatever is in the
-- way.
-------------------------------------------------------------------------------
function walk(dest,abortOnError)
centerMouse();
srReadScreen();
local coords = findCoords();
local startPos = coords;
local failures = 0;
while coords[0] ~= dest[0] or coords[1] ~= dest[1] do
centerMouse();
local dx = 0;
local dy = 0;
if coords[0] < dest[0] then
dx = 1;
elseif coords[0] > dest[0] then
dx = -1;
end
if coords[1] < dest[1] then
dy = -1;
elseif coords[1] > dest[1] then
dy = 1;
end
lsPrintln("Walking from (" .. coords[0] .. "," .. coords[1] .. ") to (" .. dest[0] .. "," ..dest[1] .. ") stepping to (" .. dx .. "," .. dy .. ")");
stepTo(makePoint(dx, dy));
srReadScreen();
coords = findCoords();
checkForEnd();
if checkForMenu() then
if(coords[0] == dest[0] and coords[1] == dest[1]) then
return true;
end
if abortOnError then
return false;
end
failures = failures + 1;
if failures > 50 then
return false;
end
lsPrintln("Hit a menu, moving randomly");
stepTo(makePoint(math.random(-1,1),math.random(-1,1)));
srReadScreen();
else
failures = 0;
end
end
return true;
end
function walkOld(dest,abortOnError)
centerMouse();
local coords = findCoords();
local startPos = coords;
local failures = 0;
srReadScreen();
while coords[0] ~= dest[0] or coords[1] ~= dest[1] do
while coords[0] < dest[0] do
centerMouse();
stepTo(makePoint(1, 0));
coords = findCoords();
checkForEnd();
if checkForMenu() then
if abortOnError then
return false;
end
failures = failures + 1;
if failures > 50 then
return false;
end
stepTo(makePoint(math.random(-1,0),math.random(-1,1)));
else
failures = 0;
end
end
while coords[0] > dest[0] do
centerMouse();
stepTo(makePoint(-1, 0));
coords = findCoords();
checkForEnd();
if checkForMenu() then
if abortOnError then
return false;
end
failures = failures + 1;
if failures > 50 then
return false;
end
stepTo(makePoint(math.random(0,1),math.random(-1,1)));
else
failures = 0;
end
end
while coords[1] < dest[1] do
centerMouse();
stepTo(makePoint(0, -1));
coords = findCoords();
checkForEnd();
if checkForMenu() then
if abortOnError then
return false;
end
failures = failures + 1;
if failures > 50 then
return false;
end
stepTo(makePoint(math.random(-1,1),math.random(0,1)));
else
failures = 0;
end
end
while coords[1] > dest[1] do
centerMouse();
stepTo(makePoint(0, 1));
coords = findCoords();
checkForEnd();
if checkForMenu() then
if abortOnError then
return false;
end
failures = failures + 1;
if failures > 50 then
return false;
end
stepTo(makePoint(math.random(-1,1),math.random(-1,0)));
else
failures = 0;
end
end
end
return true;
end
function checkForMenu()
srReadScreen();
pos = srFindImage("unpinnedPin.png", 5000);
if pos then
safeClick(pos[0]-5,pos[1]);
lsPrintln("checkForMenu(): Found a menu...returning true");
return true;
end
return false;
end
-------------------------------------------------------------------------------
-- pixelBlockCheck(x, y, color, rgbTol, hueTol, size)
--
-- Checks for a block of pixels centered on (x, y), within radius size
-- matching color within the tolerances rgbTol and hueTol
-------------------------------------------------------------------------------
function pixelBlockCheck(x, y, color, rgbTol, hueTol, size)
local startX = x - size;
local startY = y - size;
local endX = x + size;
local endY = y + size;
local i;
for i = startX, endX do
local j;
for j = startY, endY do
local currColor = srReadPixelFromBuffer(x, y);
if(not compareColorEx(color,currColor,rgbTol,hueTol)) then
return false;
end
end
end
return true;
end
-------------------------------------------------------------------------------
-- clickMax()
--
-- Waits for and then click the Max button
-------------------------------------------------------------------------------
function clickMax()
local pos = srFindImage("crem-max.png", 1000);
if pos then
safeClick(pos[0]+5, pos[1]+5);
return true;
end
return false;
end
-------------------------------------------------------------------------------
-- centerMouse()
--
-- Moves the mouse to the center of the screen
-------------------------------------------------------------------------------
function centerMouse()
local xyWindowSize = srGetWindowSize();
local mid = {};
mid[0] = xyWindowSize[0] / 2;
mid[1] = xyWindowSize[1] / 2;
srSetMousePos(mid[0],mid[1]);
end
function prepareCamera()
statusScreen("Configuring camera");
characterMenu();
local pos = findText("Options...");
if(pos) then
offsetClick(pos,8);
lsSleep(100);
pos = findText("Camera");
if(pos) then
offsetClick(pos,8);
lsSleep(100);
pos = findText("Cartographer's Cam");
if(pos) then
offsetClick(pos,8);
lsSleep(100);
pos = srFindImage("ok-faint.png");
if(pos) then
offsetClick(pos);
else
error("Unable to find the Ok button.");
end
else
error("Unable to find the Cartographer's Cam item.");
end
else
error("Unable to find the Camera menu item.");
end
else
error("Unable to find the Options menu item.");
end
lsSleep(150);
srReadScreen();
pos = findText("Year");
if(pos) then
offsetClick(pos);
else
-- error("Unable to find the clock.");
end
srSetMousePos(100,-20);
sleepWithStatus(10000,"Zooming in");
statusScreen("");
end
function prepareOptions()
statusScreen("Checking and setting avatar options");
characterMenu();
local pos = findText("Options...");
if(pos) then
offsetClick(pos,8);
lsSleep(100);
pos = findText("One-Click");
if(pos) then
offsetClick(pos,8);
lsSleep(100);
pos = srFindImage(imgPlantWhereChecked,5000);
if(not pos) then
pos = srFindImage(imgPlantWhereUnchecked,5000);
if(pos) then
offsetClick(pos,4);
end
end
pos = srFindImage(imgHotkeysOnFlax,5000);
if(pos) then
offsetClick(pos,4);
lsSleep(100);
end
pos = srFindImage(imgOptionsX,5000);
if(pos) then
srClickMouse(pos[0]+24,pos[1]+9); -- close options window
lsSleep(500);
srReadScreen();
end
end
end
characterMenu();
local pos = findText("Options...");
if(pos) then
offsetClick(pos,8);
pos = findText("Interface Options");
if(pos) then
offsetClick(pos,8);
pos = srFindImage(imgRightClickPins,5000);
if(pos) then
offsetClick(pos,4);
end
end
pos = srFindImage(imgSmallX,5000);
if(pos) then
offsetClick(pos,4);
end
end
statusScreen("");
end
function offsetClick(pos,offset)
if(offset == nil) then
offset = 4;
end
srClickMouse(pos[0]+offset,pos[1]+offset);
lsSleep(150);
srReadScreen();
end
function characterMenu()
centerMouse();
lsSleep(150);
local escape = "\27";
srKeyEvent(escape);
lsSleep(150);
srReadScreen();
end
-------------------------------------------------------------------------------
-- closeAllFlaxWindows()
--
-- Close all open flax windows and many others, but not the plant window.
--
-------------------------------------------------------------------------------
function closeAllFlaxWindows()
x = 0;
y = 0;
width = srGetWindowSize()[0];
height = srGetWindowSize()[1];
local closeImages = {"ThisIs.png", "Ok.png"};
local closeRight = {1, 1, nil};
local found = true;
while found do
found = false;
for i=1,#closeImages do
local image = closeImages[i];
local right = closeRight[i];
srReadScreen();
local images = findAllImagesInRange(image, x, y, width, height);
while #images >= 1 do
done = true;
safeClick(images[#images][0], images[#images][1], right);
sleepWithStatus(200, "Closing Windows");
srReadScreen();
images = findAllImagesInRange(image, x, y, width, height);
end
end
end
safeClick(width/2-45,height/2-45);
end
| 30.438427 | 152 | 0.554215 |
2a1887f45fadc5146c79d80355d11b44f1727198 | 347 | java | Java | design-patterns/src/main/java/pattern/behavioral/template/course/BigDataCourse.java | leishiguang/design-patterns | 052e0a8d81967ea15d4427fbed770ebedab152d6 | [
"MIT"
] | 1 | 2019-03-27T01:04:54.000Z | 2019-03-27T01:04:54.000Z | design-patterns/src/main/java/pattern/behavioral/template/course/BigDataCourse.java | LeiShiGuang/HeadFirstDesignPatterns | 052e0a8d81967ea15d4427fbed770ebedab152d6 | [
"MIT"
] | null | null | null | design-patterns/src/main/java/pattern/behavioral/template/course/BigDataCourse.java | LeiShiGuang/HeadFirstDesignPatterns | 052e0a8d81967ea15d4427fbed770ebedab152d6 | [
"MIT"
] | 2 | 2019-08-28T09:44:09.000Z | 2021-01-28T14:44:24.000Z | package pattern.behavioral.template.course;
/**
* 大数据课程
*
* @author leishiguang
* @version v1.0.0
* @since v1.0
*/
public class BigDataCourse extends BaseNetworkCourse {
@Override
void checkHomework() {
System.out.println("检查大数据课程");
}
@Override
protected boolean needHomework() {
return true;
}
}
| 15.772727 | 54 | 0.636888 |
3f876e3985a3469b995deb567999496ac5071a3b | 2,629 | kt | Kotlin | radixdlt-kotlin/src/test/kotlin/com/radixdlt/client/application/translate/TransferTokensActionTranslatorTest.kt | radixdlt/radixdlt-kotlin | 37d86b43bd5e9e5c24c85a8f2d7865b51cd24a7b | [
"MIT"
] | 7 | 2018-09-04T15:45:27.000Z | 2020-09-16T10:31:19.000Z | radixdlt-kotlin/src/test/kotlin/com/radixdlt/client/application/translate/TransferTokensActionTranslatorTest.kt | radixdlt/radixdlt-kotlin | 37d86b43bd5e9e5c24c85a8f2d7865b51cd24a7b | [
"MIT"
] | 3 | 2018-11-23T08:49:54.000Z | 2019-03-13T16:23:37.000Z | radixdlt-kotlin/src/test/kotlin/com/radixdlt/client/application/translate/TransferTokensActionTranslatorTest.kt | radixdlt/radixdlt-kotlin | 37d86b43bd5e9e5c24c85a8f2d7865b51cd24a7b | [
"MIT"
] | 2 | 2018-09-07T07:37:31.000Z | 2022-03-07T18:36:18.000Z | package com.radixdlt.client.application.translate
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import com.radixdlt.client.application.actions.TransferTokensAction
import com.radixdlt.client.application.objects.TokenTransfer
import com.radixdlt.client.assets.Asset
import com.radixdlt.client.core.RadixUniverse
import com.radixdlt.client.core.address.RadixAddress
import com.radixdlt.client.core.atoms.AbstractConsumable
import com.radixdlt.client.core.atoms.AtomBuilder
import com.radixdlt.client.core.atoms.TransactionAtom
import com.radixdlt.client.core.crypto.ECPublicKey
import com.radixdlt.client.core.ledger.ParticleStore
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import org.junit.Test
import java.util.Collections
class TransferTokensActionTranslatorTest {
@Test
fun testSendToSelfTest() {
val universe = mock<RadixUniverse>()
val particleStore = mock<ParticleStore>()
val atom = mock<TransactionAtom>()
val myKey = mock<ECPublicKey>()
val myAddress = mock<RadixAddress>()
whenever(universe.getAddressFrom(myKey)).thenReturn(myAddress)
whenever(atom.summary()).thenReturn(
Collections.singletonMap(
setOf(myKey), Collections.singletonMap(Asset.TEST.id, 0L)
)
)
val testObserver = TestObserver.create<TokenTransfer>()
val tokenTransferTranslator = TokenTransferTranslator(universe, particleStore)
tokenTransferTranslator.fromAtom(atom, mock()).subscribe(testObserver)
testObserver.assertValue { transfer -> myAddress == transfer.from && myAddress == transfer.to }
}
@Test
fun createTransactionWithNoFunds() {
val universe = mock<RadixUniverse>()
val address = mock<RadixAddress>()
val transferTranslator = TokenTransferTranslator(universe, object : ParticleStore {
override fun getConsumables(address: RadixAddress): Observable<AbstractConsumable> {
return Observable.never()
}
})
val transferTokensAction = mock<TransferTokensAction>()
whenever(transferTokensAction.subUnitAmount).thenReturn(10L)
whenever(transferTokensAction.from).thenReturn(address)
whenever(transferTokensAction.tokenClass).thenReturn(Asset.TEST)
val observer = TestObserver.create<Any>()
transferTranslator.translate(transferTokensAction, AtomBuilder()).subscribe(observer)
observer.awaitTerminalEvent()
observer.assertError(InsufficientFundsException(Asset.TEST, 0, 10))
}
}
| 41.730159 | 103 | 0.738684 |
7d94acf5f1d4ca8b378aad4e215024fcad80408c | 1,037 | swift | Swift | Tests/SwiftagramTests/Shared/Reflection/Comment.swift | beedgtl/Swiftagram | c4e87a5e2db018f8be9f40a44b8ce9b5df8e257f | [
"Apache-2.0"
] | 190 | 2020-03-10T22:28:10.000Z | 2022-03-30T21:56:03.000Z | Tests/SwiftagramTests/Shared/Reflection/Comment.swift | beedgtl/Swiftagram | c4e87a5e2db018f8be9f40a44b8ce9b5df8e257f | [
"Apache-2.0"
] | 150 | 2020-03-15T23:59:25.000Z | 2022-03-29T17:20:37.000Z | Tests/SwiftagramTests/Shared/Reflection/Comment.swift | beedgtl/Swiftagram | c4e87a5e2db018f8be9f40a44b8ce9b5df8e257f | [
"Apache-2.0"
] | 34 | 2020-04-16T13:24:51.000Z | 2022-03-16T21:25:26.000Z | //
// Comment.swift
// SwiftagramTests
//
// Created by Stefano Bertagno on 20/03/21.
//
import Foundation
import Swiftagram
extension Comment: Reflected {
/// The debug description prefix.
public static let debugDescriptionPrefix: String = ""
/// A list of to-be-reflected properties.
public static let properties: [String: PartialKeyPath<Self>] = ["text": \Self.text,
"likes": \Self.likes,
"user": \Self.user,
"identifier": \Self.identifier]
}
extension Comment.Collection: Reflected {
/// The prefix.
public static var debugDescriptionPrefix: String { "Comment." }
/// A list of to-be-reflected properties.
public static let properties: [String: PartialKeyPath<Self>] = ["comments": \Self.comments,
"error": \Self.error]
}
| 35.758621 | 99 | 0.513018 |
7a4e4aac6fc0d952ed7050738a5dfee7647d6df5 | 677 | rb | Ruby | spec/models/message_spec.rb | osaris/sp-gestion | 1c32df0c59238852330137884a757c7a551930e3 | [
"MIT"
] | 1 | 2015-02-18T22:25:30.000Z | 2015-02-18T22:25:30.000Z | spec/models/message_spec.rb | osaris/sp-gestion | 1c32df0c59238852330137884a757c7a551930e3 | [
"MIT"
] | 6 | 2016-08-02T15:08:43.000Z | 2021-09-27T21:01:20.000Z | spec/models/message_spec.rb | osaris/sp-gestion | 1c32df0c59238852330137884a757c7a551930e3 | [
"MIT"
] | 3 | 2015-02-19T01:22:35.000Z | 2018-10-07T17:51:58.000Z | require 'rails_helper'
describe Message do
it { should belong_to(:user) }
let(:message) { build(:message, :title => "test", :body => "test content", :user => build(:user)) }
describe "#read?" do
subject { message.read? }
context "and message not read" do
it { should be_falsey }
end
context "and message read" do
before { message.read! }
it { should be_truthy }
end
end
describe "#read_at" do
subject { message.read_at }
context "and message not read" do
it { should be_nil }
end
context "and message read" do
before { message.read! }
it { should_not be_nil }
end
end
end
| 15.744186 | 101 | 0.598227 |
85690b88d249ef85c767f15d6cf33be58d4d2907 | 321 | js | JavaScript | aula15/ambiente.js | jpsantoss/Js | e4951a6ac5b8aa4277ec8907448f2d55cf5aae95 | [
"MIT"
] | null | null | null | aula15/ambiente.js | jpsantoss/Js | e4951a6ac5b8aa4277ec8907448f2d55cf5aae95 | [
"MIT"
] | null | null | null | aula15/ambiente.js | jpsantoss/Js | e4951a6ac5b8aa4277ec8907448f2d55cf5aae95 | [
"MIT"
] | null | null | null | let num = [5,8,2,9,3]
num[3] = 6
num.push(7)
num.length
num.sort()
console.log(`O vetor tem ${num.length} posilções`)
console.log(`O primeiro valor do vetor é ${num[0]}`)
let pos = num.indexOf(8)
if (pos == -1 ){
console.log('O valor n foi encontrado!')
} else {
console.log(`O valor 8 está na posição ${pos}`)
}
| 22.928571 | 52 | 0.632399 |
52c8fd84db8d5b8731ab298d6010168c48a40057 | 644 | sql | SQL | queries/tournament_hint_dist_pct.sql | mracsys/ootr-stats | 564758e677483bd6aba6e3824360ee5694fc32a8 | [
"MIT"
] | 1 | 2020-09-04T03:42:57.000Z | 2020-09-04T03:42:57.000Z | queries/tournament_hint_dist_pct.sql | mracsys/ootr-stats | 564758e677483bd6aba6e3824360ee5694fc32a8 | [
"MIT"
] | null | null | null | queries/tournament_hint_dist_pct.sql | mracsys/ootr-stats | 564758e677483bd6aba6e3824360ee5694fc32a8 | [
"MIT"
] | null | null | null | SELECT ispheres.seed, ispheres.item, (CASE WHEN ispheres.sphere = 0 THEN 'Yes' WHEN obvious_areas.area IS NULL THEN 'No' ELSE 'Yes' END) AS obvious
FROM ispheres
LEFT JOIN locations ON ispheres.loc = locations.loc
LEFT JOIN obvious_areas ON (obvious_areas.area = locations.area AND obvious_areas.seed = ispheres.seed)
WHERE ispheres.item != 'Gold Skulltula Token'
AND ispheres.item != 'Time Travel'
AND ispheres.item != 'Triforce'
AND ispheres.item != 'Scarecrow Song'
AND ispheres.item != 'Skull Mask'
AND ispheres.item != 'Blue Fire'
AND ispheres.item != 'Big Poe'
AND ispheres.item != 'Sell Big Poe'
AND ispheres.item != 'Water Temple Clear' | 49.538462 | 147 | 0.754658 |
41a77c900cb743ff1192409fa16dbca51e834164 | 1,141 | h | C | TMuffin/TMuffin.h | thirty30/Muffin | 06db87761be740408457728a40d95cdc8ec05108 | [
"MIT"
] | 5 | 2019-10-06T02:41:59.000Z | 2020-10-10T13:07:26.000Z | TMuffin/TMuffin.h | thirty30/Muffin | 06db87761be740408457728a40d95cdc8ec05108 | [
"MIT"
] | null | null | null | TMuffin/TMuffin.h | thirty30/Muffin | 06db87761be740408457728a40d95cdc8ec05108 | [
"MIT"
] | null | null | null | #pragma once
#include "./CommonDefine.h"
#include "./Component/CComponentBase.h"
#include "./Utility/CGUIDMaker.h"
#include "./Utility/Utility.h"
#include "AssetsLoader/AssetsInclude.h"
#include "./Light/CLight.h"
#include "./Light/CLightManager.h"
#include "./GameObject/CGameObject.h"
#include "./GameObject/CGameObjectManager.h"
#include "./Camera/CCamera.h"
#include "./Camera/CCameraManager.h"
#include "./Graphics/CGraphicsComponent.h"
#include "./Graphics/FBO/CFBOComponent.h"
#include "./Graphics/SkyBox/CSkyBox.h"
#include "./Graphics/Stencil/CStencilComponent.h"
#include "./Physics/CPhysicsComponent.h"
#include "./Animation/CAnimation.h"
#include "./Animation/CAnimator.h"
#include "./Particle/CParticle.h"
#include "./Particle/CParticleEmitter.h"
#include "./LineTween/CLineTween.h"
#include "./LineTween/CLineTweenMove.h"
#include "./LineTween/CLineTweenScale.h"
#include "./LineTween/CLineTweenRotation.h"
#include "./LineTween/CLineTweenCurve.h"
#include "./LineTween/CLineTweenFollow.h"
#include "./Window/CWindow.h"
#include "./Engine/ExportFunction.h"
#include "./Engine/Muffin.h"
#include "./Engine/Engine.h"
| 25.931818 | 49 | 0.750219 |