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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7182702434e15a5b0b6dc7706c5df388061229d4 | 2,211 | ts | TypeScript | src/pages/profile/profile.ts | kewban/HerbyApp | a6820d9a818c2de2d8504e347c9da407cd7b39eb | [
"MIT"
] | null | null | null | src/pages/profile/profile.ts | kewban/HerbyApp | a6820d9a818c2de2d8504e347c9da407cd7b39eb | [
"MIT"
] | null | null | null | src/pages/profile/profile.ts | kewban/HerbyApp | a6820d9a818c2de2d8504e347c9da407cd7b39eb | [
"MIT"
] | null | null | null | import {Component} from "@angular/core";
import {NavController, Events, ModalController, NavParams} from "ionic-angular";
import {UserDataProvider} from "../../providers/user-data";
import {AccountEditModalPage} from "../account-edit-modal/account-edit-modal";
@Component({
selector : 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage {
user: any;
username: string;
loading: boolean = true;
type: string = 'list';
moreItem: boolean = true;
eventName: string;
profile: any = {
name : '',
username : '',
photo : null,
status : '',
galleriesTotal : 0,
followersTotal : 0,
followingsTotal: 0,
};
params = {
limit : 12,
page : 1,
privacity: 'public',
username : ''
}
constructor(public navCtrl: NavController,
public User: UserDataProvider,
public events: Events,
public navParams: NavParams,
public modalCtrl: ModalController
) {
this.username = this.navParams.get('username');
this.params.username = this.username;
this.eventName = this.username;
this.loading = true;
this.User.profile(this.username).then(profile => {
this.profile = profile;
this.loading = false;
});
setTimeout(() => this.onSelectType('list'), 1000);
}
onEditProfile() {
let modal = this.modalCtrl.create(AccountEditModalPage);
modal.present();
}
onSelectType(type: string) {
this.type = type;
this.sendParams();
}
public doInfinite(event) {
this.params.page++;
this.events.unsubscribe(this.eventName + ':complete');
this.events.subscribe(this.eventName + ':complete', () => event.complete());
this.sendParams();
}
public doRefresh(event?) {
event.complete();
this.params.page = 1;
this.sendParams();
}
private sendParams(): void {
this.events.publish(this.eventName + ':params', this.params);
}
}
| 26.011765 | 84 | 0.553143 |
861bc82b726400f141f3d49a1968a1f9c7b4acfc | 656 | java | Java | laundry-jt/laundry-common/src/main/java/com/jietu/common/entity/merchant/MerchantTopUpRules.java | yinxiaoer/jietu-laundry | 742bede1a834068edd732ac9f9fa9b7b06b4d7ba | [
"MIT"
] | 9 | 2021-11-18T06:06:26.000Z | 2022-02-25T09:09:48.000Z | laundry-jt/laundry-common/src/main/java/com/jietu/common/entity/merchant/MerchantTopUpRules.java | yinxiaoer/jietu-laundry | 742bede1a834068edd732ac9f9fa9b7b06b4d7ba | [
"MIT"
] | 1 | 2022-02-25T09:15:24.000Z | 2022-02-25T09:15:24.000Z | laundry-jt/laundry-common/src/main/java/com/jietu/common/entity/merchant/MerchantTopUpRules.java | yinxiaoer/jietu-laundry | 742bede1a834068edd732ac9f9fa9b7b06b4d7ba | [
"MIT"
] | null | null | null | package com.jietu.common.entity.merchant;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 商户充值规则
* @author: 印修河
* @date: 2019/3/30 22:22
*/
@Data
public class MerchantTopUpRules implements Serializable {
private static final long serialVersionUID = -4782500081453935537L;
private Long id;
/** 商户id */
private Long merchantId;
/** 充值金额 */
private BigDecimal topUpAmount;
/** 赠送金额 */
private BigDecimal presenterAmount;
/** 描述 */
private String desc;
/** 排序 */
private Integer seq;
private Date createDate;
private Date updateDate;
}
| 19.878788 | 71 | 0.679878 |
9067d5894786ceea389d634e486426a46cc0f9bb | 2,106 | go | Go | main.go | the-mountain-rcj/gogogo | 4ce0e2dfe226587ecebda19918dc9637aa1dcc19 | [
"MIT"
] | null | null | null | main.go | the-mountain-rcj/gogogo | 4ce0e2dfe226587ecebda19918dc9637aa1dcc19 | [
"MIT"
] | null | null | null | main.go | the-mountain-rcj/gogogo | 4ce0e2dfe226587ecebda19918dc9637aa1dcc19 | [
"MIT"
] | null | null | null | package main
import (
"fmt"
"reflect"
)
//type student struct {
// id int
// name string
// class string
//}
//// 构造函数
//func newStudent(id int, name string, class string) *student {
// return &student{
// id:id,
// name: name,
// class: class,
//
// }
//}
//
//
//type studentMgr struct {
// allStudents []*student
//}
//
//func newStudenrMgr() *studentMgr {
// return &studentMgr{
// allStudents: make([]*student, 0, 100),
// }
//}
//
//func (s *studentMgr) addStudent(newStu *student) {
// s.allStudents = append(s.allStudents,newStu)
//}
//
//func (s *studentMgr) modifyStudent(newStu *student) {
// for i, v := range s.allStudents{
// if newStu.id == v.id{
// s.allStudents[i] = newStu
// return
// }
// }
//
// fmt.Printf("Do not exist this student %v", newStu.id)
//
//
//}
//
//func (s *studentMgr) showStudent() {
// for _, v := range s.allStudents {
// fmt.Printf("id: %v name: %v class: %v \n",v.id, v.name, v.class)
// }
//}
//
//func showMenu() {
// fmt.Println("------Welcome---")
// fmt.Println("1.Append")
// fmt.Println("2.Modify")
// fmt.Println("3.Show")
// fmt.Println("4.exit")
//}
//
//func getInput() *student {
// var(
// id int
// name string
// class string
// )
// fmt.Println("input information:\n")
// fmt.Println("id:")
// fmt.Scanf("%d\n", &id)
// fmt.Println("name:")
// fmt.Scanf("%s\n", &name)
// fmt.Println("class:")
// fmt.Scanf("%s\n", &class)
// stu := newStudent(id, name, class)
// return stu
//}
type student struct {
Name string `json:"name"`
Score int `json:"score"`
}
func main() {
stu1 := student{
Name: "小王子",
Score: 90,
}
t := reflect.TypeOf(stu1)
fmt.Println(t.Name(), t.Kind()) // student struct
// 通过for循环遍历结构体的所有字段信息
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("name:%s index:%d type:%v json tag:%v\n", field.Name, field.Index, field.Type, field.Tag.Get("json"))
}
// 通过字段名获取指定结构体字段信息
if scoreField, ok := t.FieldByName("Score"); ok {
fmt.Printf("name:%s index:%d type:%v json tag:%v\n", scoreField.Name, scoreField.Index, scoreField.Type, scoreField.Tag.Get("json"))
}
}
| 18.313043 | 134 | 0.594492 |
86a881bfbd18a8f201d2e532dfb0522e0763fc7b | 198 | rs | Rust | src/test/pretty/llvm-asm-options.rs | Eric-Arellano/rust | 0f6f2d681b39c5f95459cd09cb936b6ceb27cd82 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 66,762 | 2015-01-01T08:32:03.000Z | 2022-03-31T23:26:40.000Z | src/test/pretty/llvm-asm-options.rs | Eric-Arellano/rust | 0f6f2d681b39c5f95459cd09cb936b6ceb27cd82 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 76,993 | 2015-01-01T00:06:33.000Z | 2022-03-31T23:59:15.000Z | src/test/pretty/llvm-asm-options.rs | Eric-Arellano/rust | 0f6f2d681b39c5f95459cd09cb936b6ceb27cd82 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11,787 | 2015-01-01T00:01:19.000Z | 2022-03-31T19:03:42.000Z | #![feature(llvm_asm)]
// pp-exact
pub fn main() {
unsafe {
llvm_asm!("" : : : : "volatile");
llvm_asm!("" : : : : "alignstack");
llvm_asm!("" : : : : "intel");
}
}
| 16.5 | 43 | 0.424242 |
80479f927decff3b872d9e887f927b21df03f1f0 | 1,156 | java | Java | src/main/java/com/terreni/cctv/model/BaseEntity.java | maurizioterreni/CCTV_OpenCV | 38dcc15573b454ab196bf02a0e27045b0a22a35e | [
"Apache-2.0"
] | 1 | 2017-03-23T09:38:50.000Z | 2017-03-23T09:38:50.000Z | src/main/java/com/terreni/cctv/model/BaseEntity.java | maurizioterreni/CCTV_OpenCV | 38dcc15573b454ab196bf02a0e27045b0a22a35e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/terreni/cctv/model/BaseEntity.java | maurizioterreni/CCTV_OpenCV | 38dcc15573b454ab196bf02a0e27045b0a22a35e | [
"Apache-2.0"
] | null | null | null | package com.terreni.cctv.model;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class BaseEntity{
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String uuid;
protected BaseEntity() {
}
public BaseEntity(String uuid) {
this.uuid = uuid;
}
public Long getId() {
return id;
}
void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof BaseEntity)) {
return false;
}
if (uuid == null) {
return false;
}
BaseEntity other = (BaseEntity) obj;
return uuid.equals(other.getUuid());
}
}
| 16.753623 | 67 | 0.67301 |
c5b415a09d164e37cc56ca5b4bd28fbb13692a91 | 1,023 | cpp | C++ | source/Material.cpp | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | source/Material.cpp | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | source/Material.cpp | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Material.h"
Material::Material(const std::string& name)
: m_Name{name}
, m_pNormalmap{nullptr}
, m_pDiffusemap{nullptr}
{
}
Material::~Material()
{
if (m_pDiffusemap)
{
delete m_pDiffusemap;
m_pDiffusemap = nullptr;
}
if (m_pNormalmap)
{
delete m_pNormalmap;
m_pNormalmap = nullptr;
}
}
void Material::OverwriteNormalMap(NormalMap* pNormalmap)
{
if (m_pNormalmap)
{
delete m_pNormalmap;
m_pNormalmap = nullptr;
}
m_pNormalmap = pNormalmap;
}
void Material::OverwriteDiffuseMap(Texture* pDiffusemap)
{
if (m_pDiffusemap)
{
delete m_pDiffusemap;
m_pDiffusemap = nullptr;
}
m_pDiffusemap = pDiffusemap;
}
void Material::SetDefaultColor(const RGBColor& color)
{
m_DefaultColor = color;
}
void Material::SetDefaultColor(float r, float g, float b)
{
m_DefaultColor.r = r;
m_DefaultColor.g = g;
m_DefaultColor.b = b;
}
NormalMap* Material::GetNormalmap() const
{
return m_pNormalmap;
}
Texture* Material::GetDiffusemap() const
{
return m_pDiffusemap;
} | 14.826087 | 57 | 0.72434 |
50cd2ca5135e2652612ebbd1c64765e9a02b3776 | 1,058 | asm | Assembly | src/util/oli/app/cpycfg.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | src/util/oli/app/cpycfg.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | src/util/oli/app/cpycfg.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | ; copy config infos to data area
include win1_mac_oli
section utility
xdef ut_cpycfg
;+++
; copy config infos to data area
;
; Entry Exit
; a0 copy list
; a6 base of data area
;---
ut_cpycfg subr a0/a1/a2
move.l a0,a2
lp move.w (a2)+,d0 ; get next item
bmi.s ok ; end of list marker
move.l a2,a1 ; a1 is from ptr
add.l (a2)+,a1 ; this is relative to itself
move.l (a2)+,a0 ; a0 is to ptr
adda.l a6,a0 ; this is relative to a6
cmpi.w #$08,d0
beq.s do_byte
cmpi.w #$0a,d0
beq.s do_word
cmpi.w #$0c,d0
beq.s do_long
xjsr ut_cpyst
bra.s lp
ok moveq #0,d0
exit subend
do_byte move.b (a1),(a0)
bra.s lp
do_word move.w (a1),(a0)
bra.s lp
do_long move.l (a1),(a0)
bra.s lp
end
| 24.604651 | 68 | 0.438563 |
80d803a973dc8cb12acaeaa71a29dfb10017912a | 1,700 | java | Java | src/main/java/com/emarte/regurgitator/core/Parameter.java | talmeym/regurgitator-core | f2e91691b4729167712121e4c0b94ca566625433 | [
"MIT"
] | null | null | null | src/main/java/com/emarte/regurgitator/core/Parameter.java | talmeym/regurgitator-core | f2e91691b4729167712121e4c0b94ca566625433 | [
"MIT"
] | null | null | null | src/main/java/com/emarte/regurgitator/core/Parameter.java | talmeym/regurgitator-core | f2e91691b4729167712121e4c0b94ca566625433 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2017 Miles Talmey.
* Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
package com.emarte.regurgitator.core;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import static com.emarte.regurgitator.core.Log.getLog;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
public final class Parameter implements HasId {
private static final Log log = getLog(Parameter.class);
private final ParameterPrototype prototype;
private Object value;
public Parameter(ParameterPrototype prototype, Object value) {
prototype.validateValue(value);
this.prototype = prototype;
this.value = value;
}
@Override
public Object getId() {
return getName();
}
public String getName() {
return prototype.getName();
}
public ParameterType getType() {
return prototype.getType();
}
public ConflictPolicy getConflictPolicy() {
return prototype.getConflictPolicy();
}
public Object getValue() {
if(value instanceof Collection) {
if (value instanceof List) {
return unmodifiableList((List) value);
}
if (value instanceof Set) {
return unmodifiableSet((Set) value);
}
}
return value;
}
void merge(Parameter parameter) {
Object newValue = getType().convert(parameter.getValue());
value = parameter.getConflictPolicy().resolveConflict(value, newValue, getType());
log.debug("Merge resulted in value '{}'", value);
}
}
| 26.5625 | 95 | 0.654118 |
5a55b2d8a847d512e3d292ac4e95e34ea51a36be | 5,119 | html | HTML | blogs.html | naemazam/Front-end-dev-portfolio | 3f9b89462a6523709f986e277395781afca22860 | [
"MIT"
] | 1 | 2022-02-05T14:42:17.000Z | 2022-02-05T14:42:17.000Z | blogs.html | naemazam/Front-end-dev-portfolio | 3f9b89462a6523709f986e277395781afca22860 | [
"MIT"
] | null | null | null | blogs.html | naemazam/Front-end-dev-portfolio | 3f9b89462a6523709f986e277395781afca22860 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blogs</title>
<!-- font awesome cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<!-- custom css file link -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- navbar section starts -->
<nav class="navbar">
<a href="index.html"> <i class="fas fa-home"></i> <span>home</span> </a>
<a href="about.html"> <i class="fas fa-user"></i> <span>about</span> </a>
<a href="portfolio.html"> <i class="fas fa-briefcase"></i> <span>portfolio</span> </a>
<a href="blogs.html"> <i class="fas fa-blog"></i> <span>blogs</span> </a>
<a href="contact.html"> <i class="fas fa-address-book"></i> <span>contact</span> </a>
</nav>
<!-- navbar section ends -->
<!-- blogs section starts -->
<section class="blogs">
<h1 class="heading"> <span>my</span> blogs </h1>
<div class="box-container">
<div class="box">
<div class="image">
<img src="images/blog1.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Impossible-OS</h3>
<p>Everyone is saying make a OS by using Html CSS and js is not possible that's why I named it Impossible OS. But I Know You will Like IT.</p>
<a href="https://naemazam.github.io/Impossible-OS/" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
<div class="box">
<div class="image">
<img src="images/blog2.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Live Browser</h3>
<p>Live Browser is a fully browser based (funny) BROWSER!!</p>
<a href="https://naemazam.github.io/Live-Browser/" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
<div class="box">
<div class="image">
<img src="images/blog3.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Note Keeper</h3>
<p>Take Your Note Online</p>
<a href="#" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
<div class="box">
<div class="image">
<img src="images/blog4.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Voov Automation</h3>
<p>Join Online Meeting Auto</p>
<a href="#" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
<div class="box">
<div class="image">
<img src="images/blog5.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Chrome-Dinosaur</h3>
<p>simple chrome offline T-rex Runner game clone using html CSS and JS</p>
<a href="#" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
<div class="box">
<div class="image">
<img src="images/blog6.png" alt="">
</div>
<div class="content">
<div class="icons">
<a href="#"> <i class="fas fa-calendar"></i> 21st may, 2021 </a>
<a href="#"> <i class="fas fa-user"></i> by admin </a>
</div>
<h3>Google Clone</h3>
<p>Make Google Search Clone</p>
<a href="#" class="btn"> read more <i class="fas fa-link"></i> </a>
</div>
</div>
</div>
</section>
<!-- blogs section ends -->
</body>
</html> | 37.918519 | 159 | 0.448916 |
d46d0732e855c28385a5436d196b42a3f5b7f63a | 1,314 | dart | Dart | moor/test/engines/connection_pool_integration_test.dart | abumalick/moor | e89f1c924c05b9f4cc5ff8efbed53c027691369a | [
"MIT"
] | 1 | 2020-06-08T21:19:38.000Z | 2020-06-08T21:19:38.000Z | moor/test/engines/connection_pool_integration_test.dart | TheStarkster/moor | e89f1c924c05b9f4cc5ff8efbed53c027691369a | [
"MIT"
] | null | null | null | moor/test/engines/connection_pool_integration_test.dart | TheStarkster/moor | e89f1c924c05b9f4cc5ff8efbed53c027691369a | [
"MIT"
] | null | null | null | @TestOn('vm')
import 'dart:io';
import 'package:moor/isolate.dart';
import 'package:moor/moor.dart';
import 'package:moor_ffi/moor_ffi.dart';
import 'package:test/test.dart';
import 'package:path/path.dart' show join;
import '../data/tables/todos.dart';
String fileName = 'moor-wal-integration-test.db';
final _file = File(join(Directory.systemTemp.path, fileName));
QueryExecutor _createExecutor() => VmDatabase(_file);
DatabaseConnection _forBackgroundIsolate() {
return DatabaseConnection.fromExecutor(_createExecutor());
}
void main() {
test('can use a multi-executor setup', () async {
final isolate = await MoorIsolate.spawn(_forBackgroundIsolate);
// create an executor that runs selects in this isolate and writes in
// another isolate.
final background = await isolate.connect();
final foreground = background.withExecutor(MultiExecutor(
read: _createExecutor(),
write: background.executor,
));
final db = TodoDb.connect(foreground);
await db
.into(db.categories)
.insert(CategoriesCompanion.insert(description: 'description'));
final result = await db.select(db.categories).getSingle();
expect(result.description, 'description');
await db.close();
await isolate.shutdownAll();
});
tearDown(_file.delete);
}
| 26.816327 | 73 | 0.714612 |
475a51722de082d36ec9639efb0981941ab0364f | 1,077 | html | HTML | docs/index.html | UNIwise/parrot | db8a6bb466424881e867e997f3f7025a0779d6a3 | [
"Apache-2.0"
] | 2 | 2021-02-15T15:26:39.000Z | 2021-02-16T19:56:10.000Z | docs/index.html | UNIwise/parrot | db8a6bb466424881e867e997f3f7025a0779d6a3 | [
"Apache-2.0"
] | 16 | 2021-02-14T01:57:10.000Z | 2022-01-13T12:36:26.000Z | docs/index.html | UNIwise/parrot | db8a6bb466424881e867e997f3f7025a0779d6a3 | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.1/swagger-ui.min.css" integrity="sha512-aEbfSpriGJ1mxZoWXLSwbJ8GSMLVNXBmHidn2cAGFHfJCFKSuqZEVzJy3ULeFRvvBIo7AHQbhkPIJ6sKW00GWQ==" crossorigin="anonymous" />
<title>Parrot API</title>
</head>
<body>
<div id="openapi">
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.1/swagger-ui-bundle.js" integrity="sha512-bEDewjT/ufwN2J2lPn+3dUcuWJOr2CrxSx31L4V72Ovux/GvoLTgCC/rkdmw6H84aTWfOhXe4uMCrp0E4y+OVw==" crossorigin="anonymous"></script>
<script>
window.onload = function () {
const ui = SwaggerUIBundle({
url: "v1.yaml",
dom_id: "#openapi"
});
}
</script>
</body>
</html> | 41.423077 | 244 | 0.67688 |
2a00597ab4fa6e2b7dddb386e77f9c9494a1dcba | 6,765 | java | Java | src/noaa/coastwatch/render/LatLonOverlay.java | phollemans/cwutils | b555d096edd284818fa2aa15a73f703693cd23d9 | [
"Unlicense"
] | 1 | 2019-09-09T01:38:45.000Z | 2019-09-09T01:38:45.000Z | src/noaa/coastwatch/render/LatLonOverlay.java | phollemans/cwutils | b555d096edd284818fa2aa15a73f703693cd23d9 | [
"Unlicense"
] | 2 | 2019-07-16T01:45:28.000Z | 2019-09-27T04:21:19.000Z | src/noaa/coastwatch/render/LatLonOverlay.java | phollemans/cwutils | b555d096edd284818fa2aa15a73f703693cd23d9 | [
"Unlicense"
] | null | null | null | ////////////////////////////////////////////////////////////////////////
/*
File: LatLonOverlay.java
Author: Peter Hollemans
Date: 2002/07/25
CoastWatch Software Library and Utilities
Copyright (c) 2002 National Oceanic and Atmospheric Administration
All rights reserved.
Developed by: CoastWatch / OceanWatch
Center for Satellite Applications and Research
http://coastwatch.noaa.gov
For conditions of distribution and use, see the accompanying
license.txt file.
*/
////////////////////////////////////////////////////////////////////////
// Package
// -------
package noaa.coastwatch.render;
// Imports
// -------
import java.awt.Color;
import java.awt.Font;
import java.awt.Stroke;
import java.util.Iterator;
import noaa.coastwatch.render.EarthDataView;
import noaa.coastwatch.render.EarthImageTransform;
import noaa.coastwatch.render.LabeledLineOverlay;
import noaa.coastwatch.render.lines.LineCollection;
import noaa.coastwatch.util.EarthArea;
import noaa.coastwatch.util.EarthLocation;
import noaa.coastwatch.util.trans.Datum;
import noaa.coastwatch.util.trans.EarthTransform;
/**
* The <code>LatLonOverlay</code> class annotates an {@link
* EarthDataView} view with latitude/longitude grid lines and
* labels.
*
* @author Peter Hollemans
* @since 3.1.1
*/
public class LatLonOverlay
extends LabeledLineOverlay {
// Constants
// ---------
/** The serialization constant. */
private static final long serialVersionUID = -6424130357334364832L;
/** The allowed automatic grid increment values. */
private static final int[] GRID_INCS = {1, 2, 5, 10, 15, 20, 30};
/** The default number of desired grid lines. */
private final static int GRID_LINES = 5;
// Variables
// ---------
/** The grid increment in degrees. */
private int inc;
/** The manual grid increment flag. */
private boolean manualIncrement;
////////////////////////////////////////////////////////////
/**
* Sets the manual grid increment mode flag. When off, the grid
* increment is calculated automatically at rendering time for an
* optimal number of grid lines.
*/
public void setManualIncrement (boolean flag) {
if (manualIncrement != flag) {
manualIncrement = flag;
prepared = false;
} // if
} // setManualIncrement
////////////////////////////////////////////////////////////
/** Gets the manual grid increment mode flag. */
public boolean getManualIncrement () { return (manualIncrement); }
////////////////////////////////////////////////////////////
/** Sets the grid increment in degrees. */
public void setIncrement (int inc) {
if (this.inc != inc) {
this.inc = inc;
if (manualIncrement) prepared = false;
} // if
} // setIncrement
////////////////////////////////////////////////////////////
/** Gets the current grid increment value in degrees. */
public int getIncrement () { return (inc); }
////////////////////////////////////////////////////////////
/**
* Constructs a new grid overlay.
*
* @param color the overlay color.
* @param layer the overlay layer number.
* @param stroke the stroke to use for vector paths.
* @param manualIncrement the manual increment flag.
* @param inc the latitude and longitude grid increment in degrees.
* @param drawLabels the grid labels flag, true if grid labels
* should be drawn.
* @param font the grid labels font. The labels font may be
* null if no labels are to be drawn.
*/
public LatLonOverlay (
Color color,
int layer,
Stroke stroke,
boolean manualIncrement,
int inc,
boolean drawLabels,
Font font
) {
super (color, layer, stroke, drawLabels, font);
this.manualIncrement = manualIncrement;
this.inc = inc;
} // LatLonOverlay constructor
////////////////////////////////////////////////////////////
/**
* Constructs a new grid overlay. The layer number is
* initialized to 0, the stroke to the default
* <code>BasicStroke</code>, the grid increment mode to
* automatic, labels to true, and the font to the default font
* face, plain style, 12 point.
*
* @param color the overlay color.
*/
public LatLonOverlay (
Color color
) {
super (color);
this.manualIncrement = false;
this.inc = 1;
} // LatLonOverlay constructor
////////////////////////////////////////////////////////////
/**
* Computes a grid increment value based on the earth area for
* grid line annotation.
*
* @param area the earth area for grid lines.
*/
private int getIncrementValue (
EarthArea area
) {
// Get maximum geographic extents
// ------------------------------
int[] extremes = area.getExtremes();
int extent = Math.min (extremes[0] - extremes[1],
extremes[2] - extremes[3]);
// Search for the best increment
// -----------------------------
double lines = (double) extent / GRID_INCS[0];
int index = 0;
for (int i = 1; i < GRID_INCS.length; i++) {
double newLines = (double) extent / GRID_INCS[i];
if (Math.abs (newLines - GRID_LINES) < Math.abs (lines - GRID_LINES)) {
lines = newLines;
index = i;
} // if
} // for
return (GRID_INCS[index]);
} // getIncrementValue
////////////////////////////////////////////////////////////
@Override
protected LineCollection getLines (
EarthDataView view
) {
// Compute grid increment
// ----------------------
EarthArea area = view.getArea();
int gridInc = (!manualIncrement ? getIncrementValue (area) : inc);
// Create grid lines
// -----------------
EarthImageTransform trans = view.getTransform();
Datum datum = trans.getEarthTransform().getDatum();
Iterator iter = area.getIterator();
LineCollection lines = new LineCollection();
while (iter.hasNext()) {
int[] square = (int[]) iter.next();
EarthLocation corner = new EarthLocation (square[0], square[1], datum);
if (square[0]%gridInc == 0) {
lines.addSegment (EarthLocation.formatSingle (square[0],
EarthLocation.D, EarthLocation.LAT).replaceFirst (" ", "\u00b0"),
trans, corner, corner.translate (0,1));
} // if
if (square[1]%gridInc == 0) {
lines.addSegment (EarthLocation.formatSingle (square[1],
EarthLocation.D, EarthLocation.LON).replaceFirst (" ", "\u00b0"),
trans, corner, corner.translate (1,0));
} // if
} // while
return (lines);
} // getLines
////////////////////////////////////////////////////////////
} // LatLonOverlay class
////////////////////////////////////////////////////////////////////////
| 28.305439 | 78 | 0.569401 |
263ac8f5cbc8917dd55e52b2cdfb19f10cbb50f8 | 2,978 | java | Java | messaging/src/test/java/org/axonframework/serialization/LazyDeserializingObjectTest.java | dmurat/AxonFramework | 7fc435b5624ae83ccebbb6df07b937d444617660 | [
"ECL-2.0",
"Apache-2.0"
] | 2,576 | 2015-01-07T18:25:46.000Z | 2022-03-31T11:42:37.000Z | messaging/src/test/java/org/axonframework/serialization/LazyDeserializingObjectTest.java | Yuanxdxindong/AxonFramework | b605ed9c397ab4b70de0f9adde41cbebef82befc | [
"ECL-2.0",
"Apache-2.0"
] | 1,638 | 2015-01-08T21:19:54.000Z | 2022-03-31T12:12:26.000Z | messaging/src/test/java/org/axonframework/serialization/LazyDeserializingObjectTest.java | Yuanxdxindong/AxonFramework | b605ed9c397ab4b70de0f9adde41cbebef82befc | [
"ECL-2.0",
"Apache-2.0"
] | 798 | 2015-01-04T03:06:46.000Z | 2022-03-30T18:23:34.000Z | /*
* Copyright (c) 2010-2018. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.serialization;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* @author Allard Buijze
*/
class LazyDeserializingObjectTest {
private Serializer mockSerializer;
private SerializedType mockType;
private SerializedObject mockObject;
private String mockDeserializedObject = "I'm a mock";
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() {
mockSerializer = mock(Serializer.class);
mockType = mock(SerializedType.class);
mockObject = new SimpleSerializedObject(mockDeserializedObject, String.class, mockType);
when(mockSerializer.classForType(mockType)).thenReturn(String.class);
when(mockSerializer.deserialize(mockObject)).thenReturn(mockDeserializedObject);
}
@SuppressWarnings("unchecked")
@Test
void testLazilyDeserialized() {
LazyDeserializingObject<Object> testSubject = new LazyDeserializingObject<>(mockObject, mockSerializer);
verify(mockSerializer, never()).deserialize(any(SerializedObject.class));
assertEquals(String.class, testSubject.getType());
assertFalse(testSubject.isDeserialized());
verify(mockSerializer, never()).deserialize(any(SerializedObject.class));
assertSame(mockDeserializedObject, testSubject.getObject());
assertTrue(testSubject.isDeserialized());
}
@Test
void testLazilyDeserialized_NullObject() {
assertThrows(Exception.class, () -> new LazyDeserializingObject<>(null, mockSerializer));
}
@Test
void testLazilyDeserialized_NullSerializer() {
assertThrows(IllegalArgumentException.class, () -> new LazyDeserializingObject<>(mockObject, null));
}
@Test
void testWithProvidedDeserializedInstance() {
LazyDeserializingObject<Object> testSubject = new LazyDeserializingObject<>(mockDeserializedObject);
assertEquals(mockDeserializedObject.getClass(), testSubject.getType());
assertSame(mockDeserializedObject, testSubject.getObject());
assertTrue(testSubject.isDeserialized());
}
@Test
void testWithProvidedDeserializedNullInstance() {
assertThrows(IllegalArgumentException.class, () -> new LazyDeserializingObject<>(null));
}
}
| 35.879518 | 112 | 0.731028 |
8aec5b2fbfcc7f291deedf424ea7cb3a49bd298a | 18 | rs | Rust | src/backend/mod.rs | Twinklebear/simd | a8d3c577299985d049769862836b2d4b224e718f | [
"MIT"
] | null | null | null | src/backend/mod.rs | Twinklebear/simd | a8d3c577299985d049769862836b2d4b224e718f | [
"MIT"
] | null | null | null | src/backend/mod.rs | Twinklebear/simd | a8d3c577299985d049769862836b2d4b224e718f | [
"MIT"
] | null | null | null | pub mod generic;
| 6 | 16 | 0.722222 |
594c5e5b1922ff771945947dfdad56af73624103 | 2,012 | h | C | CppImGuidSfml/CppImGuidSfml/TestScene.h | adamkunzler/SFMLStaticTemplate | 8fa568f3c9838aaa5ac980ec1e889824dd685a09 | [
"MIT"
] | null | null | null | CppImGuidSfml/CppImGuidSfml/TestScene.h | adamkunzler/SFMLStaticTemplate | 8fa568f3c9838aaa5ac980ec1e889824dd685a09 | [
"MIT"
] | null | null | null | CppImGuidSfml/CppImGuidSfml/TestScene.h | adamkunzler/SFMLStaticTemplate | 8fa568f3c9838aaa5ac980ec1e889824dd685a09 | [
"MIT"
] | null | null | null | #pragma once
class BaseScene;
class TestScene : public BaseScene
{
private:
sf::RenderTexture _texture;
sf::Sprite _sprite;
sf::VertexArray _gfxPixels;
float _x{ halfWidth };
float _y{ halfHeight };
float _size{ 100.f };
float _angle{ 0.f };
public:
TestScene(int width, int height, std::string title)
:BaseScene{ width, height, title }
{
if (!_texture.create(width, height))
std::cout << "Failed to create _texture!" << std::endl;
_gfxPixels.setPrimitiveType(sf::Quads);
}
void processSceneEvents(const sf::Event& event)
{
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Space)
{
std::cout << "Spacebar Pressed: " << event.key.code << std::endl;
}
}
if (event.type == sf::Event::MouseMoved)
{
/*std::cout << "Mouse X: " << event.mouseMove.x << std::endl;
std::cout << "Mouse Y: " << event.mouseMove.y << std::endl;*/
}
}
void updateScene(sf::Time elapsed) override
{
_angle += 72.f * elapsed.asSeconds();
if (_angle > 360.f) _angle -= 360.f;
}
void drawScene(float elapsedRatio) override
{
_texture.clear();
// begin - "draw" the texture
_gfxPixels.clear();
sf::Transform translation;
translation.translate(_x, _y);
sf::Transform rotation;
rotation.rotate(_angle);
sf::Transform transform = translation * rotation;
sf::Vertex v1{ sf::Vector2f{transform.transformPoint(-_size, -_size)}};
sf::Vertex v2{ sf::Vector2f{transform.transformPoint(_size, -_size)} };
sf::Vertex v3{ sf::Vector2f{transform.transformPoint(_size, _size)} };
sf::Vertex v4{ sf::Vector2f{transform.transformPoint(-_size, _size)} };
_gfxPixels.append(v1); _gfxPixels.append(v2); _gfxPixels.append(v3); _gfxPixels.append(v4);
// end - "draw" the texture
_texture.draw(_gfxPixels);
_texture.display();
_sprite.setTexture(_texture.getTexture());
window.draw(_sprite);
}
std::vector<std::string> getOverlayMessages()
{
std::vector<std::string> msg;
return msg;
}
void customImGui()
{
}
}; | 23.395349 | 93 | 0.668986 |
cf7a4a4b93527185f86b20e38850c1a52726c2dd | 132 | css | CSS | src/public/page/h5map/index.css | bright00007/FloatRay_whiteBoard | fe37b78b850ae21bf8c8af29834f768f91afd533 | [
"Apache-2.0"
] | 1 | 2021-05-22T13:07:40.000Z | 2021-05-22T13:07:40.000Z | src/public/page/h5map/index.css | bright00007/FloatRay_whiteBoard | fe37b78b850ae21bf8c8af29834f768f91afd533 | [
"Apache-2.0"
] | null | null | null | src/public/page/h5map/index.css | bright00007/FloatRay_whiteBoard | fe37b78b850ae21bf8c8af29834f768f91afd533 | [
"Apache-2.0"
] | null | null | null | * {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#id {
position: relative;
}
#map {
width: 100vw;
height: 50vh;
}
| 8.8 | 25 | 0.560606 |
1f543cbe6f5f705802e9399fe7dc0460b043a0a8 | 7,427 | cc | C++ | kenlm/lm/interpolate/streaming_example_main.cc | cmedlock/deepspeech.pytorch | 7f0dbcdb3bcc41992136ebedfcd3e7d6fdb256d1 | [
"MIT"
] | 111 | 2020-08-31T04:58:54.000Z | 2022-03-29T15:44:18.000Z | Part 02/001_LM/ngram_lm_lab/kenlm/lm/interpolate/streaming_example_main.cc | Kabongosalomon/AMMI-NLP | 00a0e47399926ad1951b84a11cd936598a9c7c3b | [
"MIT"
] | 14 | 2020-12-16T07:27:22.000Z | 2022-03-15T17:39:01.000Z | Part 02/001_LM/ngram_lm_lab/kenlm/lm/interpolate/streaming_example_main.cc | Kabongosalomon/AMMI-NLP | 00a0e47399926ad1951b84a11cd936598a9c7c3b | [
"MIT"
] | 29 | 2021-02-09T08:57:15.000Z | 2022-03-12T14:09:19.000Z | #include "lm/common/compare.hh"
#include "lm/common/model_buffer.hh"
#include "lm/common/ngram.hh"
#include "util/stream/chain.hh"
#include "util/stream/multi_stream.hh"
#include "util/stream/sort.hh"
#include "lm/interpolate/split_worker.hh"
#include <boost/program_options.hpp>
#include <boost/version.hpp>
#if defined(_WIN32) || defined(_WIN64)
// Windows doesn't define <unistd.h>
//
// So we define what we need here instead:
//
#define STDIN_FILENO = 0
#define STDOUT_FILENO = 1
#else // Huzzah for POSIX!
#include <unistd.h>
#endif
/*
* This is a simple example program that takes in intermediate
* suffix-sorted ngram files and outputs two sets of files: one for backoff
* probability values (raw numbers, in suffix order) and one for
* probability values (ngram id and probability, in *context* order)
*/
int main(int argc, char *argv[]) {
using namespace lm::interpolate;
const std::size_t ONE_GB = 1 << 30;
const std::size_t SIXTY_FOUR_MB = 1 << 26;
const std::size_t NUMBER_OF_BLOCKS = 2;
std::string FILE_NAME = "ngrams";
std::string CONTEXT_SORTED_FILENAME = "csorted-ngrams";
std::string BACKOFF_FILENAME = "backoffs";
std::string TMP_DIR = "/tmp/";
try {
namespace po = boost::program_options;
po::options_description options("canhazinterp Pass-3 options");
options.add_options()
("help,h", po::bool_switch(), "Show this help message")
("ngrams,n", po::value<std::string>(&FILE_NAME), "ngrams file")
("csortngrams,c", po::value<std::string>(&CONTEXT_SORTED_FILENAME), "context sorted ngrams file")
("backoffs,b", po::value<std::string>(&BACKOFF_FILENAME), "backoffs file")
("tmpdir,t", po::value<std::string>(&TMP_DIR), "tmp dir");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
// Display help
if(vm["help"].as<bool>()) {
std::cerr << "Usage: " << options << std::endl;
return 1;
}
}
catch(const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
// The basic strategy here is to have three chains:
// - The first reads the ngram order inputs using ModelBuffer. Those are
// then stripped of their backoff values and fed into the third chain;
// the backoff values *themselves* are written to the second chain.
//
// - The second chain takes the backoff values and writes them out to a
// file (one for each order).
//
// - The third chain takes just the probability values and ngrams and
// writes them out, sorted in context-order, to a file (one for each
// order).
// This will be used to read in the binary intermediate files. There is
// one file per order (e.g. ngrams.1, ngrams.2, ...)
lm::ModelBuffer buffer(FILE_NAME);
// Create a separate chains for each ngram order for:
// - Input from the intermediate files
// - Output to the backoff file
// - Output to the (context-sorted) probability file
util::stream::Chains ngram_inputs(buffer.Order());
util::stream::Chains backoff_chains(buffer.Order());
util::stream::Chains prob_chains(buffer.Order());
for (std::size_t i = 0; i < buffer.Order(); ++i) {
ngram_inputs.push_back(util::stream::ChainConfig(
lm::NGram<lm::ProbBackoff>::TotalSize(i + 1), NUMBER_OF_BLOCKS, ONE_GB));
backoff_chains.push_back(
util::stream::ChainConfig(sizeof(float), NUMBER_OF_BLOCKS, ONE_GB));
prob_chains.push_back(util::stream::ChainConfig(
sizeof(lm::WordIndex) * (i + 1) + sizeof(float), NUMBER_OF_BLOCKS,
ONE_GB));
}
// This sets the input for each of the ngram order chains to the
// appropriate file
buffer.Source(ngram_inputs);
util::FixedArray<util::scoped_ptr<SplitWorker> > workers(buffer.Order());
for (std::size_t i = 0; i < buffer.Order(); ++i) {
// Attach a SplitWorker to each of the ngram input chains, writing to the
// corresponding order's backoff and probability chains
workers.push_back(
new SplitWorker(i + 1, backoff_chains[i], prob_chains[i]));
ngram_inputs[i] >> boost::ref(*workers.back());
}
util::stream::SortConfig sort_cfg;
sort_cfg.temp_prefix = TMP_DIR;
sort_cfg.buffer_size = SIXTY_FOUR_MB;
sort_cfg.total_memory = ONE_GB;
// This will parallel merge sort the individual order files, putting
// them in context-order instead of suffix-order.
//
// Two new threads will be running, each owned by the chains[i] object.
// - The first executes BlockSorter.Run() to sort the n-gram entries
// - The second executes WriteAndRecycle.Run() to write each sorted
// block to disk as a temporary file
util::stream::Sorts<lm::ContextOrder> sorts(buffer.Order());
for (std::size_t i = 0; i < prob_chains.size(); ++i) {
sorts.push_back(prob_chains[i], sort_cfg, lm::ContextOrder(i + 1));
}
// Set the sort output to be on the same chain
for (std::size_t i = 0; i < prob_chains.size(); ++i) {
// The following call to Chain::Wait()
// joins the threads owned by chains[i].
//
// As such the following call won't return
// until all threads owned by chains[i] have completed.
//
// The following call also resets chain[i]
// so that it can be reused
// (including free'ing the memory previously used by the chain)
prob_chains[i].Wait();
// In an ideal world (without memory restrictions)
// we could merge all of the previously sorted blocks
// by reading them all completely into memory
// and then running merge sort over them.
//
// In the real world, we have memory restrictions;
// depending on how many blocks we have,
// and how much memory we can use to read from each block
// (sort_config.buffer_size)
// it may be the case that we have insufficient memory
// to read sort_config.buffer_size of data from each block from disk.
//
// If this occurs, then it will be necessary to perform one or more rounds
// of merge sort on disk;
// doing so will reduce the number of blocks that we will eventually
// need to read from
// when performing the final round of merge sort in memory.
//
// So, the following call determines whether it is necessary
// to perform one or more rounds of merge sort on disk;
// if such on-disk merge sorting is required, such sorting is performed.
//
// Finally, the following method launches a thread that calls
// OwningMergingReader.Run()
// to perform the final round of merge sort in memory.
//
// Merge sort could have be invoked directly
// so that merge sort memory doesn't coexist with Chain memory.
sorts[i].Output(prob_chains[i]);
}
// Create another model buffer for our output on e.g. csorted-ngrams.1,
// csorted-ngrams.2, ...
lm::ModelBuffer output_buf(CONTEXT_SORTED_FILENAME, true, false);
output_buf.Sink(prob_chains, buffer.Counts());
// Create a third model buffer for our backoff output on e.g. backoff.1,
// backoff.2, ...
lm::ModelBuffer boff_buf(BACKOFF_FILENAME, true, false);
boff_buf.Sink(backoff_chains, buffer.Counts());
// Joins all threads that chains owns,
// and does a for loop over each chain object in chains,
// calling chain.Wait() on each such chain object
ngram_inputs.Wait(true);
backoff_chains.Wait(true);
prob_chains.Wait(true);
return 0;
}
| 37.892857 | 103 | 0.676047 |
4b55e0789b0abac976b1f81765fd7af0d4aa42ff | 1,638 | html | HTML | master/ecoware-monitoring-master/ecoware-monitoring-master/ECoWare/doc/overview-frame.html | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/ecoware-monitoring-master/ecoware-monitoring-master/ECoWare/doc/overview-frame.html | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/ecoware-monitoring-master/ecoware-monitoring-master/ECoWare/doc/overview-frame.html | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (version 1.7.0_21) on Mon Jul 22 04:09:15 CEST 2013 -->
<title>Overview List</title>
<meta name="date" content="2013-07-22">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<div class="indexHeader"><a href="allclasses-frame.html" target="packageFrame">All Classes</a></div>
<div class="indexContainer">
<h2 title="Packages">Packages</h2>
<ul title="Packages">
<li><a href="ecoware/ecowareaccessmanager/package-frame.html" target="packageFrame">ecoware.ecowareaccessmanager</a></li>
<li><a href="ecoware/ecowareprocessor/package-frame.html" target="packageFrame">ecoware.ecowareprocessor</a></li>
<li><a href="ecoware/ecowareprocessor/eventlisteners/package-frame.html" target="packageFrame">ecoware.ecowareprocessor.eventlisteners</a></li>
<li><a href="ecoware/ecowareprocessor/kpi/package-frame.html" target="packageFrame">ecoware.ecowareprocessor.kpi</a></li>
<li><a href="ecoware/ecowareprocessor/kpi/aggregators/package-frame.html" target="packageFrame">ecoware.ecowareprocessor.kpi.aggregators</a></li>
<li><a href="ecoware/ecowareprocessor/kpi/calculators/package-frame.html" target="packageFrame">ecoware.ecowareprocessor.kpi.calculators</a></li>
<li><a href="ecoware/ecowareprocessor/kpi/filters/package-frame.html" target="packageFrame">ecoware.ecowareprocessor.kpi.filters</a></li>
<li><a href="ecoware/util/package-frame.html" target="packageFrame">ecoware.util</a></li>
</ul>
</div>
<p> </p>
</body>
</html>
| 58.5 | 145 | 0.750305 |
dddfc41ef0d5de6634c06abf3f3a00b940f14659 | 8,417 | go | Go | encoding/ewkb/ewkb_test.go | backwardn/go-geom | a79d2004d97a864b376a34bbcfd7431bae22372f | [
"BSD-2-Clause"
] | 1 | 2020-09-17T07:13:14.000Z | 2020-09-17T07:13:14.000Z | encoding/ewkb/ewkb_test.go | backwardn/go-geom | a79d2004d97a864b376a34bbcfd7431bae22372f | [
"BSD-2-Clause"
] | null | null | null | encoding/ewkb/ewkb_test.go | backwardn/go-geom | a79d2004d97a864b376a34bbcfd7431bae22372f | [
"BSD-2-Clause"
] | 1 | 2020-09-16T03:58:19.000Z | 2020-09-16T03:58:19.000Z | package ewkb
import (
"encoding/hex"
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/twpayne/go-geom"
)
func test(t *testing.T, g geom.T, xdr, ndr []byte) {
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
t.Run("unmarshal", func(t *testing.T) {
got, err := Unmarshal(xdr)
require.NoError(t, err)
require.Equal(t, g, got)
})
t.Run("marshal", func(t *testing.T) {
got, err := Marshal(g, XDR)
require.NoError(t, err)
require.Equal(t, xdr, got)
})
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
t.Run("unmarshal", func(t *testing.T) {
got, err := Unmarshal(ndr)
require.NoError(t, err)
require.Equal(t, g, got)
})
t.Run("marshal", func(t *testing.T) {
got, err := Marshal(g, NDR)
require.NoError(t, err)
require.Equal(t, ndr, got)
})
})
}
t.Run("scan", func(t *testing.T) {
switch g := g.(type) {
case *geom.Point:
var p Point
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, p.Scan(xdr))
require.Equal(t, Point{g}, p)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, p.Scan(ndr))
require.Equal(t, Point{g}, p)
})
}
case *geom.LineString:
var ls LineString
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, ls.Scan(xdr))
require.Equal(t, LineString{g}, ls)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, ls.Scan(ndr))
require.Equal(t, LineString{g}, ls)
})
}
case *geom.Polygon:
var p Polygon
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, p.Scan(xdr))
require.Equal(t, Polygon{g}, p)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, p.Scan(ndr))
require.Equal(t, Polygon{g}, p)
})
}
case *geom.MultiPoint:
var mp MultiPoint
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, mp.Scan(xdr))
require.Equal(t, MultiPoint{g}, mp)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, mp.Scan(ndr))
require.Equal(t, MultiPoint{g}, mp)
})
}
case *geom.MultiLineString:
var mls MultiLineString
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, mls.Scan(xdr))
require.Equal(t, MultiLineString{g}, mls)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, mls.Scan(ndr))
require.Equal(t, MultiLineString{g}, mls)
})
}
case *geom.MultiPolygon:
var mp MultiPolygon
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, mp.Scan(xdr))
require.Equal(t, MultiPolygon{g}, mp)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, mp.Scan(ndr))
require.Equal(t, MultiPolygon{g}, mp)
})
}
case *geom.GeometryCollection:
var gc GeometryCollection
if xdr != nil {
t.Run("xdr", func(t *testing.T) {
require.NoError(t, gc.Scan(xdr))
require.Equal(t, GeometryCollection{g}, gc)
})
}
if ndr != nil {
t.Run("ndr", func(t *testing.T) {
require.NoError(t, gc.Scan(ndr))
require.Equal(t, GeometryCollection{g}, gc)
})
}
}
})
}
func mustDecodeString(s string) []byte {
data, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return data
}
func Test(t *testing.T) {
for _, tc := range []struct {
g geom.T
xdr []byte
ndr []byte
}{
{
g: geom.NewPointEmpty(geom.XY),
xdr: mustDecodeString("00000000017ff80000000000007ff8000000000000"),
ndr: mustDecodeString("0101000000000000000000f87f000000000000f87f"),
},
{
g: geom.NewPointEmpty(geom.XYM),
xdr: mustDecodeString("00400000017ff80000000000007ff80000000000007ff8000000000000"),
ndr: mustDecodeString("0101000040000000000000f87f000000000000f87f000000000000f87f"),
},
{
g: geom.NewPointEmpty(geom.XYZ),
xdr: mustDecodeString("00800000017ff80000000000007ff80000000000007ff8000000000000"),
ndr: mustDecodeString("0101000080000000000000f87f000000000000f87f000000000000f87f"),
},
{
g: geom.NewPointEmpty(geom.XYZM),
xdr: mustDecodeString("00c00000017ff80000000000007ff80000000000007ff80000000000007ff8000000000000"),
ndr: mustDecodeString("01010000c0000000000000f87f000000000000f87f000000000000f87f000000000000f87f"),
},
{
g: geom.NewGeometryCollection().MustPush(geom.NewPointEmpty(geom.XY)),
xdr: mustDecodeString("00000000070000000100000000017ff80000000000007ff8000000000000"),
ndr: mustDecodeString("0107000000010000000101000000000000000000f87f000000000000f87f"),
},
{
g: geom.NewPointEmpty(geom.XY).SetSRID(4326),
xdr: mustDecodeString("0020000001000010e67ff80000000000007ff8000000000000"),
ndr: mustDecodeString("0101000020e6100000000000000000f87f000000000000f87f"),
},
{
g: geom.NewPoint(geom.XY).MustSetCoords(geom.Coord{1, 2}),
xdr: mustDecodeString("00000000013ff00000000000004000000000000000"),
ndr: mustDecodeString("0101000000000000000000f03f0000000000000040"),
},
{
g: geom.NewPoint(geom.XYZ).MustSetCoords(geom.Coord{1, 2, 3}),
xdr: mustDecodeString("00800000013ff000000000000040000000000000004008000000000000"),
ndr: mustDecodeString("0101000080000000000000f03f00000000000000400000000000000840"),
},
{
g: geom.NewPoint(geom.XYM).MustSetCoords(geom.Coord{1, 2, 3}),
xdr: mustDecodeString("00400000013ff000000000000040000000000000004008000000000000"),
ndr: mustDecodeString("0101000040000000000000f03f00000000000000400000000000000840"),
},
{
g: geom.NewPoint(geom.XYZM).MustSetCoords(geom.Coord{1, 2, 3, 4}),
xdr: mustDecodeString("00c00000013ff0000000000000400000000000000040080000000000004010000000000000"),
ndr: mustDecodeString("01010000c0000000000000f03f000000000000004000000000000008400000000000001040"),
},
{
g: geom.NewPoint(geom.XY).SetSRID(4326).MustSetCoords(geom.Coord{1, 2}),
xdr: mustDecodeString("0020000001000010e63ff00000000000004000000000000000"),
ndr: mustDecodeString("0101000020e6100000000000000000f03f0000000000000040"),
},
{
g: geom.NewPoint(geom.XYZ).SetSRID(4326).MustSetCoords(geom.Coord{1, 2, 3}),
xdr: mustDecodeString("00a0000001000010e63ff000000000000040000000000000004008000000000000"),
ndr: mustDecodeString("01010000a0e6100000000000000000f03f00000000000000400000000000000840"),
},
{
g: geom.NewPoint(geom.XYM).SetSRID(4326).MustSetCoords(geom.Coord{1, 2, 3}),
xdr: mustDecodeString("0060000001000010e63ff000000000000040000000000000004008000000000000"),
ndr: mustDecodeString("0101000060e6100000000000000000f03f00000000000000400000000000000840"),
},
{
g: geom.NewPoint(geom.XYZM).SetSRID(4326).MustSetCoords(geom.Coord{1, 2, 3, 4}),
xdr: mustDecodeString("00e0000001000010e63ff0000000000000400000000000000040080000000000004010000000000000"),
ndr: mustDecodeString("01010000e0e6100000000000000000f03f000000000000004000000000000008400000000000001040"),
},
{
g: geom.NewMultiPoint(geom.XY).SetSRID(4326).MustSetCoords([]geom.Coord{{1, 2}, nil, {3, 4}}),
xdr: mustDecodeString("0020000004000010e60000000300000000013ff0000000000000400000000000000000000000017ff80000000000007ff8000000000000000000000140080000000000004010000000000000"),
ndr: mustDecodeString("0104000020e6100000030000000101000000000000000000f03f00000000000000400101000000000000000000f87f000000000000f87f010100000000000000000008400000000000001040"),
},
{
g: geom.NewGeometryCollection().SetSRID(4326),
xdr: mustDecodeString("0020000007000010e600000000"),
ndr: mustDecodeString("0107000020e610000000000000"),
},
{
g: geom.NewGeometryCollection().SetSRID(4326).MustPush(
geom.NewPoint(geom.XY).MustSetCoords(geom.Coord{1, 2}),
geom.NewLineString(geom.XY).MustSetCoords([]geom.Coord{{3, 4}, {5, 6}}),
),
ndr: mustDecodeString("0107000020E6100000020000000101000000000000000000F03F00000000000000400102000000020000000000000000000840000000000000104000000000000014400000000000001840"),
xdr: mustDecodeString("0020000007000010e60000000200000000013ff000000000000040000000000000000000000002000000024008000000000000401000000000000040140000000000004018000000000000"),
},
} {
t.Run(fmt.Sprintf("ndr:%s", tc.ndr), func(t *testing.T) {
test(t, tc.g, tc.xdr, tc.ndr)
})
}
}
| 32.878906 | 181 | 0.697636 |
26a52a83d341ca9b38809a72c4393fdf81172c1c | 132 | ps1 | PowerShell | Chapter15/3.2.1.BeginInvoke.ps1 | gr8greet/Mastering-Windows-PowerShell-Scripting-Third-Edition | e8076c68e4cb89bc3d79515c1ad535286dd639ff | [
"MIT"
] | 34 | 2019-02-03T16:13:09.000Z | 2022-03-07T00:18:09.000Z | Chapter15/3.2.1.BeginInvoke.ps1 | atifrather/Mastering-Windows-PowerShell-Scripting-Third-Edition | 90838e69947d2a1b8a21fa22697503ce65d90354 | [
"MIT"
] | null | null | null | Chapter15/3.2.1.BeginInvoke.ps1 | atifrather/Mastering-Windows-PowerShell-Scripting-Third-Edition | 90838e69947d2a1b8a21fa22697503ce65d90354 | [
"MIT"
] | 26 | 2018-12-19T14:24:46.000Z | 2021-09-27T07:15:50.000Z | $psInstance = [PowerShell]::Create().AddCommand('Start-Sleep').AddParameter('Seconds', 300)
$asyncResult = $psInstance.BeginInvoke() | 66 | 91 | 0.757576 |
80e3d2f09c636e639738e77a5a69349bb9b32c06 | 60,470 | cpp | C++ | src/add-ons/kernel/drivers/audio/usb/AudioControlInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 2 | 2020-02-02T06:48:30.000Z | 2020-04-05T13:58:32.000Z | src/add-ons/kernel/drivers/audio/usb/AudioControlInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | null | null | null | src/add-ons/kernel/drivers/audio/usb/AudioControlInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1 | 2022-02-05T11:40:54.000Z | 2022-02-05T11:40:54.000Z | /*
* Driver for USB Audio Device Class devices.
* Copyright (c) 2009-13 S.Zharski <imker@gmx.li>
* Distributed under the tems of the MIT license.
*
*/
#include "AudioControlInterface.h"
#include <usb/USB_audio.h>
#include "Device.h"
#include "Driver.h"
#include "Settings.h"
// control id is encoded in following way
// CS CN ID IF where:
// CS - control selector
// CN - channel
// ID - id of this feature unit
// IF - interface
#define CTL_ID(_CS, _CN, _ID, _IF) \
(((_CS) << 24) | ((_CN) << 16) | ((_ID) << 8) | (_IF))
#define CS_FROM_CTLID(_ID) (0xff & ((_ID) >> 24))
#define CN_FROM_CTLID(_ID) (0xff & ((_ID) >> 16))
#define ID_FROM_CTLID(_ID) (0xff & ((_ID) >> 8))
#define REQ_VALUE(_ID) (0xffff & ((_ID) >> 16))
#define REQ_INDEX(_ID) (0xffff & (_ID))
struct _Designation {
uint32 ch;
uint32 bus;
} gDesignations[AudioControlInterface::kChannels] = {
{ B_CHANNEL_LEFT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_RIGHT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_CENTER, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_SUB, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_REARLEFT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_REARRIGHT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_FRONT_LEFT_CENTER, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_FRONT_RIGHT_CENTER, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_BACK_CENTER, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_SIDE_LEFT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_SIDE_RIGHT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_TOP_CENTER, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_TOP_FRONT_LEFT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_TOP_FRONT_CENTER, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_TOP_FRONT_RIGHT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_TOP_BACK_LEFT, B_CHANNEL_STEREO_BUS },
{ B_CHANNEL_TOP_BACK_CENTER, B_CHANNEL_SURROUND_BUS },
{ B_CHANNEL_TOP_BACK_RIGHT, B_CHANNEL_STEREO_BUS }
};
struct _MixPageCollector : public Vector<multi_mix_control> {
_MixPageCollector(const char* pageName) {
multi_mix_control page;
memset(&page, 0, sizeof(multi_mix_control));
page.flags = B_MULTI_MIX_GROUP;
strlcpy(page.name, pageName, sizeof(page.name));
PushBack(page);
}
};
_AudioControl::_AudioControl(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
fStatus(B_NO_INIT),
fInterface(interface),
fSubType(Header->descriptor_subtype),
fID(0),
fSourceID(0),
fStringIndex(0)
{
}
_AudioControl::~_AudioControl()
{
}
AudioChannelCluster*
_AudioControl::OutCluster()
{
if (SourceID() == 0 || fInterface == NULL)
return NULL;
_AudioControl* control = fInterface->Find(SourceID());
if (control == NULL)
return NULL;
return control->OutCluster();
}
AudioChannelCluster::AudioChannelCluster()
:
fOutChannelsNumber(0),
fChannelsConfig(0),
fChannelNames(0)
{
}
AudioChannelCluster::~AudioChannelCluster()
{
}
bool
AudioChannelCluster::HasChannel(uint32 location)
{
return (fChannelsConfig & location) == location;
}
_Terminal::_Terminal(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header),
fTerminalType(0),
fAssociatedTerminal(0),
fClockSourceId(0),
fControlsBitmap(0)
{
}
_Terminal::~_Terminal()
{
}
const char*
_Terminal::Name()
{
return _GetTerminalDescription(fTerminalType);
}
bool
_Terminal::IsUSBIO()
{
return (fTerminalType & 0xff00) == USB_AUDIO_UNDEFINED_USB_IO;
}
const char*
_Terminal::_GetTerminalDescription(uint16 TerminalType)
{
static struct _pair {
uint16 type;
const char* description;
} termInfoPairs[] = {
// USB Terminal Types
{ USB_AUDIO_UNDEFINED_USB_IO, "USB I/O" },
{ USB_AUDIO_STREAMING_USB_IO, "USB I/O" },
{ USB_AUDIO_VENDOR_USB_IO, "Vendor USB I/O" },
// Input Terminal Types
{ USB_AUDIO_UNDEFINED_IN, "Undefined Input" },
{ USB_AUDIO_MICROPHONE_IN, "Microphone" },
{ USB_AUDIO_DESKTOPMIC_IN, "Desktop Microphone" },
{ USB_AUDIO_PERSONALMIC_IN, "Personal Microphone" },
{ USB_AUDIO_OMNI_MIC_IN, "Omni-directional Mic" },
{ USB_AUDIO_MICS_ARRAY_IN, "Microphone Array" },
{ USB_AUDIO_PROC_MICS_ARRAY_IN, "Processing Mic Array" },
// Output Terminal Types
{ USB_AUDIO_UNDEFINED_OUT, "Undefined Output" },
{ USB_AUDIO_SPEAKER_OUT, "Speaker" },
{ USB_AUDIO_HEAD_PHONES_OUT, "Headphones" },
{ USB_AUDIO_HMD_AUDIO_OUT, "Head Mounted Disp.Audio" },
{ USB_AUDIO_DESKTOP_SPEAKER, "Desktop Speaker" },
{ USB_AUDIO_ROOM_SPEAKER, "Room Speaker" },
{ USB_AUDIO_COMM_SPEAKER, "Communication Speaker" },
{ USB_AUDIO_LFE_SPEAKER, "LFE Speaker" },
// Bi-directional Terminal Types
{ USB_AUDIO_UNDEFINED_IO, "Undefined I/O" },
{ USB_AUDIO_HANDSET_IO, "Handset" },
{ USB_AUDIO_HEADSET_IO, "Headset" },
{ USB_AUDIO_SPEAKER_PHONE_IO, "Speakerphone" },
{ USB_AUDIO_SPEAKER_PHONEES_IO, "Echo-supp Speakerphone" },
{ USB_AUDIO_SPEAKER_PHONEEC_IO, "Echo-cancel Speakerphone" },
// Telephony Terminal Types
{ USB_AUDIO_UNDEF_TELEPHONY_IO, "Undefined Telephony" },
{ USB_AUDIO_PHONE_LINE_IO, "Phone Line" },
{ USB_AUDIO_TELEPHONE_IO, "Telephone" },
{ USB_AUDIO_DOWNLINE_PHONE_IO, "Down Line Phone" },
// External Terminal Types
{ USB_AUDIO_UNDEFINEDEXT_IO, "Undefined External I/O" },
{ USB_AUDIO_ANALOG_CONNECTOR_IO, "Analog Connector" },
{ USB_AUDIO_DAINTERFACE_IO, "Digital Audio Interface" },
{ USB_AUDIO_LINE_CONNECTOR_IO, "Line Connector" },
{ USB_AUDIO_LEGACY_CONNECTOR_IO, "LegacyAudioConnector" },
{ USB_AUDIO_SPDIF_INTERFACE_IO, "S/PDIF Interface" },
{ USB_AUDIO_DA1394_STREAM_IO, "1394 DA Stream" },
{ USB_AUDIO_DV1394_STREAMSOUND_IO, "1394 DV Stream Soundtrack" },
{ USB_AUDIO_ADAT_LIGHTPIPE_IO, "Alesis DAT Stream" },
{ USB_AUDIO_TDIF_IO, "Tascam Digital Interface" },
{ USB_AUDIO_MADI_IO, "AES Multi-channel interface" },
// Embedded Terminal Types
{ USB_AUDIO_UNDEF_EMBEDDED_IO, "Undefined Embedded I/O" },
{ USB_AUDIO_LC_NOISE_SOURCE_OUT, "Level Calibration Noise Source" },
{ USB_AUDIO_EQUALIZATION_NOISE_OUT, "Equalization Noise" },
{ USB_AUDIO_CDPLAYER_IN, "CD Player" },
{ USB_AUDIO_DAT_IO, "DAT" },
{ USB_AUDIO_DCC_IO, "DCC" },
{ USB_AUDIO_MINI_DISK_IO, "Mini Disk" },
{ USB_AUDIO_ANALOG_TAPE_IO, "Analog Tape" },
{ USB_AUDIO_PHONOGRAPH_IN, "Phonograph" },
{ USB_AUDIO_VCR_AUDIO_IN, "VCR Audio" },
{ USB_AUDIO_VIDEO_DISC_AUDIO_IN, "Video Disc Audio" },
{ USB_AUDIO_DVD_AUDIO_IN, "DVD Audio" },
{ USB_AUDIO_TV_TUNER_AUDIO_IN, "TV Tuner Audio" },
{ USB_AUDIO_SAT_RECEIVER_AUDIO_IN, "Satellite Receiver Audio" },
{ USB_AUDIO_CABLE_TUNER_AUDIO_IN, "Cable Tuner Audio" },
{ USB_AUDIO_DSS_AUDIO_IN, "DSS Audio" },
{ USB_AUDIO_RADIO_RECEIVER_IN, "Radio Receiver" },
{ USB_AUDIO_RADIO_TRANSMITTER_IN, "Radio Transmitter" },
{ USB_AUDIO_MULTI_TRACK_RECORDER_IO,"Multi-track Recorder" },
{ USB_AUDIO_SYNTHESIZER_IO, "Synthesizer" },
{ USB_AUDIO_PIANO_IO, "Piano" },
{ USB_AUDIO_GUITAR_IO, "Guitar" },
{ USB_AUDIO_DRUMS_IO, "Percussion Instrument" },
{ USB_AUDIO_INSTRUMENT_IO, "Musical Instrument" }
};
for (size_t i = 0; B_COUNT_OF(termInfoPairs); i++)
if (termInfoPairs[i].type == TerminalType)
return termInfoPairs[i].description;
TRACE(ERR, "Unknown Terminal Type: %#06x", TerminalType);
return "Unknown";
}
InputTerminal::InputTerminal(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioChannelCluster<_Terminal>(interface, Header)
{
usb_audio_input_terminal_descriptor* Terminal
= (usb_audio_input_terminal_descriptor*) Header;
fID = Terminal->terminal_id;
fTerminalType = Terminal->terminal_type;
fAssociatedTerminal = Terminal->assoc_terminal;
TRACE(UAC, "Input Terminal ID:%d >>>\n", fID);
TRACE(UAC, "Terminal type:%s (%#06x)\n",
_GetTerminalDescription(fTerminalType), fTerminalType);
TRACE(UAC, "Assoc.terminal:%d\n", fAssociatedTerminal);
if (fInterface->SpecReleaseNumber() < 0x200) {
fOutChannelsNumber = Terminal->r1.num_channels;
fChannelsConfig = Terminal->r1.channel_config;
fChannelNames = Terminal->r1.channel_names;
fStringIndex = Terminal->r1.terminal;
} else {
fClockSourceId = Terminal->r2.clock_source_id;
fOutChannelsNumber = Terminal->r2.num_channels;
fChannelsConfig = Terminal->r2.channel_config;
fChannelNames = Terminal->r2.channel_names;
fControlsBitmap = Terminal->r2.bm_controls;
fStringIndex = Terminal->r2.terminal;
TRACE(UAC, "Clock Source ID:%d\n", fClockSourceId);
TRACE(UAC, "Controls Bitmap:%#04x\n", fControlsBitmap);
}
TRACE(UAC, "Out.channels num:%d\n", fOutChannelsNumber);
TRACE(UAC, "Channels config:%#06x\n", fChannelsConfig);
TRACE(UAC, "Channels names:%d\n", fChannelNames);
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
fStatus = B_OK;
}
InputTerminal::~InputTerminal()
{
}
const char*
InputTerminal::Name()
{
if (fTerminalType == USB_AUDIO_STREAMING_USB_IO)
return "USB Input";
return _Terminal::Name();
}
OutputTerminal::OutputTerminal(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_Terminal(interface, Header)
{
usb_audio_output_terminal_descriptor* Terminal
= (usb_audio_output_terminal_descriptor*) Header;
fID = Terminal->terminal_id;
fTerminalType = Terminal->terminal_type;
fAssociatedTerminal = Terminal->assoc_terminal;
fSourceID = Terminal->source_id;
TRACE(UAC, "Output Terminal ID:%d >>>\n", fID);
TRACE(UAC, "Terminal type:%s (%#06x)\n",
_GetTerminalDescription(fTerminalType), fTerminalType);
TRACE(UAC, "Assoc.terminal:%d\n", fAssociatedTerminal);
TRACE(UAC, "Source ID:%d\n", fSourceID);
if (fInterface->SpecReleaseNumber() < 0x200) {
fStringIndex = Terminal->r1.terminal;
} else {
fClockSourceId = Terminal->r2.clock_source_id;
fControlsBitmap = Terminal->r2.bm_controls;
fStringIndex = Terminal->r2.terminal;
TRACE(UAC, "Clock Source ID:%d\n", fClockSourceId);
TRACE(UAC, "Controls Bitmap:%#04x\n", fControlsBitmap);
}
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
fStatus = B_OK;
}
OutputTerminal::~OutputTerminal()
{
}
const char*
OutputTerminal::Name()
{
if (fTerminalType == USB_AUDIO_STREAMING_USB_IO)
return "USB Output";
return _Terminal::Name();
}
MixerUnit::MixerUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioChannelCluster<_AudioControl>(interface, Header),
fBmControlsR2(0)
{
usb_audio_mixer_unit_descriptor* Mixer
= (usb_audio_mixer_unit_descriptor*) Header;
fID = Mixer->unit_id;
TRACE(UAC, "Mixer ID:%d >>>\n", fID);
TRACE(UAC, "Number of input pins:%d\n", Mixer->num_input_pins);
for (size_t i = 0; i < Mixer->num_input_pins; i++) {
fInputPins.PushBack(Mixer->input_pins[i]);
TRACE(UAC, "Input pin #%d:%d\n", i, fInputPins[i]);
}
uint8* mixerControlsData = NULL;
uint8 mixerControlsSize = 0;
if (fInterface->SpecReleaseNumber() < 0x200) {
usb_audio_output_channels_descriptor_r1* OutChannels
= (usb_audio_output_channels_descriptor_r1*)
&Mixer->input_pins[Mixer->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
mixerControlsData = (uint8*) ++OutChannels;
mixerControlsSize = Mixer->length - 10 - Mixer->num_input_pins;
fStringIndex = *(mixerControlsData + mixerControlsSize);
#if 0 // TEST
if (fOutChannelsNumber > 2) {
// fOutChannelsNumber = 2;
// fChannelsConfig = 0x03;
mixerControlsData[0] = 0x80;
mixerControlsData[1] = 0x40;
mixerControlsData[2] = 0x20;
mixerControlsData[3] = 0x10;
mixerControlsData[4] = 0x08;
mixerControlsData[5] = 0x04;
mixerControlsData[6] = 0x02;
mixerControlsData[7] = 0x01;
mixerControlsData[8] = 0x80;
mixerControlsData[9] = 0x40;
mixerControlsData[10] = 0x02;
mixerControlsData[11] = 0x01;
}
#endif
} else {
usb_audio_output_channels_descriptor* OutChannels
= (usb_audio_output_channels_descriptor*)
&Mixer->input_pins[Mixer->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
mixerControlsData = (uint8*) ++OutChannels;
mixerControlsSize = Mixer->length - 13 - Mixer->num_input_pins;
fBmControlsR2 = *(mixerControlsData + mixerControlsSize);
fStringIndex = *(mixerControlsData + mixerControlsSize + 1);
TRACE(UAC, "Control Bitmap:%#04x\n", fBmControlsR2);
}
TRACE(UAC, "Out channels number:%d\n", fOutChannelsNumber);
TRACE(UAC, "Out channels config:%#06x\n", fChannelsConfig);
TRACE(UAC, "Out channels names:%d\n", fChannelNames);
TRACE(UAC, "Controls Size:%d\n", mixerControlsSize);
for (size_t i = 0; i < mixerControlsSize; i++) {
fControlsBitmap.PushBack(mixerControlsData[i]);
TRACE(UAC, "Controls Data[%d]:%#x\n", i, fControlsBitmap[i]);
}
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
fStatus = B_OK;
}
MixerUnit::~MixerUnit()
{
}
bool
MixerUnit::HasProgrammableControls()
{
for (int i = 0; i < fControlsBitmap.Count(); i++)
if (fControlsBitmap[i] != 0)
return true;
return false;
}
bool
MixerUnit::IsControlProgrammable(int inChannel, int outChannel)
{
AudioChannelCluster* outCluster = OutCluster();
if (outCluster == NULL) {
TRACE(ERR, "Output cluster is not valid.\n");
return false;
}
bool result = false;
if (outChannel < outCluster->ChannelsCount()) {
int index = inChannel * outCluster->ChannelsCount()+ outChannel;
result = (fControlsBitmap[index >> 3] & (0x80 >> (index & 7))) != 0;
}
// TRACE(UAC, "in:%d out:%d is %s\n",
// inChannel, outChannel, result ? "on" : "off");
return result;
}
SelectorUnit::SelectorUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header),
fControlsBitmap(0)
{
usb_audio_selector_unit_descriptor* Selector
= (usb_audio_selector_unit_descriptor*) Header;
fID = Selector->unit_id;
TRACE(UAC, "Selector ID:%d >>>\n", fID);
TRACE(UAC, "Number of input pins:%d\n", Selector->num_input_pins);
for (size_t i = 0; i < Selector->num_input_pins; i++) {
fInputPins.PushBack(Selector->input_pins[i]);
TRACE(UAC, "Input pin #%d:%d\n", i, fInputPins[i]);
}
if (fInterface->SpecReleaseNumber() < 0x200) {
fStringIndex = Selector->input_pins[Selector->num_input_pins];
} else {
fControlsBitmap = Selector->input_pins[Selector->num_input_pins];
fStringIndex = Selector->input_pins[Selector->num_input_pins + 1];
TRACE(UAC, "Controls Bitmap:%d\n", fControlsBitmap);
}
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
fStatus = B_OK;
}
SelectorUnit::~SelectorUnit()
{
}
AudioChannelCluster*
SelectorUnit::OutCluster()
{
if (fInterface == NULL)
return NULL;
for (int i = 0; i < fInputPins.Count(); i++) {
_AudioControl* control = fInterface->Find(fInputPins[i]);
if (control == NULL)
continue;
// selector has the same channels number in the
// out cluster as anyone of his inputs
if (control->OutCluster() != NULL)
return control->OutCluster();
}
return NULL;
}
FeatureUnit::FeatureUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_feature_unit_descriptor* Feature
= (usb_audio_feature_unit_descriptor*) Header;
fID = Feature->unit_id;
TRACE(UAC, "Feature ID:%d >>>\n", fID);
fSourceID = Feature->source_id;
TRACE(UAC, "Source ID:%d\n", fSourceID);
uint8 controlSize = 4;
uint8 channelsCount = (Feature->length - 6) / controlSize;
uint8* ControlsBitmapPointer = (uint8*)&Feature->r2.bma_controls[0];
if (fInterface->SpecReleaseNumber() < 0x200) {
controlSize = Feature->r1.control_size;
channelsCount = (Feature->length - 7) / Feature->r1.control_size;
ControlsBitmapPointer = &Feature->r1.bma_controls[0];
}
TRACE(UAC, "Channel bitmap size:%d\n", controlSize);
TRACE(UAC, "Channels number:%d\n", channelsCount - 1); // not add master!
for (size_t i = 0; i < channelsCount; i++) {
uint8* controlPointer = &ControlsBitmapPointer[i* controlSize];
switch(controlSize) {
case 1: fControlBitmaps.PushBack(*controlPointer); break;
case 2: fControlBitmaps.PushBack(*(uint16*)controlPointer); break;
case 4: fControlBitmaps.PushBack(*(uint32*)controlPointer); break;
default:
TRACE(ERR, "Feature control of unsupported size %d ignored\n",
controlSize);
continue;
}
NormalizeAndTraceChannel(i);
}
fStringIndex = ControlsBitmapPointer[channelsCount* controlSize];
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
fStatus = B_OK;
}
FeatureUnit::~FeatureUnit()
{
}
const char*
FeatureUnit::Name()
{
// first check if source of this FU is an input terminal
_AudioControl* control = fInterface->Find(fSourceID);
while (control != NULL) {
if (control->SubType() != USB_AUDIO_AC_INPUT_TERMINAL)
break;
// USB I/O terminal is a not good candidate to use it's name
if (static_cast<_Terminal*>(control)->IsUSBIO())
break;
// use the name of source input terminal as name of this FU
return control->Name();
}
// check if output of this FU is connected to output terminal
control = fInterface->FindOutputTerminal(fID);
while (control != NULL) {
if (control->SubType() != USB_AUDIO_AC_OUTPUT_TERMINAL)
break;
// USB I/O terminal is a not good candidate to use it's name
if (static_cast<_Terminal*>(control)->IsUSBIO())
break;
// use the name of this output terminal as name of this FU
return control->Name();
}
// otherwise get the generic name of this FU's source
control = fInterface->Find(fSourceID);
if (control != NULL && control->Name() != NULL
&& strlen(control->Name()) > 0)
return control->Name();
// I have no more ideas, have you one?
return "Unknown";
}
bool
FeatureUnit::HasControl(int32 Channel, uint32 Control)
{
if (Channel >= fControlBitmaps.Count()) {
TRACE(ERR, "Out of limits error of retrieving control %#010x "
"for channel %d\n", Control, Channel);
return false;
}
return (Control & fControlBitmaps[Channel]) != 0;
}
void
FeatureUnit::NormalizeAndTraceChannel(int32 Channel)
{
if (Channel >= fControlBitmaps.Count()) {
TRACE(ERR, "Out of limits error of tracing channel %d\n", Channel);
return;
}
struct _RemapInfo {
uint32 rev1Bits;
uint32 rev2Bits;
const char* name;
} remapInfos[] = {
{ BMA_CTL_MUTE_R1, BMA_CTL_MUTE, "Mute" },
{ BMA_CTL_VOLUME_R1, BMA_CTL_VOLUME, "Volume" },
{ BMA_CTL_BASS_R1, BMA_CTL_BASS, "Bass" },
{ BMA_CTL_MID_R1, BMA_CTL_MID, "Mid" },
{ BMA_CTL_TREBLE_R1, BMA_CTL_TREBLE, "Treble" },
{ BMA_CTL_GRAPHEQ_R1, BMA_CTL_GRAPHEQ, "Graphic Equalizer" },
{ BMA_CTL_AUTOGAIN_R1, BMA_CTL_AUTOGAIN, "Automatic Gain"},
{ BMA_CTL_DELAY_R1, BMA_CTL_DELAY, "Delay" },
{ BMA_CTL_BASSBOOST_R1, BMA_CTL_BASSBOOST, "Bass Boost" },
{ BMA_CTL_LOUDNESS_R1, BMA_CTL_LOUDNESS, "Loudness" },
{ 0, BMA_CTL_INPUTGAIN, "InputGain" },
{ 0, BMA_CTL_INPUTGAINPAD, "InputGainPad" },
{ 0, BMA_CTL_PHASEINVERTER, "PhaseInverter" },
{ 0, BMA_CTL_UNDERFLOW, "Underflow" },
{ 0, BMA_CTL_OVERFLOW, "Overflow" }
};
if (Channel == 0)
TRACE(UAC, "Master channel bitmap:%#x\n", fControlBitmaps[Channel]);
else
TRACE(UAC, "Channel %d bitmap:%#x\n", Channel, fControlBitmaps[Channel]);
bool isRev1 = (fInterface->SpecReleaseNumber() < 0x200);
uint32 remappedBitmap = 0;
for (size_t i = 0; i < B_COUNT_OF(remapInfos); i++) {
uint32 bits = isRev1 ? remapInfos[i].rev1Bits : remapInfos[i].rev2Bits;
if ((fControlBitmaps[Channel] & bits) > 0) {
if (isRev1)
remappedBitmap |= remapInfos[i].rev2Bits;
TRACE(UAC, "\t%s\n", remapInfos[i].name);
}
}
if (isRev1) {
TRACE(UAC, "\t%#08x -> %#08x.\n",
fControlBitmaps[Channel], remappedBitmap);
fControlBitmaps[Channel] = remappedBitmap;
}
}
EffectUnit::EffectUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_input_terminal_descriptor* descriptor
= (usb_audio_input_terminal_descriptor*) Header;
TRACE(UAC, "Effect Unit:%d >>>\n", descriptor->terminal_id);
}
EffectUnit::~EffectUnit()
{
}
ProcessingUnit::ProcessingUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioChannelCluster<_AudioControl>(interface, Header),
fProcessType(0),
fControlsBitmap(0)
{
usb_audio_processing_unit_descriptor* Processing
= (usb_audio_processing_unit_descriptor*) Header;
fID = Processing->unit_id;
TRACE(UAC, "Processing ID:%d >>>\n", fID);
fProcessType = Processing->process_type;
TRACE(UAC, "Processing Type:%d\n", fProcessType);
TRACE(UAC, "Number of input pins:%d\n", Processing->num_input_pins);
for (size_t i = 0; i < Processing->num_input_pins; i++) {
fInputPins.PushBack(Processing->input_pins[i]);
TRACE(UAC, "Input pin #%d:%d\n", i, fInputPins[i]);
}
if (fInterface->SpecReleaseNumber() < 0x200) {
usb_audio_output_channels_descriptor_r1* OutChannels
= (usb_audio_output_channels_descriptor_r1*)
&Processing->input_pins[Processing->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
} else {
usb_audio_output_channels_descriptor* OutChannels
= (usb_audio_output_channels_descriptor*)
&Processing->input_pins[Processing->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
}
TRACE(UAC, "Out channels number:%d\n", fOutChannelsNumber);
TRACE(UAC, "Out channels config:%#06x\n", fChannelsConfig);
TRACE(UAC, "Out channels names:%d\n", fChannelNames);
/*
uint8 controlsSize = Processing->length - 10 - Processing->num_input_pins;
TRACE(UAC, "Controls Size:%d\n", controlsSize);
uint8* controlsData = (uint8*) ++OutChannels;
for (size_t i = 0; i < controlsSize; i++) {
fProgrammableControls.PushBack(controlsData[i]);
TRACE(UAC, "Controls Data[%d]:%#x\n", i, controlsData[i]);
}
fStringIndex = *(controlsData + controlsSize);
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
*/
fStatus = B_OK;
}
ProcessingUnit::~ProcessingUnit()
{
}
ExtensionUnit::ExtensionUnit(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioChannelCluster<_AudioControl>(interface, Header),
fExtensionCode(0),
fControlsBitmap(0)
{
usb_audio_extension_unit_descriptor* Extension
= (usb_audio_extension_unit_descriptor*) Header;
fID = Extension->unit_id;
TRACE(UAC, "Extension ID:%d >>>\n", fID);
fExtensionCode = Extension->extension_code;
TRACE(UAC, "Extension Type:%d\n", fExtensionCode);
TRACE(UAC, "Number of input pins:%d\n", Extension->num_input_pins);
for (size_t i = 0; i < Extension->num_input_pins; i++) {
fInputPins.PushBack(Extension->input_pins[i]);
TRACE(UAC, "Input pin #%d:%d\n", i, fInputPins[i]);
}
if (fInterface->SpecReleaseNumber() < 0x200) {
usb_audio_output_channels_descriptor_r1* OutChannels
= (usb_audio_output_channels_descriptor_r1*)
&Extension->input_pins[Extension->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
} else {
usb_audio_output_channels_descriptor* OutChannels
= (usb_audio_output_channels_descriptor*)
&Extension->input_pins[Extension->num_input_pins];
fOutChannelsNumber = OutChannels->num_output_pins;
fChannelsConfig = OutChannels->channel_config;
fChannelNames = OutChannels->channel_names;
}
TRACE(UAC, "Out channels number:%d\n", fOutChannelsNumber);
TRACE(UAC, "Out channels config:%#06x\n", fChannelsConfig);
TRACE(UAC, "Out channels names:%d\n", fChannelNames);
/*
uint8 controlsSize = Processing->length - 10 - Processing->num_input_pins;
TRACE(UAC, "Controls Size:%d\n", controlsSize);
uint8* controlsData = (uint8*) ++OutChannels;
for (size_t i = 0; i < controlsSize; i++) {
fProgrammableControls.PushBack(controlsData[i]);
TRACE(UAC, "Controls Data[%d]:%#x\n", i, controlsData[i]);
}
fStringIndex = *(controlsData + controlsSize);
TRACE(UAC, "StringIndex:%d\n", fStringIndex);
*/
fStatus = B_OK;
}
ExtensionUnit::~ExtensionUnit()
{
}
ClockSource::ClockSource(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_input_terminal_descriptor* descriptor
= (usb_audio_input_terminal_descriptor*) Header;
TRACE(UAC, "Clock Source:%d >>>\n", descriptor->terminal_id);
}
ClockSource::~ClockSource()
{
}
ClockSelector::ClockSelector(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_input_terminal_descriptor* descriptor
= (usb_audio_input_terminal_descriptor*) Header;
TRACE(UAC, "Clock Selector:%d >>>\n", descriptor->terminal_id);
}
ClockSelector::~ClockSelector()
{
}
ClockMultiplier::ClockMultiplier(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_input_terminal_descriptor* descriptor
= (usb_audio_input_terminal_descriptor*) Header;
TRACE(UAC, "Clock Multiplier:%d >>>\n", descriptor->terminal_id);
}
ClockMultiplier::~ClockMultiplier()
{
}
SampleRateConverter::SampleRateConverter(AudioControlInterface* interface,
usb_audiocontrol_header_descriptor* Header)
:
_AudioControl(interface, Header)
{
usb_audio_input_terminal_descriptor* descriptor
= (usb_audio_input_terminal_descriptor*) Header;
TRACE(UAC, "Sample Rate Converter:%d >>>\n", descriptor->terminal_id);
}
SampleRateConverter::~SampleRateConverter()
{
}
AudioControlInterface::AudioControlInterface(Device* device)
:
fInterface(0),
fStatus(B_NO_INIT),
fADCSpecification(0),
fFunctionCategory(0),
fControlsBitmap(0),
fDevice(device)
{
}
AudioControlInterface::~AudioControlInterface()
{
for (AudioControlsIterator I = fAudioControls.Begin();
I != fAudioControls.End(); I++)
delete I->Value();
fAudioControls.MakeEmpty();
// object already freed. just purge the map
fOutputTerminals.MakeEmpty();
// object already freed. just purge the map
fInputTerminals.MakeEmpty();
}
status_t
AudioControlInterface::Init(size_t interface, usb_interface_info* Interface)
{
for (size_t i = 0; i < Interface->generic_count; i++) {
usb_audiocontrol_header_descriptor* Header
= (usb_audiocontrol_header_descriptor* )Interface->generic[i];
if (Header->descriptor_type != USB_AUDIO_CS_INTERFACE) {
TRACE(ERR, "Ignore Audio Control of "
"unknown descriptor type %#04x.\n", Header->descriptor_type);
continue;
}
_AudioControl* control = NULL;
switch(Header->descriptor_subtype) {
default:
TRACE(ERR, "Ignore Audio Control of unknown "
"descriptor sub-type %#04x\n", Header->descriptor_subtype);
break;
case USB_AUDIO_AC_DESCRIPTOR_UNDEFINED:
TRACE(ERR, "Ignore Audio Control of undefined sub-type\n");
break;
case USB_AUDIO_AC_HEADER:
InitACHeader(interface, Header);
break;
case USB_AUDIO_AC_INPUT_TERMINAL:
control = new(std::nothrow) InputTerminal(this, Header);
break;
case USB_AUDIO_AC_OUTPUT_TERMINAL:
control = new(std::nothrow) OutputTerminal(this, Header);
break;
case USB_AUDIO_AC_MIXER_UNIT:
control = new(std::nothrow) MixerUnit(this, Header);
break;
case USB_AUDIO_AC_SELECTOR_UNIT:
control = new(std::nothrow) SelectorUnit(this, Header);
break;
case USB_AUDIO_AC_FEATURE_UNIT:
control = new(std::nothrow) FeatureUnit(this, Header);
break;
case USB_AUDIO_AC_PROCESSING_UNIT:
if (SpecReleaseNumber() < 200)
control = new(std::nothrow) ProcessingUnit(this, Header);
else
control = new(std::nothrow) EffectUnit(this, Header);
break;
case USB_AUDIO_AC_EXTENSION_UNIT:
if (SpecReleaseNumber() < 200)
control = new(std::nothrow) ExtensionUnit(this, Header);
else
control = new(std::nothrow) ProcessingUnit(this, Header);
break;
case USB_AUDIO_AC_EXTENSION_UNIT_R2:
control = new(std::nothrow) ExtensionUnit(this, Header);
break;
case USB_AUDIO_AC_CLOCK_SOURCE_R2:
control = new(std::nothrow) ClockSource(this, Header);
break;
case USB_AUDIO_AC_CLOCK_SELECTOR_R2:
control = new(std::nothrow) ClockSelector(this, Header);
break;
case USB_AUDIO_AC_CLOCK_MULTIPLIER_R2:
control = new(std::nothrow) ClockMultiplier(this, Header);
break;
case USB_AUDIO_AC_SAMPLE_RATE_CONVERTER_R2:
control = new(std::nothrow) SampleRateConverter(this, Header);
break;
}
if (control != 0 && control->InitCheck() == B_OK) {
switch(control->SubType()) {
case USB_AUDIO_AC_OUTPUT_TERMINAL:
fOutputTerminals.Put(control->SourceID(), control);
break;
case USB_AUDIO_AC_INPUT_TERMINAL:
fInputTerminals.Put(control->ID(), control);
break;
}
fAudioControls.Put(control->ID(), control);
} else
delete control;
}
return fStatus = B_OK;
}
_AudioControl*
AudioControlInterface::Find(uint8 id)
{
return fAudioControls.Get(id);
}
_AudioControl*
AudioControlInterface::FindOutputTerminal(uint8 id)
{
return fOutputTerminals.Get(id);
}
status_t
AudioControlInterface::InitACHeader(size_t interface,
usb_audiocontrol_header_descriptor* Header)
{
if (Header == NULL)
return fStatus = B_NO_INIT;
fInterface = interface;
fADCSpecification = Header->bcd_release_no;
TRACE(UAC, "ADCSpecification:%#06x\n", fADCSpecification);
if (fADCSpecification < 0x200) {
TRACE(UAC, "InterfacesCount:%d\n", Header->r1.in_collection);
for (size_t i = 0; i < Header->r1.in_collection; i++) {
fStreams.PushBack(Header->r1.interface_numbers[i]);
TRACE(UAC, "Interface[%d] number is %d\n", i, fStreams[i]);
}
} else {
fFunctionCategory = Header->r2.function_category;
fControlsBitmap = Header->r2.bm_controls;
TRACE(UAC, "Function Category:%#04x\n", fFunctionCategory);
TRACE(UAC, "Controls Bitmap:%#04x\n", fControlsBitmap);
}
return B_OK;
}
uint32
AudioControlInterface::GetChannelsDescription(
Vector<multi_channel_info>& Channels, multi_description* Description,
Vector<_AudioControl*>&Terminals)
{
uint32 addedChannels = 0;
for (int32 i = 0; i < Terminals.Count(); i++) {
bool bIsInputTerminal
= Terminals[i]->SubType() == USB_AUDIO_AC_INPUT_TERMINAL;
AudioChannelCluster* cluster = Terminals[i]->OutCluster();
if (cluster == 0 || cluster->ChannelsCount() <= 0) {
TRACE(ERR, "Terminal #%d ignored due null "
"channels cluster (%08x)\n", Terminals[i]->ID(), cluster);
continue;
}
uint32 channels = GetTerminalChannels(Channels, cluster,
bIsInputTerminal ? B_MULTI_INPUT_CHANNEL : B_MULTI_OUTPUT_CHANNEL);
if (bIsInputTerminal)
Description->input_channel_count += channels;
else
Description->output_channel_count += channels;
addedChannels += channels;
}
return addedChannels;
}
uint32
AudioControlInterface::GetTerminalChannels(Vector<multi_channel_info>& Channels,
AudioChannelCluster* cluster, channel_kind kind, uint32 connectors)
{
if (cluster->ChannelsCount() < 2) { // mono channel
multi_channel_info info;
info.channel_id = Channels.Count();
info.kind = kind;
info.designations= B_CHANNEL_MONO_BUS;
info.connectors = connectors;
Channels.PushBack(info);
return 1;
}
uint32 startCount = Channels.Count();
// Haiku multi-aduio designations have the same bits
// as USB Audio 2.0 cluster spatial locations :-)
for (size_t i = 0; i < kChannels; i++) {
uint32 designation = 1 << i;
if ((cluster->ChannelsConfig() & designation) == designation) {
multi_channel_info info;
info.channel_id = Channels.Count();
info.kind = kind;
info.designations= gDesignations[i].ch | gDesignations[i].bus;
info.connectors = connectors;
Channels.PushBack(info);
}
}
return Channels.Count() - startCount;
}
uint32
AudioControlInterface::GetBusChannelsDescription(
Vector<multi_channel_info>& Channels, multi_description* Description)
{
uint32 addedChannels = 0;
// first iterate output channels
for (AudioControlsIterator I = fOutputTerminals.Begin();
I != fOutputTerminals.End(); I++) {
_AudioControl* control = I->Value();
if (static_cast<_Terminal*>(control)->IsUSBIO())
continue;
AudioChannelCluster* cluster = control->OutCluster();
if (cluster == 0 || cluster->ChannelsCount() <= 0) {
TRACE(ERR, "Terminal #%d ignored due null "
"channels cluster (%08x)\n", control->ID(), cluster);
continue;
}
uint32 channels = GetTerminalChannels(Channels,
cluster, B_MULTI_OUTPUT_BUS);
Description->output_bus_channel_count += channels;
addedChannels += channels;
}
// input channels should follow too
for (AudioControlsIterator I = fInputTerminals.Begin();
I != fInputTerminals.End(); I++) {
_AudioControl* control = I->Value();
if (static_cast<_Terminal*>(control)->IsUSBIO())
continue;
AudioChannelCluster* cluster = control->OutCluster();
if (cluster == 0 || cluster->ChannelsCount() <= 0) {
TRACE(ERR, "Terminal #%d ignored due null "
"channels cluster (%08x)\n", control->ID(), cluster);
continue;
}
uint32 channels = GetTerminalChannels(Channels,
cluster, B_MULTI_INPUT_BUS);
Description->input_bus_channel_count += channels;
addedChannels += channels;
}
return addedChannels;
}
void
AudioControlInterface::_HarvestRecordFeatureUnits(_AudioControl* rootControl,
AudioControlsMap& Map)
{
if (rootControl == 0) {
TRACE(ERR, "Not processing due NULL root control.\n");
return;
}
switch(rootControl->SubType()) {
case USB_AUDIO_AC_SELECTOR_UNIT:
{
SelectorUnit* unit = static_cast<SelectorUnit*>(rootControl);
for (int i = 0; i < unit->fInputPins.Count(); i++)
_HarvestRecordFeatureUnits(Find(unit->fInputPins[i]), Map);
Map.Put(rootControl->ID(), rootControl);
}
break;
case USB_AUDIO_AC_FEATURE_UNIT:
Map.Put(rootControl->ID(), rootControl);
break;
}
}
void
AudioControlInterface::_HarvestOutputFeatureUnits(_AudioControl* rootControl,
AudioControlsMap& Map)
{
if (rootControl == 0) {
TRACE(ERR, "Not processing due NULL root control.\n");
return;
}
switch(rootControl->SubType()) {
case USB_AUDIO_AC_MIXER_UNIT:
{
MixerUnit* unit = static_cast<MixerUnit*>(rootControl);
for (int i = 0; i < unit->fInputPins.Count(); i++)
_HarvestOutputFeatureUnits(Find(unit->fInputPins[i]), Map);
Map.Put(rootControl->ID(), rootControl);
}
break;
case USB_AUDIO_AC_FEATURE_UNIT:
Map.Put(rootControl->ID(), rootControl);
break;
}
}
bool
AudioControlInterface::_InitGainLimits(multi_mix_control& Control)
{
bool canControl = false;
float current = 0.;
struct _GainInfo {
uint8 request;
int16 data;
float& value;
} gainInfos[] = {
{ USB_AUDIO_GET_CUR, 0, current },
{ USB_AUDIO_GET_MIN, 0, Control.gain.min_gain },
{ USB_AUDIO_GET_MAX, 0, Control.gain.max_gain },
{ USB_AUDIO_GET_RES, 0, Control.gain.granularity }
};
Control.gain.min_gain = 0.;
Control.gain.max_gain = 100.;
Control.gain.granularity = 1.;
size_t actualLength = 0;
for (size_t i = 0; i < B_COUNT_OF(gainInfos); i++) {
status_t status = gUSBModule->send_request(fDevice->USBDevice(),
USB_REQTYPE_INTERFACE_IN | USB_REQTYPE_CLASS,
gainInfos[i].request, REQ_VALUE(Control.id),
REQ_INDEX(Control.id), sizeof(gainInfos[i].data),
&gainInfos[i].data, &actualLength);
if (status != B_OK || actualLength != sizeof(gainInfos[i].data)) {
TRACE(ERR, "Request %d (%04x:%04x) fail:%#08x; received %d of %d\n",
i, REQ_VALUE(Control.id), REQ_INDEX(Control.id), status,
actualLength, sizeof(gainInfos[i].data));
continue;
}
if (i == 0)
canControl = true;
gainInfos[i].value = static_cast<float>(gainInfos[i].data) / 256.;
}
TRACE(ERR, "Control %s: %f dB, from %f to %f dB, step %f dB.\n",
Control.name, current, Control.gain.min_gain, Control.gain.max_gain,
Control.gain.granularity);
return canControl;
}
uint32
AudioControlInterface::_ListFeatureUnitOption(uint32 controlType,
int32& index, int32 parentIndex, multi_mix_control_info* Info,
FeatureUnit* unit, uint32 channel, uint32 channels)
{
int32 startIndex = index;
uint32 id = 0;
uint32 flags = 0;
strind_id string = S_null;
const char* name = NULL;
bool initGainLimits = false;
switch(controlType) {
case BMA_CTL_MUTE:
id = USB_AUDIO_MUTE_CONTROL;
flags = B_MULTI_MIX_ENABLE;
string = S_MUTE;
break;
case BMA_CTL_VOLUME:
id = USB_AUDIO_VOLUME_CONTROL;
flags = B_MULTI_MIX_GAIN;
string = S_GAIN;
initGainLimits = true;
break;
case BMA_CTL_AUTOGAIN:
id = USB_AUDIO_AUTOMATIC_GAIN_CONTROL;
flags = B_MULTI_MIX_ENABLE;
name = "Auto Gain";
break;
default:
TRACE(ERR, "Unsupported type %#08x ignored.\n", controlType);
return 0;
}
multi_mix_control* Controls = Info->controls;
if (unit->HasControl(channel, controlType)) {
uint32 masterIndex = CTL_ID(id, channel, unit->ID(), fInterface);
Controls[index].id = masterIndex;
Controls[index].flags = flags;
Controls[index].parent = parentIndex;
Controls[index].string = string;
if (name != NULL)
strlcpy(Controls[index].name, name, sizeof(Controls[index].name));
if (initGainLimits)
_InitGainLimits(Controls[index]);
index++;
if (channels == 2) {
Controls[index].id = CTL_ID(id, channel + 1, unit->ID(), fInterface);
Controls[index].flags = flags;
Controls[index].parent = parentIndex;
Controls[index].master = masterIndex;
Controls[index].string = string;
if (name != NULL)
strlcpy(Controls[index].name, name, sizeof(Controls[index].name));
if (initGainLimits)
_InitGainLimits(Controls[index]);
index++;
}
}
return index - startIndex;
}
int32
AudioControlInterface::_ListFeatureUnitControl(int32& index, int32 parentIndex,
multi_mix_control_info* Info, _AudioControl* control)
{
FeatureUnit* unit = static_cast<FeatureUnit*>(control);
if (unit == 0) {
TRACE(ERR, "Feature Unit for null control ignored.\n");
return 0;
}
if (index + 4 > Info->control_count) {
TRACE(ERR, "Could not list feature control group."
" Limit %d of %d has been reached.\n",
index, Info->control_count);
return 0;
}
AudioChannelCluster* cluster = unit->OutCluster();
if (cluster == 0) {
TRACE(ERR, "Control %s with null cluster ignored.\n", unit->Name());
return 0;
}
struct _ChannelInfo {
const char* Name;
uint8 channels;
uint32 Mask;
} channelInfos[] = {
{ "", 1, 0 }, // Master channel entry - no bitmask
{ "", 2, B_CHANNEL_LEFT | B_CHANNEL_RIGHT },
{ "Left", 1, B_CHANNEL_LEFT },
{ "Right", 1, B_CHANNEL_RIGHT },
{ "Center", 1, B_CHANNEL_CENTER },
{ "L.F.E.", 1, B_CHANNEL_SUB },
{ "Back", 2, B_CHANNEL_REARLEFT | B_CHANNEL_REARRIGHT },
{ "Back Left", 1, B_CHANNEL_REARLEFT },
{ "Back Right", 1, B_CHANNEL_REARRIGHT },
{ "Front of Center", 2, B_CHANNEL_FRONT_LEFT_CENTER
| B_CHANNEL_FRONT_RIGHT_CENTER },
{ "Front Left of Center", 1, B_CHANNEL_FRONT_LEFT_CENTER },
{ "Front Right of Center", 1, B_CHANNEL_FRONT_RIGHT_CENTER },
{ "Back Center", 1, B_CHANNEL_BACK_CENTER },
{ "Side", 2, B_CHANNEL_SIDE_LEFT | B_CHANNEL_SIDE_RIGHT },
{ "Side Left", 1, B_CHANNEL_SIDE_LEFT },
{ "Side Right", 1, B_CHANNEL_SIDE_RIGHT },
{ "Top Center", 1, B_CHANNEL_TOP_CENTER },
{ "Top Front Left", 1, B_CHANNEL_TOP_FRONT_LEFT },
{ "Top Front Center", 1, B_CHANNEL_TOP_FRONT_CENTER },
{ "Top Front Right", 1, B_CHANNEL_TOP_FRONT_RIGHT },
{ "Top Back Left", 1, B_CHANNEL_TOP_BACK_LEFT },
{ "Top Back Center", 1, B_CHANNEL_TOP_BACK_CENTER },
{ "Top Back Right", 1, B_CHANNEL_TOP_BACK_RIGHT }
};
multi_mix_control* Controls = Info->controls;
uint32 channelsConfig = cluster->ChannelsConfig();
int32 groupIndex = 0;
int32 channel = 0;
int32 masterIndex = 0; // in case master channel has no volume
// control - add following "L+R" channels into it
for (size_t i = 0; i < B_COUNT_OF(channelInfos); i++) {
if ((channelsConfig & channelInfos[i].Mask) != channelInfos[i].Mask) {
// ignore non-listed and possibly non-paired stereo channels.
// note that master channel with zero mask pass this check! ;-)
continue;
}
if (masterIndex == 0) {
groupIndex = index;
Controls[index].id = groupIndex;
Controls[index].flags = B_MULTI_MIX_GROUP;
Controls[index].parent = parentIndex;
snprintf(Controls[index].name, sizeof(Controls[index].name),
"%s %s", unit->Name(), channelInfos[i].Name);
index++;
} else {
groupIndex = masterIndex;
masterIndex = 0;
}
// First list possible Mute controls
_ListFeatureUnitOption(BMA_CTL_MUTE, index, groupIndex, Info,
unit, channel, channelInfos[i].channels);
// Gain controls may be usefull too
if (_ListFeatureUnitOption(BMA_CTL_VOLUME, index, groupIndex, Info,
unit, channel, channelInfos[i].channels) == 0) {
masterIndex = (i == 0) ? groupIndex : 0 ;
TRACE(UAC, "channel:%d set master index to %d\n",
channel, masterIndex);
}
// Auto Gain checkbox will be listed too
_ListFeatureUnitOption(BMA_CTL_AUTOGAIN, index, groupIndex, Info,
unit, channel, channelInfos[i].channels);
// Now check if the group filled with something usefull.
// In case no controls were added into it - "remove" it
if (Controls[index - 1].flags == B_MULTI_MIX_GROUP) {
Controls[index - 1].id = 0;
index--;
masterIndex = 0;
}
channel += channelInfos[i].channels;
// remove bits for already processed channels - this prevent from
// duplication of the stereo channels as "orphaned" ones and optimize
// exit from this iterations after all channels are processed.
channelsConfig &= ~channelInfos[i].Mask;
if (0 == channelsConfig)
break;
}
if (channelsConfig > 0)
TRACE(ERR, "Following channels were not processed: %#08x.\n",
channelsConfig);
// return last group index to stick possible selector unit to it. ;-)
return groupIndex;
}
void
AudioControlInterface::_ListSelectorUnitControl(int32& index, int32 parentGroup,
multi_mix_control_info* Info, _AudioControl* control)
{
SelectorUnit* selector = static_cast<SelectorUnit*>(control);
if (selector == 0 || selector->SubType() != USB_AUDIO_AC_SELECTOR_UNIT)
return;
if ((index + 1 + selector->fInputPins.Count()) > Info->control_count) {
TRACE(ERR, "Could not list selector control."
" Limit %d of %d has been reached.\n",
index, Info->control_count);
return;
}
multi_mix_control* Controls = Info->controls;
int32 recordMUX = CTL_ID(0, 0, selector->ID(), fInterface);
Controls[index].id = recordMUX;
Controls[index].flags = B_MULTI_MIX_MUX;
Controls[index].parent = parentGroup;
Controls[index].string = S_null;
strlcpy(Controls[index].name, "Source", sizeof(Controls[index].name));
index++;
for (int i = 0; i < selector->fInputPins.Count(); i++) {
Controls[index].id = CTL_ID(0, 1, selector->ID(), fInterface);
Controls[index].flags = B_MULTI_MIX_MUX_VALUE;
Controls[index].master = 0;
Controls[index].string = S_null;
Controls[index].parent = recordMUX;
_AudioControl* control = Find(selector->fInputPins[i]);
if (control != NULL)
strlcpy(Controls[index].name,
control->Name(), sizeof(Controls[index].name));
else
snprintf(Controls[index].name,
sizeof(Controls[index].name), "Input #%d", i + 1);
index++;
}
}
size_t
AudioControlInterface::_CollectMixerUnitControls(
const uint32 controlIds[kChannels][kChannels],
size_t inLeft, size_t outLeft, size_t inRight, size_t outRight,
const char* inputName, const char* name,
Vector<multi_mix_control>& Controls)
{
size_t count = 0;
uint32 leftId = controlIds[inLeft][outLeft];
uint32 rightId = controlIds[inRight][outRight];
// TRACE(UAC, "left:%d %d: %08x; right:%d %d: %08x\n",
// inLeft, outLeft, leftId, inRight, outRight, rightId);
multi_mix_control control;
memset(&control, 0, sizeof(multi_mix_control));
snprintf(control.name, sizeof(control.name), "%s %s", inputName, name);
for (size_t i = 0; i < 2; i++) {
if (leftId != 0 || rightId != 0) {
control.flags = B_MULTI_MIX_GROUP;
control.string = S_null;
Controls.PushBack(control);
int gainControls = 0;
if (leftId != 0) {
control.id = leftId;
control.flags = B_MULTI_MIX_GAIN;
control.string = S_GAIN;
if (_InitGainLimits(control)) {
gainControls++;
Controls.PushBack(control);
}
}
if (rightId != 0) {
control.id = rightId;
control.flags = B_MULTI_MIX_GAIN;
control.string = S_GAIN;
control.master = leftId;
if (_InitGainLimits(control)) {
gainControls++;
Controls.PushBack(control);
}
}
// remove empty mix group
if (gainControls == 0)
Controls.PopBack();
else
count++;
}
// take care about surround bus
if (inLeft == inRight)
break;
// handle possible reverse controls
leftId = controlIds[inLeft][outRight];
rightId = controlIds[inRight][outLeft];
snprintf(control.name, sizeof(control.name),
"%s %s (Reverse)", inputName, name);
}
return count;
}
void
AudioControlInterface::_ListMixerUnitControls(int32& index,
multi_mix_control_info* Info, Vector<multi_mix_control>& controls)
{
multi_mix_control* Controls = Info->controls;
uint32 groupParent = 0;
uint32 gainParent = 0;
for (Vector<multi_mix_control>::Iterator I = controls.Begin();
I != controls.End() && index < Info->control_count; I++) {
memcpy(Controls + index, &*I, sizeof(multi_mix_control));
switch (I->flags) {
case B_MULTI_MIX_GROUP:
Controls[index].id = index;
Controls[index].parent = groupParent;
if (groupParent == 0) {
Controls[index].id |= 0x10000;
groupParent = Controls[index].id;
}
gainParent = Controls[index].id;
break;
case B_MULTI_MIX_GAIN:
Controls[index].parent = gainParent;
break;
default:
TRACE(ERR, "Control type %d ignored\n", I->flags);
continue;
}
index++;
}
if (index == Info->control_count)
TRACE(ERR, "Control count limit %d has been reached.\n", index);
}
void
AudioControlInterface::_ListMixControlsForMixerUnit(int32& index,
multi_mix_control_info* Info, _AudioControl* control)
{
MixerUnit* mixer = static_cast<MixerUnit*>(control);
if (mixer == 0 || mixer->SubType() != USB_AUDIO_AC_MIXER_UNIT)
return;
struct _ChannelPair {
size_t inLeft;
size_t inRight;
const char* name;
} channelPairs[] = {
{ 0, 1, "" },
{ 2, 2, "Center" },
{ 3, 3, "L.F.E" },
{ 4, 5, "Back" },
{ 6, 7, "Front of Center" },
{ 8, 8, "Back Center" },
{ 9, 10, "Side" },
{ 11, 11, "Top Center" },
{ 12, 14, "Top Front" },
{ 13, 13, "Top Front Center" },
{ 15, 17, "Top Back" },
{ 16, 16, "Top Back Center" }
};
Vector<_MixPageCollector*> mixControls;
_MixPageCollector* genericPage = new(std::nothrow) _MixPageCollector("Mixer");
mixControls.PushBack(genericPage);
// page for extended in (>2) and out (>2) mixer controls
size_t controlsOnExMixerPage = 0;
_MixPageCollector* exMixerPage = new(std::nothrow) _MixPageCollector("Mixer");
AudioChannelCluster* outCluster = mixer->OutCluster();
int inOffset = 0;
for (int iPin = 0; iPin < mixer->fInputPins.Count(); iPin++) {
_AudioControl* control = Find(mixer->fInputPins[iPin]);
AudioChannelCluster* inCluster = NULL;
if (control != NULL)
inCluster = control->OutCluster();
if (inCluster == NULL) {
TRACE(ERR, "control %p cluster %p failed!\n", control, inCluster);
break;
}
// at first - collect programmable control ids
uint32 controlIds[kChannels][kChannels] = { { 0 } };
int inChannel = 0;
for (size_t in = 0; in < kChannels
&& inChannel < inCluster->ChannelsCount(); in++) {
if ((inCluster->ChannelsConfig() & (1 << in)) == 0)
continue;
for (size_t out = 0, outChannel = 0; out < kChannels
&& outChannel < outCluster->ChannelsCount(); out++) {
if ((outCluster->ChannelsConfig() & (1 << out)) == 0)
continue;
if (mixer->IsControlProgrammable(
inOffset + inChannel, outChannel)) {
if (SpecReleaseNumber() < 0x200)
// USB Audio 1.0 uses ICN/OCN for request
controlIds[in][out] = CTL_ID(inOffset + inChannel + 1,
outChannel + 1, mixer->ID(), fInterface);
else
// USB Audio 2.0 uses CS/MCN for request
controlIds[in][out] = CTL_ID(USB_AUDIO_MIXER_CONTROL,
(inOffset + inChannel) * outCluster->ChannelsCount()
+ outChannel, mixer->ID(), fInterface);
}
outChannel++;
}
inChannel++;
}
inOffset += inChannel;
for (size_t in = 0; in < kChannels; in++)
for (size_t out = 0; out < kChannels; out++)
if (controlIds[in][out] != 0)
TRACE(UAC, "ctrl:%08x for in %d; out %d;\n",
controlIds[in][out], in, out);
// second step - distribute controls on
// mixer pages in logical groups
uint32 exChannelsMask = ~(B_CHANNEL_LEFT | B_CHANNEL_RIGHT);
bool inIsEx = (inCluster->ChannelsConfig() & exChannelsMask) != 0;
bool outIsEx = (outCluster->ChannelsConfig() & exChannelsMask) != 0;
if (!inIsEx && !outIsEx) {
// heap up all mono and stereo controls into single "Mixer" page
for (size_t i = 0; i < 2; i++)
_CollectMixerUnitControls(controlIds,
kLeftChannel, channelPairs[i].inLeft,
kRightChannel, channelPairs[i].inRight,
control->Name(), channelPairs[i].name,
*mixControls[0]);
continue; // go next input cluster
}
if (!outIsEx) {
// special case - extended (>2 channels) input cluster
// connected to 2-channels output - add into generic "Mixer" page
for (size_t i = 0; i < B_COUNT_OF(channelPairs); i++)
_CollectMixerUnitControls(controlIds,
channelPairs[i].inLeft, kLeftChannel,
channelPairs[i].inRight, kRightChannel,
control->Name(), channelPairs[i].name,
*mixControls[0]);
continue; // go next input cluster
}
// make separate mixer pages for set of extended (>2) input
// channels connected to extended (>2 channels) output
for (size_t in = 0; in < B_COUNT_OF(channelPairs); in++) {
for (size_t out = 0; out < B_COUNT_OF(channelPairs); out++) {
char outName[sizeof(Info->controls->name)] = { 0 };
if (in == out)
strlcpy(outName, channelPairs[out].name, sizeof(outName));
else
snprintf(outName, sizeof(outName), "%s to %s",
channelPairs[in].name, channelPairs[out].name);
controlsOnExMixerPage += _CollectMixerUnitControls(controlIds,
channelPairs[in].inLeft, channelPairs[out].inLeft,
channelPairs[in].inRight, channelPairs[out].inRight,
control->Name(), outName, *exMixerPage);
}
if (controlsOnExMixerPage >= 6) {
mixControls.PushBack(exMixerPage);
exMixerPage = new(std::nothrow) _MixPageCollector("Mixer");
controlsOnExMixerPage = 0;
}
}
}
if (exMixerPage->Count() > 1)
mixControls.PushBack(exMixerPage);
else
delete exMixerPage;
// final step - fill multiaudio controls info with
// already structured pages/controls info arrays
for (Vector<_MixPageCollector*>::Iterator I = mixControls.Begin();
I != mixControls.End(); I++) {
Vector<multi_mix_control>* controls = *I;
TRACE(UAC, "controls count: %d\n", controls->Count());
if (controls->Count() > 1)
_ListMixerUnitControls(index, Info, *controls);
delete controls;
}
}
void
AudioControlInterface::_ListMixControlsPage(int32& index,
multi_mix_control_info* Info, AudioControlsMap& Map, const char* Name)
{
multi_mix_control* Controls = Info->controls;
int32 groupIndex = index | 0x10000;
Controls[index].id = groupIndex;
Controls[index].flags = B_MULTI_MIX_GROUP;
Controls[index].parent = 0;
strlcpy(Controls[index].name, Name, sizeof(Controls[index].name));
index++;
int32 group = groupIndex;
for (AudioControlsIterator I = Map.Begin(); I != Map.End(); I++) {
TRACE(UAC, "%s control %d listed.\n", Name, I->Value()->ID());
switch(I->Value()->SubType()) {
case USB_AUDIO_AC_FEATURE_UNIT:
group = _ListFeatureUnitControl(index, groupIndex,
Info, I->Value());
break;
case USB_AUDIO_AC_SELECTOR_UNIT:
_ListSelectorUnitControl(index, group, Info, I->Value());
break;
default:
break;
}
}
}
status_t
AudioControlInterface::ListMixControls(multi_mix_control_info* Info)
{
// first harvest feature units that assigned to output terminal(s)
AudioControlsMap RecordControlsMap;
AudioControlsMap OutputControlsMap;
for (AudioControlsIterator I = fOutputTerminals.Begin();
I != fOutputTerminals.End(); I++) {
_Terminal* terminal = static_cast<_Terminal*>(I->Value());
if (terminal->IsUSBIO())
_HarvestRecordFeatureUnits(terminal, RecordControlsMap);
else
_HarvestOutputFeatureUnits(terminal, OutputControlsMap);
}
// separate input and output Feature units
// and collect mixer units that can be controlled
AudioControlsMap InputControlsMap;
AudioControlsMap MixerControlsMap;
for (AudioControlsIterator I = fAudioControls.Begin();
I != fAudioControls.End(); I++) {
_AudioControl* control = I->Value();
if (control->SubType() == USB_AUDIO_AC_MIXER_UNIT) {
MixerUnit* mixerControl = static_cast<MixerUnit*>(control);
if (mixerControl->HasProgrammableControls())
MixerControlsMap.Put(control->ID(), control);
continue;
}
// filter out feature units
if (control->SubType() != USB_AUDIO_AC_FEATURE_UNIT)
continue;
// ignore controls that are already in the output controls maps
if (RecordControlsMap.Find(control->ID()) != RecordControlsMap.End()
|| OutputControlsMap.Find(control->ID()) != OutputControlsMap.End())
continue;
_AudioControl* sourceControl = Find(control->SourceID());
if (sourceControl != 0
&& sourceControl->SubType() == USB_AUDIO_AC_INPUT_TERMINAL)
InputControlsMap.Put(control->ID(), control);
else
OutputControlsMap.Put(control->ID(), control);
}
int32 index = 0;
if (InputControlsMap.Count() > 0)
_ListMixControlsPage(index, Info, InputControlsMap, "Input");
if (OutputControlsMap.Count() > 0)
_ListMixControlsPage(index, Info, OutputControlsMap, "Output");
if (RecordControlsMap.Count() > 0)
_ListMixControlsPage(index, Info, RecordControlsMap, "Record");
for (AudioControlsIterator I = MixerControlsMap.Begin();
I != MixerControlsMap.End(); I++)
_ListMixControlsForMixerUnit(index, Info, I->Value());
Info->control_count = index;
return B_OK;
}
status_t
AudioControlInterface::GetMix(multi_mix_value_info* Info)
{
for (int32 i = 0; i < Info->item_count; i++) {
uint16 length = 0;
int16 data = 0;
_AudioControl* control = Find(ID_FROM_CTLID(Info->values[i].id));
if (control == NULL) {
TRACE(ERR, "No control found for unit id %#02x. Ignore it.\n",
ID_FROM_CTLID(Info->values[i].id));
continue;
}
switch (control->SubType()) {
case USB_AUDIO_AC_FEATURE_UNIT:
switch(CS_FROM_CTLID(Info->values[i].id)) {
case USB_AUDIO_VOLUME_CONTROL:
length = 2;
break;
case USB_AUDIO_MUTE_CONTROL:
case USB_AUDIO_AUTOMATIC_GAIN_CONTROL:
length = 1;
break;
default:
TRACE(ERR, "Unsupported control id:%08x of type %#02x "
"ignored.\n", ID_FROM_CTLID(Info->values[i].id),
CS_FROM_CTLID(Info->values[i].id));
continue;
}
break;
case USB_AUDIO_AC_SELECTOR_UNIT:
length = 1;
break;
case USB_AUDIO_AC_MIXER_UNIT:
length = 2;
break;
default:
TRACE(ERR, "Control id:%08x of type %d is not supported\n",
ID_FROM_CTLID(Info->values[i].id), control->SubType());
continue;
}
size_t actualLength = 0;
status_t status = gUSBModule->send_request(fDevice->USBDevice(),
USB_REQTYPE_INTERFACE_IN | USB_REQTYPE_CLASS, USB_AUDIO_GET_CUR,
REQ_VALUE(Info->values[i].id), REQ_INDEX(Info->values[i].id),
length, &data, &actualLength);
if (status != B_OK || actualLength != length) {
TRACE(ERR, "Request (%04x:%04x) failed:%#08x; received %d of %d\n",
REQ_VALUE(Info->values[i].id), REQ_INDEX(Info->values[i].id),
status, actualLength, length);
continue;
}
switch (control->SubType()) {
case USB_AUDIO_AC_FEATURE_UNIT:
switch(CS_FROM_CTLID(Info->values[i].id)) {
case USB_AUDIO_VOLUME_CONTROL:
Info->values[i].gain = static_cast<float>(data) / 256.;
TRACE(MIX, "Gain control %d; channel: %d; is %f dB.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].gain);
break;
case USB_AUDIO_MUTE_CONTROL:
Info->values[i].enable = data > 0;
TRACE(MIX, "Mute control %d; channel: %d; is %d.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].enable);
break;
case USB_AUDIO_AUTOMATIC_GAIN_CONTROL:
Info->values[i].enable = data > 0;
TRACE(MIX, "AGain control %d; channel: %d; is %d.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].enable);
break;
default:
break;
}
break;
case USB_AUDIO_AC_SELECTOR_UNIT:
Info->values[i].mux = data - 1;
TRACE(MIX, "Selector control %d; is %d.\n",
ID_FROM_CTLID(Info->values[i].id),
Info->values[i].mux);
break;
case USB_AUDIO_AC_MIXER_UNIT:
Info->values[i].gain = static_cast<float>(data) / 256.;
TRACE(MIX, "Mixer #%d channels in: %d; out: %d; is %f dB.\n",
ID_FROM_CTLID(Info->values[i].id),
CS_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].gain);
break;
}
}
return B_OK;
}
status_t
AudioControlInterface::SetMix(multi_mix_value_info* Info)
{
for (int32 i = 0; i < Info->item_count; i++) {
uint16 length = 0;
int16 data = 0;
_AudioControl* control = Find(ID_FROM_CTLID(Info->values[i].id));
if (control == NULL) {
TRACE(ERR, "No control found for unit id %#02x. Ignore it.\n",
ID_FROM_CTLID(Info->values[i].id));
continue;
}
switch (control->SubType()) {
case USB_AUDIO_AC_FEATURE_UNIT:
switch(CS_FROM_CTLID(Info->values[i].id)) {
case USB_AUDIO_VOLUME_CONTROL:
data = static_cast<int16>(Info->values[i].gain * 256.);
length = 2;
TRACE(MIX, "Gain control %d; channel: %d; "
"about to set to %f dB.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].gain);
break;
case USB_AUDIO_MUTE_CONTROL:
data = (Info->values[i].enable ? 1 : 0);
length = 1;
TRACE(MIX, "Mute control %d; channel: %d; "
"about to set to %d.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].enable);
break;
case USB_AUDIO_AUTOMATIC_GAIN_CONTROL:
data = (Info->values[i].enable ? 1 : 0);
length = 1;
TRACE(MIX, "AGain control %d; channel: %d; "
"about to set to %d.\n",
ID_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].enable);
break;
default:
TRACE(ERR, "Unsupported control id:%08x of type %#02x "
"ignored.\n", ID_FROM_CTLID(Info->values[i].id),
CS_FROM_CTLID(Info->values[i].id));
continue;
}
break;
case USB_AUDIO_AC_SELECTOR_UNIT:
data = Info->values[i].mux + 1;
length = 1;
TRACE(MIX, "Selector Control %d about to set to %d.\n",
ID_FROM_CTLID(Info->values[i].id),
Info->values[i].mux);
break;
case USB_AUDIO_AC_MIXER_UNIT:
data = static_cast<int16>(Info->values[i].gain * 256.);
length = 2;
TRACE(MIX, "Mixer %d channels in: %d; out: %d; "
"about to set to %f dB.\n",
ID_FROM_CTLID(Info->values[i].id),
CS_FROM_CTLID(Info->values[i].id),
CN_FROM_CTLID(Info->values[i].id),
Info->values[i].gain);
break;
default:
TRACE(ERR, "Control id:%08x of type %d is not supported\n",
Info->values[i].id, control->SubType());
continue;
}
size_t actualLength = 0;
status_t status = gUSBModule->send_request(fDevice->USBDevice(),
USB_REQTYPE_INTERFACE_OUT | USB_REQTYPE_CLASS, USB_AUDIO_SET_CUR,
REQ_VALUE(Info->values[i].id), REQ_INDEX(Info->values[i].id),
length, &data, &actualLength);
if (status != B_OK || actualLength != length) {
TRACE(ERR, "Request (%04x:%04x) failed:%#08x; send %d of %d\n",
REQ_VALUE(Info->values[i].id), REQ_INDEX(Info->values[i].id),
status, actualLength, length);
continue;
}
TRACE(MIX, "Value set OK\n");
}
return B_OK;
}
| 28.974605 | 80 | 0.699537 |
4388cd88e0e7fae60690037c4eea7beeb2261960 | 2,296 | asm | Assembly | programs/oeis/228/A228124.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/228/A228124.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/228/A228124.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A228124: Number of blocks in a Steiner Quadruple System of order A047235(n+1).
; 1,14,30,91,140,285,385,650,819,1240,1496,2109,2470,3311,3795,4900,5525,6930,7714,9455,10416,12529,13685,16206,17575,20540,22140,25585,27434,31395,33511,38024,40425,45526,48230,53955,56980,63365,66729,73810,77531,85344,89440,98021,102510,111895,116795,127020,132349,143450,149226,161239,167480,180441,187165,201110,208335,223300,231044,247065,255346,272459,281295,299536,308945,328350,338350,358955,369564,391405,402641,425754,437635,462056,474600,500365,513590,540735,554659,583220,597861,627874,643250,674751,690880,723905,740805,775390,793079,829260,847756,885569,904890,944371,964535,1005720,1026745,1069670,1091574,1136275,1159076,1205589,1229305,1277666,1302315,1352560,1378160,1430325,1456894,1511015,1538571,1594684,1623245,1681386,1710970,1771175,1801800,1864105,1895789,1960230,1992991,2059604,2093460,2162281,2197250,2268315,2304415,2377760,2415009,2490670,2529086,2607099,2646700,2727101,2767905,2850730,2892755,2978040,3021304,3109085,3153606,3243919,3289715,3382596,3429685,3525170,3573570,3671695,3721424,3822225,3873301,3976814,4029255,4135516,4189340,4298385,4353610,4465475,4522119,4636840,4694921,4812534,4872070,4992611,5053620,5177125,5239625,5366130,5430139,5559680,5625216,5757829,5824910,5960631,6029275,6168140,6238365,6380410,6452234,6597495,6670936,6819449,6894525,7046326,7123055,7278180,7356580,7515065,7595154,7757035,7838831,8004144,8087665,8256446,8341710,8513995,8601020,8776845,8865649,9045050,9135651,9318664,9411080,9597741,9691990,9882335,9978435,10172500,10270469,10468290,10568146,10769759,10871520,11076961,11180645,11389950,11495575,11708780,11816364,12033505,12143066,12364179,12475735,12700856,12814425,13043590,13159190,13392435,13510084,13747445,13867161,14108674,14230475,14476176,14600080,14850005,14976030,15230215,15358379,15616860,15747181,16009994,16142490,16409671,16544360,16815945,16952845,17228870,17367999,17648500
mov $2,$0
add $2,1
mov $7,$0
lpb $2,1
mov $0,$7
sub $2,1
sub $0,$2
add $0,1
mul $0,6
mov $5,6
lpb $0,1
trn $0,2
mov $6,$0
add $0,2
gcd $0,4
sub $0,1
add $4,$5
pow $6,2
add $4,$6
mov $5,$6
lpe
div $3,$4
mov $6,$4
mov $4,$3
mov $3,$6
div $3,48
mul $3,3
add $3,1
add $1,$3
lpe
| 67.529412 | 1,871 | 0.796603 |
e8d88902f01648a1a306cb467ca0848605b55795 | 855 | cpp | C++ | 1301-1400/1372-Longest ZigZag Path in a Binary Tree/1372-Longest ZigZag Path in a Binary Tree.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 1301-1400/1372-Longest ZigZag Path in a Binary Tree/1372-Longest ZigZag Path in a Binary Tree.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 1301-1400/1372-Longest ZigZag Path in a Binary Tree/1372-Longest ZigZag Path in a Binary Tree.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestZigZag(TreeNode* root) {
int maxLen = 0, leftLen = -1, rightLen = -1;
dfs(root, leftLen, rightLen, maxLen);
return maxLen;
}
private:
void dfs(TreeNode* root, int& leftLen, int& rightLen, int& maxLen) {
if (root == nullptr) {
return;
}
int leftLen1 = -1, rightLen1 = -1, leftLen2 = -1, rightLen2 = -1;
dfs(root->left, leftLen1, rightLen1, maxLen);
dfs(root->right, leftLen2, rightLen2, maxLen);
maxLen = max(maxLen, 1 + max(rightLen1, leftLen2));
leftLen = 1 + rightLen1;
rightLen = 1 + leftLen2;
}
};
| 27.580645 | 73 | 0.555556 |
64ea0a866486f914f485bb50eeca860429d3c621 | 5,373 | java | Java | src/main/java/com/aneeshajose/genericadapters/GenericRecyclerViewAdapter.java | aneesha-jose/genericadapters | d58b2ab6a18af389af16f661fc24217863254246 | [
"Apache-2.0"
] | 2 | 2020-09-16T02:51:54.000Z | 2021-12-03T02:40:11.000Z | src/main/java/com/aneeshajose/genericadapters/GenericRecyclerViewAdapter.java | aneesha-jose/genericadapters | d58b2ab6a18af389af16f661fc24217863254246 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/aneeshajose/genericadapters/GenericRecyclerViewAdapter.java | aneesha-jose/genericadapters | d58b2ab6a18af389af16f661fc24217863254246 | [
"Apache-2.0"
] | null | null | null | package com.aneeshajose.genericadapters;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.aneeshajose.genericadapters.model.AbstractBetterViewHolder;
import com.aneeshajose.genericadapters.model.ItemEncapsulator;
import com.aneeshajose.genericadapters.utils.GenericAdapterUtilsKt;
import com.aneeshajose.miscellaneous.utils.Optional;
import java.util.ArrayList;
import java.util.List;
public class GenericRecyclerViewAdapter<T extends ItemEncapsulator> extends RecyclerView.Adapter<AbstractBetterViewHolder<T>> implements Filterable, GenericDialogListFilter.GenericDialogListFilterListener<T> {
private List<T> selectedItems = new ArrayList<>();
protected List<T> mItems = new ArrayList<>();
private GenericAdapterListener<T> listener;
private GenericDialogListFilter<T> filter;
public GenericRecyclerViewAdapter(GenericAdapterListener<T> listener) {
this.listener = listener;
if (listener != null && listener.getItems() != null)
mItems.addAll(listener.getItems());
}
public void setListener(GenericAdapterListener<T> listener) {
this.listener = listener;
if (listener != null && listener.getItems() != null) {
mItems.clear();
mItems.addAll(listener.getItems());
}
}
public void setSelectedItems(List<T> selectedItems) {
if (selectedItems != null)
this.selectedItems = new ArrayList<>(selectedItems);
notifyDataSetChanged();
}
public List<T> getSelectedItems() {
return selectedItems;
}
public List<T> getSelectedItemsOfCertainClass(final Class cls) {
return GenericAdapterUtilsKt.getItemEncapsulatorsWithItemClassType(selectedItems,cls);
}
public void addToSelectedItems(T item) {
if (selectedItems == null)
selectedItems = new ArrayList<>();
selectedItems.add(item);
notifyDataSetChanged();
}
public void removeFromSelectedItem(ItemEncapsulator item) {
if (selectedItems == null)
selectedItems = new ArrayList<>();
selectedItems.remove(item);
notifyDataSetChanged();
}
public void clearSelectedItems() {
if (selectedItems == null)
selectedItems = new ArrayList<>();
selectedItems.clear();
notifyDataSetChanged();
}
@NonNull
@Override
public AbstractBetterViewHolder<T> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return listener.getViewHolder(listener.getView(parent, viewType), viewType);
}
@Override
public void onBindViewHolder(@NonNull AbstractBetterViewHolder<T> holder, int position) {
T item = mItems.get(position);
if (listener.isTypeClickable(item.getItemType()) || listener.isTypeSelectable(item.getItemType())) {
holder.itemView.setOnClickListener(v -> {
if (listener.isTypeSelectable(item.getItemType())) {
boolean isSelected = !selectedItems.contains(item);
if (listener.isSingleSelection() && listener.maxSelectableItems() != 1) {
selectedItems.clear();
}
if (selectedItems.size() < listener.maxSelectableItems() || !isSelected) {
if (listener != null) {
listener.onItemSelectionChanged(position, isSelected, item);
}
if (isSelected)
addToSelectedItems(item);
else
removeFromSelectedItem(item);
}
return;
}
listener.onItemClicked(position, item);
});
}
listener.setSelectedIndicator(holder, selectedItems.contains(item));
holder.bind(item, getItemCount(), position);
}
@Override
public int getItemCount() {
return mItems.size();
}
@Override
public int getItemViewType(int position) {
return Optional.orElse(mItems.get(position).getItemType(), super.getItemViewType(position)).get();
}
@Override
public long getItemId(int position) {
return mItems.get(position) == null ? super.getItemId(position) : mItems.get(position).hashCode();
}
@Override
public Filter getFilter() {
if (filter == null)
filter = new GenericDialogListFilter<>(this);
filter.setMasterList(listener.getItems());
return filter;
}
@Override
public List<T> filterResults(List<T> masterList, String searchConstraint) {
return listener == null ? masterList : listener.filterResults(masterList, searchConstraint);
}
@Override
public void publishResults(List<T> filteredList) {
if (mItems == null)
mItems = new ArrayList<>();
else mItems.clear();
mItems.addAll(Optional.orElse(filteredList, new ArrayList<T>()).get());
notifyDataSetChanged();
}
public void resetItems(List<T> items) {
if (selectedItems == null)
selectedItems = new ArrayList<>();
else selectedItems.clear();
publishResults(items);
}
}
| 35.117647 | 209 | 0.638563 |
3bec4437d6c5f21d22ce31a1475a90ecc00cc878 | 770 | dart | Dart | lib/home_page.dart | JLodha/find-my-senior | 79565b68da4797232defd2030e668637c71a5a93 | [
"MIT"
] | null | null | null | lib/home_page.dart | JLodha/find-my-senior | 79565b68da4797232defd2030e668637c71a5a93 | [
"MIT"
] | null | null | null | lib/home_page.dart | JLodha/find-my-senior | 79565b68da4797232defd2030e668637c71a5a93 | [
"MIT"
] | null | null | null | import 'package:find_my_senior/root.dart';
import 'package:find_my_senior/services/auth_service.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final AuthService _auth = AuthService();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () async {
_auth.signOutUser();
Navigator.push(
context, MaterialPageRoute(builder: (context) => Root()));
},
child: Text('Logout'),
),
),
);
}
}
| 23.333333 | 74 | 0.628571 |
3d2e945893319adf0c77162d1f634e62228ab144 | 241,902 | dart | Dart | generated/googleapis/lib/retail/v2.dart | interpretme/googleapis.dart | 5fa41daad6f25d89bdffc2d2cdfc633cce7a5dc3 | [
"BSD-3-Clause"
] | null | null | null | generated/googleapis/lib/retail/v2.dart | interpretme/googleapis.dart | 5fa41daad6f25d89bdffc2d2cdfc633cce7a5dc3 | [
"BSD-3-Clause"
] | null | null | null | generated/googleapis/lib/retail/v2.dart | interpretme/googleapis.dart | 5fa41daad6f25d89bdffc2d2cdfc633cce7a5dc3 | [
"BSD-3-Clause"
] | null | null | null | // This is a generated file (see the discoveryapis_generator project).
// ignore_for_file: camel_case_types
// ignore_for_file: comment_references
// ignore_for_file: file_names
// ignore_for_file: library_names
// ignore_for_file: lines_longer_than_80_chars
// ignore_for_file: non_constant_identifier_names
// ignore_for_file: prefer_expression_function_bodies
// ignore_for_file: prefer_interpolation_to_compose_strings
// ignore_for_file: unnecessary_brace_in_string_interps
// ignore_for_file: unnecessary_lambdas
// ignore_for_file: unnecessary_string_interpolations
/// Retail API - v2
///
/// Cloud Retail service enables customers to build end-to-end personalized
/// recommendation systems without requiring a high level of expertise in
/// machine learning, recommendation system, or Google Cloud.
///
/// For more information, see <https://cloud.google.com/recommendations>
///
/// Create an instance of [CloudRetailApi] to access these resources:
///
/// - [ProjectsResource]
/// - [ProjectsLocationsResource]
/// - [ProjectsLocationsCatalogsResource]
/// - [ProjectsLocationsCatalogsBranchesResource]
/// - [ProjectsLocationsCatalogsBranchesOperationsResource]
/// - [ProjectsLocationsCatalogsBranchesProductsResource]
/// - [ProjectsLocationsCatalogsCompletionDataResource]
/// - [ProjectsLocationsCatalogsOperationsResource]
/// - [ProjectsLocationsCatalogsPlacementsResource]
/// - [ProjectsLocationsCatalogsUserEventsResource]
/// - [ProjectsLocationsOperationsResource]
/// - [ProjectsOperationsResource]
library retail.v2;
import 'dart:async' as async;
import 'dart:convert' as convert;
import 'dart:core' as core;
import 'package:_discoveryapis_commons/_discoveryapis_commons.dart' as commons;
import 'package:http/http.dart' as http;
// ignore: deprecated_member_use_from_same_package
import '../shared.dart';
import '../src/user_agent.dart';
export 'package:_discoveryapis_commons/_discoveryapis_commons.dart'
show ApiRequestError, DetailedApiRequestError;
/// Cloud Retail service enables customers to build end-to-end personalized
/// recommendation systems without requiring a high level of expertise in
/// machine learning, recommendation system, or Google Cloud.
class CloudRetailApi {
/// See, edit, configure, and delete your Google Cloud data and see the email
/// address for your Google Account.
static const cloudPlatformScope =
'https://www.googleapis.com/auth/cloud-platform';
final commons.ApiRequester _requester;
ProjectsResource get projects => ProjectsResource(_requester);
CloudRetailApi(http.Client client,
{core.String rootUrl = 'https://retail.googleapis.com/',
core.String servicePath = ''})
: _requester =
commons.ApiRequester(client, rootUrl, servicePath, requestHeaders);
}
class ProjectsResource {
final commons.ApiRequester _requester;
ProjectsLocationsResource get locations =>
ProjectsLocationsResource(_requester);
ProjectsOperationsResource get operations =>
ProjectsOperationsResource(_requester);
ProjectsResource(commons.ApiRequester client) : _requester = client;
}
class ProjectsLocationsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsResource get catalogs =>
ProjectsLocationsCatalogsResource(_requester);
ProjectsLocationsOperationsResource get operations =>
ProjectsLocationsOperationsResource(_requester);
ProjectsLocationsResource(commons.ApiRequester client) : _requester = client;
}
class ProjectsLocationsCatalogsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsBranchesResource get branches =>
ProjectsLocationsCatalogsBranchesResource(_requester);
ProjectsLocationsCatalogsCompletionDataResource get completionData =>
ProjectsLocationsCatalogsCompletionDataResource(_requester);
ProjectsLocationsCatalogsOperationsResource get operations =>
ProjectsLocationsCatalogsOperationsResource(_requester);
ProjectsLocationsCatalogsPlacementsResource get placements =>
ProjectsLocationsCatalogsPlacementsResource(_requester);
ProjectsLocationsCatalogsUserEventsResource get userEvents =>
ProjectsLocationsCatalogsUserEventsResource(_requester);
ProjectsLocationsCatalogsResource(commons.ApiRequester client)
: _requester = client;
/// Completes the specified prefix with keyword suggestions.
///
/// This feature is only available for users who have Retail Search enabled.
/// Please submit a form [here](https://cloud.google.com/contact) to contact
/// cloud sales if you are interested in using Retail Search.
///
/// Request parameters:
///
/// [catalog] - Required. Catalog for which the completion is performed. Full
/// resource name of catalog, such as `projects / *
/// /locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [dataset] - Determines which dataset to use for fetching completion.
/// "user-data" will use the imported dataset through
/// CompletionService.ImportCompletionData. "cloud-retail" will use the
/// dataset generated by cloud retail based on user events. If leave empty, it
/// will use the "user-data". Current supported values: * user-data *
/// cloud-retail This option requires additional allowlisting. Before using
/// cloud-retail, contact Cloud Retail support team first.
///
/// [deviceType] - The device type context for completion suggestions. It is
/// useful to apply different suggestions on different device types, e.g.
/// `DESKTOP`, `MOBILE`. If it is empty, the suggestions are across all device
/// types. Supported formats: * `UNKNOWN_DEVICE_TYPE` * `DESKTOP` * `MOBILE` *
/// A customized string starts with `OTHER_`, e.g. `OTHER_IPHONE`.
///
/// [languageCodes] - The list of languages of the query. This is the BCP-47
/// language code, such as "en-US" or "sr-Latn". For more information, see
/// [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). The
/// maximum number of allowed characters is 255. Only "en-US" is currently
/// supported.
///
/// [maxSuggestions] - Completion max suggestions. If left unset or set to 0,
/// then will fallback to the configured value
/// CompletionConfig.max_suggestions. The maximum allowed max suggestions is
/// 20. If it is set higher, it will be capped by 20.
///
/// [query] - Required. The query used to generate suggestions. The maximum
/// number of allowed characters is 255.
///
/// [visitorId] - A unique identifier for tracking visitors. For example, this
/// could be implemented with an HTTP cookie, which should be able to uniquely
/// identify a visitor on a single device. This unique identifier should not
/// change if the visitor logs in or out of the website. The field must be a
/// UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2CompleteQueryResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2CompleteQueryResponse> completeQuery(
core.String catalog, {
core.String? dataset,
core.String? deviceType,
core.List<core.String>? languageCodes,
core.int? maxSuggestions,
core.String? query,
core.String? visitorId,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (dataset != null) 'dataset': [dataset],
if (deviceType != null) 'deviceType': [deviceType],
if (languageCodes != null) 'languageCodes': languageCodes,
if (maxSuggestions != null) 'maxSuggestions': ['${maxSuggestions}'],
if (query != null) 'query': [query],
if (visitorId != null) 'visitorId': [visitorId],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$catalog') + ':completeQuery';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleCloudRetailV2CompleteQueryResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Get which branch is currently default branch set by
/// CatalogService.SetDefaultBranch method under a specified parent catalog.
///
/// Request parameters:
///
/// [catalog] - The parent catalog resource name, such as `projects / *
/// /locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2GetDefaultBranchResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2GetDefaultBranchResponse> getDefaultBranch(
core.String catalog, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$catalog') + ':getDefaultBranch';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleCloudRetailV2GetDefaultBranchResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Lists all the Catalogs associated with the project.
///
/// Request parameters:
///
/// [parent] - Required. The account resource name with an associated
/// location. If the caller does not have permission to list Catalogs under
/// this location, regardless of whether or not this location exists, a
/// PERMISSION_DENIED error is returned.
/// Value must have pattern `^projects/\[^/\]+/locations/\[^/\]+$`.
///
/// [pageSize] - Maximum number of Catalogs to return. If unspecified,
/// defaults to 50. The maximum allowed value is 1000. Values above 1000 will
/// be coerced to 1000. If this field is negative, an INVALID_ARGUMENT is
/// returned.
///
/// [pageToken] - A page token ListCatalogsResponse.next_page_token, received
/// from a previous CatalogService.ListCatalogs call. Provide this to retrieve
/// the subsequent page. When paginating, all other parameters provided to
/// CatalogService.ListCatalogs must match the call that provided the page
/// token. Otherwise, an INVALID_ARGUMENT error is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2ListCatalogsResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2ListCatalogsResponse> list(
core.String parent, {
core.int? pageSize,
core.String? pageToken,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (pageSize != null) 'pageSize': ['${pageSize}'],
if (pageToken != null) 'pageToken': [pageToken],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/catalogs';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleCloudRetailV2ListCatalogsResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Updates the Catalogs.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [name] - Required. Immutable. The fully qualified resource name of the
/// catalog.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [updateMask] - Indicates which fields in the provided Catalog to update.
/// If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
/// is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2Catalog].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2Catalog> patch(
GoogleCloudRetailV2Catalog request,
core.String name, {
core.String? updateMask,
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if (updateMask != null) 'updateMask': [updateMask],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'PATCH',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2Catalog.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Set a specified branch id as default branch.
///
/// API methods such as SearchService.Search, ProductService.GetProduct,
/// ProductService.ListProducts will treat requests using "default_branch" to
/// the actual branch id set as default. For example, if `projects / *
/// /locations / * /catalogs / * /branches/1` is set as default, setting
/// SearchRequest.branch to `projects / * /locations / * /catalogs / *
/// /branches/default_branch` is equivalent to setting SearchRequest.branch to
/// `projects / * /locations / * /catalogs / * /branches/1`. Using multiple
/// branches can be useful when developers would like to have a staging branch
/// to test and verify for future usage. When it becomes ready, developers
/// switch on the staging branch using this API while keeping using `projects
/// / * /locations / * /catalogs / * /branches/default_branch` as
/// SearchRequest.branch to route the traffic to this staging branch. CAUTION:
/// If you have live predict/search traffic, switching the default branch
/// could potentially cause outages if the ID space of the new branch is very
/// different from the old one. More specifically: * PredictionService will
/// only return product IDs from branch {newBranch}. * SearchService will only
/// return product IDs from branch {newBranch} (if branch is not explicitly
/// set). * UserEventService will only join events with products from branch
/// {newBranch}.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [catalog] - Full resource name of the catalog, such as `projects / *
/// /locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleProtobufEmpty].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleProtobufEmpty> setDefaultBranch(
GoogleCloudRetailV2SetDefaultBranchRequest request,
core.String catalog, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$catalog') + ':setDefaultBranch';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleProtobufEmpty.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsBranchesResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsBranchesOperationsResource get operations =>
ProjectsLocationsCatalogsBranchesOperationsResource(_requester);
ProjectsLocationsCatalogsBranchesProductsResource get products =>
ProjectsLocationsCatalogsBranchesProductsResource(_requester);
ProjectsLocationsCatalogsBranchesResource(commons.ApiRequester client)
: _requester = client;
}
class ProjectsLocationsCatalogsBranchesOperationsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsBranchesOperationsResource(
commons.ApiRequester client)
: _requester = client;
/// Gets the latest state of a long-running operation.
///
/// Clients can use this method to poll the operation result at intervals as
/// recommended by the API service.
///
/// Request parameters:
///
/// [name] - The name of the operation resource.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/operations/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> get(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsBranchesProductsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsBranchesProductsResource(commons.ApiRequester client)
: _requester = client;
/// Incrementally adds place IDs to Product.fulfillment_info.place_ids.
///
/// This process is asynchronous and does not require the Product to exist
/// before updating fulfillment information. If the request is valid, the
/// update will be enqueued and processed downstream. As a consequence, when a
/// response is returned, the added place IDs are not immediately manifested
/// in the Product queried by GetProduct or ListProducts. This feature is only
/// available for users who have Retail Search enabled. Please submit a form
/// [here](https://cloud.google.com/contact) to contact cloud sales if you are
/// interested in using Retail Search.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [product] - Required. Full resource name of Product, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
/// If the caller does not have permission to access the Product, regardless
/// of whether or not it exists, a PERMISSION_DENIED error is returned.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> addFulfillmentPlaces(
GoogleCloudRetailV2AddFulfillmentPlacesRequest request,
core.String product, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url =
'v2/' + core.Uri.encodeFull('$product') + ':addFulfillmentPlaces';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Creates a Product.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required. The parent catalog resource name, such as `projects /
/// * /locations/global/catalogs/default_catalog/branches/default_branch`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+$`.
///
/// [productId] - Required. The ID to use for the Product, which will become
/// the final component of the Product.name. If the caller does not have
/// permission to create the Product, regardless of whether or not it exists,
/// a PERMISSION_DENIED error is returned. This field must be unique among all
/// Products with the same parent. Otherwise, an ALREADY_EXISTS error is
/// returned. This field must be a UTF-8 encoded string with a length limit of
/// 128 characters. Otherwise, an INVALID_ARGUMENT error is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2Product].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2Product> create(
GoogleCloudRetailV2Product request,
core.String parent, {
core.String? productId,
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if (productId != null) 'productId': [productId],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/products';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2Product.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Deletes a Product.
///
/// Request parameters:
///
/// [name] - Required. Full resource name of Product, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
/// If the caller does not have permission to delete the Product, regardless
/// of whether or not it exists, a PERMISSION_DENIED error is returned. If the
/// Product to delete does not exist, a NOT_FOUND error is returned. The
/// Product to delete can neither be a Product.Type.COLLECTION Product member
/// nor a Product.Type.PRIMARY Product with more than one variants. Otherwise,
/// an INVALID_ARGUMENT error is returned. All inventory information for the
/// named Product will be deleted.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleProtobufEmpty].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleProtobufEmpty> delete(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'DELETE',
queryParams: _queryParams,
);
return GoogleProtobufEmpty.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Gets a Product.
///
/// Request parameters:
///
/// [name] - Required. Full resource name of Product, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
/// If the caller does not have permission to access the Product, regardless
/// of whether or not it exists, a PERMISSION_DENIED error is returned. If the
/// requested Product does not exist, a NOT_FOUND error is returned.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2Product].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2Product> get(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleCloudRetailV2Product.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Bulk import of multiple Products.
///
/// Request processing may be synchronous. No partial updating is supported.
/// Non-existing items are created. Note that it is possible for a subset of
/// the Products to be successfully updated.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required.
/// `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`
/// If no updateMask is specified, requires products.create permission. If
/// updateMask is specified, requires products.update permission.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> import(
GoogleCloudRetailV2ImportProductsRequest request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/products:import';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Gets a list of Products.
///
/// Request parameters:
///
/// [parent] - Required. The parent branch resource name, such as `projects /
/// * /locations/global/catalogs/default_catalog/branches/0`. Use
/// `default_branch` as the branch ID, to list products under the default
/// branch. If the caller does not have permission to list Products under this
/// branch, regardless of whether or not this branch exists, a
/// PERMISSION_DENIED error is returned.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+$`.
///
/// [filter] - A filter to apply on the list results. Supported features: *
/// List all the products under the parent branch if filter is unset. * List
/// Product.Type.VARIANT Products sharing the same Product.Type.PRIMARY
/// Product. For example: `primary_product_id = "some_product_id"` * List
/// Products bundled in a Product.Type.COLLECTION Product. For example:
/// `collection_product_id = "some_product_id"` * List Products with a
/// partibular type. For example: `type = "PRIMARY"` `type = "VARIANT"` `type
/// = "COLLECTION"` If the field is unrecognizable, an INVALID_ARGUMENT error
/// is returned. If the specified Product.Type.PRIMARY Product or
/// Product.Type.COLLECTION Product does not exist, a NOT_FOUND error is
/// returned.
///
/// [pageSize] - Maximum number of Products to return. If unspecified,
/// defaults to 100. The maximum allowed value is 1000. Values above 1000 will
/// be coerced to 1000. If this field is negative, an INVALID_ARGUMENT error
/// is returned.
///
/// [pageToken] - A page token ListProductsResponse.next_page_token, received
/// from a previous ProductService.ListProducts call. Provide this to retrieve
/// the subsequent page. When paginating, all other parameters provided to
/// ProductService.ListProducts must match the call that provided the page
/// token. Otherwise, an INVALID_ARGUMENT error is returned.
///
/// [readMask] - The fields of Product to return in the responses. If not set
/// or empty, the following fields are returned: * Product.name * Product.id *
/// Product.title * Product.uri * Product.images * Product.price_info *
/// Product.brands If "*" is provided, all fields are returned. Product.name
/// is always returned no matter what mask is set. If an unsupported or
/// unknown field is provided, an INVALID_ARGUMENT error is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2ListProductsResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2ListProductsResponse> list(
core.String parent, {
core.String? filter,
core.int? pageSize,
core.String? pageToken,
core.String? readMask,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (filter != null) 'filter': [filter],
if (pageSize != null) 'pageSize': ['${pageSize}'],
if (pageToken != null) 'pageToken': [pageToken],
if (readMask != null) 'readMask': [readMask],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/products';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleCloudRetailV2ListProductsResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Updates a Product.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [name] - Immutable. Full resource name of the product, such as `projects /
/// *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/product_id`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [allowMissing] - If set to true, and the Product is not found, a new
/// Product will be created. In this situation, `update_mask` is ignored.
///
/// [updateMask] - Indicates which fields in the provided Product to update.
/// The immutable and output only fields are NOT supported. If not set, all
/// supported fields (the fields that are neither immutable nor output only)
/// are updated. If an unsupported or unknown field is provided, an
/// INVALID_ARGUMENT error is returned.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2Product].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2Product> patch(
GoogleCloudRetailV2Product request,
core.String name, {
core.bool? allowMissing,
core.String? updateMask,
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if (allowMissing != null) 'allowMissing': ['${allowMissing}'],
if (updateMask != null) 'updateMask': [updateMask],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'PATCH',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2Product.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Incrementally removes place IDs from a Product.fulfillment_info.place_ids.
///
/// This process is asynchronous and does not require the Product to exist
/// before updating fulfillment information. If the request is valid, the
/// update will be enqueued and processed downstream. As a consequence, when a
/// response is returned, the removed place IDs are not immediately manifested
/// in the Product queried by GetProduct or ListProducts. This feature is only
/// available for users who have Retail Search enabled. Please submit a form
/// [here](https://cloud.google.com/contact) to contact cloud sales if you are
/// interested in using Retail Search.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [product] - Required. Full resource name of Product, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
/// If the caller does not have permission to access the Product, regardless
/// of whether or not it exists, a PERMISSION_DENIED error is returned.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> removeFulfillmentPlaces(
GoogleCloudRetailV2RemoveFulfillmentPlacesRequest request,
core.String product, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url =
'v2/' + core.Uri.encodeFull('$product') + ':removeFulfillmentPlaces';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Updates inventory information for a Product while respecting the last
/// update timestamps of each inventory field.
///
/// This process is asynchronous and does not require the Product to exist
/// before updating fulfillment information. If the request is valid, the
/// update will be enqueued and processed downstream. As a consequence, when a
/// response is returned, updates are not immediately manifested in the
/// Product queried by GetProduct or ListProducts. When inventory is updated
/// with CreateProduct and UpdateProduct, the specified inventory field
/// value(s) will overwrite any existing value(s) while ignoring the last
/// update time for this field. Furthermore, the last update time for the
/// specified inventory fields will be overwritten to the time of the
/// CreateProduct or UpdateProduct request. If no inventory fields are set in
/// CreateProductRequest.product, then any pre-existing inventory information
/// for this product will be used. If no inventory fields are set in
/// SetInventoryRequest.set_mask, then any existing inventory information will
/// be preserved. Pre-existing inventory information can only be updated with
/// SetInventory, AddFulfillmentPlaces, and RemoveFulfillmentPlaces. This
/// feature is only available for users who have Retail Search enabled. Please
/// submit a form [here](https://cloud.google.com/contact) to contact cloud
/// sales if you are interested in using Retail Search.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [name] - Immutable. Full resource name of the product, such as `projects /
/// *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/product_id`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/branches/\[^/\]+/products/.*$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> setInventory(
GoogleCloudRetailV2SetInventoryRequest request,
core.String name, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name') + ':setInventory';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsCompletionDataResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsCompletionDataResource(commons.ApiRequester client)
: _requester = client;
/// Bulk import of processed completion dataset.
///
/// Request processing may be synchronous. Partial updating is not supported.
/// This feature is only available for users who have Retail Search enabled.
/// Please submit a form [here](https://cloud.google.com/contact) to contact
/// cloud sales if you are interested in using Retail Search.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required. The catalog which the suggestions dataset belongs to.
/// Format: `projects/1234/locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> import(
GoogleCloudRetailV2ImportCompletionDataRequest request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url =
'v2/' + core.Uri.encodeFull('$parent') + '/completionData:import';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsOperationsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsOperationsResource(commons.ApiRequester client)
: _requester = client;
/// Gets the latest state of a long-running operation.
///
/// Clients can use this method to poll the operation result at intervals as
/// recommended by the API service.
///
/// Request parameters:
///
/// [name] - The name of the operation resource.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/operations/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> get(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Lists operations that match the specified filter in the request.
///
/// If the server doesn't support this method, it returns `UNIMPLEMENTED`.
/// NOTE: the `name` binding allows API services to override the binding to
/// use different resource name schemes, such as `users / * /operations`. To
/// override the binding, API services can add a binding such as
/// `"/v1/{name=users / * }/operations"` to their service configuration. For
/// backwards compatibility, the default name includes the operations
/// collection id, however overriding users must ensure the name binding is
/// the parent resource, without the operations collection id.
///
/// Request parameters:
///
/// [name] - The name of the operation's parent resource.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [filter] - The standard list filter.
///
/// [pageSize] - The standard list page size.
///
/// [pageToken] - The standard list page token.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningListOperationsResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningListOperationsResponse> list(
core.String name, {
core.String? filter,
core.int? pageSize,
core.String? pageToken,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (filter != null) 'filter': [filter],
if (pageSize != null) 'pageSize': ['${pageSize}'],
if (pageToken != null) 'pageToken': [pageToken],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name') + '/operations';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningListOperationsResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsPlacementsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsPlacementsResource(commons.ApiRequester client)
: _requester = client;
/// Makes a recommendation prediction.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [placement] - Required. Full resource name of the format: {name=projects /
/// * /locations/global/catalogs/default_catalog/placements / * } The ID of
/// the Recommendations AI placement. Before you can request predictions from
/// your model, you must create at least one placement for it. For more
/// information, see
/// [Managing placements](https://cloud.google.com/retail/recommendations-ai/docs/manage-placements).
/// The full list of available placements can be seen at
/// https://console.cloud.google.com/recommendation/catalogs/default_catalog/placements
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/placements/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2PredictResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2PredictResponse> predict(
GoogleCloudRetailV2PredictRequest request,
core.String placement, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$placement') + ':predict';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2PredictResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Performs a search.
///
/// This feature is only available for users who have Retail Search enabled.
/// Please submit a form [here](https://cloud.google.com/contact) to contact
/// cloud sales if you are interested in using Retail Search.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [placement] - Required. The resource name of the search engine placement,
/// such as `projects / *
/// /locations/global/catalogs/default_catalog/placements/default_search`.
/// This field is used to identify the serving configuration name and the set
/// of models that will be used to make the search.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+/placements/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2SearchResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2SearchResponse> search(
GoogleCloudRetailV2SearchRequest request,
core.String placement, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$placement') + ':search';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2SearchResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsCatalogsUserEventsResource {
final commons.ApiRequester _requester;
ProjectsLocationsCatalogsUserEventsResource(commons.ApiRequester client)
: _requester = client;
/// Writes a single user event from the browser.
///
/// This uses a GET request to due to browser restriction of POST-ing to a 3rd
/// party domain. This method is used only by the Retail API JavaScript pixel
/// and Google Tag Manager. Users should not call this method directly.
///
/// Request parameters:
///
/// [parent] - Required. The parent catalog name, such as
/// `projects/1234/locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [ets] - The event timestamp in milliseconds. This prevents browser caching
/// of otherwise identical get requests. The name is abbreviated to reduce the
/// payload bytes.
///
/// [uri] - The URL including cgi-parameters but excluding the hash fragment
/// with a length limit of 5,000 characters. This is often more useful than
/// the referer URL, because many browsers only send the domain for 3rd party
/// requests.
///
/// [userEvent] - Required. URL encoded UserEvent proto with a length limit of
/// 2,000,000 characters.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleApiHttpBody].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleApiHttpBody> collect(
core.String parent, {
core.String? ets,
core.String? uri,
core.String? userEvent,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (ets != null) 'ets': [ets],
if (uri != null) 'uri': [uri],
if (userEvent != null) 'userEvent': [userEvent],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/userEvents:collect';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleApiHttpBody.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Bulk import of User events.
///
/// Request processing might be synchronous. Events that already exist are
/// skipped. Use this method for backfilling historical user events.
/// Operation.response is of type ImportResponse. Note that it is possible for
/// a subset of the items to be successfully inserted. Operation.metadata is
/// of type ImportMetadata.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required.
/// `projects/1234/locations/global/catalogs/default_catalog`
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> import(
GoogleCloudRetailV2ImportUserEventsRequest request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/userEvents:import';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Deletes permanently all user events specified by the filter provided.
///
/// Depending on the number of events specified by the filter, this operation
/// could take hours or days to complete. To test a filter, use the list
/// command first.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required. The resource name of the catalog under which the
/// events are created. The format is
/// `projects/${projectId}/locations/global/catalogs/${catalogId}`
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> purge(
GoogleCloudRetailV2PurgeUserEventsRequest request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/userEvents:purge';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Triggers a user event rejoin operation with latest product catalog.
///
/// Events will not be annotated with detailed product information if product
/// is missing from the catalog at the time the user event is ingested, and
/// these events are stored as unjoined events with a limited usage on
/// training and serving. This API can be used to trigger a 'join' operation
/// on specified events with latest version of product catalog. It can also be
/// used to correct events joined with wrong product catalog.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required. The parent catalog resource name, such as
/// `projects/1234/locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> rejoin(
GoogleCloudRetailV2RejoinUserEventsRequest request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/userEvents:rejoin';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Writes a single user event.
///
/// [request] - The metadata request object.
///
/// Request parameters:
///
/// [parent] - Required. The parent catalog resource name, such as
/// `projects/1234/locations/global/catalogs/default_catalog`.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/catalogs/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleCloudRetailV2UserEvent].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleCloudRetailV2UserEvent> write(
GoogleCloudRetailV2UserEvent request,
core.String parent, {
core.String? $fields,
}) async {
final _body = convert.json.encode(request);
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$parent') + '/userEvents:write';
final _response = await _requester.request(
_url,
'POST',
body: _body,
queryParams: _queryParams,
);
return GoogleCloudRetailV2UserEvent.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsLocationsOperationsResource {
final commons.ApiRequester _requester;
ProjectsLocationsOperationsResource(commons.ApiRequester client)
: _requester = client;
/// Gets the latest state of a long-running operation.
///
/// Clients can use this method to poll the operation result at intervals as
/// recommended by the API service.
///
/// Request parameters:
///
/// [name] - The name of the operation resource.
/// Value must have pattern
/// `^projects/\[^/\]+/locations/\[^/\]+/operations/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> get(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Lists operations that match the specified filter in the request.
///
/// If the server doesn't support this method, it returns `UNIMPLEMENTED`.
/// NOTE: the `name` binding allows API services to override the binding to
/// use different resource name schemes, such as `users / * /operations`. To
/// override the binding, API services can add a binding such as
/// `"/v1/{name=users / * }/operations"` to their service configuration. For
/// backwards compatibility, the default name includes the operations
/// collection id, however overriding users must ensure the name binding is
/// the parent resource, without the operations collection id.
///
/// Request parameters:
///
/// [name] - The name of the operation's parent resource.
/// Value must have pattern `^projects/\[^/\]+/locations/\[^/\]+$`.
///
/// [filter] - The standard list filter.
///
/// [pageSize] - The standard list page size.
///
/// [pageToken] - The standard list page token.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningListOperationsResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningListOperationsResponse> list(
core.String name, {
core.String? filter,
core.int? pageSize,
core.String? pageToken,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (filter != null) 'filter': [filter],
if (pageSize != null) 'pageSize': ['${pageSize}'],
if (pageToken != null) 'pageToken': [pageToken],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name') + '/operations';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningListOperationsResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
class ProjectsOperationsResource {
final commons.ApiRequester _requester;
ProjectsOperationsResource(commons.ApiRequester client) : _requester = client;
/// Gets the latest state of a long-running operation.
///
/// Clients can use this method to poll the operation result at intervals as
/// recommended by the API service.
///
/// Request parameters:
///
/// [name] - The name of the operation resource.
/// Value must have pattern `^projects/\[^/\]+/operations/\[^/\]+$`.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningOperation].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningOperation> get(
core.String name, {
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name');
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningOperation.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
/// Lists operations that match the specified filter in the request.
///
/// If the server doesn't support this method, it returns `UNIMPLEMENTED`.
/// NOTE: the `name` binding allows API services to override the binding to
/// use different resource name schemes, such as `users / * /operations`. To
/// override the binding, API services can add a binding such as
/// `"/v1/{name=users / * }/operations"` to their service configuration. For
/// backwards compatibility, the default name includes the operations
/// collection id, however overriding users must ensure the name binding is
/// the parent resource, without the operations collection id.
///
/// Request parameters:
///
/// [name] - The name of the operation's parent resource.
/// Value must have pattern `^projects/\[^/\]+$`.
///
/// [filter] - The standard list filter.
///
/// [pageSize] - The standard list page size.
///
/// [pageToken] - The standard list page token.
///
/// [$fields] - Selector specifying which fields to include in a partial
/// response.
///
/// Completes with a [GoogleLongrunningListOperationsResponse].
///
/// Completes with a [commons.ApiRequestError] if the API endpoint returned an
/// error.
///
/// If the used [http.Client] completes with an error when making a REST call,
/// this method will complete with the same error.
async.Future<GoogleLongrunningListOperationsResponse> list(
core.String name, {
core.String? filter,
core.int? pageSize,
core.String? pageToken,
core.String? $fields,
}) async {
final _queryParams = <core.String, core.List<core.String>>{
if (filter != null) 'filter': [filter],
if (pageSize != null) 'pageSize': ['${pageSize}'],
if (pageToken != null) 'pageToken': [pageToken],
if ($fields != null) 'fields': [$fields],
};
final _url = 'v2/' + core.Uri.encodeFull('$name') + '/operations';
final _response = await _requester.request(
_url,
'GET',
queryParams: _queryParams,
);
return GoogleLongrunningListOperationsResponse.fromJson(
_response as core.Map<core.String, core.dynamic>);
}
}
/// Message that represents an arbitrary HTTP body.
///
/// It should only be used for payload formats that can't be represented as
/// JSON, such as raw binary or an HTML page. This message can be used both in
/// streaming and non-streaming API methods in the request as well as the
/// response. It can be used as a top-level request field, which is convenient
/// if one wants to extract parameters from either the URL or HTTP template into
/// the request fields and also want access to the raw HTTP body. Example:
/// message GetResourceRequest { // A unique request id. string request_id = 1;
/// // The raw HTTP body is bound to this field. google.api.HttpBody http_body =
/// 2; } service ResourceService { rpc GetResource(GetResourceRequest) returns
/// (google.api.HttpBody); rpc UpdateResource(google.api.HttpBody) returns
/// (google.protobuf.Empty); } Example with streaming methods: service
/// CaldavService { rpc GetCalendar(stream google.api.HttpBody) returns (stream
/// google.api.HttpBody); rpc UpdateCalendar(stream google.api.HttpBody) returns
/// (stream google.api.HttpBody); } Use of this type only changes how the
/// request and response bodies are handled, all other features will continue to
/// work unchanged.
typedef GoogleApiHttpBody = $HttpBody;
/// Request message for AddFulfillmentPlaces method.
class GoogleCloudRetailV2AddFulfillmentPlacesRequest {
/// The time when the fulfillment updates are issued, used to prevent
/// out-of-order updates on fulfillment information.
///
/// If not provided, the internal system time will be used.
core.String? addTime;
/// If set to true, and the Product is not found, the fulfillment information
/// will still be processed and retained for at most 1 day and processed once
/// the Product is created.
///
/// If set to false, a NOT_FOUND error is returned if the Product is not
/// found.
core.bool? allowMissing;
/// The IDs for this type, such as the store IDs for "pickup-in-store" or the
/// region IDs for "same-day-delivery" to be added for this type.
///
/// Duplicate IDs will be automatically ignored. At least 1 value is required,
/// and a maximum of 2000 values are allowed. Each value must be a string with
/// a length limit of 10 characters, matching the pattern `[a-zA-Z0-9_-]+`,
/// such as "store1" or "REGION-2". Otherwise, an INVALID_ARGUMENT error is
/// returned. If the total number of place IDs exceeds 2000 for this type
/// after adding, then the update will be rejected.
///
/// Required.
core.List<core.String>? placeIds;
/// The fulfillment type, including commonly used types (such as pickup in
/// store and same day delivery), and custom types.
///
/// Supported values: * "pickup-in-store" * "ship-to-store" *
/// "same-day-delivery" * "next-day-delivery" * "custom-type-1" *
/// "custom-type-2" * "custom-type-3" * "custom-type-4" * "custom-type-5" If
/// this field is set to an invalid value other than these, an
/// INVALID_ARGUMENT error is returned. This field directly corresponds to
/// Product.fulfillment_info.type.
///
/// Required.
core.String? type;
GoogleCloudRetailV2AddFulfillmentPlacesRequest({
this.addTime,
this.allowMissing,
this.placeIds,
this.type,
});
GoogleCloudRetailV2AddFulfillmentPlacesRequest.fromJson(core.Map _json)
: this(
addTime: _json.containsKey('addTime')
? _json['addTime'] as core.String
: null,
allowMissing: _json.containsKey('allowMissing')
? _json['allowMissing'] as core.bool
: null,
placeIds: _json.containsKey('placeIds')
? (_json['placeIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
type: _json.containsKey('type') ? _json['type'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (addTime != null) 'addTime': addTime!,
if (allowMissing != null) 'allowMissing': allowMissing!,
if (placeIds != null) 'placeIds': placeIds!,
if (type != null) 'type': type!,
};
}
/// An intended audience of the Product for whom it's sold.
class GoogleCloudRetailV2Audience {
/// The age groups of the audience.
///
/// Strongly encouraged to use the standard values: "newborn" (up to 3 months
/// old), "infant" (3–12 months old), "toddler" (1–5 years old), "kids" (5–13
/// years old), "adult" (typically teens or older). At most 5 values are
/// allowed. Each value must be a UTF-8 encoded string with a length limit of
/// 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Google
/// Merchant Center property
/// [age_group](https://support.google.com/merchants/answer/6324463).
/// Schema.org property
/// [Product.audience.suggestedMinAge](https://schema.org/suggestedMinAge) and
/// [Product.audience.suggestedMaxAge](https://schema.org/suggestedMaxAge).
core.List<core.String>? ageGroups;
/// The genders of the audience.
///
/// Strongly encouraged to use the standard values: "male", "female",
/// "unisex". At most 5 values are allowed. Each value must be a UTF-8 encoded
/// string with a length limit of 128 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. Google Merchant Center property
/// [gender](https://support.google.com/merchants/answer/6324479). Schema.org
/// property
/// [Product.audience.suggestedGender](https://schema.org/suggestedGender).
core.List<core.String>? genders;
GoogleCloudRetailV2Audience({
this.ageGroups,
this.genders,
});
GoogleCloudRetailV2Audience.fromJson(core.Map _json)
: this(
ageGroups: _json.containsKey('ageGroups')
? (_json['ageGroups'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
genders: _json.containsKey('genders')
? (_json['genders'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (ageGroups != null) 'ageGroups': ageGroups!,
if (genders != null) 'genders': genders!,
};
}
/// BigQuery source import data from.
class GoogleCloudRetailV2BigQuerySource {
/// The schema to use when parsing the data from the source.
///
/// Supported values for product imports: * `product` (default): One JSON
/// Product per line. Each product must have a valid Product.id. *
/// `product_merchant_center`: See
/// [Importing catalog data from Merchant Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc).
/// Supported values for user events imports: * `user_event` (default): One
/// JSON UserEvent per line. * `user_event_ga360`: The schema is available
/// here: https://support.google.com/analytics/answer/3437719. *
/// `user_event_ga4`: This feature is in private preview. Please contact the
/// support team for importing Google Analytics 4 events. The schema is
/// available here: https://support.google.com/analytics/answer/7029846.
core.String? dataSchema;
/// The BigQuery data set to copy the data from with a length limit of 1,024
/// characters.
///
/// Required.
core.String? datasetId;
/// Intermediate Cloud Storage directory used for the import with a length
/// limit of 2,000 characters.
///
/// Can be specified if one wants to have the BigQuery export to a specific
/// Cloud Storage directory.
core.String? gcsStagingDir;
/// BigQuery time partitioned table's _PARTITIONDATE in YYYY-MM-DD format.
///
/// Only supported when ImportProductsRequest.reconciliation_mode is set to
/// `FULL`.
GoogleTypeDate? partitionDate;
/// The project ID (can be project # or ID) that the BigQuery source is in
/// with a length limit of 128 characters.
///
/// If not specified, inherits the project ID from the parent request.
core.String? projectId;
/// The BigQuery table to copy the data from with a length limit of 1,024
/// characters.
///
/// Required.
core.String? tableId;
GoogleCloudRetailV2BigQuerySource({
this.dataSchema,
this.datasetId,
this.gcsStagingDir,
this.partitionDate,
this.projectId,
this.tableId,
});
GoogleCloudRetailV2BigQuerySource.fromJson(core.Map _json)
: this(
dataSchema: _json.containsKey('dataSchema')
? _json['dataSchema'] as core.String
: null,
datasetId: _json.containsKey('datasetId')
? _json['datasetId'] as core.String
: null,
gcsStagingDir: _json.containsKey('gcsStagingDir')
? _json['gcsStagingDir'] as core.String
: null,
partitionDate: _json.containsKey('partitionDate')
? GoogleTypeDate.fromJson(
_json['partitionDate'] as core.Map<core.String, core.dynamic>)
: null,
projectId: _json.containsKey('projectId')
? _json['projectId'] as core.String
: null,
tableId: _json.containsKey('tableId')
? _json['tableId'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (dataSchema != null) 'dataSchema': dataSchema!,
if (datasetId != null) 'datasetId': datasetId!,
if (gcsStagingDir != null) 'gcsStagingDir': gcsStagingDir!,
if (partitionDate != null) 'partitionDate': partitionDate!,
if (projectId != null) 'projectId': projectId!,
if (tableId != null) 'tableId': tableId!,
};
}
/// The catalog configuration.
class GoogleCloudRetailV2Catalog {
/// The catalog display name.
///
/// This field must be a UTF-8 encoded string with a length limit of 128
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Required. Immutable.
core.String? displayName;
/// The fully qualified resource name of the catalog.
///
/// Required. Immutable.
core.String? name;
/// The product level configuration.
///
/// Required.
GoogleCloudRetailV2ProductLevelConfig? productLevelConfig;
GoogleCloudRetailV2Catalog({
this.displayName,
this.name,
this.productLevelConfig,
});
GoogleCloudRetailV2Catalog.fromJson(core.Map _json)
: this(
displayName: _json.containsKey('displayName')
? _json['displayName'] as core.String
: null,
name: _json.containsKey('name') ? _json['name'] as core.String : null,
productLevelConfig: _json.containsKey('productLevelConfig')
? GoogleCloudRetailV2ProductLevelConfig.fromJson(
_json['productLevelConfig']
as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (displayName != null) 'displayName': displayName!,
if (name != null) 'name': name!,
if (productLevelConfig != null)
'productLevelConfig': productLevelConfig!,
};
}
/// The color information of a Product.
class GoogleCloudRetailV2ColorInfo {
/// The standard color families.
///
/// Strongly recommended to use the following standard color groups: "Red",
/// "Pink", "Orange", "Yellow", "Purple", "Green", "Cyan", "Blue", "Brown",
/// "White", "Gray", "Black" and "Mixed". Normally it is expected to have only
/// 1 color family. May consider using single "Mixed" instead of multiple
/// values. A maximum of 5 values are allowed. Each value must be a UTF-8
/// encoded string with a length limit of 128 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. Google Merchant Center property
/// [color](https://support.google.com/merchants/answer/6324487). Schema.org
/// property [Product.color](https://schema.org/color).
core.List<core.String>? colorFamilies;
/// The color display names, which may be different from standard color family
/// names, such as the color aliases used in the website frontend.
///
/// Normally it is expected to have only 1 color. May consider using single
/// "Mixed" instead of multiple values. A maximum of 25 colors are allowed.
/// Each value must be a UTF-8 encoded string with a length limit of 128
/// characters. Otherwise, an INVALID_ARGUMENT error is returned. Google
/// Merchant Center property
/// [color](https://support.google.com/merchants/answer/6324487). Schema.org
/// property [Product.color](https://schema.org/color).
core.List<core.String>? colors;
GoogleCloudRetailV2ColorInfo({
this.colorFamilies,
this.colors,
});
GoogleCloudRetailV2ColorInfo.fromJson(core.Map _json)
: this(
colorFamilies: _json.containsKey('colorFamilies')
? (_json['colorFamilies'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
colors: _json.containsKey('colors')
? (_json['colors'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (colorFamilies != null) 'colorFamilies': colorFamilies!,
if (colors != null) 'colors': colors!,
};
}
/// Response of the auto-complete query.
class GoogleCloudRetailV2CompleteQueryResponse {
/// A unique complete token.
///
/// This should be included in the SearchRequest resulting from this
/// completion, which enables accurate attribution of complete model
/// performance.
core.String? attributionToken;
/// Results of the matching suggestions.
///
/// The result list is ordered and the first result is top suggestion.
core.List<GoogleCloudRetailV2CompleteQueryResponseCompletionResult>?
completionResults;
/// Matched recent searches of this user.
///
/// The maximum number of recent searches is 10. This field is a restricted
/// feature. Contact Retail Search support team if you are interested in
/// enabling it. This feature is only available when
/// CompleteQueryRequest.visitor_id field is set and UserEvent is imported.
/// The recent searches satisfy the follow rules: * They are ordered from
/// latest to oldest. * They are matched with CompleteQueryRequest.query case
/// insensitively. * They are transformed to lower cases. * They are UTF-8
/// safe. Recent searches are deduplicated. More recent searches will be
/// reserved when duplication happens.
core.List<GoogleCloudRetailV2CompleteQueryResponseRecentSearchResult>?
recentSearchResults;
GoogleCloudRetailV2CompleteQueryResponse({
this.attributionToken,
this.completionResults,
this.recentSearchResults,
});
GoogleCloudRetailV2CompleteQueryResponse.fromJson(core.Map _json)
: this(
attributionToken: _json.containsKey('attributionToken')
? _json['attributionToken'] as core.String
: null,
completionResults: _json.containsKey('completionResults')
? (_json['completionResults'] as core.List)
.map((value) =>
GoogleCloudRetailV2CompleteQueryResponseCompletionResult
.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
recentSearchResults: _json.containsKey('recentSearchResults')
? (_json['recentSearchResults'] as core.List)
.map((value) =>
GoogleCloudRetailV2CompleteQueryResponseRecentSearchResult
.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (attributionToken != null) 'attributionToken': attributionToken!,
if (completionResults != null) 'completionResults': completionResults!,
if (recentSearchResults != null)
'recentSearchResults': recentSearchResults!,
};
}
/// Resource that represents completion results.
class GoogleCloudRetailV2CompleteQueryResponseCompletionResult {
/// Additional custom attributes ingested through BigQuery.
core.Map<core.String, GoogleCloudRetailV2CustomAttribute>? attributes;
/// The suggestion for the query.
core.String? suggestion;
GoogleCloudRetailV2CompleteQueryResponseCompletionResult({
this.attributes,
this.suggestion,
});
GoogleCloudRetailV2CompleteQueryResponseCompletionResult.fromJson(
core.Map _json)
: this(
attributes: _json.containsKey('attributes')
? (_json['attributes'] as core.Map<core.String, core.dynamic>)
.map(
(key, item) => core.MapEntry(
key,
GoogleCloudRetailV2CustomAttribute.fromJson(
item as core.Map<core.String, core.dynamic>),
),
)
: null,
suggestion: _json.containsKey('suggestion')
? _json['suggestion'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (attributes != null) 'attributes': attributes!,
if (suggestion != null) 'suggestion': suggestion!,
};
}
/// Recent search of this user.
class GoogleCloudRetailV2CompleteQueryResponseRecentSearchResult {
/// The recent search query.
core.String? recentSearch;
GoogleCloudRetailV2CompleteQueryResponseRecentSearchResult({
this.recentSearch,
});
GoogleCloudRetailV2CompleteQueryResponseRecentSearchResult.fromJson(
core.Map _json)
: this(
recentSearch: _json.containsKey('recentSearch')
? _json['recentSearch'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (recentSearch != null) 'recentSearch': recentSearch!,
};
}
/// The input config source for completion data.
class GoogleCloudRetailV2CompletionDataInputConfig {
/// BigQuery input source.
///
/// Add the IAM permission "BigQuery Data Viewer" for
/// cloud-retail-customer-data-access@system.gserviceaccount.com before using
/// this feature otherwise an error is thrown.
///
/// Required.
GoogleCloudRetailV2BigQuerySource? bigQuerySource;
GoogleCloudRetailV2CompletionDataInputConfig({
this.bigQuerySource,
});
GoogleCloudRetailV2CompletionDataInputConfig.fromJson(core.Map _json)
: this(
bigQuerySource: _json.containsKey('bigQuerySource')
? GoogleCloudRetailV2BigQuerySource.fromJson(
_json['bigQuerySource']
as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (bigQuerySource != null) 'bigQuerySource': bigQuerySource!,
};
}
/// Detailed completion information including completion attribution token and
/// clicked completion info.
class GoogleCloudRetailV2CompletionDetail {
/// Completion attribution token in CompleteQueryResponse.attribution_token.
core.String? completionAttributionToken;
/// End user selected CompleteQueryResponse.CompletionResult.suggestion
/// position, starting from 0.
core.int? selectedPosition;
/// End user selected CompleteQueryResponse.CompletionResult.suggestion.
core.String? selectedSuggestion;
GoogleCloudRetailV2CompletionDetail({
this.completionAttributionToken,
this.selectedPosition,
this.selectedSuggestion,
});
GoogleCloudRetailV2CompletionDetail.fromJson(core.Map _json)
: this(
completionAttributionToken:
_json.containsKey('completionAttributionToken')
? _json['completionAttributionToken'] as core.String
: null,
selectedPosition: _json.containsKey('selectedPosition')
? _json['selectedPosition'] as core.int
: null,
selectedSuggestion: _json.containsKey('selectedSuggestion')
? _json['selectedSuggestion'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (completionAttributionToken != null)
'completionAttributionToken': completionAttributionToken!,
if (selectedPosition != null) 'selectedPosition': selectedPosition!,
if (selectedSuggestion != null)
'selectedSuggestion': selectedSuggestion!,
};
}
/// A custom attribute that is not explicitly modeled in Product.
class GoogleCloudRetailV2CustomAttribute {
/// This field will only be used when AttributesConfig.attribute_config_level
/// of the Catalog is 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom
/// attribute values are indexed, so that it can be filtered, faceted or
/// boosted in SearchService.Search.
///
/// This field is ignored in a UserEvent. See SearchRequest.filter,
/// SearchRequest.facet_specs and SearchRequest.boost_spec for more details.
core.bool? indexable;
/// The numerical values of this custom attribute.
///
/// For example, `[2.3, 15.4]` when the key is "lengths_cm". Exactly one of
/// text or numbers should be set. Otherwise, an INVALID_ARGUMENT error is
/// returned.
core.List<core.double>? numbers;
/// This field will only be used when AttributesConfig.attribute_config_level
/// of the Catalog is 'PRODUCT_LEVEL_ATTRIBUTE_CONFIG', if true, custom
/// attribute values are searchable by text queries in SearchService.Search.
///
/// This field is ignored in a UserEvent. Only set if type text is set.
/// Otherwise, a INVALID_ARGUMENT error is returned.
core.bool? searchable;
/// The textual values of this custom attribute.
///
/// For example, `["yellow", "green"]` when the key is "color". Empty string
/// is not allowed. Otherwise, an INVALID_ARGUMENT error is returned. Exactly
/// one of text or numbers should be set. Otherwise, an INVALID_ARGUMENT error
/// is returned.
core.List<core.String>? text;
GoogleCloudRetailV2CustomAttribute({
this.indexable,
this.numbers,
this.searchable,
this.text,
});
GoogleCloudRetailV2CustomAttribute.fromJson(core.Map _json)
: this(
indexable: _json.containsKey('indexable')
? _json['indexable'] as core.bool
: null,
numbers: _json.containsKey('numbers')
? (_json['numbers'] as core.List)
.map((value) => (value as core.num).toDouble())
.toList()
: null,
searchable: _json.containsKey('searchable')
? _json['searchable'] as core.bool
: null,
text: _json.containsKey('text')
? (_json['text'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (indexable != null) 'indexable': indexable!,
if (numbers != null) 'numbers': numbers!,
if (searchable != null) 'searchable': searchable!,
if (text != null) 'text': text!,
};
}
/// Fulfillment information, such as the store IDs for in-store pickup or region
/// IDs for different shipping methods.
class GoogleCloudRetailV2FulfillmentInfo {
/// The IDs for this type, such as the store IDs for
/// FulfillmentInfo.type.pickup-in-store or the region IDs for
/// FulfillmentInfo.type.same-day-delivery.
///
/// A maximum of 3000 values are allowed. Each value must be a string with a
/// length limit of 30 characters, matching the pattern `[a-zA-Z0-9_-]+`, such
/// as "store1" or "REGION-2". Otherwise, an INVALID_ARGUMENT error is
/// returned.
core.List<core.String>? placeIds;
/// The fulfillment type, including commonly used types (such as pickup in
/// store and same day delivery), and custom types.
///
/// Customers have to map custom types to their display names before rendering
/// UI. Supported values: * "pickup-in-store" * "ship-to-store" *
/// "same-day-delivery" * "next-day-delivery" * "custom-type-1" *
/// "custom-type-2" * "custom-type-3" * "custom-type-4" * "custom-type-5" If
/// this field is set to an invalid value other than these, an
/// INVALID_ARGUMENT error is returned.
core.String? type;
GoogleCloudRetailV2FulfillmentInfo({
this.placeIds,
this.type,
});
GoogleCloudRetailV2FulfillmentInfo.fromJson(core.Map _json)
: this(
placeIds: _json.containsKey('placeIds')
? (_json['placeIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
type: _json.containsKey('type') ? _json['type'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (placeIds != null) 'placeIds': placeIds!,
if (type != null) 'type': type!,
};
}
/// Google Cloud Storage location for input content.
///
/// format.
class GoogleCloudRetailV2GcsSource {
/// The schema to use when parsing the data from the source.
///
/// Supported values for product imports: * `product` (default): One JSON
/// Product per line. Each product must have a valid Product.id. *
/// `product_merchant_center`: See
/// [Importing catalog data from Merchant Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc).
/// Supported values for user events imports: * `user_event` (default): One
/// JSON UserEvent per line. * `user_event_ga360`: Using
/// https://support.google.com/analytics/answer/3437719. Supported values for
/// control imports: * 'control' (default): One JSON Control per line.
/// Supported values for catalog attribute imports: * 'catalog_attribute'
/// (default): One CSV CatalogAttribute per line.
core.String? dataSchema;
/// Google Cloud Storage URIs to input files.
///
/// URI can be up to 2000 characters long. URIs can match the full object path
/// (for example, `gs://bucket/directory/object.json`) or a pattern matching
/// one or more files, such as `gs://bucket/directory / * .json`. A request
/// can contain at most 100 files, and each file can be up to 2 GB. See
/// [Importing product information](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog)
/// for the expected file format and setup instructions.
///
/// Required.
core.List<core.String>? inputUris;
GoogleCloudRetailV2GcsSource({
this.dataSchema,
this.inputUris,
});
GoogleCloudRetailV2GcsSource.fromJson(core.Map _json)
: this(
dataSchema: _json.containsKey('dataSchema')
? _json['dataSchema'] as core.String
: null,
inputUris: _json.containsKey('inputUris')
? (_json['inputUris'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (dataSchema != null) 'dataSchema': dataSchema!,
if (inputUris != null) 'inputUris': inputUris!,
};
}
/// Response message of CatalogService.GetDefaultBranch.
class GoogleCloudRetailV2GetDefaultBranchResponse {
/// Full resource name of the branch id currently set as default branch.
core.String? branch;
/// This corresponds to SetDefaultBranchRequest.note field, when this branch
/// was set as default.
core.String? note;
/// The time when this branch is set to default.
core.String? setTime;
GoogleCloudRetailV2GetDefaultBranchResponse({
this.branch,
this.note,
this.setTime,
});
GoogleCloudRetailV2GetDefaultBranchResponse.fromJson(core.Map _json)
: this(
branch: _json.containsKey('branch')
? _json['branch'] as core.String
: null,
note: _json.containsKey('note') ? _json['note'] as core.String : null,
setTime: _json.containsKey('setTime')
? _json['setTime'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (branch != null) 'branch': branch!,
if (note != null) 'note': note!,
if (setTime != null) 'setTime': setTime!,
};
}
/// Product thumbnail/detail image.
class GoogleCloudRetailV2Image {
/// Height of the image in number of pixels.
///
/// This field must be nonnegative. Otherwise, an INVALID_ARGUMENT error is
/// returned.
core.int? height;
/// URI of the image.
///
/// This field must be a valid UTF-8 encoded URI with a length limit of 5,000
/// characters. Otherwise, an INVALID_ARGUMENT error is returned. Google
/// Merchant Center property
/// [image_link](https://support.google.com/merchants/answer/6324350).
/// Schema.org property [Product.image](https://schema.org/image).
///
/// Required.
core.String? uri;
/// Width of the image in number of pixels.
///
/// This field must be nonnegative. Otherwise, an INVALID_ARGUMENT error is
/// returned.
core.int? width;
GoogleCloudRetailV2Image({
this.height,
this.uri,
this.width,
});
GoogleCloudRetailV2Image.fromJson(core.Map _json)
: this(
height:
_json.containsKey('height') ? _json['height'] as core.int : null,
uri: _json.containsKey('uri') ? _json['uri'] as core.String : null,
width: _json.containsKey('width') ? _json['width'] as core.int : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (height != null) 'height': height!,
if (uri != null) 'uri': uri!,
if (width != null) 'width': width!,
};
}
/// Request message for ImportCompletionData methods.
class GoogleCloudRetailV2ImportCompletionDataRequest {
/// The desired input location of the data.
///
/// Required.
GoogleCloudRetailV2CompletionDataInputConfig? inputConfig;
/// Pub/Sub topic for receiving notification.
///
/// If this field is set, when the import is finished, a notification will be
/// sent to specified Pub/Sub topic. The message data will be JSON string of a
/// Operation. Format of the Pub/Sub topic is
/// `projects/{project}/topics/{topic}`.
core.String? notificationPubsubTopic;
GoogleCloudRetailV2ImportCompletionDataRequest({
this.inputConfig,
this.notificationPubsubTopic,
});
GoogleCloudRetailV2ImportCompletionDataRequest.fromJson(core.Map _json)
: this(
inputConfig: _json.containsKey('inputConfig')
? GoogleCloudRetailV2CompletionDataInputConfig.fromJson(
_json['inputConfig'] as core.Map<core.String, core.dynamic>)
: null,
notificationPubsubTopic: _json.containsKey('notificationPubsubTopic')
? _json['notificationPubsubTopic'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (inputConfig != null) 'inputConfig': inputConfig!,
if (notificationPubsubTopic != null)
'notificationPubsubTopic': notificationPubsubTopic!,
};
}
/// Configuration of destination for Import related errors.
class GoogleCloudRetailV2ImportErrorsConfig {
/// Google Cloud Storage prefix for import errors.
///
/// This must be an empty, existing Cloud Storage directory. Import errors
/// will be written to sharded files in this directory, one per line, as a
/// JSON-encoded `google.rpc.Status` message.
core.String? gcsPrefix;
GoogleCloudRetailV2ImportErrorsConfig({
this.gcsPrefix,
});
GoogleCloudRetailV2ImportErrorsConfig.fromJson(core.Map _json)
: this(
gcsPrefix: _json.containsKey('gcsPrefix')
? _json['gcsPrefix'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (gcsPrefix != null) 'gcsPrefix': gcsPrefix!,
};
}
/// Request message for Import methods.
class GoogleCloudRetailV2ImportProductsRequest {
/// The desired location of errors incurred during the Import.
GoogleCloudRetailV2ImportErrorsConfig? errorsConfig;
/// The desired input location of the data.
///
/// Required.
GoogleCloudRetailV2ProductInputConfig? inputConfig;
/// Pub/Sub topic for receiving notification.
///
/// If this field is set, when the import is finished, a notification will be
/// sent to specified Pub/Sub topic. The message data will be JSON string of a
/// Operation. Format of the Pub/Sub topic is
/// `projects/{project}/topics/{topic}`. Only supported when
/// ImportProductsRequest.reconciliation_mode is set to `FULL`.
core.String? notificationPubsubTopic;
/// The mode of reconciliation between existing products and the products to
/// be imported.
///
/// Defaults to ReconciliationMode.INCREMENTAL.
/// Possible string values are:
/// - "RECONCILIATION_MODE_UNSPECIFIED" : Defaults to INCREMENTAL.
/// - "INCREMENTAL" : Inserts new products or updates existing products.
/// - "FULL" : Calculates diff and replaces the entire product dataset.
/// Existing products may be deleted if they are not present in the source
/// location. Can only be set while using BigQuerySource. And the BigQuery
/// dataset must be created in the data location "us (multiple regions in
/// United States)", otherwise a PERMISSION_DENIED error is thrown. Add the
/// IAM permission "BigQuery Data Viewer" for
/// cloud-retail-customer-data-access@system.gserviceaccount.com before using
/// this feature otherwise an error is thrown. This feature is only available
/// for users who have Retail Search enabled. Please submit a form
/// [here](https://cloud.google.com/contact) to contact cloud sales if you are
/// interested in using Retail Search.
core.String? reconciliationMode;
/// Unique identifier provided by client, within the ancestor dataset scope.
///
/// Ensures idempotency and used for request deduplication. Server-generated
/// if unspecified. Up to 128 characters long and must match the pattern:
/// `[a-zA-Z0-9_]+`. This is returned as Operation.name in ImportMetadata.
/// Only supported when ImportProductsRequest.reconciliation_mode is set to
/// `FULL`.
core.String? requestId;
/// Indicates which fields in the provided imported 'products' to update.
///
/// If not set, will by default update all fields.
core.String? updateMask;
GoogleCloudRetailV2ImportProductsRequest({
this.errorsConfig,
this.inputConfig,
this.notificationPubsubTopic,
this.reconciliationMode,
this.requestId,
this.updateMask,
});
GoogleCloudRetailV2ImportProductsRequest.fromJson(core.Map _json)
: this(
errorsConfig: _json.containsKey('errorsConfig')
? GoogleCloudRetailV2ImportErrorsConfig.fromJson(
_json['errorsConfig'] as core.Map<core.String, core.dynamic>)
: null,
inputConfig: _json.containsKey('inputConfig')
? GoogleCloudRetailV2ProductInputConfig.fromJson(
_json['inputConfig'] as core.Map<core.String, core.dynamic>)
: null,
notificationPubsubTopic: _json.containsKey('notificationPubsubTopic')
? _json['notificationPubsubTopic'] as core.String
: null,
reconciliationMode: _json.containsKey('reconciliationMode')
? _json['reconciliationMode'] as core.String
: null,
requestId: _json.containsKey('requestId')
? _json['requestId'] as core.String
: null,
updateMask: _json.containsKey('updateMask')
? _json['updateMask'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (errorsConfig != null) 'errorsConfig': errorsConfig!,
if (inputConfig != null) 'inputConfig': inputConfig!,
if (notificationPubsubTopic != null)
'notificationPubsubTopic': notificationPubsubTopic!,
if (reconciliationMode != null)
'reconciliationMode': reconciliationMode!,
if (requestId != null) 'requestId': requestId!,
if (updateMask != null) 'updateMask': updateMask!,
};
}
/// Request message for the ImportUserEvents request.
class GoogleCloudRetailV2ImportUserEventsRequest {
/// The desired location of errors incurred during the Import.
///
/// Cannot be set for inline user event imports.
GoogleCloudRetailV2ImportErrorsConfig? errorsConfig;
/// The desired input location of the data.
///
/// Required.
GoogleCloudRetailV2UserEventInputConfig? inputConfig;
GoogleCloudRetailV2ImportUserEventsRequest({
this.errorsConfig,
this.inputConfig,
});
GoogleCloudRetailV2ImportUserEventsRequest.fromJson(core.Map _json)
: this(
errorsConfig: _json.containsKey('errorsConfig')
? GoogleCloudRetailV2ImportErrorsConfig.fromJson(
_json['errorsConfig'] as core.Map<core.String, core.dynamic>)
: null,
inputConfig: _json.containsKey('inputConfig')
? GoogleCloudRetailV2UserEventInputConfig.fromJson(
_json['inputConfig'] as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (errorsConfig != null) 'errorsConfig': errorsConfig!,
if (inputConfig != null) 'inputConfig': inputConfig!,
};
}
/// A floating point interval.
class GoogleCloudRetailV2Interval {
/// Exclusive upper bound.
core.double? exclusiveMaximum;
/// Exclusive lower bound.
core.double? exclusiveMinimum;
/// Inclusive upper bound.
core.double? maximum;
/// Inclusive lower bound.
core.double? minimum;
GoogleCloudRetailV2Interval({
this.exclusiveMaximum,
this.exclusiveMinimum,
this.maximum,
this.minimum,
});
GoogleCloudRetailV2Interval.fromJson(core.Map _json)
: this(
exclusiveMaximum: _json.containsKey('exclusiveMaximum')
? (_json['exclusiveMaximum'] as core.num).toDouble()
: null,
exclusiveMinimum: _json.containsKey('exclusiveMinimum')
? (_json['exclusiveMinimum'] as core.num).toDouble()
: null,
maximum: _json.containsKey('maximum')
? (_json['maximum'] as core.num).toDouble()
: null,
minimum: _json.containsKey('minimum')
? (_json['minimum'] as core.num).toDouble()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (exclusiveMaximum != null) 'exclusiveMaximum': exclusiveMaximum!,
if (exclusiveMinimum != null) 'exclusiveMinimum': exclusiveMinimum!,
if (maximum != null) 'maximum': maximum!,
if (minimum != null) 'minimum': minimum!,
};
}
/// Response for CatalogService.ListCatalogs method.
class GoogleCloudRetailV2ListCatalogsResponse {
/// All the customer's Catalogs.
core.List<GoogleCloudRetailV2Catalog>? catalogs;
/// A token that can be sent as ListCatalogsRequest.page_token to retrieve the
/// next page.
///
/// If this field is omitted, there are no subsequent pages.
core.String? nextPageToken;
GoogleCloudRetailV2ListCatalogsResponse({
this.catalogs,
this.nextPageToken,
});
GoogleCloudRetailV2ListCatalogsResponse.fromJson(core.Map _json)
: this(
catalogs: _json.containsKey('catalogs')
? (_json['catalogs'] as core.List)
.map((value) => GoogleCloudRetailV2Catalog.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
nextPageToken: _json.containsKey('nextPageToken')
? _json['nextPageToken'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (catalogs != null) 'catalogs': catalogs!,
if (nextPageToken != null) 'nextPageToken': nextPageToken!,
};
}
/// Response message for ProductService.ListProducts method.
class GoogleCloudRetailV2ListProductsResponse {
/// A token that can be sent as ListProductsRequest.page_token to retrieve the
/// next page.
///
/// If this field is omitted, there are no subsequent pages.
core.String? nextPageToken;
/// The Products.
core.List<GoogleCloudRetailV2Product>? products;
GoogleCloudRetailV2ListProductsResponse({
this.nextPageToken,
this.products,
});
GoogleCloudRetailV2ListProductsResponse.fromJson(core.Map _json)
: this(
nextPageToken: _json.containsKey('nextPageToken')
? _json['nextPageToken'] as core.String
: null,
products: _json.containsKey('products')
? (_json['products'] as core.List)
.map((value) => GoogleCloudRetailV2Product.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (nextPageToken != null) 'nextPageToken': nextPageToken!,
if (products != null) 'products': products!,
};
}
/// Request message for Predict method.
class GoogleCloudRetailV2PredictRequest {
/// Filter for restricting prediction results with a length limit of 5,000
/// characters.
///
/// Accepts values for tags and the `filterOutOfStockItems` flag. * Tag
/// expressions. Restricts predictions to products that match all of the
/// specified tags. Boolean operators `OR` and `NOT` are supported if the
/// expression is enclosed in parentheses, and must be separated from the tag
/// values by a space. `-"tagA"` is also supported and is equivalent to `NOT
/// "tagA"`. Tag values must be double quoted UTF-8 encoded strings with a
/// size limit of 1,000 characters. Note: "Recently viewed" models don't
/// support tag filtering at the moment. * filterOutOfStockItems. Restricts
/// predictions to products that do not have a stockState value of
/// OUT_OF_STOCK. Examples: * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT
/// "promotional") * filterOutOfStockItems tag=(-"promotional") *
/// filterOutOfStockItems If your filter blocks all prediction results,
/// nothing will be returned. If you want generic (unfiltered) popular
/// products to be returned instead, set `strictFiltering` to false in
/// `PredictRequest.params`.
core.String? filter;
/// The labels applied to a resource must meet the following requirements: *
/// Each resource can have multiple labels, up to a maximum of 64.
///
/// * Each label must be a key-value pair. * Keys have a minimum length of 1
/// character and a maximum length of 63 characters, and cannot be empty.
/// Values can be empty, and have a maximum length of 63 characters. * Keys
/// and values can contain only lowercase letters, numeric characters,
/// underscores, and dashes. All characters must use UTF-8 encoding, and
/// international characters are allowed. * The key portion of a label must be
/// unique. However, you can use the same key with multiple resources. * Keys
/// must start with a lowercase letter or international character. See
/// [Google Cloud Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
/// for more details.
core.Map<core.String, core.String>? labels;
/// Maximum number of results to return per page.
///
/// Set this property to the number of prediction results needed. If zero, the
/// service will choose a reasonable default. The maximum allowed value is
/// 100. Values above 100 will be coerced to 100.
core.int? pageSize;
/// The previous PredictResponse.next_page_token.
core.String? pageToken;
/// Additional domain specific parameters for the predictions.
///
/// Allowed values: * `returnProduct`: Boolean. If set to true, the associated
/// product object will be returned in the `results.metadata` field in the
/// prediction response. * `returnScore`: Boolean. If set to true, the
/// prediction 'score' corresponding to each returned product will be set in
/// the `results.metadata` field in the prediction response. The given 'score'
/// indicates the probability of an product being clicked/purchased given the
/// user's context and history. * `strictFiltering`: Boolean. True by default.
/// If set to false, the service will return generic (unfiltered) popular
/// products instead of empty if your filter blocks all prediction results. *
/// `priceRerankLevel`: String. Default empty. If set to be non-empty, then it
/// needs to be one of {'no-price-reranking', 'low-price-reranking',
/// 'medium-price-reranking', 'high-price-reranking'}. This gives
/// request-level control and adjusts prediction results based on product
/// price. * `diversityLevel`: String. Default empty. If set to be non-empty,
/// then it needs to be one of {'no-diversity', 'low-diversity',
/// 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives
/// request-level control and adjusts prediction results based on product
/// category.
///
/// The values for Object must be JSON objects. It can consist of `num`,
/// `String`, `bool` and `null` as well as `Map` and `List` values.
core.Map<core.String, core.Object?>? params;
/// Context about the user, what they are looking at and what action they took
/// to trigger the predict request.
///
/// Note that this user event detail won't be ingested to userEvent logs.
/// Thus, a separate userEvent write request is required for event logging.
///
/// Required.
GoogleCloudRetailV2UserEvent? userEvent;
/// Use validate only mode for this prediction query.
///
/// If set to true, a dummy model will be used that returns arbitrary
/// products. Note that the validate only mode should only be used for testing
/// the API, or if the model is not ready.
core.bool? validateOnly;
GoogleCloudRetailV2PredictRequest({
this.filter,
this.labels,
this.pageSize,
this.pageToken,
this.params,
this.userEvent,
this.validateOnly,
});
GoogleCloudRetailV2PredictRequest.fromJson(core.Map _json)
: this(
filter: _json.containsKey('filter')
? _json['filter'] as core.String
: null,
labels: _json.containsKey('labels')
? (_json['labels'] as core.Map<core.String, core.dynamic>).map(
(key, item) => core.MapEntry(
key,
item as core.String,
),
)
: null,
pageSize: _json.containsKey('pageSize')
? _json['pageSize'] as core.int
: null,
pageToken: _json.containsKey('pageToken')
? _json['pageToken'] as core.String
: null,
params: _json.containsKey('params')
? _json['params'] as core.Map<core.String, core.dynamic>
: null,
userEvent: _json.containsKey('userEvent')
? GoogleCloudRetailV2UserEvent.fromJson(
_json['userEvent'] as core.Map<core.String, core.dynamic>)
: null,
validateOnly: _json.containsKey('validateOnly')
? _json['validateOnly'] as core.bool
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (filter != null) 'filter': filter!,
if (labels != null) 'labels': labels!,
if (pageSize != null) 'pageSize': pageSize!,
if (pageToken != null) 'pageToken': pageToken!,
if (params != null) 'params': params!,
if (userEvent != null) 'userEvent': userEvent!,
if (validateOnly != null) 'validateOnly': validateOnly!,
};
}
/// Response message for predict method.
class GoogleCloudRetailV2PredictResponse {
/// A unique attribution token.
///
/// This should be included in the UserEvent logs resulting from this
/// recommendation, which enables accurate attribution of recommendation model
/// performance.
core.String? attributionToken;
/// IDs of products in the request that were missing from the inventory.
core.List<core.String>? missingIds;
/// A list of recommended products.
///
/// The order represents the ranking (from the most relevant product to the
/// least).
core.List<GoogleCloudRetailV2PredictResponsePredictionResult>? results;
/// True if the validateOnly property was set in the request.
core.bool? validateOnly;
GoogleCloudRetailV2PredictResponse({
this.attributionToken,
this.missingIds,
this.results,
this.validateOnly,
});
GoogleCloudRetailV2PredictResponse.fromJson(core.Map _json)
: this(
attributionToken: _json.containsKey('attributionToken')
? _json['attributionToken'] as core.String
: null,
missingIds: _json.containsKey('missingIds')
? (_json['missingIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
results: _json.containsKey('results')
? (_json['results'] as core.List)
.map((value) =>
GoogleCloudRetailV2PredictResponsePredictionResult
.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
validateOnly: _json.containsKey('validateOnly')
? _json['validateOnly'] as core.bool
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (attributionToken != null) 'attributionToken': attributionToken!,
if (missingIds != null) 'missingIds': missingIds!,
if (results != null) 'results': results!,
if (validateOnly != null) 'validateOnly': validateOnly!,
};
}
/// PredictionResult represents the recommendation prediction results.
class GoogleCloudRetailV2PredictResponsePredictionResult {
/// ID of the recommended product
core.String? id;
/// Additional product metadata / annotations.
///
/// Possible values: * `product`: JSON representation of the product. Will be
/// set if `returnProduct` is set to true in `PredictRequest.params`. *
/// `score`: Prediction score in double value. Will be set if `returnScore` is
/// set to true in `PredictRequest.params`.
///
/// The values for Object must be JSON objects. It can consist of `num`,
/// `String`, `bool` and `null` as well as `Map` and `List` values.
core.Map<core.String, core.Object?>? metadata;
GoogleCloudRetailV2PredictResponsePredictionResult({
this.id,
this.metadata,
});
GoogleCloudRetailV2PredictResponsePredictionResult.fromJson(core.Map _json)
: this(
id: _json.containsKey('id') ? _json['id'] as core.String : null,
metadata: _json.containsKey('metadata')
? _json['metadata'] as core.Map<core.String, core.dynamic>
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (id != null) 'id': id!,
if (metadata != null) 'metadata': metadata!,
};
}
/// The price information of a Product.
class GoogleCloudRetailV2PriceInfo {
/// The costs associated with the sale of a particular product.
///
/// Used for gross profit reporting. * Profit = price - cost Google Merchant
/// Center property
/// [cost_of_goods_sold](https://support.google.com/merchants/answer/9017895).
core.double? cost;
/// The 3-letter currency code defined in
/// [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html).
///
/// If this field is an unrecognizable currency code, an INVALID_ARGUMENT
/// error is returned. The Product.Type.VARIANT Products with the same
/// Product.primary_product_id must share the same currency_code. Otherwise, a
/// FAILED_PRECONDITION error is returned.
core.String? currencyCode;
/// Price of the product without any discount.
///
/// If zero, by default set to be the price.
core.double? originalPrice;
/// Price of the product.
///
/// Google Merchant Center property
/// [price](https://support.google.com/merchants/answer/6324371). Schema.org
/// property [Offer.price](https://schema.org/price).
core.double? price;
/// The timestamp when the price starts to be effective.
///
/// This can be set as a future timestamp, and the price is only used for
/// search after price_effective_time. If so, the original_price must be set
/// and original_price is used before price_effective_time. Do not set if
/// price is always effective because it will cause additional latency during
/// search.
core.String? priceEffectiveTime;
/// The timestamp when the price stops to be effective.
///
/// The price is used for search before price_expire_time. If this field is
/// set, the original_price must be set and original_price is used after
/// price_expire_time. Do not set if price is always effective because it will
/// cause additional latency during search.
core.String? priceExpireTime;
/// The price range of all the child Product.Type.VARIANT Products grouped
/// together on the Product.Type.PRIMARY Product.
///
/// Only populated for Product.Type.PRIMARY Products. Note: This field is
/// OUTPUT_ONLY for ProductService.GetProduct. Do not set this field in API
/// requests.
///
/// Output only.
GoogleCloudRetailV2PriceInfoPriceRange? priceRange;
GoogleCloudRetailV2PriceInfo({
this.cost,
this.currencyCode,
this.originalPrice,
this.price,
this.priceEffectiveTime,
this.priceExpireTime,
this.priceRange,
});
GoogleCloudRetailV2PriceInfo.fromJson(core.Map _json)
: this(
cost: _json.containsKey('cost')
? (_json['cost'] as core.num).toDouble()
: null,
currencyCode: _json.containsKey('currencyCode')
? _json['currencyCode'] as core.String
: null,
originalPrice: _json.containsKey('originalPrice')
? (_json['originalPrice'] as core.num).toDouble()
: null,
price: _json.containsKey('price')
? (_json['price'] as core.num).toDouble()
: null,
priceEffectiveTime: _json.containsKey('priceEffectiveTime')
? _json['priceEffectiveTime'] as core.String
: null,
priceExpireTime: _json.containsKey('priceExpireTime')
? _json['priceExpireTime'] as core.String
: null,
priceRange: _json.containsKey('priceRange')
? GoogleCloudRetailV2PriceInfoPriceRange.fromJson(
_json['priceRange'] as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (cost != null) 'cost': cost!,
if (currencyCode != null) 'currencyCode': currencyCode!,
if (originalPrice != null) 'originalPrice': originalPrice!,
if (price != null) 'price': price!,
if (priceEffectiveTime != null)
'priceEffectiveTime': priceEffectiveTime!,
if (priceExpireTime != null) 'priceExpireTime': priceExpireTime!,
if (priceRange != null) 'priceRange': priceRange!,
};
}
/// The price range of all variant Product having the same
/// Product.primary_product_id.
class GoogleCloudRetailV2PriceInfoPriceRange {
/// The inclusive Product.pricing_info.original_price internal of all variant
/// Product having the same Product.primary_product_id.
GoogleCloudRetailV2Interval? originalPrice;
/// The inclusive Product.pricing_info.price interval of all variant Product
/// having the same Product.primary_product_id.
GoogleCloudRetailV2Interval? price;
GoogleCloudRetailV2PriceInfoPriceRange({
this.originalPrice,
this.price,
});
GoogleCloudRetailV2PriceInfoPriceRange.fromJson(core.Map _json)
: this(
originalPrice: _json.containsKey('originalPrice')
? GoogleCloudRetailV2Interval.fromJson(
_json['originalPrice'] as core.Map<core.String, core.dynamic>)
: null,
price: _json.containsKey('price')
? GoogleCloudRetailV2Interval.fromJson(
_json['price'] as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (originalPrice != null) 'originalPrice': originalPrice!,
if (price != null) 'price': price!,
};
}
/// Product captures all metadata information of items to be recommended or
/// searched.
class GoogleCloudRetailV2Product {
/// Highly encouraged.
///
/// Extra product attributes to be included. For example, for products, this
/// could include the store name, vendor, style, color, etc. These are very
/// strong signals for recommendation model, thus we highly recommend
/// providing the attributes here. Features that can take on one of a limited
/// number of possible values. Two types of features can be set are: Textual
/// features. some examples would be the brand/maker of a product, or country
/// of a customer. Numerical features. Some examples would be the
/// height/weight of a product, or age of a customer. For example: `{
/// "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
/// {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This
/// field needs to pass all below criteria, otherwise an INVALID_ARGUMENT
/// error is returned: * Max entries count: 200. * The key must be a UTF-8
/// encoded string with a length limit of 128 characters. * For indexable
/// attribute, the key must match the pattern: `a-zA-Z0-9*`. For example,
/// `key0LikeThis` or `KEY_1_LIKE_THIS`. * For text attributes, at most 400
/// values are allowed. Empty values are not allowed. Each value must be a
/// non-empty UTF-8 encoded string with a length limit of 256 characters. *
/// For number attributes, at most 400 values are allowed.
core.Map<core.String, GoogleCloudRetailV2CustomAttribute>? attributes;
/// The target group associated with a given audience (e.g. male, veterans,
/// car owners, musicians, etc.) of the product.
GoogleCloudRetailV2Audience? audience;
/// The online availability of the Product.
///
/// Default to Availability.IN_STOCK. Corresponding properties: Google
/// Merchant Center property
/// [availability](https://support.google.com/merchants/answer/6324448).
/// Schema.org property [Offer.availability](https://schema.org/availability).
/// Possible string values are:
/// - "AVAILABILITY_UNSPECIFIED" : Default product availability. Default to
/// Availability.IN_STOCK if unset.
/// - "IN_STOCK" : Product in stock.
/// - "OUT_OF_STOCK" : Product out of stock.
/// - "PREORDER" : Product that is in pre-order state.
/// - "BACKORDER" : Product that is back-ordered (i.e. temporarily out of
/// stock).
core.String? availability;
/// The available quantity of the item.
core.int? availableQuantity;
/// The timestamp when this Product becomes available for
/// SearchService.Search.
core.String? availableTime;
/// The brands of the product.
///
/// A maximum of 30 brands are allowed. Each brand must be a UTF-8 encoded
/// string with a length limit of 1,000 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. Corresponding properties: Google
/// Merchant Center property
/// [brand](https://support.google.com/merchants/answer/6324351). Schema.org
/// property [Product.brand](https://schema.org/brand).
core.List<core.String>? brands;
/// Product categories.
///
/// This field is repeated for supporting one product belonging to several
/// parallel categories. Strongly recommended using the full path for better
/// search / recommendation quality. To represent full path of category, use
/// '\>' sign to separate different hierarchies. If '\>' is part of the
/// category name, please replace it with other character(s). For example, if
/// a shoes product belongs to both \["Shoes & Accessories" -\> "Shoes"\] and
/// \["Sports & Fitness" -\> "Athletic Clothing" -\> "Shoes"\], it could be
/// represented as: "categories": \[ "Shoes & Accessories \> Shoes", "Sports &
/// Fitness \> Athletic Clothing \> Shoes" \] Must be set for Type.PRIMARY
/// Product otherwise an INVALID_ARGUMENT error is returned. At most 250
/// values are allowed per Product. Empty values are not allowed. Each value
/// must be a UTF-8 encoded string with a length limit of 5,000 characters.
/// Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
/// properties: Google Merchant Center property google_product_category.
/// Schema.org property [Product.category](https://schema.org/category).
/// \[mc_google_product_category\]:
/// https://support.google.com/merchants/answer/6324436
core.List<core.String>? categories;
/// The id of the collection members when type is Type.COLLECTION.
///
/// Non-existent product ids are allowed. The type of the members must be
/// either Type.PRIMARY or Type.VARIANT otherwise and INVALID_ARGUMENT error
/// is thrown. Should not set it for other types. A maximum of 1000 values are
/// allowed. Otherwise, an INVALID_ARGUMENT error is return.
core.List<core.String>? collectionMemberIds;
/// The color of the product.
///
/// Corresponding properties: Google Merchant Center property
/// [color](https://support.google.com/merchants/answer/6324487). Schema.org
/// property [Product.color](https://schema.org/color).
GoogleCloudRetailV2ColorInfo? colorInfo;
/// The condition of the product.
///
/// Strongly encouraged to use the standard values: "new", "refurbished",
/// "used". A maximum of 1 value is allowed per Product. Each value must be a
/// UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. Corresponding properties: Google
/// Merchant Center property
/// [condition](https://support.google.com/merchants/answer/6324469).
/// Schema.org property
/// [Offer.itemCondition](https://schema.org/itemCondition).
core.List<core.String>? conditions;
/// Product description.
///
/// This field must be a UTF-8 encoded string with a length limit of 5,000
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [description](https://support.google.com/merchants/answer/6324468).
/// Schema.org property [Product.description](https://schema.org/description).
core.String? description;
/// The timestamp when this product becomes unavailable for
/// SearchService.Search.
///
/// If it is set, the Product is not available for SearchService.Search after
/// expire_time. However, the product can still be retrieved by
/// ProductService.GetProduct and ProductService.ListProducts. expire_time
/// must be later than available_time and publish_time, otherwise an
/// INVALID_ARGUMENT error is thrown. Corresponding properties: Google
/// Merchant Center property
/// [expiration_date](https://support.google.com/merchants/answer/6324499).
core.String? expireTime;
/// Fulfillment information, such as the store IDs for in-store pickup or
/// region IDs for different shipping methods.
///
/// All the elements must have distinct FulfillmentInfo.type. Otherwise, an
/// INVALID_ARGUMENT error is returned.
core.List<GoogleCloudRetailV2FulfillmentInfo>? fulfillmentInfo;
/// The Global Trade Item Number (GTIN) of the product.
///
/// This field must be a UTF-8 encoded string with a length limit of 128
/// characters. Otherwise, an INVALID_ARGUMENT error is returned. This field
/// must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [gtin](https://support.google.com/merchants/answer/6324461). Schema.org
/// property [Product.isbn](https://schema.org/isbn),
/// [Product.gtin8](https://schema.org/gtin8),
/// [Product.gtin12](https://schema.org/gtin12),
/// [Product.gtin13](https://schema.org/gtin13), or
/// [Product.gtin14](https://schema.org/gtin14). If the value is not a valid
/// GTIN, an INVALID_ARGUMENT error is returned.
core.String? gtin;
/// Product identifier, which is the final component of name.
///
/// For example, this field is "id_1", if name is `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
/// This field must be a UTF-8 encoded string with a length limit of 128
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [id](https://support.google.com/merchants/answer/6324405). Schema.org
/// property [Product.sku](https://schema.org/sku).
///
/// Immutable.
core.String? id;
/// Product images for the product.Highly recommended to put the main image to
/// the first.
///
/// A maximum of 300 images are allowed. Corresponding properties: Google
/// Merchant Center property
/// [image_link](https://support.google.com/merchants/answer/6324350).
/// Schema.org property [Product.image](https://schema.org/image).
core.List<GoogleCloudRetailV2Image>? images;
/// Language of the title/description and other string attributes.
///
/// Use language tags defined by
/// [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product
/// prediction, this field is ignored and the model automatically detects the
/// text language. The Product can include text in different languages, but
/// duplicating Products to provide text in multiple languages can result in
/// degraded model performance. For product search this field is in use. It
/// defaults to "en-US" if unset.
core.String? languageCode;
/// The material of the product.
///
/// For example, "leather", "wooden". A maximum of 20 values are allowed. Each
/// value must be a UTF-8 encoded string with a length limit of 200
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [material](https://support.google.com/merchants/answer/6324410).
/// Schema.org property [Product.material](https://schema.org/material).
core.List<core.String>? materials;
/// Full resource name of the product, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/default_branch/products/product_id`.
///
/// Immutable.
core.String? name;
/// The pattern or graphic print of the product.
///
/// For example, "striped", "polka dot", "paisley". A maximum of 20 values are
/// allowed per Product. Each value must be a UTF-8 encoded string with a
/// length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
/// returned. Corresponding properties: Google Merchant Center property
/// [pattern](https://support.google.com/merchants/answer/6324483). Schema.org
/// property [Product.pattern](https://schema.org/pattern).
core.List<core.String>? patterns;
/// Product price and cost information.
///
/// Corresponding properties: Google Merchant Center property
/// [price](https://support.google.com/merchants/answer/6324371).
GoogleCloudRetailV2PriceInfo? priceInfo;
/// Variant group identifier.
///
/// Must be an id, with the same parent branch with this product. Otherwise,
/// an error is thrown. For Type.PRIMARY Products, this field can only be
/// empty or set to the same value as id. For VARIANT Products, this field
/// cannot be empty. A maximum of 2,000 products are allowed to share the same
/// Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [item_group_id](https://support.google.com/merchants/answer/6324507).
/// Schema.org property
/// [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
core.String? primaryProductId;
/// The promotions applied to the product.
///
/// A maximum of 10 values are allowed per Product. Only
/// Promotion.promotion_id will be used, other fields will be ignored if set.
core.List<GoogleCloudRetailV2Promotion>? promotions;
/// The timestamp when the product is published by the retailer for the first
/// time, which indicates the freshness of the products.
///
/// Note that this field is different from available_time, given it purely
/// describes product freshness regardless of when it is available on search
/// and recommendation.
core.String? publishTime;
/// The rating of this product.
GoogleCloudRetailV2Rating? rating;
/// Indicates which fields in the Products are returned in SearchResponse.
///
/// Supported fields for all types: * audience * availability * brands *
/// color_info * conditions * gtin * materials * name * patterns * price_info
/// * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
/// Type.COLLECTION: * categories * description * images Supported fields only
/// for Type.VARIANT: * Only the first image in images To mark attributes as
/// retrievable, include paths of the form "attributes.key" where "key" is the
/// key of a custom attribute, as specified in attributes. For Type.PRIMARY
/// and Type.COLLECTION, the following fields are always returned in
/// SearchResponse by default: * name For Type.VARIANT, the following fields
/// are always returned in by default: * name * color_info Maximum number of
/// paths is 30. Otherwise, an INVALID_ARGUMENT error is returned. Note:
/// Returning more fields in SearchResponse may increase response payload size
/// and serving latency.
core.String? retrievableFields;
/// The size of the product.
///
/// To represent different size systems or size types, consider using this
/// format: \[\[\[size_system:\]size_type:\]size_value\]. For example, in
/// "US:MENS:M", "US" represents size system; "MENS" represents size type; "M"
/// represents size value. In "GIRLS:27", size system is empty; "GIRLS"
/// represents size type; "27" represents size value. In "32 inches", both
/// size system and size type are empty, while size value is "32 inches". A
/// maximum of 20 values are allowed per Product. Each value must be a UTF-8
/// encoded string with a length limit of 128 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. Corresponding properties: Google
/// Merchant Center property
/// [size](https://support.google.com/merchants/answer/6324492),
/// [size_type](https://support.google.com/merchants/answer/6324497), and
/// [size_system](https://support.google.com/merchants/answer/6324502).
/// Schema.org property [Product.size](https://schema.org/size).
core.List<core.String>? sizes;
/// Custom tags associated with the product.
///
/// At most 250 values are allowed per Product. This value must be a UTF-8
/// encoded string with a length limit of 1,000 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. This tag can be used for filtering
/// recommendation results by passing the tag as part of the
/// PredictRequest.filter. Corresponding properties: Google Merchant Center
/// property
/// \[custom_label_0–4\](https://support.google.com/merchants/answer/6324473).
core.List<core.String>? tags;
/// Product title.
///
/// This field must be a UTF-8 encoded string with a length limit of 1,000
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [title](https://support.google.com/merchants/answer/6324415). Schema.org
/// property [Product.name](https://schema.org/name).
///
/// Required.
core.String? title;
/// Input only.
///
/// The TTL (time to live) of the product. If it is set, it must be a
/// non-negative value, and expire_time is set as current timestamp plus ttl.
/// The derived expire_time is returned in the output and ttl is left blank
/// when retrieving the Product. If it is set, the product is not available
/// for SearchService.Search after current timestamp plus ttl. However, the
/// product can still be retrieved by ProductService.GetProduct and
/// ProductService.ListProducts.
core.String? ttl;
/// The type of the product.
///
/// Default to Catalog.product_level_config.ingestion_product_type if unset.
///
/// Immutable.
/// Possible string values are:
/// - "TYPE_UNSPECIFIED" : Default value. Default to
/// Catalog.product_level_config.ingestion_product_type if unset.
/// - "PRIMARY" : The primary type. As the primary unit for predicting,
/// indexing and search serving, a Type.PRIMARY Product is grouped with
/// multiple Type.VARIANT Products.
/// - "VARIANT" : The variant type. Type.VARIANT Products usually share some
/// common attributes on the same Type.PRIMARY Products, but they have variant
/// attributes like different colors, sizes and prices, etc.
/// - "COLLECTION" : The collection type. Collection products are bundled
/// Type.PRIMARY Products or Type.VARIANT Products that are sold together,
/// such as a jewelry set with necklaces, earrings and rings, etc.
core.String? type;
/// Canonical URL directly linking to the product detail page.
///
/// It is strongly recommended to provide a valid uri for the product,
/// otherwise the service performance could be significantly degraded. This
/// field must be a UTF-8 encoded string with a length limit of 5,000
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
/// Corresponding properties: Google Merchant Center property
/// [link](https://support.google.com/merchants/answer/6324416). Schema.org
/// property [Offer.url](https://schema.org/url).
core.String? uri;
/// Product variants grouped together on primary product which share similar
/// product attributes.
///
/// It's automatically grouped by primary_product_id for all the product
/// variants. Only populated for Type.PRIMARY Products. Note: This field is
/// OUTPUT_ONLY for ProductService.GetProduct. Do not set this field in API
/// requests.
///
/// Output only.
core.List<GoogleCloudRetailV2Product>? variants;
GoogleCloudRetailV2Product({
this.attributes,
this.audience,
this.availability,
this.availableQuantity,
this.availableTime,
this.brands,
this.categories,
this.collectionMemberIds,
this.colorInfo,
this.conditions,
this.description,
this.expireTime,
this.fulfillmentInfo,
this.gtin,
this.id,
this.images,
this.languageCode,
this.materials,
this.name,
this.patterns,
this.priceInfo,
this.primaryProductId,
this.promotions,
this.publishTime,
this.rating,
this.retrievableFields,
this.sizes,
this.tags,
this.title,
this.ttl,
this.type,
this.uri,
this.variants,
});
GoogleCloudRetailV2Product.fromJson(core.Map _json)
: this(
attributes: _json.containsKey('attributes')
? (_json['attributes'] as core.Map<core.String, core.dynamic>)
.map(
(key, item) => core.MapEntry(
key,
GoogleCloudRetailV2CustomAttribute.fromJson(
item as core.Map<core.String, core.dynamic>),
),
)
: null,
audience: _json.containsKey('audience')
? GoogleCloudRetailV2Audience.fromJson(
_json['audience'] as core.Map<core.String, core.dynamic>)
: null,
availability: _json.containsKey('availability')
? _json['availability'] as core.String
: null,
availableQuantity: _json.containsKey('availableQuantity')
? _json['availableQuantity'] as core.int
: null,
availableTime: _json.containsKey('availableTime')
? _json['availableTime'] as core.String
: null,
brands: _json.containsKey('brands')
? (_json['brands'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
categories: _json.containsKey('categories')
? (_json['categories'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
collectionMemberIds: _json.containsKey('collectionMemberIds')
? (_json['collectionMemberIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
colorInfo: _json.containsKey('colorInfo')
? GoogleCloudRetailV2ColorInfo.fromJson(
_json['colorInfo'] as core.Map<core.String, core.dynamic>)
: null,
conditions: _json.containsKey('conditions')
? (_json['conditions'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
description: _json.containsKey('description')
? _json['description'] as core.String
: null,
expireTime: _json.containsKey('expireTime')
? _json['expireTime'] as core.String
: null,
fulfillmentInfo: _json.containsKey('fulfillmentInfo')
? (_json['fulfillmentInfo'] as core.List)
.map((value) => GoogleCloudRetailV2FulfillmentInfo.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
gtin: _json.containsKey('gtin') ? _json['gtin'] as core.String : null,
id: _json.containsKey('id') ? _json['id'] as core.String : null,
images: _json.containsKey('images')
? (_json['images'] as core.List)
.map((value) => GoogleCloudRetailV2Image.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
languageCode: _json.containsKey('languageCode')
? _json['languageCode'] as core.String
: null,
materials: _json.containsKey('materials')
? (_json['materials'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
name: _json.containsKey('name') ? _json['name'] as core.String : null,
patterns: _json.containsKey('patterns')
? (_json['patterns'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
priceInfo: _json.containsKey('priceInfo')
? GoogleCloudRetailV2PriceInfo.fromJson(
_json['priceInfo'] as core.Map<core.String, core.dynamic>)
: null,
primaryProductId: _json.containsKey('primaryProductId')
? _json['primaryProductId'] as core.String
: null,
promotions: _json.containsKey('promotions')
? (_json['promotions'] as core.List)
.map((value) => GoogleCloudRetailV2Promotion.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
publishTime: _json.containsKey('publishTime')
? _json['publishTime'] as core.String
: null,
rating: _json.containsKey('rating')
? GoogleCloudRetailV2Rating.fromJson(
_json['rating'] as core.Map<core.String, core.dynamic>)
: null,
retrievableFields: _json.containsKey('retrievableFields')
? _json['retrievableFields'] as core.String
: null,
sizes: _json.containsKey('sizes')
? (_json['sizes'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
tags: _json.containsKey('tags')
? (_json['tags'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
title:
_json.containsKey('title') ? _json['title'] as core.String : null,
ttl: _json.containsKey('ttl') ? _json['ttl'] as core.String : null,
type: _json.containsKey('type') ? _json['type'] as core.String : null,
uri: _json.containsKey('uri') ? _json['uri'] as core.String : null,
variants: _json.containsKey('variants')
? (_json['variants'] as core.List)
.map((value) => GoogleCloudRetailV2Product.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (attributes != null) 'attributes': attributes!,
if (audience != null) 'audience': audience!,
if (availability != null) 'availability': availability!,
if (availableQuantity != null) 'availableQuantity': availableQuantity!,
if (availableTime != null) 'availableTime': availableTime!,
if (brands != null) 'brands': brands!,
if (categories != null) 'categories': categories!,
if (collectionMemberIds != null)
'collectionMemberIds': collectionMemberIds!,
if (colorInfo != null) 'colorInfo': colorInfo!,
if (conditions != null) 'conditions': conditions!,
if (description != null) 'description': description!,
if (expireTime != null) 'expireTime': expireTime!,
if (fulfillmentInfo != null) 'fulfillmentInfo': fulfillmentInfo!,
if (gtin != null) 'gtin': gtin!,
if (id != null) 'id': id!,
if (images != null) 'images': images!,
if (languageCode != null) 'languageCode': languageCode!,
if (materials != null) 'materials': materials!,
if (name != null) 'name': name!,
if (patterns != null) 'patterns': patterns!,
if (priceInfo != null) 'priceInfo': priceInfo!,
if (primaryProductId != null) 'primaryProductId': primaryProductId!,
if (promotions != null) 'promotions': promotions!,
if (publishTime != null) 'publishTime': publishTime!,
if (rating != null) 'rating': rating!,
if (retrievableFields != null) 'retrievableFields': retrievableFields!,
if (sizes != null) 'sizes': sizes!,
if (tags != null) 'tags': tags!,
if (title != null) 'title': title!,
if (ttl != null) 'ttl': ttl!,
if (type != null) 'type': type!,
if (uri != null) 'uri': uri!,
if (variants != null) 'variants': variants!,
};
}
/// Detailed product information associated with a user event.
class GoogleCloudRetailV2ProductDetail {
/// Product information.
///
/// Required field(s): * Product.id Optional override field(s): *
/// Product.price_info If any supported optional fields are provided, we will
/// treat them as a full override when looking up product information from the
/// catalog. Thus, it is important to ensure that the overriding fields are
/// accurate and complete. All other product fields are ignored and instead
/// populated via catalog lookup after event ingestion.
///
/// Required.
GoogleCloudRetailV2Product? product;
/// Quantity of the product associated with the user event.
///
/// For example, this field will be 2 if two products are added to the
/// shopping cart for `purchase-complete` event. Required for `add-to-cart`
/// and `purchase-complete` event types.
core.int? quantity;
GoogleCloudRetailV2ProductDetail({
this.product,
this.quantity,
});
GoogleCloudRetailV2ProductDetail.fromJson(core.Map _json)
: this(
product: _json.containsKey('product')
? GoogleCloudRetailV2Product.fromJson(
_json['product'] as core.Map<core.String, core.dynamic>)
: null,
quantity: _json.containsKey('quantity')
? _json['quantity'] as core.int
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (product != null) 'product': product!,
if (quantity != null) 'quantity': quantity!,
};
}
/// The inline source for the input config for ImportProducts method.
class GoogleCloudRetailV2ProductInlineSource {
/// A list of products to update/create.
///
/// Each product must have a valid Product.id. Recommended max of 100 items.
///
/// Required.
core.List<GoogleCloudRetailV2Product>? products;
GoogleCloudRetailV2ProductInlineSource({
this.products,
});
GoogleCloudRetailV2ProductInlineSource.fromJson(core.Map _json)
: this(
products: _json.containsKey('products')
? (_json['products'] as core.List)
.map((value) => GoogleCloudRetailV2Product.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (products != null) 'products': products!,
};
}
/// The input config source for products.
class GoogleCloudRetailV2ProductInputConfig {
/// BigQuery input source.
GoogleCloudRetailV2BigQuerySource? bigQuerySource;
/// Google Cloud Storage location for the input content.
GoogleCloudRetailV2GcsSource? gcsSource;
/// The Inline source for the input content for products.
GoogleCloudRetailV2ProductInlineSource? productInlineSource;
GoogleCloudRetailV2ProductInputConfig({
this.bigQuerySource,
this.gcsSource,
this.productInlineSource,
});
GoogleCloudRetailV2ProductInputConfig.fromJson(core.Map _json)
: this(
bigQuerySource: _json.containsKey('bigQuerySource')
? GoogleCloudRetailV2BigQuerySource.fromJson(
_json['bigQuerySource']
as core.Map<core.String, core.dynamic>)
: null,
gcsSource: _json.containsKey('gcsSource')
? GoogleCloudRetailV2GcsSource.fromJson(
_json['gcsSource'] as core.Map<core.String, core.dynamic>)
: null,
productInlineSource: _json.containsKey('productInlineSource')
? GoogleCloudRetailV2ProductInlineSource.fromJson(
_json['productInlineSource']
as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (bigQuerySource != null) 'bigQuerySource': bigQuerySource!,
if (gcsSource != null) 'gcsSource': gcsSource!,
if (productInlineSource != null)
'productInlineSource': productInlineSource!,
};
}
/// Configures what level the product should be uploaded with regards to how
/// users will be send events and how predictions will be made.
class GoogleCloudRetailV2ProductLevelConfig {
/// The type of Products allowed to be ingested into the catalog.
///
/// Acceptable values are: * `primary` (default): You can ingest Products of
/// all types. When ingesting a Product, its type will default to
/// Product.Type.PRIMARY if unset. * `variant`: You can only ingest
/// Product.Type.VARIANT Products. This means Product.primary_product_id
/// cannot be empty. If this field is set to an invalid value other than
/// these, an INVALID_ARGUMENT error is returned. If this field is `variant`
/// and merchant_center_product_id_field is `itemGroupId`, an INVALID_ARGUMENT
/// error is returned. See
/// [Using product levels](https://cloud.google.com/retail/recommendations-ai/docs/catalog#product-levels)
/// for more details.
core.String? ingestionProductType;
/// Which field of \[Merchant Center
/// Product\](/bigquery-transfer/docs/merchant-center-products-schema) should
/// be imported as Product.id.
///
/// Acceptable values are: * `offerId` (default): Import `offerId` as the
/// product ID. * `itemGroupId`: Import `itemGroupId` as the product ID.
/// Notice that Retail API will choose one item from the ones with the same
/// `itemGroupId`, and use it to represent the item group. If this field is
/// set to an invalid value other than these, an INVALID_ARGUMENT error is
/// returned. If this field is `itemGroupId` and ingestion_product_type is
/// `variant`, an INVALID_ARGUMENT error is returned. See
/// [Using product levels](https://cloud.google.com/retail/recommendations-ai/docs/catalog#product-levels)
/// for more details.
core.String? merchantCenterProductIdField;
GoogleCloudRetailV2ProductLevelConfig({
this.ingestionProductType,
this.merchantCenterProductIdField,
});
GoogleCloudRetailV2ProductLevelConfig.fromJson(core.Map _json)
: this(
ingestionProductType: _json.containsKey('ingestionProductType')
? _json['ingestionProductType'] as core.String
: null,
merchantCenterProductIdField:
_json.containsKey('merchantCenterProductIdField')
? _json['merchantCenterProductIdField'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (ingestionProductType != null)
'ingestionProductType': ingestionProductType!,
if (merchantCenterProductIdField != null)
'merchantCenterProductIdField': merchantCenterProductIdField!,
};
}
/// Promotion information.
class GoogleCloudRetailV2Promotion {
/// ID of the promotion.
///
/// For example, "free gift". The value must be a UTF-8 encoded string with a
/// length limit of 128 characters, and match the pattern: `a-zA-Z*`. For
/// example, id0LikeThis or ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT
/// error is returned. Google Merchant Center property
/// [promotion](https://support.google.com/merchants/answer/7050148).
core.String? promotionId;
GoogleCloudRetailV2Promotion({
this.promotionId,
});
GoogleCloudRetailV2Promotion.fromJson(core.Map _json)
: this(
promotionId: _json.containsKey('promotionId')
? _json['promotionId'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (promotionId != null) 'promotionId': promotionId!,
};
}
/// A transaction represents the entire purchase transaction.
class GoogleCloudRetailV2PurchaseTransaction {
/// All the costs associated with the products.
///
/// These can be manufacturing costs, shipping expenses not borne by the end
/// user, or any other costs, such that: * Profit = revenue - tax - cost
core.double? cost;
/// Currency code.
///
/// Use three-character ISO-4217 code.
///
/// Required.
core.String? currencyCode;
/// The transaction ID with a length limit of 128 characters.
core.String? id;
/// Total non-zero revenue or grand total associated with the transaction.
///
/// This value include shipping, tax, or other adjustments to total revenue
/// that you want to include as part of your revenue calculations.
///
/// Required.
core.double? revenue;
/// All the taxes associated with the transaction.
core.double? tax;
GoogleCloudRetailV2PurchaseTransaction({
this.cost,
this.currencyCode,
this.id,
this.revenue,
this.tax,
});
GoogleCloudRetailV2PurchaseTransaction.fromJson(core.Map _json)
: this(
cost: _json.containsKey('cost')
? (_json['cost'] as core.num).toDouble()
: null,
currencyCode: _json.containsKey('currencyCode')
? _json['currencyCode'] as core.String
: null,
id: _json.containsKey('id') ? _json['id'] as core.String : null,
revenue: _json.containsKey('revenue')
? (_json['revenue'] as core.num).toDouble()
: null,
tax: _json.containsKey('tax')
? (_json['tax'] as core.num).toDouble()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (cost != null) 'cost': cost!,
if (currencyCode != null) 'currencyCode': currencyCode!,
if (id != null) 'id': id!,
if (revenue != null) 'revenue': revenue!,
if (tax != null) 'tax': tax!,
};
}
/// Request message for PurgeUserEvents method.
class GoogleCloudRetailV2PurgeUserEventsRequest {
/// The filter string to specify the events to be deleted with a length limit
/// of 5,000 characters.
///
/// Empty string filter is not allowed. The eligible fields for filtering are:
/// * `eventType`: Double quoted UserEvent.event_type string. * `eventTime`:
/// in ISO 8601 "zulu" format. * `visitorId`: Double quoted string. Specifying
/// this will delete all events associated with a visitor. * `userId`: Double
/// quoted string. Specifying this will delete all events associated with a
/// user. Examples: * Deleting all events in a time range: `eventTime >
/// "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"` *
/// Deleting specific eventType in time range: `eventTime >
/// "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` * Deleting all
/// events for a specific visitor: `visitorId = "visitor1024"` The filtering
/// fields are assumed to have an implicit AND.
///
/// Required.
core.String? filter;
/// Actually perform the purge.
///
/// If `force` is set to false, the method will return the expected purge
/// count without deleting any user events.
core.bool? force;
GoogleCloudRetailV2PurgeUserEventsRequest({
this.filter,
this.force,
});
GoogleCloudRetailV2PurgeUserEventsRequest.fromJson(core.Map _json)
: this(
filter: _json.containsKey('filter')
? _json['filter'] as core.String
: null,
force:
_json.containsKey('force') ? _json['force'] as core.bool : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (filter != null) 'filter': filter!,
if (force != null) 'force': force!,
};
}
/// The rating of a Product.
class GoogleCloudRetailV2Rating {
/// The average rating of the Product.
///
/// The rating is scaled at 1-5. Otherwise, an INVALID_ARGUMENT error is
/// returned.
core.double? averageRating;
/// The total number of ratings.
///
/// This value is independent of the value of rating_histogram. This value
/// must be nonnegative. Otherwise, an INVALID_ARGUMENT error is returned.
core.int? ratingCount;
/// List of rating counts per rating value (index = rating - 1).
///
/// The list is empty if there is no rating. If the list is non-empty, its
/// size is always 5. Otherwise, an INVALID_ARGUMENT error is returned. For
/// example, \[41, 14, 13, 47, 303\]. It means that the Product got 41 ratings
/// with 1 star, 14 ratings with 2 star, and so on.
core.List<core.int>? ratingHistogram;
GoogleCloudRetailV2Rating({
this.averageRating,
this.ratingCount,
this.ratingHistogram,
});
GoogleCloudRetailV2Rating.fromJson(core.Map _json)
: this(
averageRating: _json.containsKey('averageRating')
? (_json['averageRating'] as core.num).toDouble()
: null,
ratingCount: _json.containsKey('ratingCount')
? _json['ratingCount'] as core.int
: null,
ratingHistogram: _json.containsKey('ratingHistogram')
? (_json['ratingHistogram'] as core.List)
.map((value) => value as core.int)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (averageRating != null) 'averageRating': averageRating!,
if (ratingCount != null) 'ratingCount': ratingCount!,
if (ratingHistogram != null) 'ratingHistogram': ratingHistogram!,
};
}
/// Request message for RejoinUserEvents method.
class GoogleCloudRetailV2RejoinUserEventsRequest {
/// The type of the user event rejoin to define the scope and range of the
/// user events to be rejoined with the latest product catalog.
///
/// Defaults to USER_EVENT_REJOIN_SCOPE_UNSPECIFIED if this field is not set,
/// or set to an invalid integer value.
/// Possible string values are:
/// - "USER_EVENT_REJOIN_SCOPE_UNSPECIFIED" : Rejoin all events with the
/// latest product catalog, including both joined events and unjoined events.
/// - "JOINED_EVENTS" : Only rejoin joined events with the latest product
/// catalog.
/// - "UNJOINED_EVENTS" : Only rejoin unjoined events with the latest product
/// catalog.
core.String? userEventRejoinScope;
GoogleCloudRetailV2RejoinUserEventsRequest({
this.userEventRejoinScope,
});
GoogleCloudRetailV2RejoinUserEventsRequest.fromJson(core.Map _json)
: this(
userEventRejoinScope: _json.containsKey('userEventRejoinScope')
? _json['userEventRejoinScope'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (userEventRejoinScope != null)
'userEventRejoinScope': userEventRejoinScope!,
};
}
/// Request message for RemoveFulfillmentPlaces method.
class GoogleCloudRetailV2RemoveFulfillmentPlacesRequest {
/// If set to true, and the Product is not found, the fulfillment information
/// will still be processed and retained for at most 1 day and processed once
/// the Product is created.
///
/// If set to false, a NOT_FOUND error is returned if the Product is not
/// found.
core.bool? allowMissing;
/// The IDs for this type, such as the store IDs for "pickup-in-store" or the
/// region IDs for "same-day-delivery", to be removed for this type.
///
/// At least 1 value is required, and a maximum of 2000 values are allowed.
/// Each value must be a string with a length limit of 10 characters, matching
/// the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise,
/// an INVALID_ARGUMENT error is returned.
///
/// Required.
core.List<core.String>? placeIds;
/// The time when the fulfillment updates are issued, used to prevent
/// out-of-order updates on fulfillment information.
///
/// If not provided, the internal system time will be used.
core.String? removeTime;
/// The fulfillment type, including commonly used types (such as pickup in
/// store and same day delivery), and custom types.
///
/// Supported values: * "pickup-in-store" * "ship-to-store" *
/// "same-day-delivery" * "next-day-delivery" * "custom-type-1" *
/// "custom-type-2" * "custom-type-3" * "custom-type-4" * "custom-type-5" If
/// this field is set to an invalid value other than these, an
/// INVALID_ARGUMENT error is returned. This field directly corresponds to
/// Product.fulfillment_info.type.
///
/// Required.
core.String? type;
GoogleCloudRetailV2RemoveFulfillmentPlacesRequest({
this.allowMissing,
this.placeIds,
this.removeTime,
this.type,
});
GoogleCloudRetailV2RemoveFulfillmentPlacesRequest.fromJson(core.Map _json)
: this(
allowMissing: _json.containsKey('allowMissing')
? _json['allowMissing'] as core.bool
: null,
placeIds: _json.containsKey('placeIds')
? (_json['placeIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
removeTime: _json.containsKey('removeTime')
? _json['removeTime'] as core.String
: null,
type: _json.containsKey('type') ? _json['type'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (allowMissing != null) 'allowMissing': allowMissing!,
if (placeIds != null) 'placeIds': placeIds!,
if (removeTime != null) 'removeTime': removeTime!,
if (type != null) 'type': type!,
};
}
/// Request message for SearchService.Search method.
class GoogleCloudRetailV2SearchRequest {
/// Boost specification to boost certain products.
///
/// See more details at this
/// [user guide](https://cloud.google.com/retail/docs/boosting). Notice that
/// if both ServingConfig.boost_control_ids and \[SearchRequest.boost_spec\]
/// are set, the boost conditions from both places are evaluated. If a search
/// request matches multiple boost conditions, the final boost score is equal
/// to the sum of the boost scores from all matched boost conditions.
GoogleCloudRetailV2SearchRequestBoostSpec? boostSpec;
/// The branch resource name, such as `projects / *
/// /locations/global/catalogs/default_catalog/branches/0`.
///
/// Use "default_branch" as the branch ID or leave this field empty, to search
/// products under the default branch.
core.String? branch;
/// The filter applied to every search request when quality improvement such
/// as query expansion is needed.
///
/// For example, if a query does not have enough results, an expanded query
/// with SearchRequest.canonical_filter will be returned as a supplement of
/// the original query. This field is strongly recommended to achieve high
/// search quality. See SearchRequest.filter for more details about filter
/// syntax.
core.String? canonicalFilter;
/// The specification for dynamically generated facets.
///
/// Notice that only textual facets can be dynamically generated. This feature
/// requires additional allowlisting. Contact Retail Search support team if
/// you are interested in using dynamic facet feature.
GoogleCloudRetailV2SearchRequestDynamicFacetSpec? dynamicFacetSpec;
/// Facet specifications for faceted search.
///
/// If empty, no facets are returned. A maximum of 100 values are allowed.
/// Otherwise, an INVALID_ARGUMENT error is returned.
core.List<GoogleCloudRetailV2SearchRequestFacetSpec>? facetSpecs;
/// The filter syntax consists of an expression language for constructing a
/// predicate from one or more fields of the products being filtered.
///
/// Filter expression is case-sensitive. See more details at this
/// [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter).
/// If this field is unrecognizable, an INVALID_ARGUMENT is returned.
core.String? filter;
/// A 0-indexed integer that specifies the current offset (that is, starting
/// result location, amongst the Products deemed by the API as relevant) in
/// search results.
///
/// This field is only considered if page_token is unset. If this field is
/// negative, an INVALID_ARGUMENT is returned.
core.int? offset;
/// The order in which products are returned.
///
/// Products can be ordered by a field in an Product object. Leave it unset if
/// ordered by relevance. OrderBy expression is case-sensitive. See more
/// details at this
/// [user guide](https://cloud.google.com/retail/docs/filter-and-order#order).
/// If this field is unrecognizable, an INVALID_ARGUMENT is returned.
core.String? orderBy;
/// The categories associated with a category page.
///
/// Required for category navigation queries to achieve good search quality.
/// The format should be the same as UserEvent.page_categories; To represent
/// full path of category, use '\>' sign to separate different hierarchies. If
/// '\>' is part of the category name, please replace it with other
/// character(s). Category pages include special pages such as sales or
/// promotions. For instance, a special sale page may have the category
/// hierarchy: "pageCategories" : \["Sales \> 2017 Black Friday Deals"\].
core.List<core.String>? pageCategories;
/// Maximum number of Products to return.
///
/// If unspecified, defaults to a reasonable value. The maximum allowed value
/// is 120. Values above 120 will be coerced to 120. If this field is
/// negative, an INVALID_ARGUMENT is returned.
core.int? pageSize;
/// A page token SearchResponse.next_page_token, received from a previous
/// SearchService.Search call.
///
/// Provide this to retrieve the subsequent page. When paginating, all other
/// parameters provided to SearchService.Search must match the call that
/// provided the page token. Otherwise, an INVALID_ARGUMENT error is returned.
core.String? pageToken;
/// The specification for personalization.
GoogleCloudRetailV2SearchRequestPersonalizationSpec? personalizationSpec;
/// Raw search query.
core.String? query;
/// The query expansion specification that specifies the conditions under
/// which query expansion will occur.
///
/// See more details at this
/// [user guide](https://cloud.google.com/retail/docs/result-size#query_expansion).
GoogleCloudRetailV2SearchRequestQueryExpansionSpec? queryExpansionSpec;
/// The search mode of the search request.
///
/// If not specified, a single search request triggers both product search and
/// faceted search.
/// Possible string values are:
/// - "SEARCH_MODE_UNSPECIFIED" : Default value. In this case both product
/// search and faceted search will be performed. Both
/// \[SearchResponse.SearchResult\] and \[SearchResponse.Facet\] will be
/// returned.
/// - "PRODUCT_SEARCH_ONLY" : Only product search will be performed. The
/// faceted search will be disabled. Only \[SearchResponse.SearchResult\] will
/// be returned. \[SearchResponse.Facet\] will not be returned, even if
/// SearchRequest.facet_specs or SearchRequest.dynamic_facet_spec is set.
/// - "FACETED_SEARCH_ONLY" : Only faceted search will be performed. The
/// product search will be disabled. When in this mode, one or both of
/// SearchRequest.facet_spec and SearchRequest.dynamic_facet_spec should be
/// set. Otherwise, an INVALID_ARGUMENT error is returned. Only
/// \[SearchResponse.Facet\] will be returned. \[SearchResponse.SearchResult\]
/// will not be returned.
core.String? searchMode;
/// User information.
GoogleCloudRetailV2UserInfo? userInfo;
/// The keys to fetch and rollup the matching variant Products attributes,
/// FulfillmentInfo or LocalInventorys attributes.
///
/// The attributes from all the matching variant Products or LocalInventorys
/// are merged and de-duplicated. Notice that rollup attributes will lead to
/// extra query latency. Maximum number of keys is 30. For FulfillmentInfo, a
/// fulfillment type and a fulfillment ID must be provided in the format of
/// "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123",
/// "pickupInStore" is fulfillment type and "store123" is the store ID.
/// Supported keys are: * colorFamilies * price * originalPrice * discount *
/// variantId * inventory(place_id,price) * inventory(place_id,original_price)
/// * inventory(place_id,attributes.key), where key is any key in the
/// Product.inventories.attributes map. * attributes.key, where key is any key
/// in the Product.attributes map. * pickupInStore.id, where id is any
/// FulfillmentInfo.place_ids for FulfillmentInfo.type "pickup-in-store". *
/// shipToStore.id, where id is any FulfillmentInfo.place_ids for
/// FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where id is
/// any FulfillmentInfo.place_ids for FulfillmentInfo.type
/// "same-day-delivery". * nextDayDelivery.id, where id is any
/// FulfillmentInfo.place_ids for FulfillmentInfo.type "next-day-delivery". *
/// customFulfillment1.id, where id is any FulfillmentInfo.place_ids for
/// FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is
/// any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". *
/// customFulfillment3.id, where id is any FulfillmentInfo.place_ids for
/// FulfillmentInfo.type "custom-type-3". * customFulfillment4.id, where id is
/// any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-4". *
/// customFulfillment5.id, where id is any FulfillmentInfo.place_ids for
/// FulfillmentInfo.type "custom-type-5". If this field is set to an invalid
/// value other than these, an INVALID_ARGUMENT error is returned.
core.List<core.String>? variantRollupKeys;
/// A unique identifier for tracking visitors.
///
/// For example, this could be implemented with an HTTP cookie, which should
/// be able to uniquely identify a visitor on a single device. This unique
/// identifier should not change if the visitor logs in or out of the website.
/// This should be the same identifier as UserEvent.visitor_id. The field must
/// be a UTF-8 encoded string with a length limit of 128 characters.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Required.
core.String? visitorId;
GoogleCloudRetailV2SearchRequest({
this.boostSpec,
this.branch,
this.canonicalFilter,
this.dynamicFacetSpec,
this.facetSpecs,
this.filter,
this.offset,
this.orderBy,
this.pageCategories,
this.pageSize,
this.pageToken,
this.personalizationSpec,
this.query,
this.queryExpansionSpec,
this.searchMode,
this.userInfo,
this.variantRollupKeys,
this.visitorId,
});
GoogleCloudRetailV2SearchRequest.fromJson(core.Map _json)
: this(
boostSpec: _json.containsKey('boostSpec')
? GoogleCloudRetailV2SearchRequestBoostSpec.fromJson(
_json['boostSpec'] as core.Map<core.String, core.dynamic>)
: null,
branch: _json.containsKey('branch')
? _json['branch'] as core.String
: null,
canonicalFilter: _json.containsKey('canonicalFilter')
? _json['canonicalFilter'] as core.String
: null,
dynamicFacetSpec: _json.containsKey('dynamicFacetSpec')
? GoogleCloudRetailV2SearchRequestDynamicFacetSpec.fromJson(
_json['dynamicFacetSpec']
as core.Map<core.String, core.dynamic>)
: null,
facetSpecs: _json.containsKey('facetSpecs')
? (_json['facetSpecs'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchRequestFacetSpec.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
filter: _json.containsKey('filter')
? _json['filter'] as core.String
: null,
offset:
_json.containsKey('offset') ? _json['offset'] as core.int : null,
orderBy: _json.containsKey('orderBy')
? _json['orderBy'] as core.String
: null,
pageCategories: _json.containsKey('pageCategories')
? (_json['pageCategories'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
pageSize: _json.containsKey('pageSize')
? _json['pageSize'] as core.int
: null,
pageToken: _json.containsKey('pageToken')
? _json['pageToken'] as core.String
: null,
personalizationSpec: _json.containsKey('personalizationSpec')
? GoogleCloudRetailV2SearchRequestPersonalizationSpec.fromJson(
_json['personalizationSpec']
as core.Map<core.String, core.dynamic>)
: null,
query:
_json.containsKey('query') ? _json['query'] as core.String : null,
queryExpansionSpec: _json.containsKey('queryExpansionSpec')
? GoogleCloudRetailV2SearchRequestQueryExpansionSpec.fromJson(
_json['queryExpansionSpec']
as core.Map<core.String, core.dynamic>)
: null,
searchMode: _json.containsKey('searchMode')
? _json['searchMode'] as core.String
: null,
userInfo: _json.containsKey('userInfo')
? GoogleCloudRetailV2UserInfo.fromJson(
_json['userInfo'] as core.Map<core.String, core.dynamic>)
: null,
variantRollupKeys: _json.containsKey('variantRollupKeys')
? (_json['variantRollupKeys'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
visitorId: _json.containsKey('visitorId')
? _json['visitorId'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (boostSpec != null) 'boostSpec': boostSpec!,
if (branch != null) 'branch': branch!,
if (canonicalFilter != null) 'canonicalFilter': canonicalFilter!,
if (dynamicFacetSpec != null) 'dynamicFacetSpec': dynamicFacetSpec!,
if (facetSpecs != null) 'facetSpecs': facetSpecs!,
if (filter != null) 'filter': filter!,
if (offset != null) 'offset': offset!,
if (orderBy != null) 'orderBy': orderBy!,
if (pageCategories != null) 'pageCategories': pageCategories!,
if (pageSize != null) 'pageSize': pageSize!,
if (pageToken != null) 'pageToken': pageToken!,
if (personalizationSpec != null)
'personalizationSpec': personalizationSpec!,
if (query != null) 'query': query!,
if (queryExpansionSpec != null)
'queryExpansionSpec': queryExpansionSpec!,
if (searchMode != null) 'searchMode': searchMode!,
if (userInfo != null) 'userInfo': userInfo!,
if (variantRollupKeys != null) 'variantRollupKeys': variantRollupKeys!,
if (visitorId != null) 'visitorId': visitorId!,
};
}
/// Boost specification to boost certain items.
class GoogleCloudRetailV2SearchRequestBoostSpec {
/// Condition boost specifications.
///
/// If a product matches multiple conditions in the specifictions, boost
/// scores from these specifications are all applied and combined in a
/// non-linear way. Maximum number of specifications is 10.
core.List<GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec>?
conditionBoostSpecs;
/// Whether to skip boostspec validation.
///
/// If this field is set to true, invalid BoostSpec.condition_boost_specs will
/// be ignored and valid BoostSpec.condition_boost_specs will still be
/// applied.
core.bool? skipBoostSpecValidation;
GoogleCloudRetailV2SearchRequestBoostSpec({
this.conditionBoostSpecs,
this.skipBoostSpecValidation,
});
GoogleCloudRetailV2SearchRequestBoostSpec.fromJson(core.Map _json)
: this(
conditionBoostSpecs: _json.containsKey('conditionBoostSpecs')
? (_json['conditionBoostSpecs'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec
.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
skipBoostSpecValidation: _json.containsKey('skipBoostSpecValidation')
? _json['skipBoostSpecValidation'] as core.bool
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (conditionBoostSpecs != null)
'conditionBoostSpecs': conditionBoostSpecs!,
if (skipBoostSpecValidation != null)
'skipBoostSpecValidation': skipBoostSpecValidation!,
};
}
/// Boost applies to products which match a condition.
class GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec {
/// Strength of the condition boost, which should be in \[-1, 1\].
///
/// Negative boost means demotion. Default is 0.0. Setting to 1.0 gives the
/// item a big promotion. However, it does not necessarily mean that the
/// boosted item will be the top result at all times, nor that other items
/// will be excluded. Results could still be shown even when none of them
/// matches the condition. And results that are significantly more relevant to
/// the search query can still trump your heavily favored but irrelevant
/// items. Setting to -1.0 gives the item a big demotion. However, results
/// that are deeply relevant might still be shown. The item will have an
/// upstream battle to get a fairly high ranking, but it is not blocked out
/// completely. Setting to 0.0 means no boost applied. The boosting condition
/// is ignored.
core.double? boost;
/// An expression which specifies a boost condition.
///
/// The syntax and supported fields are the same as a filter expression. See
/// SearchRequest.filter for detail syntax and limitations. Examples: * To
/// boost products with product ID "product_1" or "product_2", and color "Red"
/// or "Blue": * (id: ANY("product_1", "product_2")) AND (colorFamilies:
/// ANY("Red","Blue"))
core.String? condition;
GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec({
this.boost,
this.condition,
});
GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec.fromJson(
core.Map _json)
: this(
boost: _json.containsKey('boost')
? (_json['boost'] as core.num).toDouble()
: null,
condition: _json.containsKey('condition')
? _json['condition'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (boost != null) 'boost': boost!,
if (condition != null) 'condition': condition!,
};
}
/// The specifications of dynamically generated facets.
class GoogleCloudRetailV2SearchRequestDynamicFacetSpec {
/// Mode of the DynamicFacet feature.
///
/// Defaults to Mode.DISABLED if it's unset.
/// Possible string values are:
/// - "MODE_UNSPECIFIED" : Default value.
/// - "DISABLED" : Disable Dynamic Facet.
/// - "ENABLED" : Automatic mode built by Google Retail Search.
core.String? mode;
GoogleCloudRetailV2SearchRequestDynamicFacetSpec({
this.mode,
});
GoogleCloudRetailV2SearchRequestDynamicFacetSpec.fromJson(core.Map _json)
: this(
mode: _json.containsKey('mode') ? _json['mode'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (mode != null) 'mode': mode!,
};
}
/// A facet specification to perform faceted search.
class GoogleCloudRetailV2SearchRequestFacetSpec {
/// Enables dynamic position for this facet.
///
/// If set to true, the position of this facet among all facets in the
/// response is determined by Google Retail Search. It will be ordered
/// together with dynamic facets if dynamic facets is enabled. If set to
/// false, the position of this facet in the response will be the same as in
/// the request, and it will be ranked before the facets with dynamic position
/// enable and all dynamic facets. For example, you may always want to have
/// rating facet returned in the response, but it's not necessarily to always
/// display the rating facet at the top. In that case, you can set
/// enable_dynamic_position to true so that the position of rating facet in
/// response will be determined by Google Retail Search. Another example,
/// assuming you have the following facets in the request: * "rating",
/// enable_dynamic_position = true * "price", enable_dynamic_position = false
/// * "brands", enable_dynamic_position = false And also you have a dynamic
/// facets enable, which will generate a facet 'gender'. Then the final order
/// of the facets in the response can be ("price", "brands", "rating",
/// "gender") or ("price", "brands", "gender", "rating") depends on how Google
/// Retail Search orders "gender" and "rating" facets. However, notice that
/// "price" and "brands" will always be ranked at 1st and 2nd position since
/// their enable_dynamic_position are false.
core.bool? enableDynamicPosition;
/// List of keys to exclude when faceting.
///
/// By default, FacetKey.key is not excluded from the filter unless it is
/// listed in this field. For example, suppose there are 100 products with
/// color facet "Red" and 200 products with color facet "Blue". A query
/// containing the filter "colorFamilies:ANY("Red")" and have "colorFamilies"
/// as FacetKey.key will by default return the "Red" with count 100. If this
/// field contains "colorFamilies", then the query returns both the "Red" with
/// count 100 and "Blue" with count 200, because the "colorFamilies" key is
/// now excluded from the filter. A maximum of 100 values are allowed.
/// Otherwise, an INVALID_ARGUMENT error is returned.
core.List<core.String>? excludedFilterKeys;
/// The facet key specification.
///
/// Required.
GoogleCloudRetailV2SearchRequestFacetSpecFacetKey? facetKey;
/// Maximum of facet values that should be returned for this facet.
///
/// If unspecified, defaults to 20. The maximum allowed value is 300. Values
/// above 300 will be coerced to 300. If this field is negative, an
/// INVALID_ARGUMENT is returned.
core.int? limit;
GoogleCloudRetailV2SearchRequestFacetSpec({
this.enableDynamicPosition,
this.excludedFilterKeys,
this.facetKey,
this.limit,
});
GoogleCloudRetailV2SearchRequestFacetSpec.fromJson(core.Map _json)
: this(
enableDynamicPosition: _json.containsKey('enableDynamicPosition')
? _json['enableDynamicPosition'] as core.bool
: null,
excludedFilterKeys: _json.containsKey('excludedFilterKeys')
? (_json['excludedFilterKeys'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
facetKey: _json.containsKey('facetKey')
? GoogleCloudRetailV2SearchRequestFacetSpecFacetKey.fromJson(
_json['facetKey'] as core.Map<core.String, core.dynamic>)
: null,
limit: _json.containsKey('limit') ? _json['limit'] as core.int : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (enableDynamicPosition != null)
'enableDynamicPosition': enableDynamicPosition!,
if (excludedFilterKeys != null)
'excludedFilterKeys': excludedFilterKeys!,
if (facetKey != null) 'facetKey': facetKey!,
if (limit != null) 'limit': limit!,
};
}
/// Specifies how a facet is computed.
class GoogleCloudRetailV2SearchRequestFacetSpecFacetKey {
/// Only get facet values that contains the given strings.
///
/// For example, suppose "categories" has three values "Women \> Shoe", "Women
/// \> Dress" and "Men \> Shoe". If set "contains" to "Shoe", the "categories"
/// facet will give only "Women \> Shoe" and "Men \> Shoe". Only supported on
/// textual fields. Maximum is 10.
core.List<core.String>? contains;
/// Set only if values should be bucketized into intervals.
///
/// Must be set for facets with numerical values. Must not be set for facet
/// with text values. Maximum number of intervals is 30.
core.List<GoogleCloudRetailV2Interval>? intervals;
/// Supported textual and numerical facet keys in Product object, over which
/// the facet values are computed.
///
/// Facet key is case-sensitive. Allowed facet keys when FacetKey.query is not
/// specified: * textual_field = * "brands" * "categories" * "genders" *
/// "ageGroups" * "availability" * "colorFamilies" * "colors" * "sizes" *
/// "materials" * "patterns" * "conditions" * "attributes.key" *
/// "pickupInStore" * "shipToStore" * "sameDayDelivery" * "nextDayDelivery" *
/// "customFulfillment1" * "customFulfillment2" * "customFulfillment3" *
/// "customFulfillment4" * "customFulfillment5" *
/// "inventory(place_id,attributes.key)" * numerical_field = * "price" *
/// "discount" * "rating" * "ratingCount" * "attributes.key" *
/// "inventory(place_id,price)" * "inventory(place_id,original_price)" *
/// "inventory(place_id,attributes.key)"
///
/// Required.
core.String? key;
/// The order in which Facet.values are returned.
///
/// Allowed values are: * "count desc", which means order by
/// Facet.FacetValue.count descending. * "value desc", which means order by
/// Facet.FacetValue.value descending. Only applies to textual facets. If not
/// set, textual values are sorted in
/// [natural order](https://en.wikipedia.org/wiki/Natural_sort_order);
/// numerical intervals are sorted in the order given by
/// FacetSpec.FacetKey.intervals; FulfillmentInfo.place_ids are sorted in the
/// order given by FacetSpec.FacetKey.restricted_values.
core.String? orderBy;
/// Only get facet values that start with the given string prefix.
///
/// For example, suppose "categories" has three values "Women \> Shoe", "Women
/// \> Dress" and "Men \> Shoe". If set "prefixes" to "Women", the
/// "categories" facet will give only "Women \> Shoe" and "Women \> Dress".
/// Only supported on textual fields. Maximum is 10.
core.List<core.String>? prefixes;
/// The query that is used to compute facet for the given facet key.
///
/// When provided, it will override the default behavior of facet computation.
/// The query syntax is the same as a filter expression. See
/// SearchRequest.filter for detail syntax and limitations. Notice that there
/// is no limitation on FacetKey.key when query is specified. In the response,
/// FacetValue.value will be always "1" and FacetValue.count will be the
/// number of results that matches the query. For example, you can set a
/// customized facet for "shipToStore", where FacetKey.key is
/// "customizedShipToStore", and FacetKey.query is "availability:
/// ANY(\"IN_STOCK\") AND shipToStore: ANY(\"123\")". Then the facet will
/// count the products that are both in stock and ship to store "123".
core.String? query;
/// Only get facet for the given restricted values.
///
/// For example, when using "pickupInStore" as key and set restricted values
/// to \["store123", "store456"\], only facets for "store123" and "store456"
/// are returned. Only supported on textual fields and fulfillments. Maximum
/// is 20. Must be set for the fulfillment facet keys: * pickupInStore *
/// shipToStore * sameDayDelivery * nextDayDelivery * customFulfillment1 *
/// customFulfillment2 * customFulfillment3 * customFulfillment4 *
/// customFulfillment5
core.List<core.String>? restrictedValues;
GoogleCloudRetailV2SearchRequestFacetSpecFacetKey({
this.contains,
this.intervals,
this.key,
this.orderBy,
this.prefixes,
this.query,
this.restrictedValues,
});
GoogleCloudRetailV2SearchRequestFacetSpecFacetKey.fromJson(core.Map _json)
: this(
contains: _json.containsKey('contains')
? (_json['contains'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
intervals: _json.containsKey('intervals')
? (_json['intervals'] as core.List)
.map((value) => GoogleCloudRetailV2Interval.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
key: _json.containsKey('key') ? _json['key'] as core.String : null,
orderBy: _json.containsKey('orderBy')
? _json['orderBy'] as core.String
: null,
prefixes: _json.containsKey('prefixes')
? (_json['prefixes'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
query:
_json.containsKey('query') ? _json['query'] as core.String : null,
restrictedValues: _json.containsKey('restrictedValues')
? (_json['restrictedValues'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (contains != null) 'contains': contains!,
if (intervals != null) 'intervals': intervals!,
if (key != null) 'key': key!,
if (orderBy != null) 'orderBy': orderBy!,
if (prefixes != null) 'prefixes': prefixes!,
if (query != null) 'query': query!,
if (restrictedValues != null) 'restrictedValues': restrictedValues!,
};
}
/// The specification for personalization.
class GoogleCloudRetailV2SearchRequestPersonalizationSpec {
/// Defaults to Mode.AUTO.
/// Possible string values are:
/// - "MODE_UNSPECIFIED" : Default value. Defaults to Mode.AUTO.
/// - "AUTO" : Let CRS decide whether to use personalization.
/// - "DISABLED" : Disable personalization.
core.String? mode;
GoogleCloudRetailV2SearchRequestPersonalizationSpec({
this.mode,
});
GoogleCloudRetailV2SearchRequestPersonalizationSpec.fromJson(core.Map _json)
: this(
mode: _json.containsKey('mode') ? _json['mode'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (mode != null) 'mode': mode!,
};
}
/// Specification to determine under which conditions query expansion should
/// occur.
class GoogleCloudRetailV2SearchRequestQueryExpansionSpec {
/// The condition under which query expansion should occur.
///
/// Default to Condition.DISABLED.
/// Possible string values are:
/// - "CONDITION_UNSPECIFIED" : Unspecified query expansion condition. This
/// defaults to Condition.DISABLED.
/// - "DISABLED" : Disabled query expansion. Only the exact search query is
/// used, even if SearchResponse.total_size is zero.
/// - "AUTO" : Automatic query expansion built by Google Retail Search.
core.String? condition;
/// Whether to pin unexpanded results.
///
/// If this field is set to true, unexpanded products are always at the top of
/// the search results, followed by the expanded results.
core.bool? pinUnexpandedResults;
GoogleCloudRetailV2SearchRequestQueryExpansionSpec({
this.condition,
this.pinUnexpandedResults,
});
GoogleCloudRetailV2SearchRequestQueryExpansionSpec.fromJson(core.Map _json)
: this(
condition: _json.containsKey('condition')
? _json['condition'] as core.String
: null,
pinUnexpandedResults: _json.containsKey('pinUnexpandedResults')
? _json['pinUnexpandedResults'] as core.bool
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (condition != null) 'condition': condition!,
if (pinUnexpandedResults != null)
'pinUnexpandedResults': pinUnexpandedResults!,
};
}
/// Response message for SearchService.Search method.
class GoogleCloudRetailV2SearchResponse {
/// The fully qualified resource name of applied
/// [controls](https://cloud.google.com/retail/docs/serving-control-rules).
core.List<core.String>? appliedControls;
/// A unique search token.
///
/// This should be included in the UserEvent logs resulting from this search,
/// which enables accurate attribution of search model performance.
core.String? attributionToken;
/// If spell correction applies, the corrected query.
///
/// Otherwise, empty.
core.String? correctedQuery;
/// Results of facets requested by user.
core.List<GoogleCloudRetailV2SearchResponseFacet>? facets;
/// The invalid SearchRequest.BoostSpec.condition_boost_specs that are not
/// applied during serving.
core.List<GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec>?
invalidConditionBoostSpecs;
/// A token that can be sent as SearchRequest.page_token to retrieve the next
/// page.
///
/// If this field is omitted, there are no subsequent pages.
core.String? nextPageToken;
/// Query expansion information for the returned results.
GoogleCloudRetailV2SearchResponseQueryExpansionInfo? queryExpansionInfo;
/// The URI of a customer-defined redirect page.
///
/// If redirect action is triggered, no search will be performed, and only
/// redirect_uri and attribution_token will be set in the response.
core.String? redirectUri;
/// A list of matched items.
///
/// The order represents the ranking.
core.List<GoogleCloudRetailV2SearchResponseSearchResult>? results;
/// The estimated total count of matched items irrespective of pagination.
///
/// The count of results returned by pagination may be less than the
/// total_size that matches.
core.int? totalSize;
GoogleCloudRetailV2SearchResponse({
this.appliedControls,
this.attributionToken,
this.correctedQuery,
this.facets,
this.invalidConditionBoostSpecs,
this.nextPageToken,
this.queryExpansionInfo,
this.redirectUri,
this.results,
this.totalSize,
});
GoogleCloudRetailV2SearchResponse.fromJson(core.Map _json)
: this(
appliedControls: _json.containsKey('appliedControls')
? (_json['appliedControls'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
attributionToken: _json.containsKey('attributionToken')
? _json['attributionToken'] as core.String
: null,
correctedQuery: _json.containsKey('correctedQuery')
? _json['correctedQuery'] as core.String
: null,
facets: _json.containsKey('facets')
? (_json['facets'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchResponseFacet.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
invalidConditionBoostSpecs: _json
.containsKey('invalidConditionBoostSpecs')
? (_json['invalidConditionBoostSpecs'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec
.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
nextPageToken: _json.containsKey('nextPageToken')
? _json['nextPageToken'] as core.String
: null,
queryExpansionInfo: _json.containsKey('queryExpansionInfo')
? GoogleCloudRetailV2SearchResponseQueryExpansionInfo.fromJson(
_json['queryExpansionInfo']
as core.Map<core.String, core.dynamic>)
: null,
redirectUri: _json.containsKey('redirectUri')
? _json['redirectUri'] as core.String
: null,
results: _json.containsKey('results')
? (_json['results'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchResponseSearchResult.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
totalSize: _json.containsKey('totalSize')
? _json['totalSize'] as core.int
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (appliedControls != null) 'appliedControls': appliedControls!,
if (attributionToken != null) 'attributionToken': attributionToken!,
if (correctedQuery != null) 'correctedQuery': correctedQuery!,
if (facets != null) 'facets': facets!,
if (invalidConditionBoostSpecs != null)
'invalidConditionBoostSpecs': invalidConditionBoostSpecs!,
if (nextPageToken != null) 'nextPageToken': nextPageToken!,
if (queryExpansionInfo != null)
'queryExpansionInfo': queryExpansionInfo!,
if (redirectUri != null) 'redirectUri': redirectUri!,
if (results != null) 'results': results!,
if (totalSize != null) 'totalSize': totalSize!,
};
}
/// A facet result.
class GoogleCloudRetailV2SearchResponseFacet {
/// Whether the facet is dynamically generated.
core.bool? dynamicFacet;
/// The key for this facet.
///
/// E.g., "colorFamilies" or "price" or "attributes.attr1".
core.String? key;
/// The facet values for this field.
core.List<GoogleCloudRetailV2SearchResponseFacetFacetValue>? values;
GoogleCloudRetailV2SearchResponseFacet({
this.dynamicFacet,
this.key,
this.values,
});
GoogleCloudRetailV2SearchResponseFacet.fromJson(core.Map _json)
: this(
dynamicFacet: _json.containsKey('dynamicFacet')
? _json['dynamicFacet'] as core.bool
: null,
key: _json.containsKey('key') ? _json['key'] as core.String : null,
values: _json.containsKey('values')
? (_json['values'] as core.List)
.map((value) =>
GoogleCloudRetailV2SearchResponseFacetFacetValue.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (dynamicFacet != null) 'dynamicFacet': dynamicFacet!,
if (key != null) 'key': key!,
if (values != null) 'values': values!,
};
}
/// A facet value which contains value names and their count.
class GoogleCloudRetailV2SearchResponseFacetFacetValue {
/// Number of items that have this facet value.
core.String? count;
/// Interval value for a facet, such as \[10, 20) for facet "price".
GoogleCloudRetailV2Interval? interval;
/// Text value of a facet, such as "Black" for facet "colorFamilies".
core.String? value;
GoogleCloudRetailV2SearchResponseFacetFacetValue({
this.count,
this.interval,
this.value,
});
GoogleCloudRetailV2SearchResponseFacetFacetValue.fromJson(core.Map _json)
: this(
count:
_json.containsKey('count') ? _json['count'] as core.String : null,
interval: _json.containsKey('interval')
? GoogleCloudRetailV2Interval.fromJson(
_json['interval'] as core.Map<core.String, core.dynamic>)
: null,
value:
_json.containsKey('value') ? _json['value'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (count != null) 'count': count!,
if (interval != null) 'interval': interval!,
if (value != null) 'value': value!,
};
}
/// Information describing query expansion including whether expansion has
/// occurred.
class GoogleCloudRetailV2SearchResponseQueryExpansionInfo {
/// Bool describing whether query expansion has occurred.
core.bool? expandedQuery;
/// Number of pinned results.
///
/// This field will only be set when expansion happens and
/// SearchRequest.QueryExpansionSpec.pin_unexpanded_results is set to true.
core.String? pinnedResultCount;
GoogleCloudRetailV2SearchResponseQueryExpansionInfo({
this.expandedQuery,
this.pinnedResultCount,
});
GoogleCloudRetailV2SearchResponseQueryExpansionInfo.fromJson(core.Map _json)
: this(
expandedQuery: _json.containsKey('expandedQuery')
? _json['expandedQuery'] as core.bool
: null,
pinnedResultCount: _json.containsKey('pinnedResultCount')
? _json['pinnedResultCount'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (expandedQuery != null) 'expandedQuery': expandedQuery!,
if (pinnedResultCount != null) 'pinnedResultCount': pinnedResultCount!,
};
}
/// Represents the search results.
class GoogleCloudRetailV2SearchResponseSearchResult {
/// Product.id of the searched Product.
core.String? id;
/// The count of matched variant Products.
core.int? matchingVariantCount;
/// If a variant Product matches the search query, this map indicates which
/// Product fields are matched.
///
/// The key is the Product.name, the value is a field mask of the matched
/// Product fields. If matched attributes cannot be determined, this map will
/// be empty. For example, a key "sku1" with field mask "products.color_info"
/// indicates there is a match between "sku1" ColorInfo and the query.
core.Map<core.String, core.String>? matchingVariantFields;
/// The product data snippet in the search response.
///
/// Only Product.name is guaranteed to be populated. Product.variants contains
/// the product variants that match the search query. If there are multiple
/// product variants matching the query, top 5 most relevant product variants
/// are returned and ordered by relevancy. If relevancy can be deternmined,
/// use matching_variant_fields to look up matched product variants fields. If
/// relevancy cannot be determined, e.g. when searching "shoe" all products in
/// a shoe product can be a match, 5 product variants are returned but order
/// is meaningless.
GoogleCloudRetailV2Product? product;
/// The rollup matching variant Product attributes.
///
/// The key is one of the SearchRequest.variant_rollup_keys. The values are
/// the merged and de-duplicated Product attributes. Notice that the rollup
/// values are respect filter. For example, when filtering by
/// "colorFamilies:ANY(\"red\")" and rollup "colorFamilies", only "red" is
/// returned. For textual and numerical attributes, the rollup values is a
/// list of string or double values with type google.protobuf.ListValue. For
/// example, if there are two variants with colors "red" and "blue", the
/// rollup values are { key: "colorFamilies" value { list_value { values {
/// string_value: "red" } values { string_value: "blue" } } } } For
/// FulfillmentInfo, the rollup values is a double value with type
/// google.protobuf.Value. For example, `{key: "pickupInStore.store1" value {
/// number_value: 10 }}` means a there are 10 variants in this product are
/// available in the store "store1".
///
/// The values for Object must be JSON objects. It can consist of `num`,
/// `String`, `bool` and `null` as well as `Map` and `List` values.
core.Map<core.String, core.Object?>? variantRollupValues;
GoogleCloudRetailV2SearchResponseSearchResult({
this.id,
this.matchingVariantCount,
this.matchingVariantFields,
this.product,
this.variantRollupValues,
});
GoogleCloudRetailV2SearchResponseSearchResult.fromJson(core.Map _json)
: this(
id: _json.containsKey('id') ? _json['id'] as core.String : null,
matchingVariantCount: _json.containsKey('matchingVariantCount')
? _json['matchingVariantCount'] as core.int
: null,
matchingVariantFields: _json.containsKey('matchingVariantFields')
? (_json['matchingVariantFields']
as core.Map<core.String, core.dynamic>)
.map(
(key, item) => core.MapEntry(
key,
item as core.String,
),
)
: null,
product: _json.containsKey('product')
? GoogleCloudRetailV2Product.fromJson(
_json['product'] as core.Map<core.String, core.dynamic>)
: null,
variantRollupValues: _json.containsKey('variantRollupValues')
? _json['variantRollupValues']
as core.Map<core.String, core.dynamic>
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (id != null) 'id': id!,
if (matchingVariantCount != null)
'matchingVariantCount': matchingVariantCount!,
if (matchingVariantFields != null)
'matchingVariantFields': matchingVariantFields!,
if (product != null) 'product': product!,
if (variantRollupValues != null)
'variantRollupValues': variantRollupValues!,
};
}
/// Request message to set a specified branch as new default_branch.
class GoogleCloudRetailV2SetDefaultBranchRequest {
/// The final component of the resource name of a branch.
///
/// This field must be one of "0", "1" or "2". Otherwise, an INVALID_ARGUMENT
/// error is returned. If there are no sufficient active products in the
/// targeted branch and force is not set, a FAILED_PRECONDITION error is
/// returned.
core.String? branchId;
/// If set to true, it permits switching to a branch with branch_id even if it
/// has no sufficient active products.
core.bool? force;
/// Some note on this request, this can be retrieved by
/// CatalogService.GetDefaultBranch before next valid default branch set
/// occurs.
///
/// This field must be a UTF-8 encoded string with a length limit of 1,000
/// characters. Otherwise, an INVALID_ARGUMENT error is returned.
core.String? note;
GoogleCloudRetailV2SetDefaultBranchRequest({
this.branchId,
this.force,
this.note,
});
GoogleCloudRetailV2SetDefaultBranchRequest.fromJson(core.Map _json)
: this(
branchId: _json.containsKey('branchId')
? _json['branchId'] as core.String
: null,
force:
_json.containsKey('force') ? _json['force'] as core.bool : null,
note: _json.containsKey('note') ? _json['note'] as core.String : null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (branchId != null) 'branchId': branchId!,
if (force != null) 'force': force!,
if (note != null) 'note': note!,
};
}
/// Request message for SetInventory method.
class GoogleCloudRetailV2SetInventoryRequest {
/// If set to true, and the Product with name Product.name is not found, the
/// inventory update will still be processed and retained for at most 1 day
/// until the Product is created.
///
/// If set to false, a NOT_FOUND error is returned if the Product is not
/// found.
core.bool? allowMissing;
/// The inventory information to update.
///
/// The allowable fields to update are: * Product.price_info *
/// Product.availability * Product.available_quantity *
/// Product.fulfillment_info The updated inventory fields must be specified in
/// SetInventoryRequest.set_mask. If SetInventoryRequest.inventory.name is
/// empty or invalid, an INVALID_ARGUMENT error is returned. If the caller
/// does not have permission to update the Product named in Product.name,
/// regardless of whether or not it exists, a PERMISSION_DENIED error is
/// returned. If the Product to update does not have existing inventory
/// information, the provided inventory information will be inserted. If the
/// Product to update has existing inventory information, the provided
/// inventory information will be merged while respecting the last update time
/// for each inventory field, using the provided or default value for
/// SetInventoryRequest.set_time. The caller can replace place IDs for a
/// subset of fulfillment types in the following ways: * Adds
/// "fulfillment_info" in SetInventoryRequest.set_mask * Specifies only the
/// desired fulfillment types and corresponding place IDs to update in
/// SetInventoryRequest.inventory.fulfillment_info The caller can clear all
/// place IDs from a subset of fulfillment types in the following ways: * Adds
/// "fulfillment_info" in SetInventoryRequest.set_mask * Specifies only the
/// desired fulfillment types to clear in
/// SetInventoryRequest.inventory.fulfillment_info * Checks that only the
/// desired fulfillment info types have empty
/// SetInventoryRequest.inventory.fulfillment_info.place_ids The last update
/// time is recorded for the following inventory fields: * Product.price_info
/// * Product.availability * Product.available_quantity *
/// Product.fulfillment_info If a full overwrite of inventory information
/// while ignoring timestamps is needed, UpdateProduct should be invoked
/// instead.
///
/// Required.
GoogleCloudRetailV2Product? inventory;
/// Indicates which inventory fields in the provided Product to update.
///
/// At least one field must be provided. If an unsupported or unknown field is
/// provided, an INVALID_ARGUMENT error is returned and the entire update will
/// be ignored.
core.String? setMask;
/// The time when the request is issued, used to prevent out-of-order updates
/// on inventory fields with the last update time recorded.
///
/// If not provided, the internal system time will be used.
core.String? setTime;
GoogleCloudRetailV2SetInventoryRequest({
this.allowMissing,
this.inventory,
this.setMask,
this.setTime,
});
GoogleCloudRetailV2SetInventoryRequest.fromJson(core.Map _json)
: this(
allowMissing: _json.containsKey('allowMissing')
? _json['allowMissing'] as core.bool
: null,
inventory: _json.containsKey('inventory')
? GoogleCloudRetailV2Product.fromJson(
_json['inventory'] as core.Map<core.String, core.dynamic>)
: null,
setMask: _json.containsKey('setMask')
? _json['setMask'] as core.String
: null,
setTime: _json.containsKey('setTime')
? _json['setTime'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (allowMissing != null) 'allowMissing': allowMissing!,
if (inventory != null) 'inventory': inventory!,
if (setMask != null) 'setMask': setMask!,
if (setTime != null) 'setTime': setTime!,
};
}
/// UserEvent captures all metadata information Retail API needs to know about
/// how end users interact with customers' website.
class GoogleCloudRetailV2UserEvent {
/// Extra user event features to include in the recommendation model.
///
/// This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT
/// error is returned: * The key must be a UTF-8 encoded string with a length
/// limit of 5,000 characters. * For text attributes, at most 400 values are
/// allowed. Empty values are not allowed. Each value must be a UTF-8 encoded
/// string with a length limit of 256 characters. * For number attributes, at
/// most 400 values are allowed. For product recommendation, an example of
/// extra user information is traffic_channel, i.e. how user arrives at the
/// site. Users can arrive at the site by coming to the site directly, or
/// coming through Google search, and etc.
core.Map<core.String, GoogleCloudRetailV2CustomAttribute>? attributes;
/// Highly recommended for user events that are the result of
/// PredictionService.Predict.
///
/// This field enables accurate attribution of recommendation model
/// performance. The value must be a valid PredictResponse.attribution_token
/// for user events that are the result of PredictionService.Predict. The
/// value must be a valid SearchResponse.attribution_token for user events
/// that are the result of SearchService.Search. This token enables us to
/// accurately attribute page view or purchase back to the event and the
/// particular predict response containing this clicked/purchased product. If
/// user clicks on product K in the recommendation results, pass
/// PredictResponse.attribution_token as a URL parameter to product K's page.
/// When recording events on product K's page, log the
/// PredictResponse.attribution_token to this field.
core.String? attributionToken;
/// The ID or name of the associated shopping cart.
///
/// This ID is used to associate multiple items added or present in the cart
/// before purchase. This can only be set for `add-to-cart`,
/// `purchase-complete`, or `shopping-cart-page-view` events.
core.String? cartId;
/// The main auto-completion details related to the event.
///
/// This field should be set for `search` event when autocomplete function is
/// enabled and the user clicks a suggestion for search.
GoogleCloudRetailV2CompletionDetail? completionDetail;
/// Only required for UserEventService.ImportUserEvents method.
///
/// Timestamp of when the user event happened.
core.String? eventTime;
/// User event type.
///
/// Allowed values are: * `add-to-cart`: Products being added to cart. *
/// `category-page-view`: Special pages such as sale or promotion pages
/// viewed. * `detail-page-view`: Products detail page viewed. *
/// `home-page-view`: Homepage viewed. * `promotion-offered`: Promotion is
/// offered to a user. * `promotion-not-offered`: Promotion is not offered to
/// a user. * `purchase-complete`: User finishing a purchase. * `search`:
/// Product search. * `shopping-cart-page-view`: User viewing a shopping cart.
///
/// Required.
core.String? eventType;
/// A list of identifiers for the independent experiment groups this user
/// event belongs to.
///
/// This is used to distinguish between user events associated with different
/// experiment setups (e.g. using Retail API, using different recommendation
/// models).
core.List<core.String>? experimentIds;
/// The filter syntax consists of an expression language for constructing a
/// predicate from one or more fields of the products being filtered.
///
/// See SearchRequest.filter for definition and syntax. The value must be a
/// UTF-8 encoded string with a length limit of 1,000 characters. Otherwise,
/// an INVALID_ARGUMENT error is returned.
core.String? filter;
/// An integer that specifies the current offset for pagination (the 0-indexed
/// starting location, amongst the products deemed by the API as relevant).
///
/// See SearchRequest.offset for definition. If this field is negative, an
/// INVALID_ARGUMENT is returned. This can only be set for `search` events.
/// Other event types should not set this field. Otherwise, an
/// INVALID_ARGUMENT error is returned.
core.int? offset;
/// The order in which products are returned.
///
/// See SearchRequest.order_by for definition and syntax. The value must be a
/// UTF-8 encoded string with a length limit of 1,000 characters. Otherwise,
/// an INVALID_ARGUMENT error is returned. This can only be set for `search`
/// events. Other event types should not set this field. Otherwise, an
/// INVALID_ARGUMENT error is returned.
core.String? orderBy;
/// The categories associated with a category page.
///
/// To represent full path of category, use '\>' sign to separate different
/// hierarchies. If '\>' is part of the category name, please replace it with
/// other character(s). Category pages include special pages such as sales or
/// promotions. For instance, a special sale page may have the category
/// hierarchy: "pageCategories" : \["Sales \> 2017 Black Friday Deals"\].
/// Required for `category-page-view` events. At least one of search_query or
/// page_categories is required for `search` events. Other event types should
/// not set this field. Otherwise, an INVALID_ARGUMENT error is returned.
core.List<core.String>? pageCategories;
/// A unique ID of a web page view.
///
/// This should be kept the same for all user events triggered from the same
/// pageview. For example, an item detail page view could trigger multiple
/// events as the user is browsing the page. The `pageViewId` property should
/// be kept the same for all these events so that they can be grouped together
/// properly. When using the client side event reporting with JavaScript pixel
/// and Google Tag Manager, this value is filled in automatically.
core.String? pageViewId;
/// The main product details related to the event.
///
/// This field is required for the following event types: * `add-to-cart` *
/// `detail-page-view` * `purchase-complete` * `search` In a `search` event,
/// this field represents the products returned to the end user on the current
/// page (the end user may have not finished browsing the whole page yet).
/// When a new page is returned to the end user, after
/// pagination/filtering/ordering even for the same query, a new `search`
/// event with different product_details is desired. The end user may have not
/// finished browsing the whole page yet.
core.List<GoogleCloudRetailV2ProductDetail>? productDetails;
/// A transaction represents the entire purchase transaction.
///
/// Required for `purchase-complete` events. Other event types should not set
/// this field. Otherwise, an INVALID_ARGUMENT error is returned.
GoogleCloudRetailV2PurchaseTransaction? purchaseTransaction;
/// The referrer URL of the current page.
///
/// When using the client side event reporting with JavaScript pixel and
/// Google Tag Manager, this value is filled in automatically.
core.String? referrerUri;
/// The user's search query.
///
/// See SearchRequest.query for definition. The value must be a UTF-8 encoded
/// string with a length limit of 5,000 characters. Otherwise, an
/// INVALID_ARGUMENT error is returned. At least one of search_query or
/// page_categories is required for `search` events. Other event types should
/// not set this field. Otherwise, an INVALID_ARGUMENT error is returned.
core.String? searchQuery;
/// A unique identifier for tracking a visitor session with a length limit of
/// 128 bytes.
///
/// A session is an aggregation of an end user behavior in a time span. A
/// general guideline to populate the sesion_id: 1. If user has no activity
/// for 30 min, a new session_id should be assigned. 2. The session_id should
/// be unique across users, suggest use uuid or add visitor_id as prefix.
core.String? sessionId;
/// Complete URL (window.location.href) of the user's current page.
///
/// When using the client side event reporting with JavaScript pixel and
/// Google Tag Manager, this value is filled in automatically. Maximum length
/// 5,000 characters.
core.String? uri;
/// User information.
GoogleCloudRetailV2UserInfo? userInfo;
/// A unique identifier for tracking visitors.
///
/// For example, this could be implemented with an HTTP cookie, which should
/// be able to uniquely identify a visitor on a single device. This unique
/// identifier should not change if the visitor log in/out of the website. The
/// field must be a UTF-8 encoded string with a length limit of 128
/// characters. Otherwise, an INVALID_ARGUMENT error is returned. The field
/// should not contain PII or user-data. We recommend to use Google Analystics
/// [Client ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#clientId)
/// for this field.
///
/// Required.
core.String? visitorId;
GoogleCloudRetailV2UserEvent({
this.attributes,
this.attributionToken,
this.cartId,
this.completionDetail,
this.eventTime,
this.eventType,
this.experimentIds,
this.filter,
this.offset,
this.orderBy,
this.pageCategories,
this.pageViewId,
this.productDetails,
this.purchaseTransaction,
this.referrerUri,
this.searchQuery,
this.sessionId,
this.uri,
this.userInfo,
this.visitorId,
});
GoogleCloudRetailV2UserEvent.fromJson(core.Map _json)
: this(
attributes: _json.containsKey('attributes')
? (_json['attributes'] as core.Map<core.String, core.dynamic>)
.map(
(key, item) => core.MapEntry(
key,
GoogleCloudRetailV2CustomAttribute.fromJson(
item as core.Map<core.String, core.dynamic>),
),
)
: null,
attributionToken: _json.containsKey('attributionToken')
? _json['attributionToken'] as core.String
: null,
cartId: _json.containsKey('cartId')
? _json['cartId'] as core.String
: null,
completionDetail: _json.containsKey('completionDetail')
? GoogleCloudRetailV2CompletionDetail.fromJson(
_json['completionDetail']
as core.Map<core.String, core.dynamic>)
: null,
eventTime: _json.containsKey('eventTime')
? _json['eventTime'] as core.String
: null,
eventType: _json.containsKey('eventType')
? _json['eventType'] as core.String
: null,
experimentIds: _json.containsKey('experimentIds')
? (_json['experimentIds'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
filter: _json.containsKey('filter')
? _json['filter'] as core.String
: null,
offset:
_json.containsKey('offset') ? _json['offset'] as core.int : null,
orderBy: _json.containsKey('orderBy')
? _json['orderBy'] as core.String
: null,
pageCategories: _json.containsKey('pageCategories')
? (_json['pageCategories'] as core.List)
.map((value) => value as core.String)
.toList()
: null,
pageViewId: _json.containsKey('pageViewId')
? _json['pageViewId'] as core.String
: null,
productDetails: _json.containsKey('productDetails')
? (_json['productDetails'] as core.List)
.map((value) => GoogleCloudRetailV2ProductDetail.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
purchaseTransaction: _json.containsKey('purchaseTransaction')
? GoogleCloudRetailV2PurchaseTransaction.fromJson(
_json['purchaseTransaction']
as core.Map<core.String, core.dynamic>)
: null,
referrerUri: _json.containsKey('referrerUri')
? _json['referrerUri'] as core.String
: null,
searchQuery: _json.containsKey('searchQuery')
? _json['searchQuery'] as core.String
: null,
sessionId: _json.containsKey('sessionId')
? _json['sessionId'] as core.String
: null,
uri: _json.containsKey('uri') ? _json['uri'] as core.String : null,
userInfo: _json.containsKey('userInfo')
? GoogleCloudRetailV2UserInfo.fromJson(
_json['userInfo'] as core.Map<core.String, core.dynamic>)
: null,
visitorId: _json.containsKey('visitorId')
? _json['visitorId'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (attributes != null) 'attributes': attributes!,
if (attributionToken != null) 'attributionToken': attributionToken!,
if (cartId != null) 'cartId': cartId!,
if (completionDetail != null) 'completionDetail': completionDetail!,
if (eventTime != null) 'eventTime': eventTime!,
if (eventType != null) 'eventType': eventType!,
if (experimentIds != null) 'experimentIds': experimentIds!,
if (filter != null) 'filter': filter!,
if (offset != null) 'offset': offset!,
if (orderBy != null) 'orderBy': orderBy!,
if (pageCategories != null) 'pageCategories': pageCategories!,
if (pageViewId != null) 'pageViewId': pageViewId!,
if (productDetails != null) 'productDetails': productDetails!,
if (purchaseTransaction != null)
'purchaseTransaction': purchaseTransaction!,
if (referrerUri != null) 'referrerUri': referrerUri!,
if (searchQuery != null) 'searchQuery': searchQuery!,
if (sessionId != null) 'sessionId': sessionId!,
if (uri != null) 'uri': uri!,
if (userInfo != null) 'userInfo': userInfo!,
if (visitorId != null) 'visitorId': visitorId!,
};
}
/// The inline source for the input config for ImportUserEvents method.
class GoogleCloudRetailV2UserEventInlineSource {
/// A list of user events to import.
///
/// Recommended max of 10k items.
///
/// Required.
core.List<GoogleCloudRetailV2UserEvent>? userEvents;
GoogleCloudRetailV2UserEventInlineSource({
this.userEvents,
});
GoogleCloudRetailV2UserEventInlineSource.fromJson(core.Map _json)
: this(
userEvents: _json.containsKey('userEvents')
? (_json['userEvents'] as core.List)
.map((value) => GoogleCloudRetailV2UserEvent.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (userEvents != null) 'userEvents': userEvents!,
};
}
/// The input config source for user events.
class GoogleCloudRetailV2UserEventInputConfig {
/// BigQuery input source.
///
/// Required.
GoogleCloudRetailV2BigQuerySource? bigQuerySource;
/// Google Cloud Storage location for the input content.
///
/// Required.
GoogleCloudRetailV2GcsSource? gcsSource;
/// The Inline source for the input content for UserEvents.
///
/// Required.
GoogleCloudRetailV2UserEventInlineSource? userEventInlineSource;
GoogleCloudRetailV2UserEventInputConfig({
this.bigQuerySource,
this.gcsSource,
this.userEventInlineSource,
});
GoogleCloudRetailV2UserEventInputConfig.fromJson(core.Map _json)
: this(
bigQuerySource: _json.containsKey('bigQuerySource')
? GoogleCloudRetailV2BigQuerySource.fromJson(
_json['bigQuerySource']
as core.Map<core.String, core.dynamic>)
: null,
gcsSource: _json.containsKey('gcsSource')
? GoogleCloudRetailV2GcsSource.fromJson(
_json['gcsSource'] as core.Map<core.String, core.dynamic>)
: null,
userEventInlineSource: _json.containsKey('userEventInlineSource')
? GoogleCloudRetailV2UserEventInlineSource.fromJson(
_json['userEventInlineSource']
as core.Map<core.String, core.dynamic>)
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (bigQuerySource != null) 'bigQuerySource': bigQuerySource!,
if (gcsSource != null) 'gcsSource': gcsSource!,
if (userEventInlineSource != null)
'userEventInlineSource': userEventInlineSource!,
};
}
/// Information of an end user.
class GoogleCloudRetailV2UserInfo {
/// True if the request is made directly from the end user, in which case the
/// ip_address and user_agent can be populated from the HTTP request.
///
/// This flag should be set only if the API request is made directly from the
/// end user such as a mobile app (and not if a gateway or a server is
/// processing and pushing the user events). This should not be set when using
/// the JavaScript tag in UserEventService.CollectUserEvent.
core.bool? directUserRequest;
/// The end user's IP address.
///
/// Required for getting SearchResponse.sponsored_results. This field is used
/// to extract location information for personalization. This field must be
/// either an IPv4 address (e.g. "104.133.9.80") or an IPv6 address (e.g.
/// "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an INVALID_ARGUMENT
/// error is returned. This should not be set when using the JavaScript tag in
/// UserEventService.CollectUserEvent or if direct_user_request is set.
core.String? ipAddress;
/// User agent as included in the HTTP header.
///
/// Required for getting SearchResponse.sponsored_results. The field must be a
/// UTF-8 encoded string with a length limit of 1,000 characters. Otherwise,
/// an INVALID_ARGUMENT error is returned. This should not be set when using
/// the client side event reporting with GTM or JavaScript tag in
/// UserEventService.CollectUserEvent or if direct_user_request is set.
core.String? userAgent;
/// Highly recommended for logged-in users.
///
/// Unique identifier for logged-in user, such as a user name. The field must
/// be a UTF-8 encoded string with a length limit of 128 characters.
/// Otherwise, an INVALID_ARGUMENT error is returned.
core.String? userId;
GoogleCloudRetailV2UserInfo({
this.directUserRequest,
this.ipAddress,
this.userAgent,
this.userId,
});
GoogleCloudRetailV2UserInfo.fromJson(core.Map _json)
: this(
directUserRequest: _json.containsKey('directUserRequest')
? _json['directUserRequest'] as core.bool
: null,
ipAddress: _json.containsKey('ipAddress')
? _json['ipAddress'] as core.String
: null,
userAgent: _json.containsKey('userAgent')
? _json['userAgent'] as core.String
: null,
userId: _json.containsKey('userId')
? _json['userId'] as core.String
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (directUserRequest != null) 'directUserRequest': directUserRequest!,
if (ipAddress != null) 'ipAddress': ipAddress!,
if (userAgent != null) 'userAgent': userAgent!,
if (userId != null) 'userId': userId!,
};
}
/// The response message for Operations.ListOperations.
class GoogleLongrunningListOperationsResponse {
/// The standard List next-page token.
core.String? nextPageToken;
/// A list of operations that matches the specified filter in the request.
core.List<GoogleLongrunningOperation>? operations;
GoogleLongrunningListOperationsResponse({
this.nextPageToken,
this.operations,
});
GoogleLongrunningListOperationsResponse.fromJson(core.Map _json)
: this(
nextPageToken: _json.containsKey('nextPageToken')
? _json['nextPageToken'] as core.String
: null,
operations: _json.containsKey('operations')
? (_json['operations'] as core.List)
.map((value) => GoogleLongrunningOperation.fromJson(
value as core.Map<core.String, core.dynamic>))
.toList()
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (nextPageToken != null) 'nextPageToken': nextPageToken!,
if (operations != null) 'operations': operations!,
};
}
/// This resource represents a long-running operation that is the result of a
/// network API call.
class GoogleLongrunningOperation {
/// If the value is `false`, it means the operation is still in progress.
///
/// If `true`, the operation is completed, and either `error` or `response` is
/// available.
core.bool? done;
/// The error result of the operation in case of failure or cancellation.
GoogleRpcStatus? error;
/// Service-specific metadata associated with the operation.
///
/// It typically contains progress information and common metadata such as
/// create time. Some services might not provide such metadata. Any method
/// that returns a long-running operation should document the metadata type,
/// if any.
///
/// The values for Object must be JSON objects. It can consist of `num`,
/// `String`, `bool` and `null` as well as `Map` and `List` values.
core.Map<core.String, core.Object?>? metadata;
/// The server-assigned name, which is only unique within the same service
/// that originally returns it.
///
/// If you use the default HTTP mapping, the `name` should be a resource name
/// ending with `operations/{unique_id}`.
core.String? name;
/// The normal response of the operation in case of success.
///
/// If the original method returns no data on success, such as `Delete`, the
/// response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other
/// methods, the response should have the type `XxxResponse`, where `Xxx` is
/// the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
///
/// The values for Object must be JSON objects. It can consist of `num`,
/// `String`, `bool` and `null` as well as `Map` and `List` values.
core.Map<core.String, core.Object?>? response;
GoogleLongrunningOperation({
this.done,
this.error,
this.metadata,
this.name,
this.response,
});
GoogleLongrunningOperation.fromJson(core.Map _json)
: this(
done: _json.containsKey('done') ? _json['done'] as core.bool : null,
error: _json.containsKey('error')
? GoogleRpcStatus.fromJson(
_json['error'] as core.Map<core.String, core.dynamic>)
: null,
metadata: _json.containsKey('metadata')
? _json['metadata'] as core.Map<core.String, core.dynamic>
: null,
name: _json.containsKey('name') ? _json['name'] as core.String : null,
response: _json.containsKey('response')
? _json['response'] as core.Map<core.String, core.dynamic>
: null,
);
core.Map<core.String, core.dynamic> toJson() => {
if (done != null) 'done': done!,
if (error != null) 'error': error!,
if (metadata != null) 'metadata': metadata!,
if (name != null) 'name': name!,
if (response != null) 'response': response!,
};
}
/// A generic empty message that you can re-use to avoid defining duplicated
/// empty messages in your APIs.
///
/// A typical example is to use it as the request or the response type of an API
/// method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns
/// (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
typedef GoogleProtobufEmpty = $Empty;
/// The `Status` type defines a logical error model that is suitable for
/// different programming environments, including REST APIs and RPC APIs.
///
/// It is used by [gRPC](https://github.com/grpc). Each `Status` message
/// contains three pieces of data: error code, error message, and error details.
/// You can find out more about this error model and how to work with it in the
/// [API Design Guide](https://cloud.google.com/apis/design/errors).
typedef GoogleRpcStatus = $Status;
/// Represents a whole or partial calendar date, such as a birthday.
///
/// The time of day and time zone are either specified elsewhere or are
/// insignificant. The date is relative to the Gregorian Calendar. This can
/// represent one of the following: * A full date, with non-zero year, month,
/// and day values * A month and day, with a zero year (e.g., an anniversary) *
/// A year on its own, with a zero month and a zero day * A year and month, with
/// a zero day (e.g., a credit card expiration date) Related types: *
/// google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp
typedef GoogleTypeDate = $Date;
| 40.7311 | 127 | 0.666882 |
2f57f16cd07aa8eb83de7a119bf2a3ef0edf58c0 | 3,705 | php | PHP | src/vendor/magento/module-inventory-source-selection-api/Test/Api/SourceSelectionServiceTest.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | null | null | null | src/vendor/magento/module-inventory-source-selection-api/Test/Api/SourceSelectionServiceTest.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | null | null | null | src/vendor/magento/module-inventory-source-selection-api/Test/Api/SourceSelectionServiceTest.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | null | null | null | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\InventorySourceSelectionApi\Test\Api;
use Magento\Framework\Webapi\Rest\Request;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\TestFramework\Assert\AssertArrayContains;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\InventorySourceSelectionApi\Api\GetDefaultSourceSelectionAlgorithmCodeInterface;
class SourceSelectionServiceTest extends WebapiAbstract
{
/**#@+
* Service constants
*/
const RESOURCE_PATH = '/V1/inventory/source-selection-algorithm-result';
const SERVICE_NAME = 'inventorySourceSelectionApiSourceSelectionServiceV1';
/**#@-*/
/**
* @var GetDefaultSourceSelectionAlgorithmCodeInterface
*/
private $defaultAlgorithmCode;
protected function setUp()
{
parent::setUp();
$this->defaultAlgorithmCode = Bootstrap::getObjectManager()->get(
GetDefaultSourceSelectionAlgorithmCodeInterface::class
);
}
/**
* @magentoApiDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php
* @magentoApiDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php
* @magentoApiDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php
* @magentoApiDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_links.php
* @magentoApiDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php
*/
public function testSourceSelectionService()
{
$inventoryRequest = [
'stockId' => 10,
'items' => [
[
'sku' => 'SKU-1',
'qty' => 8
],
[
'sku' => 'SKU-4',
'qty' => 4
]
]
];
$expectedResultData = [
'source_selection_items' => [
[
'source_code' => 'eu-1',
'sku' => 'SKU-1',
'qty_to_deduct' => 5.5,
'qty_available' => 5.5
],
[
'source_code' => 'eu-2',
'sku' => 'SKU-1',
'qty_to_deduct' => 2.5,
'qty_available' => 3
],
[
'source_code' => 'eu-2',
'sku' => 'SKU-4',
'qty_to_deduct' => 4,
'qty_available' => 6
],
],
'shippable' => 1
];
$algorithmCode = $this->defaultAlgorithmCode->execute();
$requestData = [
'inventoryRequest' => $inventoryRequest,
'algorithmCode' => $algorithmCode
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'operation' => self::SERVICE_NAME . 'Execute',
],
];
$sourceSelectionAlgorithmResult = (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST)
? $this->_webApiCall($serviceInfo, $requestData)
: $this->_webApiCall($serviceInfo, $requestData);
self::assertInternalType('array', $sourceSelectionAlgorithmResult);
self::assertNotEmpty($sourceSelectionAlgorithmResult);
AssertArrayContains::assert($expectedResultData, $sourceSelectionAlgorithmResult);
}
}
| 33.378378 | 106 | 0.54332 |
14147f631d93db132f98dc8ba99bb3aa3c4b6e1c | 1,326 | dart | Dart | lib/app/modules/home/presenter/pages/home/home_store.g.dart | TECFlyingCommunity/rede | fd330b1c885619df76d6fcb1f674dc333467ff24 | [
"MIT"
] | null | null | null | lib/app/modules/home/presenter/pages/home/home_store.g.dart | TECFlyingCommunity/rede | fd330b1c885619df76d6fcb1f674dc333467ff24 | [
"MIT"
] | null | null | null | lib/app/modules/home/presenter/pages/home/home_store.g.dart | TECFlyingCommunity/rede | fd330b1c885619df76d6fcb1f674dc333467ff24 | [
"MIT"
] | null | null | null | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_store.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$HomeStore on HomeStoreBase, Store {
final _$listWidgetAtom = Atom(name: 'HomeStoreBase.listWidget');
@override
ObservableList<Widget> get listWidget {
_$listWidgetAtom.reportRead();
return super.listWidget;
}
@override
set listWidget(ObservableList<Widget> value) {
_$listWidgetAtom.reportWrite(value, super.listWidget, () {
super.listWidget = value;
});
}
final _$HomeStoreBaseActionController =
ActionController(name: 'HomeStoreBase');
@override
dynamic gerarDados() {
final _$actionInfo = _$HomeStoreBaseActionController.startAction(
name: 'HomeStoreBase.gerarDados');
try {
return super.gerarDados();
} finally {
_$HomeStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
listWidget: ${listWidget}
''';
}
}
| 27.625 | 211 | 0.640271 |
90c940a1ed51f36bc8565cfe0aa8cd3e6f2804d0 | 134 | kt | Kotlin | src/main/kotlin/com/nmalaguti/dropwizard/cometd/CometDBundleConfiguration.kt | nmalaguti/dropwizard-cometd | b6a1959af482130a87af9e13b631955f5c087150 | [
"MIT"
] | null | null | null | src/main/kotlin/com/nmalaguti/dropwizard/cometd/CometDBundleConfiguration.kt | nmalaguti/dropwizard-cometd | b6a1959af482130a87af9e13b631955f5c087150 | [
"MIT"
] | null | null | null | src/main/kotlin/com/nmalaguti/dropwizard/cometd/CometDBundleConfiguration.kt | nmalaguti/dropwizard-cometd | b6a1959af482130a87af9e13b631955f5c087150 | [
"MIT"
] | null | null | null | package com.nmalaguti.dropwizard.cometd
interface CometDBundleConfiguration {
fun getCometDConfiguration(): CometDConfiguration
} | 26.8 | 53 | 0.843284 |
3a900ece50c108f57ae05cb17de03bf8f789eca7 | 3,108 | sql | SQL | coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/log/Release_2_0_logs/KCAWD-585.sql | mrudulpolus/kc | 55f529e5ff0985f3bf5247e2a1e63c5dec07f560 | [
"ECL-2.0"
] | null | null | null | coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/log/Release_2_0_logs/KCAWD-585.sql | mrudulpolus/kc | 55f529e5ff0985f3bf5247e2a1e63c5dec07f560 | [
"ECL-2.0"
] | null | null | null | coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/log/Release_2_0_logs/KCAWD-585.sql | mrudulpolus/kc | 55f529e5ff0985f3bf5247e2a1e63c5dec07f560 | [
"ECL-2.0"
] | null | null | null | set define off
delete from AWARD_TRANSACTION_TYPE;
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 1, 'Administrative Amendment', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 2, 'Allotment (Increment)', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 3, 'Continuation (Amendment)', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 4, 'Correction', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 5, 'Date Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 6, 'Deobligation', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 7, 'F&A Rate Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 8, 'Investigator Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 9, 'New', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 10, 'No Cost Extension', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 11, 'Restriction Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 12, 'Subaward Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 13, 'Supplement', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 14, 'Suspension (Stop Work Order)', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 15, 'Unit Change', sysdate, user, 'Y' );
INSERT INTO AWARD_TRANSACTION_TYPE ( AWARD_TRANSACTION_TYPE_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER, SHOW_IN_ACTION_SUMMARY )
VALUES ( 16, 'Terminiation', sysdate, user, 'Y' ); | 88.8 | 135 | 0.800193 |
5bd6ace75199fc71a709e8571f34daeb8b07cb8b | 784 | cs | C# | Prism.CommonDialogPack/Converters/BoolToDataGridSelectionModeConverter.cs | Kuro4/Prism.CommonDialogPack | 648795ff52464386f1f4cdbaf9b50f04a4e36aa8 | [
"MIT"
] | 9 | 2020-04-20T11:51:46.000Z | 2022-02-15T02:09:45.000Z | Prism.CommonDialogPack/Converters/BoolToDataGridSelectionModeConverter.cs | Kuro4/Prism.CommonDialogPack | 648795ff52464386f1f4cdbaf9b50f04a4e36aa8 | [
"MIT"
] | null | null | null | Prism.CommonDialogPack/Converters/BoolToDataGridSelectionModeConverter.cs | Kuro4/Prism.CommonDialogPack | 648795ff52464386f1f4cdbaf9b50f04a4e36aa8 | [
"MIT"
] | 2 | 2020-08-19T17:11:09.000Z | 2020-12-20T19:44:07.000Z | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
namespace Prism.CommonDialogPack.Converters
{
public class BoolToDataGridSelectionModeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is bool canMultiselect)) throw new ArgumentException("value is not bool type");
return canMultiselect ? DataGridSelectionMode.Extended : DataGridSelectionMode.Single;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 32.666667 | 103 | 0.719388 |
6a9aa12fcd7cdc9e7cd16b662cc3436995c62127 | 2,010 | kt | Kotlin | examples/movie_review_kotlin/app/src/main/java/com/surveysparrow/sdk/example/movie_review_kotlin/PlaybackActivity.kt | surveysparrow/surveysparrow-android-sdk | 93835b623bfe632265a877659c0df986fba43575 | [
"MIT"
] | 2 | 2020-11-23T13:02:34.000Z | 2021-04-23T06:53:43.000Z | examples/movie_review_kotlin/app/src/main/java/com/surveysparrow/sdk/example/movie_review_kotlin/PlaybackActivity.kt | surveysparrow/surveysparrow-android-sdk | 93835b623bfe632265a877659c0df986fba43575 | [
"MIT"
] | null | null | null | examples/movie_review_kotlin/app/src/main/java/com/surveysparrow/sdk/example/movie_review_kotlin/PlaybackActivity.kt | surveysparrow/surveysparrow-android-sdk | 93835b623bfe632265a877659c0df986fba43575 | [
"MIT"
] | null | null | null | package com.surveysparrow.sdk.example.movie_review_kotlin
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.surveysparrow.ss_android_sdk.SsSurvey
import com.surveysparrow.ss_android_sdk.SurveySparrow
class PlaybackActivity : AppCompatActivity() {
private val RATE_MOVIE_REQUEST = 102
val LOG_TAG = "MOVIE_APP_TOAST"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_playback)
}
fun rateMovie(view: View) {
// Create a survey
val survey = SsSurvey("your_domain", "your_survey_token")
.addCustomParam("movieName", "Sparrow Life") // Pass data to the survey from your code
// Create SurveySparrow to set configs and trigger survey.
val surveySparrow = SurveySparrow(this, survey)
.setWaitTime(2000) // How long you should display thank you page
// Start survey as an Activity for result
surveySparrow.startSurveyForResult(RATE_MOVIE_REQUEST)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == RATE_MOVIE_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
// Get the survey response
val response = SurveySparrow.toJSON(data?.data.toString())
val responseData = response.getJSONArray("response")
val rating = responseData.getJSONObject(0).getInt("answer")
// Show a recommendation page if the user give 4+ rating
if(rating >= 4) {
startActivity(Intent(this, RecommendationsActivity::class.java))
}
} else {
Log.v(LOG_TAG, "Review survey not completed!")
}
}
}
}
| 37.222222 | 98 | 0.666667 |
83f7f653c186503de28b94d3d974d393ea76da39 | 826 | java | Java | core-it-suite/src/test/resources/mng-6210-core-extensions-scopes/repo-src/maven-it-plugin/src/main/java/org/apache/maven/its/plugin/ValidateMojoExecutionScopedMojo.java | mthmulders/maven-integration-testing | c1344c081955d62d0f3a45a2821eab243e5ef2f0 | [
"Apache-2.0"
] | 19 | 2015-11-04T21:13:52.000Z | 2022-03-22T21:50:57.000Z | core-it-suite/src/test/resources/mng-6210-core-extensions-scopes/repo-src/maven-it-plugin/src/main/java/org/apache/maven/its/plugin/ValidateMojoExecutionScopedMojo.java | mthmulders/maven-integration-testing | c1344c081955d62d0f3a45a2821eab243e5ef2f0 | [
"Apache-2.0"
] | 61 | 2016-01-07T11:55:14.000Z | 2022-03-11T19:02:37.000Z | core-it-suite/src/test/resources/mng-6210-core-extensions-scopes/repo-src/maven-it-plugin/src/main/java/org/apache/maven/its/plugin/ValidateMojoExecutionScopedMojo.java | mthmulders/maven-integration-testing | c1344c081955d62d0f3a45a2821eab243e5ef2f0 | [
"Apache-2.0"
] | 68 | 2015-04-19T21:45:36.000Z | 2022-03-21T20:31:12.000Z | package org.apache.maven.its.plugin;
import org.apache.maven.its.extensions.TestMojoExecutionScopedComponent;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
@Mojo( name = "validate-session-execution-scoped" )
public class ValidateMojoExecutionScopedMojo
extends AbstractMojo
{
@Component
private TestMojoExecutionScopedComponent component;
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( this.component == null )
{
throw new MojoExecutionException( "Expected core extension component is not available" );
}
}
}
| 31.769231 | 101 | 0.762712 |
804c720491da4d7bc97f888ae1f064b5e5d5381f | 5,126 | java | Java | elara-core/src/main/java/org/tools4j/elara/plugin/replication/ReplicationPlugin.java | tools4j/elara | cdc9e3600ab023931dfce15224b8eeab4a1e58b2 | [
"MIT"
] | 8 | 2020-09-12T21:17:28.000Z | 2022-03-27T13:40:07.000Z | elara-core/src/main/java/org/tools4j/elara/plugin/replication/ReplicationPlugin.java | tools4j/elara | cdc9e3600ab023931dfce15224b8eeab4a1e58b2 | [
"MIT"
] | null | null | null | elara-core/src/main/java/org/tools4j/elara/plugin/replication/ReplicationPlugin.java | tools4j/elara | cdc9e3600ab023931dfce15224b8eeab4a1e58b2 | [
"MIT"
] | 2 | 2020-10-11T03:00:59.000Z | 2022-01-03T11:55:29.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2020-2021 tools4j.org (Marco Terzer, Anton Anufriev)
*
* 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 org.tools4j.elara.plugin.replication;
import org.tools4j.elara.application.CommandProcessor;
import org.tools4j.elara.application.EventApplier;
import org.tools4j.elara.factory.InterceptableSingletons;
import org.tools4j.elara.factory.Singletons;
import org.tools4j.elara.init.ExecutionType;
import org.tools4j.elara.log.MessageLog;
import org.tools4j.elara.log.MessageLog.Appender;
import org.tools4j.elara.plugin.api.SystemPlugin;
import org.tools4j.elara.plugin.api.TypeRange;
import org.tools4j.elara.plugin.base.BaseState;
import org.tools4j.elara.plugin.replication.Connection.Handler;
import org.tools4j.nobark.loop.Step;
import static java.util.Objects.requireNonNull;
/**
* A plugin that issues a commands and events related to booting an elara application to indicate that the application
* has been started and initialised.
*/
public class ReplicationPlugin implements SystemPlugin<ReplicationState.Mutable> {
private final org.tools4j.elara.plugin.replication.Configuration configuration;
public ReplicationPlugin(final org.tools4j.elara.plugin.replication.Configuration configuration) {
this.configuration = org.tools4j.elara.plugin.replication.Configuration.validate(configuration);
}
public static Context configure() {
return Context.create();
}
@Override
public TypeRange typeRange() {
return TypeRange.REPLICATION;
}
@Override
public ReplicationState.Mutable defaultPluginState() {
return new DefaultReplicationState();
}
@Override
public Configuration configuration(final org.tools4j.elara.init.Configuration appConfig,
final ReplicationState.Mutable replicationState) {
requireNonNull(appConfig);
requireNonNull(replicationState);
final MessageLog eventLog = appConfig.eventLog();
final Appender eventLogAppender = eventLog.appender();
final EnforcedLeaderEventReceiver enforcedLeaderEventReceiver = new EnforcedLeaderEventReceiver(
appConfig.loggerFactory(), appConfig.timeSource(), configuration, replicationState, eventLogAppender
);
final DispatchingPublisher dispatchingPublisher = new DispatchingPublisher(configuration);
final EventSender eventSender = new DefaultEventSender(configuration, replicationState, eventLog,
dispatchingPublisher);
return new Configuration.Default() {
@Override
public Step step(final BaseState baseState, final ExecutionType executionType) {
switch (executionType) {
case ALWAYS_WHEN_EVENTS_APPLIED:
final Handler connectionHandler = new ConnectionHandler(
appConfig.loggerFactory(), configuration, baseState, replicationState, eventLogAppender, dispatchingPublisher
);
return new ReplicationPluginStep(
configuration, replicationState, enforcedLeaderEventReceiver, connectionHandler, eventSender
);
default:
return Step.NO_OP;
}
}
@Override
public CommandProcessor commandProcessor(final BaseState baseState) {
return new ReplicationCommandProcessor(appConfig.loggerFactory(), configuration, replicationState);
}
@Override
public EventApplier eventApplier(final BaseState.Mutable baseState) {
return new ReplicationEventApplier(appConfig.loggerFactory(), configuration, replicationState);
}
@Override
public InterceptableSingletons interceptOrNull(final Singletons singletons) {
return new ReplicationInterceptor(singletons, appConfig, configuration, replicationState);
}
};
}
}
| 44.964912 | 141 | 0.70835 |
0a8cd484f87f60881b73da30e6a248007e5faa9f | 1,336 | go | Go | analyzer.go | smartystreets/gitreview | 933a8a0b43843d80596f3c2f407d461d019b2e61 | [
"MIT"
] | 3 | 2019-09-14T00:15:57.000Z | 2019-09-16T03:51:41.000Z | analyzer.go | smartystreets/gitreview | 933a8a0b43843d80596f3c2f407d461d019b2e61 | [
"MIT"
] | 2 | 2019-08-30T20:39:23.000Z | 2020-07-06T16:21:41.000Z | analyzer.go | smartystreets/gitreview | 933a8a0b43843d80596f3c2f407d461d019b2e61 | [
"MIT"
] | 1 | 2020-07-03T15:06:42.000Z | 2020-07-03T15:06:42.000Z | package main
import (
"sort"
"sync"
)
type Analyzer struct {
workerCount int
workerInput chan string
}
func NewAnalyzer(workerCount int) *Analyzer {
return &Analyzer{
workerCount: workerCount,
workerInput: make(chan string),
}
}
func (this *Analyzer) AnalyzeAll(paths []string) (fetches []*GitReport) {
go this.loadInputs(paths)
outputs := this.startWorkers()
for fetch := range merge(outputs...) {
fetches = append(fetches, fetch)
}
sort.Slice(fetches, func(i, j int) bool {
return fetches[i].RepoPath < fetches[j].RepoPath
})
return fetches
}
func (this *Analyzer) loadInputs(paths []string) {
for _, path := range paths {
this.workerInput <- path
}
close(this.workerInput)
}
func (this *Analyzer) startWorkers() (outputs []chan *GitReport) {
for x := 0; x < this.workerCount; x++ {
output := make(chan *GitReport)
outputs = append(outputs, output)
go NewWorker(x, this.workerInput, output).Start()
}
return outputs
}
func merge(fannedOut ...chan *GitReport) chan *GitReport {
var waiter sync.WaitGroup
waiter.Add(len(fannedOut))
fannedIn := make(chan *GitReport)
output := func(c <-chan *GitReport) {
for n := range c {
fannedIn <- n
}
waiter.Done()
}
for _, c := range fannedOut {
go output(c)
}
go func() {
waiter.Wait()
close(fannedIn)
}()
return fannedIn
}
| 18.555556 | 73 | 0.675898 |
f9ac43b5084c725f84c9e754f08c58368ffd7f6f | 858 | go | Go | clear_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | clear_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | clear_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | package main
import (
"reflect"
"testing"
)
func Test_clearAndTrim(t *testing.T) {
cases := []struct {
secretBytes []byte
n int
trimmedSecretBytes []byte
}{
{
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
-1,
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
},
{
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
0,
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
},
{
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
3,
[]byte{3, 4, 5, 6, 7, 8, 9},
},
{
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
10,
[]byte{},
},
{
[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
15,
[]byte{},
},
}
for _, c := range cases {
clearAndTrim(&c.secretBytes, c.n)
if !reflect.DeepEqual(c.secretBytes, c.trimmedSecretBytes) {
t.Errorf("clearAndTrim(&c.secretBytes, %d) == %v want %v", c.n, c.secretBytes, c.trimmedSecretBytes)
}
}
}
| 18.255319 | 103 | 0.463869 |
e86a0e02fe3b7c36648857d0acdd6622eb11598a | 8,237 | cpp | C++ | webrtc-jni/src/main/cpp/src/media/audio/windows/WasapiAudioDeviceManager.cpp | hhgyu/webrtc-java | 572c3814c94a407cfacdee1e2bc898522063731f | [
"Apache-2.0"
] | 1 | 2020-10-18T04:59:44.000Z | 2020-10-18T04:59:44.000Z | webrtc-jni/src/main/cpp/src/media/audio/windows/WasapiAudioDeviceManager.cpp | hhgyu/webrtc-java | 572c3814c94a407cfacdee1e2bc898522063731f | [
"Apache-2.0"
] | null | null | null | webrtc-jni/src/main/cpp/src/media/audio/windows/WasapiAudioDeviceManager.cpp | hhgyu/webrtc-java | 572c3814c94a407cfacdee1e2bc898522063731f | [
"Apache-2.0"
] | 1 | 2021-04-22T12:30:45.000Z | 2021-04-22T12:30:45.000Z | /*
* Copyright 2019 Alex Andres
*
* 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.
*/
#include "media/audio/windows/WasapiAudioDeviceManager.h"
#include "platform/windows/WinUtils.h"
#include "functiondiscoverykeys_devpkey.h"
#include "rtc_base/logging.h"
namespace jni
{
namespace avdev
{
WasapiAudioDeviceManager::WasapiAudioDeviceManager() :
deviceEnumerator()
{
ComInitializer initializer;
HRESULT hr;
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&deviceEnumerator);
THROW_IF_FAILED(hr, "WASAPI: Create device enumerator failed");
deviceEnumerator->RegisterEndpointNotificationCallback(this);
getAudioCaptureDevices();
getAudioPlaybackDevices();
}
WasapiAudioDeviceManager::~WasapiAudioDeviceManager()
{
if (deviceEnumerator) {
deviceEnumerator->UnregisterEndpointNotificationCallback(this);
}
}
std::set<AudioDevicePtr> WasapiAudioDeviceManager::getAudioCaptureDevices()
{
if (captureDevices.empty()) {
enumerateDevices(eCapture);
}
return captureDevices.devices();
}
std::set<AudioDevicePtr> WasapiAudioDeviceManager::getAudioPlaybackDevices()
{
if (playbackDevices.empty()) {
enumerateDevices(eRender);
}
return playbackDevices.devices();
}
void WasapiAudioDeviceManager::enumerateDevices(EDataFlow dataFlow)
{
ComInitializer initializer;
ComPtr<IMMDeviceCollection> deviceCollection;
ComPtr<IMMDevice> defaultDevice;
LPWSTR defaultDeviceId = nullptr;
UINT count;
HRESULT hr;
hr = deviceEnumerator->EnumAudioEndpoints(dataFlow, DEVICE_STATE_ACTIVE, &deviceCollection);
THROW_IF_FAILED(hr, "WASAPI: Enumerate audio endpoints failed");
hr = deviceCollection->GetCount(&count);
THROW_IF_FAILED(hr, "WASAPI: Get device count failed");
hr = deviceEnumerator->GetDefaultAudioEndpoint(dataFlow, eMultimedia, &defaultDevice);
if (SUCCEEDED(hr)) {
hr = defaultDevice->GetId(&defaultDeviceId);
THROW_IF_FAILED(hr, "WASAPI: Get default device id failed");
}
for (UINT i = 0; i < count; i++) {
LPWSTR deviceId = nullptr;
ComPtr<IMMDevice> pDevice;
hr = deviceCollection->Item(i, &pDevice);
if (FAILED(hr)) {
RTC_LOG(LS_WARNING) << "WASAPI: DeviceCollection get device failed";
continue;
}
hr = pDevice->GetId(&deviceId);
if (FAILED(hr)) {
RTC_LOG(LS_WARNING) << "WASAPI: Device get id failed";
continue;
}
AudioDevicePtr device = createAudioDevice(deviceId, nullptr);
if (device != nullptr) {
bool isDefault = (defaultDeviceId != nullptr && wcscmp(defaultDeviceId, deviceId) == 0);
if (dataFlow == eCapture && isDefault) {
setDefaultCaptureDevice(device);
}
else if (dataFlow == eRender && isDefault) {
setDefaultPlaybackDevice(device);
}
}
CoTaskMemFree(deviceId);
}
CoTaskMemFree(defaultDeviceId);
}
void WasapiAudioDeviceManager::addDevice(LPCWSTR deviceId)
{
if (deviceId == nullptr) {
return;
}
EDataFlow dataFlow;
std::shared_ptr<AudioDevice> device = createAudioDevice(deviceId, &dataFlow);
notifyDeviceConnected(device);
}
void WasapiAudioDeviceManager::removeDevice(LPCWSTR deviceId)
{
if (deviceId == nullptr)
return;
std::string id = WideStrToStr(deviceId);
removeAudioDevice(captureDevices, id);
removeAudioDevice(playbackDevices, id);
}
std::shared_ptr<AudioDevice> WasapiAudioDeviceManager::createAudioDevice(LPCWSTR deviceId, EDataFlow * dataFlow)
{
ComInitializer initializer;
ComPtr<IMMDevice> pDevice;
ComPtr<IMMEndpoint> endpoint;
ComPtr<IPropertyStore> propertyStore;
EDataFlow flow;
PROPVARIANT pv;
PropVariantInit(&pv);
HRESULT hr;
hr = deviceEnumerator->GetDevice(deviceId, &pDevice);
THROW_IF_FAILED(hr, "WASAPI: Enumerator get device with id: %S failed", deviceId);
hr = pDevice->QueryInterface(__uuidof(IMMEndpoint), (void**)&endpoint);
THROW_IF_FAILED(hr, "WASAPI: Device get endpoint failed");
hr = endpoint->GetDataFlow(&flow);
THROW_IF_FAILED(hr, "WASAPI: Endpoint get data flow failed");
hr = pDevice->OpenPropertyStore(STGM_READ, &propertyStore);
THROW_IF_FAILED(hr, "WASAPI: Device open property store failed");
hr = propertyStore->GetValue(PKEY_Device_FriendlyName, &pv);
THROW_IF_FAILED(hr, "WASAPI: PropertyStore get friendly name failed");
std::string id = WideStrToStr(deviceId);
std::string name = WideStrToStr(pv.pwszVal);
AudioDevicePtr device = nullptr;
if (flow == eCapture) {
device = std::make_shared<AudioDevice>(name, id);
}
else if (flow == eRender) {
device = std::make_shared<AudioDevice>(name, id);
}
if (dataFlow != nullptr) {
*dataFlow = flow;
}
PropVariantClear(&pv);
return device;
}
template <typename T>
void WasapiAudioDeviceManager::removeAudioDevice(DeviceList<T> & devices, std::string id)
{
auto predicate = [id](const AudioDevicePtr & dev) {
return id == dev->getDescriptor();
};
T removed = devices.removeDevice(predicate);
if (removed) {
notifyDeviceDisconnected(removed);
}
}
ULONG WasapiAudioDeviceManager::AddRef()
{
// We hold a reference to ourselves (static singleton).
return 1;
}
ULONG WasapiAudioDeviceManager::Release()
{
// We hold a reference to ourselves (static singleton).
return 1;
}
HRESULT WasapiAudioDeviceManager::QueryInterface(REFIID iid, void ** object)
{
if (object == nullptr) {
return E_POINTER;
}
if (iid == IID_IUnknown || iid == __uuidof(IMMNotificationClient)) {
*object = static_cast<IMMNotificationClient *>(this);
}
else {
*object = nullptr;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
HRESULT WasapiAudioDeviceManager::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR deviceId)
{
RTC_LOG(LS_INFO) << "WASAPI: Default device changed (" << RoleToStr(role).c_str() << "): " << deviceId;
std::string id;
if (deviceId != nullptr) {
id = WideStrToStr(deviceId);
}
auto predicate = [id](const AudioDevicePtr & dev) {
return id == dev->getDescriptor();
};
if (flow == eCapture) {
if (deviceId == nullptr) {
setDefaultCaptureDevice(nullptr);
return S_OK;
}
AudioDevicePtr found = captureDevices.findDevice(predicate);
if (found) {
setDefaultCaptureDevice(found);
}
}
else if (flow == eRender) {
if (deviceId == nullptr) {
setDefaultPlaybackDevice(nullptr);
return S_OK;
}
AudioDevicePtr found = playbackDevices.findDevice(predicate);
if (found) {
setDefaultPlaybackDevice(found);
}
}
return S_OK;
}
HRESULT WasapiAudioDeviceManager::OnDeviceAdded(LPCWSTR deviceId)
{
RTC_LOG(LS_INFO) << "WASAPI: Device added: " << deviceId;
addDevice(deviceId);
return S_OK;
}
HRESULT WasapiAudioDeviceManager::OnDeviceRemoved(LPCWSTR deviceId)
{
RTC_LOG(LS_INFO) << "WASAPI: Device removed: " << deviceId;
removeDevice(deviceId);
return S_OK;
}
HRESULT WasapiAudioDeviceManager::OnDeviceStateChanged(LPCWSTR deviceId, DWORD newState)
{
RTC_LOG(LS_INFO) << "WASAPI: Device state changed: " << deviceId;
if (deviceId == nullptr) {
return S_OK;
}
switch (newState) {
case DEVICE_STATE_ACTIVE:
addDevice(deviceId);
break;
case DEVICE_STATE_DISABLED:
case DEVICE_STATE_NOTPRESENT:
case DEVICE_STATE_UNPLUGGED:
removeDevice(deviceId);
break;
}
return S_OK;
}
HRESULT WasapiAudioDeviceManager::OnPropertyValueChanged(LPCWSTR /*deviceId*/, const PROPERTYKEY /*key*/)
{
return S_OK;
}
}
} | 25.189602 | 131 | 0.696491 |
40f29265b291bcf38b616cc3700c87fb69dc7f0d | 2,737 | ps1 | PowerShell | scripts/workflow/perform_statistical_control.ps1 | lmsac/GproDIA | 3fc1cdee535c9743806b7be423aba29daca24406 | [
"BSD-3-Clause"
] | 2 | 2021-11-13T21:37:42.000Z | 2021-11-16T07:40:06.000Z | scripts/workflow/perform_statistical_control.ps1 | lmsac/GproDIA | 3fc1cdee535c9743806b7be423aba29daca24406 | [
"BSD-3-Clause"
] | null | null | null | scripts/workflow/perform_statistical_control.ps1 | lmsac/GproDIA | 3fc1cdee535c9743806b7be423aba29daca24406 | [
"BSD-3-Clause"
] | null | null | null | # Statistical Control
# Global parameters and paths
$script_path = "code\GproDIA\src"
$TRIC_path = "$env:ProgramFiles\Anaconda3\Scripts\feature_alignment.py"
<#
# Fission Yeast Data
$data_path = "data\GproDIA\fissionyeast"
$library_name = "fissionyeast"
$library_pqp_file = "$library_name.PQP"
$result_name = $library_name
$result_osw_file = "$result_name.osw"
$result_tsv_file = "$($result_osw_file.Replace('.osw', '')).tsv"
$enable_glycoform_inference = $false
$threads = -1
$test = $true
#>
# Serum Data
$data_path = "data\GproDIA\serum"
$library_name = "serum"
$library_pqp_file = "$($library_name)_uis.PQP"
$result_name = $library_name
$result_osw_file = "$($result_name)_uis.osw"
$result_tsv_file = "$($result_osw_file.Replace('.osw', '')).tsv"
$enable_glycoform_inference = $true
$threads = -1
$test = $true
# Statistical control
cd "$data_path\result\$result_name"
pyprophet merge `
--template="..\..\library\$library_name\$library_pqp_file" `
--out="$result_osw_file" `
(ls *.osw -Name)
python "$script_path\score_glycopeptide_peakgroups.py" `
--level ms2 `
--threads -1 `
--in "$result_osw_file" `
"--$(if ($test) { 'test' } else { 'no-test' })"
if ($enable_glycoform_inference) {
python "$script_path\score_feature_glycoform.py" `
--level ms1 `
--threads -1 `
--in "$result_osw_file" `
"--$(if ($test) { 'test' } else { 'no-test' })"
python "$script_path\score_feature_glycoform.py" `
--level transition `
--threads -1 `
--in "$result_osw_file" `
"--$(if ($test) { 'test' } else { 'no-test' })"
python "$script_path\infer_glycoforms.py" `
--in "$result_osw_file"
}
python "$script_path\infer_glycopeptides.py" `
--context global `
--in "$result_osw_file"
if (-not $enable_glycoform_inference) {
python "$script_path\export_results.py" `
--in "$result_osw_file" `
--out "$result_tsv_file" `
--format legacy_merged `
--no-glycoform `
--max_rs_peakgroup_qvalue 0.05 `
--max_global_glycopeptide_qvalue 0.01 `
--no-transition_quantification
}
else {
python "$script_path\export_results.py" `
--in "$result_osw_file" `
--out "$result_tsv_file" `
--format legacy_merged `
--glycoform --max_glycoform_qvalue 0.05 `
--max_rs_peakgroup_qvalue 0.05 `
--max_global_glycopeptide_qvalue 0.01 `
--no-transition_quantification
}
# TRIC
python $TRIC_path `
--in "$result_tsv_file" `
--out "$($result_tsv_file.Replace('.tsv', ''))_aligned.tsv" `
--file_format openswath `
--fdr_cutoff 0.01 `
--max_fdr_quality 0.2 `
--mst:useRTCorrection True `
--mst:Stdev_multiplier 3.0 `
--method LocalMST `
--max_rt_diff 90 `
--alignment_score 0.001 `
--frac_selected 0 `
--realign_method lowess `
--disable_isotopic_grouping
| 26.317308 | 71 | 0.685057 |
f53c758c664b1441bf66e91ebe6edeee27c2f88d | 15,606 | rs | Rust | cdn-api-app/cloudcdn/src/models.rs | BeanCloudServices/cloudcdn-api-service | 756bbed8cd1d3e1f81835d849b017a1ff55bcb1a | [
"MIT"
] | null | null | null | cdn-api-app/cloudcdn/src/models.rs | BeanCloudServices/cloudcdn-api-service | 756bbed8cd1d3e1f81835d849b017a1ff55bcb1a | [
"MIT"
] | null | null | null | cdn-api-app/cloudcdn/src/models.rs | BeanCloudServices/cloudcdn-api-service | 756bbed8cd1d3e1f81835d849b017a1ff55bcb1a | [
"MIT"
] | null | null | null | #![allow(unused_qualifications)]
#![allow(missing_docs)]
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
use crate::models;
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct DistributionUpsert {
#[serde(rename = "idempotencyKey")]
pub idempotency_key: String,
#[serde(rename = "id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<uuid::Uuid>,
}
impl DistributionUpsert {
pub fn new(idempotency_key: String) -> DistributionUpsert {
DistributionUpsert {
idempotency_key: idempotency_key,
id: None,
}
}
}
/// Converts the DistributionUpsert value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl std::string::ToString for DistributionUpsert {
fn to_string(&self) -> String {
let mut params: Vec<String> = vec![];
params.push("idempotencyKey".to_string());
params.push(self.idempotency_key.to_string());
// Skipping id in query parameter serialization
params.join(",").to_string()
}
}
/// Converts Query Parameters representation (style=form, explode=false) to a DistributionUpsert value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl std::str::FromStr for DistributionUpsert {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
#[derive(Default)]
// An intermediate representation of the struct to use for parsing.
struct IntermediateRep {
pub idempotency_key: Vec<String>,
pub id: Vec<uuid::Uuid>,
}
let mut intermediate_rep = IntermediateRep::default();
// Parse into intermediate representation
let mut string_iter = s.split(',').into_iter();
let mut key_result = string_iter.next();
while key_result.is_some() {
let val = match string_iter.next() {
Some(x) => x,
None => {
return std::result::Result::Err(
"Missing value while parsing DistributionUpsert".to_string(),
)
}
};
if let Some(key) = key_result {
match key {
"idempotencyKey" => intermediate_rep.idempotency_key.push(
<String as std::str::FromStr>::from_str(val)
.map_err(|x| format!("{}", x))?,
),
"id" => intermediate_rep.id.push(
<uuid::Uuid as std::str::FromStr>::from_str(val)
.map_err(|x| format!("{}", x))?,
),
_ => {
return std::result::Result::Err(
"Unexpected key while parsing DistributionUpsert".to_string(),
)
}
}
}
// Get the next key
key_result = string_iter.next();
}
// Use the intermediate representation to return the struct
std::result::Result::Ok(DistributionUpsert {
idempotency_key: intermediate_rep
.idempotency_key
.into_iter()
.next()
.ok_or("idempotencyKey missing in DistributionUpsert".to_string())?,
id: intermediate_rep.id.into_iter().next(),
})
}
}
// Methods for converting between header::IntoHeaderValue<DistributionUpsert> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<DistributionUpsert>>
for hyper::header::HeaderValue
{
type Error = String;
fn try_from(
hdr_value: header::IntoHeaderValue<DistributionUpsert>,
) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Invalid header value for DistributionUpsert - value: {} is invalid {}",
hdr_value, e
)),
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue>
for header::IntoHeaderValue<DistributionUpsert>
{
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <DistributionUpsert as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => {
std::result::Result::Ok(header::IntoHeaderValue(value))
}
std::result::Result::Err(err) => std::result::Result::Err(format!(
"Unable to convert header value '{}' into DistributionUpsert - {}",
value, err
)),
}
}
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Unable to convert header: {:?} to string: {}",
hdr_value, e
)),
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct DistributionUpsertAllOf {
#[serde(rename = "id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<uuid::Uuid>,
}
impl DistributionUpsertAllOf {
pub fn new() -> DistributionUpsertAllOf {
DistributionUpsertAllOf { id: None }
}
}
/// Converts the DistributionUpsertAllOf value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl std::string::ToString for DistributionUpsertAllOf {
fn to_string(&self) -> String {
let mut params: Vec<String> = vec![];
// Skipping id in query parameter serialization
params.join(",").to_string()
}
}
/// Converts Query Parameters representation (style=form, explode=false) to a DistributionUpsertAllOf value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl std::str::FromStr for DistributionUpsertAllOf {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
#[derive(Default)]
// An intermediate representation of the struct to use for parsing.
struct IntermediateRep {
pub id: Vec<uuid::Uuid>,
}
let mut intermediate_rep = IntermediateRep::default();
// Parse into intermediate representation
let mut string_iter = s.split(',').into_iter();
let mut key_result = string_iter.next();
while key_result.is_some() {
let val = match string_iter.next() {
Some(x) => x,
None => {
return std::result::Result::Err(
"Missing value while parsing DistributionUpsertAllOf".to_string(),
)
}
};
if let Some(key) = key_result {
match key {
"id" => intermediate_rep.id.push(
<uuid::Uuid as std::str::FromStr>::from_str(val)
.map_err(|x| format!("{}", x))?,
),
_ => {
return std::result::Result::Err(
"Unexpected key while parsing DistributionUpsertAllOf".to_string(),
)
}
}
}
// Get the next key
key_result = string_iter.next();
}
// Use the intermediate representation to return the struct
std::result::Result::Ok(DistributionUpsertAllOf {
id: intermediate_rep.id.into_iter().next(),
})
}
}
// Methods for converting between header::IntoHeaderValue<DistributionUpsertAllOf> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<DistributionUpsertAllOf>>
for hyper::header::HeaderValue
{
type Error = String;
fn try_from(
hdr_value: header::IntoHeaderValue<DistributionUpsertAllOf>,
) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Invalid header value for DistributionUpsertAllOf - value: {} is invalid {}",
hdr_value, e
)),
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue>
for header::IntoHeaderValue<DistributionUpsertAllOf>
{
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <DistributionUpsertAllOf as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => {
std::result::Result::Ok(header::IntoHeaderValue(value))
}
std::result::Result::Err(err) => std::result::Result::Err(format!(
"Unable to convert header value '{}' into DistributionUpsertAllOf - {}",
value, err
)),
}
}
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Unable to convert header: {:?} to string: {}",
hdr_value, e
)),
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct DistributionUpsertRequest {
#[serde(rename = "idempotencyKey")]
pub idempotency_key: String,
}
impl DistributionUpsertRequest {
pub fn new(idempotency_key: String) -> DistributionUpsertRequest {
DistributionUpsertRequest {
idempotency_key: idempotency_key,
}
}
}
/// Converts the DistributionUpsertRequest value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl std::string::ToString for DistributionUpsertRequest {
fn to_string(&self) -> String {
let mut params: Vec<String> = vec![];
params.push("idempotencyKey".to_string());
params.push(self.idempotency_key.to_string());
params.join(",").to_string()
}
}
/// Converts Query Parameters representation (style=form, explode=false) to a DistributionUpsertRequest value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl std::str::FromStr for DistributionUpsertRequest {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
#[derive(Default)]
// An intermediate representation of the struct to use for parsing.
struct IntermediateRep {
pub idempotency_key: Vec<String>,
}
let mut intermediate_rep = IntermediateRep::default();
// Parse into intermediate representation
let mut string_iter = s.split(',').into_iter();
let mut key_result = string_iter.next();
while key_result.is_some() {
let val = match string_iter.next() {
Some(x) => x,
None => {
return std::result::Result::Err(
"Missing value while parsing DistributionUpsertRequest".to_string(),
)
}
};
if let Some(key) = key_result {
match key {
"idempotencyKey" => intermediate_rep.idempotency_key.push(
<String as std::str::FromStr>::from_str(val)
.map_err(|x| format!("{}", x))?,
),
_ => {
return std::result::Result::Err(
"Unexpected key while parsing DistributionUpsertRequest".to_string(),
)
}
}
}
// Get the next key
key_result = string_iter.next();
}
// Use the intermediate representation to return the struct
std::result::Result::Ok(DistributionUpsertRequest {
idempotency_key: intermediate_rep
.idempotency_key
.into_iter()
.next()
.ok_or("idempotencyKey missing in DistributionUpsertRequest".to_string())?,
})
}
}
// Methods for converting between header::IntoHeaderValue<DistributionUpsertRequest> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<DistributionUpsertRequest>>
for hyper::header::HeaderValue
{
type Error = String;
fn try_from(
hdr_value: header::IntoHeaderValue<DistributionUpsertRequest>,
) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Invalid header value for DistributionUpsertRequest - value: {} is invalid {}",
hdr_value, e
)),
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue>
for header::IntoHeaderValue<DistributionUpsertRequest>
{
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <DistributionUpsertRequest as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => {
std::result::Result::Ok(header::IntoHeaderValue(value))
}
std::result::Result::Err(err) => std::result::Result::Err(format!(
"Unable to convert header value '{}' into DistributionUpsertRequest - {}",
value, err
)),
}
}
std::result::Result::Err(e) => std::result::Result::Err(format!(
"Unable to convert header: {:?} to string: {}",
hdr_value, e
)),
}
}
}
| 37.068884 | 115 | 0.569396 |
f58065bb550997342273f5bd1042fe01567824a1 | 4,454 | hpp | C++ | HugeCTR/include/data_simulator.hpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | HugeCTR/include/data_simulator.hpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | HugeCTR/include/data_simulator.hpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <gpu_resource.hpp>
#include <tensor2.hpp>
namespace HugeCTR {
class UniformGenerator {
public:
template <typename T>
static void fill(Tensor2<T>& tensor, T a, T b, size_t sm_count,
const curandGenerator_t& generator, const cudaStream_t& stream);
};
class HostUniformGenerator {
public:
template <typename T>
static void fill(Tensor2<T>& tensor, T a, T b, const curandGenerator_t& gen);
};
class NormalGenerator {
public:
template <typename T>
static void fill(Tensor2<T>& tensor, float mean, float stddev, size_t sm_count,
const curandGenerator_t& generator, const cudaStream_t& stream);
};
class HostNormalGenerator {
public:
template <typename T>
static void fill(Tensor2<T>& tensor, float mean, float stddev, const curandGenerator_t& gen);
};
class DataSimulator {
public:
virtual ~DataSimulator() {}
virtual void fill(Tensor2<float>& tensor, const curandGenerator_t& gen) = 0;
};
/*
* Wrap of Zeros and Ones initializer.
*/
class ConstantDataSimulator : public DataSimulator {
public:
ConstantDataSimulator(float value) : value_(value) {}
void fill(Tensor2<float>& tensor, const curandGenerator_t& gen) override;
private:
float value_;
};
class UniformDataSimulator : public DataSimulator {
public:
UniformDataSimulator(float min, float max) : min_(min), max_(max) {}
void fill(Tensor2<float>& tensor, const curandGenerator_t& gen) override;
private:
float min_;
float max_;
};
class GaussianDataSimulator : public DataSimulator {
public:
GaussianDataSimulator(float mu, float sigma, float min, float max) : mu_(mu), sigma_(sigma) {}
void fill(Tensor2<float>& tensor, const curandGenerator_t& gen) override;
private:
float mu_;
float sigma_;
};
namespace data_simu {
enum class Mode_t {
Fan_in, // number of input units in the weight tensor
Fan_out, // number of output units in the weight tensor
Fan_avg // average of the numbers of input and output units
};
enum class Distribution_t { Uniform, Norm };
} // namespace data_simu
class VarianceScalingSimulator : public DataSimulator {
public:
VarianceScalingSimulator(float scale, data_simu::Mode_t mode,
data_simu::Distribution_t distribution, float in_dim, float out_dim,
bool truncated = true)
: simulator_(nullptr), scale_(scale), truncated_(truncated) {
switch (mode) {
case data_simu::Mode_t::Fan_in: {
scale_ /= std::max(1.0f, in_dim);
break;
}
case data_simu::Mode_t::Fan_out: {
scale_ /= std::max(1.0f, out_dim);
break;
}
case data_simu::Mode_t::Fan_avg: {
scale_ /= std::max(1.0f, (in_dim + out_dim) / 2.f);
break;
}
default: {
ERROR_MESSAGE_("mode should be one of {Fan_in, Fan_out, Fan_avg}.");
break;
}
}
switch (distribution) {
case data_simu::Distribution_t::Uniform: {
float limit = sqrt(3.f * scale_);
simulator_.reset(new UniformDataSimulator(-1 * limit, limit));
break;
}
case data_simu::Distribution_t::Norm: {
if (truncated_) {
float stddev = sqrt(scale_) / .87962566103423978;
simulator_.reset(new GaussianDataSimulator(0, stddev, -2 * stddev, 2 * stddev));
} else {
float stddev = sqrt(scale_);
simulator_.reset(new GaussianDataSimulator(0, stddev, -10 * stddev, 10 * stddev));
}
break;
}
default: {
ERROR_MESSAGE_("distribution should be one of {Uniform, Norm}.");
break;
}
}
}
void fill(Tensor2<float>& tensor, const curandGenerator_t& gen) override {
simulator_->fill(tensor, gen);
}
private:
std::unique_ptr<DataSimulator> simulator_;
float scale_;
bool truncated_;
};
} // namespace HugeCTR
| 28.189873 | 96 | 0.67445 |
d2615d1b62e6c08c4b33f3d9a680e6234bfd866e | 853 | php | PHP | common/models/IndexBannerModel.php | fyxemmmm/pv_service | f4ea241f6d5883236e46673f549b5c7482cdf59f | [
"BSD-3-Clause"
] | null | null | null | common/models/IndexBannerModel.php | fyxemmmm/pv_service | f4ea241f6d5883236e46673f549b5c7482cdf59f | [
"BSD-3-Clause"
] | null | null | null | common/models/IndexBannerModel.php | fyxemmmm/pv_service | f4ea241f6d5883236e46673f549b5c7482cdf59f | [
"BSD-3-Clause"
] | null | null | null | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "index_banner".
*
* @property int $id
* @property string $img_url 图片地址
* @property int $type 类型 0:文章 1:电台
* @property int $data_id 数据id
*/
class IndexBannerModel extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'index_banner';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['type', 'data_id'], 'integer'],
[['img_url'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'img_url' => '图片地址',
'type' => '类型 0:文章 1:电台',
'data_id' => '数据id',
];
}
}
| 17.408163 | 52 | 0.479484 |
e7cf5b3367f3ab1185ab6d0a5cf308b544aebb71 | 63,212 | sql | SQL | closedaydata/OLD/IAT0106191008.sql | anbya/contohUploadKeGit | 4840b27f8a88410f22ddf9fd89df44137d0c3b33 | [
"MIT"
] | null | null | null | closedaydata/OLD/IAT0106191008.sql | anbya/contohUploadKeGit | 4840b27f8a88410f22ddf9fd89df44137d0c3b33 | [
"MIT"
] | null | null | null | closedaydata/OLD/IAT0106191008.sql | anbya/contohUploadKeGit | 4840b27f8a88410f22ddf9fd89df44137d0c3b33 | [
"MIT"
] | null | null | null | INSERT INTO pos_itemtemp VALUES("IATT190000525","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000525","193044","191001","192008","25000","1","25000","0","25000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193044"),
("IATT190000526","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000526","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000526","193036","191001","192006","36000","1","36000","0","36000","1","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000526","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000527","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","beef ","193002"),
("IATT190000527","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000528","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000528","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000528","193013","191001","192002","33000","1","33000","0","33000","1","1","1","IAT0106191008","NHO2018000007","PAID","beef","PEDAS"),
("IATT190000528","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000528","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000528","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000528","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000528","193029","191001","192004","27000","1","27000","0","27000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193029"),
("IATT190000529","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","chiken","193001"),
("IATT190000529","193034","191001","192005","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193034"),
("IATT190000529","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000529","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000530","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000530","193028","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193028"),
("IATT190000530","193028","191001","192003","43000","1","43000","0","43000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193028"),
("IATT190000530","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000530","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000531","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000531","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000531","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000531","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000531","193048","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000531","193048","191002","192010","8000","1","8000","0","8000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000531","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000531","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000531","193055","191002","192010","17000","1","17000","0","17000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000531","193053","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193053"),
("IATT190000531","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","2 SEKARANG 1 BUAT BUKA","193023"),
("IATT190000531","193023","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000531","193028","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","SEKARANG","193028"),
("IATT190000531","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","BUAT BUKA","193022"),
("IATT190000531","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","BUAT BUKA","193024"),
("IATT190000531","193023","191001","192003","30000","1","30000","0","30000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000531","193007","191001","192001","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","BUAT BUKA","PEDAS"),
("IATT190000531","193007","191001","192001","37000","1","37000","0","37000","2","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000531","193007","191001","192001","37000","1","37000","0","37000","3","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000531","193016","191001","192002","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","BUAT BUKA","PEDAS"),
("IATT190000532","193050","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193050"),
("IATT190000532","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000532","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000532","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000532","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000532","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000532","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000532","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","PEDAS"),
("IATT190000533","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","BUAT BUKA PUASA","193027"),
("IATT190000533","193035","191001","192006","32000","1","32000","0","32000","1","1","1","IAT0106191008","NHO2018000007","PAID","YANG SATU ORIGINAL,YANG SATU PEDESS","ORIGINAL"),
("IATT190000533","193035","191001","192006","32000","1","32000","0","32000","2","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000533","193028","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193028"),
("IATT190000533","193052","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193052"),
("IATT190000533","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000533","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000533","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","ES BATU 2","193049"),
("IATT190000534","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000534","193048","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000534","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000534","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","SEKARANG YA ","193022"),
("IATT190000534","193022","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000535","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000535","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000535","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000535","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","SEKARANG SEMUA","193022"),
("IATT190000535","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000535","193041","191001","192008","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193041"),
("IATT190000536","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000536","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000536","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000536","193048","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000536","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","SEMUA BUAT BUKA","193022"),
("IATT190000536","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000537","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000537","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000537","193055","191002","192010","17000","1","17000","0","17000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000537","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000537","193053","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193053"),
("IATT190000537","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHICKEN","193002"),
("IATT190000537","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000537","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000537","193024","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000538","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID"," SEDENG BEEF","PEDAS"),
("IATT190000538","193003","191001","192001","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000538","193004","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193004"),
("IATT190000538","193034","191001","192005","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193034"),
("IATT190000538","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000538","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000538","193052","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193052"),
("IATT190000539","193015","191001","192002","33000","1","33000","0","33000","1","1","1","IAT0106191008","NHO2018000007","PAID","MINTA KUAH","ORIGINAL"),
("IATT190000539","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000541","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000541","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000541","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000541","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000541","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000542","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID"," CHIKEN LVL 3 NYA 3. LVL 1 NYA 1","PEDAS"),
("IATT190000542","193003","191001","192001","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000542","193003","191001","192001","30000","1","30000","0","30000","3","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000542","193003","191001","192001","30000","1","30000","0","30000","4","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000542","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000542","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000542","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000542","193052","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193052"),
("IATT190000542","193024","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193024"),
("IATT190000542","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000542","193025","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000542","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000543","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000543","193022","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000543","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000543","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000544","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000544","193052","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193052"),
("IATT190000544","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000544","193011","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000544","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000545","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000545","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000545","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000545","193008","191001","192001","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","LVL 1 PEDAS","193008"),
("IATT190000545","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","LVL 1 BEEF","ORIGINAL"),
("IATT190000546","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000546","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000546","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","BEEF","193001"),
("IATT190000546","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000546","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000546","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000547","193011","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000547","193011","191001","192001","40000","1","40000","0","40000","2","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000547","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000547","193010","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193010"),
("IATT190000547","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000547","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000547","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000547","193055","191002","192010","17000","1","17000","0","17000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000547","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000547","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","ES","193048"),
("IATT190000547","193052","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193052"),
("IATT190000547","193054","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000536","193056","191002","192010","17000","1","17000","0","17000","2","1","2","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000532","193003","191001","192001","30000","1","30000","0","30000","2","1","2","IAT0106191008","NHO2018000007","PAID","CHIKEN","ORIGINAL"),
("IATT190000538","193040","191001","192008","20000","1","20000","0","20000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193040"),
("IATT190000549","193028","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193028"),
("IATT190000549","193028","191001","192003","43000","1","43000","0","43000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193028"),
("IATT190000549","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000549","193055","191002","192010","17000","1","17000","0","17000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000550","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000550","193022","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000550","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000550","193049","191002","192010","10000","1","10000","0","10000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000551","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000551","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","BEEF","PEDAS"),
("IATT190000551","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000551","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","KASIH GULA","193047"),
("IATT190000552","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000552","193022","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193022"),
("IATT190000552","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000552","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000553","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000553","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000553","193049","191002","192010","10000","1","10000","0","10000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000553","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000537","193003","191001","192001","30000","1","30000","0","30000","1","1","2","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000551","193048","191002","192010","8000","1","8000","0","8000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000553","193048","191002","192010","8000","1","8000","0","8000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000553","193001","191001","192001","30000","1","30000","0","30000","1","1","3","IAT0106191008","NHO2018000007","PAID","CHKEN","193001"),
("IATT190000554","193039","191001","192006","36000","1","36000","0","36000","1","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000554","193039","191001","192006","36000","1","36000","0","36000","2","1","1","IAT0106191008","NHO2018000007","PAID","","PEDAS"),
("IATT190000554","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000554","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000553","193023","191001","192003","30000","1","30000","0","30000","2","1","4","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000556","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000556","193050","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193050"),
("IATT190000556","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000556","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000557","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000556","193054","191002","192010","20000","1","20000","0","20000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193054"),
("IATT190000557","193023","191001","192003","30000","1","30000","0","30000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000557","193025","191001","192003","30000","1","30000","0","30000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000557","193047","191002","192010","8000","1","8000","0","8000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000557","193047","191002","192010","8000","1","8000","0","8000","2","1","2","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000557","193047","191002","192010","8000","1","8000","0","8000","3","1","2","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000557","193047","191002","192010","8000","1","8000","0","8000","4","1","2","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000557","193023","191001","192003","30000","1","30000","0","30000","2","1","2","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000557","193023","191001","192003","30000","1","30000","0","30000","3","1","2","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000552","193001","191001","192001","30000","1","30000","0","30000","1","1","2","IAT0106191008","NHO2018000007","PAID","CHIKEN","193001"),
("IATT190000558","193018","191001","192002","37000","1","37000","0","37000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000558","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000558","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193002"),
("IATT190000558","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000558","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000558","193047","191002","192010","8000","1","8000","0","8000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000558","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000559","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CKN","193002"),
("IATT190000559","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000559","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000559","193041","191001","192008","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193041"),
("IATT190000559","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000559","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000559","193047","191002","192010","8000","1","8000","0","8000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000560","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000560","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000560","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000560","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000560","193047","191002","192010","8000","1","8000","0","8000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000560","193025","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000542","193023","191001","192003","30000","1","30000","0","30000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000542","193023","191001","192003","30000","1","30000","0","30000","2","1","2","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000542","193025","191001","192003","30000","1","30000","0","30000","3","1","2","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000562","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000562","193040","191001","192008","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193040"),
("IATT190000562","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000562","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000561","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000561","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000561","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000561","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000563","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000563","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","ORIGINAL"),
("IATT190000564","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000564","193010","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193010"),
("IATT190000564","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000564","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000565","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193001"),
("IATT190000565","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000565","193049","191002","192010","10000","1","10000","0","10000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000565","193049","191002","192010","10000","1","10000","0","10000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193049"),
("IATT190000566","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193001"),
("IATT190000566","193027","191001","192003","43000","1","43000","0","43000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193027"),
("IATT190000566","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000566","193015","191001","192002","33000","1","33000","0","33000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000566","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000567","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000567","193053","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193053"),
("IATT190000567","193051","191002","192010","20000","1","20000","0","20000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193051"),
("IATT190000567","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193002"),
("IATT190000568","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000568","193033","191001","192005","42000","1","42000","0","42000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193033"),
("IATT190000568","193055","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000568","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000568","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000568","193023","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000569","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000569","193048","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000569","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000569","193044","191001","192008","25000","1","25000","0","25000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193044"),
("IATT190000569","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193002"),
("IATT190000542","193051","191002","192010","20000","1","20000","0","20000","1","1","3","IAT0106191008","NHO2018000007","PAID","","193051"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","3","1","4","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","4","1","4","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","5","1","4","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000542","193048","191002","192010","8000","1","8000","0","8000","6","1","4","IAT0106191008","NHO2018000007","PAID","","193048"),
("IATT190000570","193011","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000570","193033","191001","192005","42000","1","42000","0","42000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193033"),
("IATT190000570","193037","191001","192006","36000","1","36000","0","36000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000570","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000570","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000571","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000571","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKN","193001"),
("IATT190000571","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000571","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000572","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193001"),
("IATT190000572","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000572","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000573","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000573","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000573","193001","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHIKEN","193001"),
("IATT190000573","193033","191001","192005","42000","1","42000","0","42000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193033"),
("IATT190000573","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000573","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000574","193025","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000574","193025","191001","192003","30000","1","30000","0","30000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193025"),
("IATT190000574","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000574","193056","191002","192010","17000","1","17000","0","17000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193056"),
("IATT190000575","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000575","193032","191001","192004","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193032"),
("IATT190000575","193012","191001","192001","40000","1","40000","0","40000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193012"),
("IATT190000575","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000575","193047","191002","192010","8000","1","8000","0","8000","2","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000575","193047","191002","192010","8000","1","8000","0","8000","3","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000576","193035","191001","192006","32000","1","32000","0","32000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000576","193055","191002","192010","17000","1","17000","0","17000","1","1","2","IAT0106191008","NHO2018000007","PAID","","193055"),
("IATT190000577","193003","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHKEN","ORIGINAL"),
("IATT190000577","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000577","193023","191001","192003","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193023"),
("IATT190000578","193002","191001","192001","30000","1","30000","0","30000","1","1","1","IAT0106191008","NHO2018000007","PAID","CHKN","193002"),
("IATT190000578","193035","191001","192006","32000","1","32000","0","32000","1","1","1","IAT0106191008","NHO2018000007","PAID","","ORIGINAL"),
("IATT190000578","193047","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193047"),
("IATT190000578","193046","191002","192010","8000","1","8000","0","8000","1","1","1","IAT0106191008","NHO2018000007","PAID","","193046"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","1","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","2","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","3","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","4","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","5","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","6","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","7","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","8","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","9","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066"),
("IATT190000579","193066","191003","192011","0","1","0","0","0","10","1","1","IAT0106191008","NHO2018000007","PAID","","193066");
INSERT INTO pos_salestemp VALUES("IATT190000525","","1","68000","0","6800","0","74800","100000","01/06/2019","13:53","01/06/2019","13:55:19","ISU000004","tbl0010","CLOSED","1","","IATR190000505","","","","","IAT0106191008","NHO2018000007"),
("IATT190000526","","2","84000","0","8400","0","92400","100000","01/06/2019","14:16","01/06/2019","14:43:50","ISU000004","tbl0012","CLOSED","1","","IATR190000506","","","","","IAT0106191008","NHO2018000007"),
("IATT190000527","","1","38000","0","3800","0","41800","100000","01/06/2019","15:54","01/06/2019","17:15:56","ISU000004","tbl0020","CLOSED","1","","IATR190000508","","","","","IAT0106191008","NHO2018000007"),
("IATT190000528","","0","170000","0","17000","0","187000","200000","01/06/2019","16:50","01/06/2019","18:14:17","ISU000004","tbl0012","CLOSED","1","","IATR190000519","","","","","IAT0106191008","NHO2018000007"),
("IATT190000529","","2","83000","0","8300","0","91300","100000","01/06/2019","16:52","01/06/2019","16:53:25","ISU000004","tbl0005","CLOSED","1","","IATR190000507","","","","","IAT0106191008","NHO2018000007"),
("IATT190000530","","2","150000","0","15000","0","165000","200000","01/06/2019","16:54","01/06/2019","17:27:19","ISU000004","tbl0011","CLOSED","1","","IATR190000509","","","","","IAT0106191008","NHO2018000007"),
("IATT190000531","","4","469000","0","46900","0","515900","515900","01/06/2019","16:58","01/06/2019","17:44:48","ISU000004","tbl0017","CLOSED","1","","IATR190000511","","","","","IAT0106191008","NHO2018000007"),
("IATT190000532","","0","193000","0","19300","0","212300","214000","01/06/2019","17:05","01/06/2019","18:07:31","ISU000004","tbl0010","CLOSED","1","","IATR190000515","","","","","IAT0106191008","NHO2018000007"),
("IATT190000533","","4","208000","0","20800","0","228800","250000","01/06/2019","17:07","01/06/2019","18:09:42","ISU000004","tbl0014","CLOSED","1","","IATR190000516","","","","","IAT0106191008","NHO2018000007"),
("IATT190000534","","2","93000","0","9300","0","102300","104000","01/06/2019","17:08","01/06/2019","17:38:11","ISU000004","tbl0003","CLOSED","1","","IATR190000510","","","","","IAT0106191008","NHO2018000007"),
("IATT190000535","","2","113000","0","11300","0","124300","150000","01/06/2019","17:12","01/06/2019","18:25:16","ISU000004","tbl0024","CLOSED","1","","IATR190000522","","","","","IAT0106191008","NHO2018000007"),
("IATT190000536","","2","120000","0","12000","0","132000","132000","01/06/2019","17:13","01/06/2019","18:31:58","ISU000004","tbl0004","CLOSED","1","","IATR190000525","","","","","IAT0106191008","NHO2018000007"),
("IATT190000537","","2","229000","0","22900","0","251900","251900","01/06/2019","17:17","01/06/2019","18:13:12","ISU000004","tbl0015","CLOSED","1","","IATR190000518","","","","","IAT0106191008","NHO2018000007"),
("IATT190000538","","4","204000","0","20400","0","224400","250000","01/06/2019","17:19","01/06/2019","18:26:32","ISU000004","tbl0020","CLOSED","1","","IATR190000523","","","","","IAT0106191008","NHO2018000007"),
("IATT190000539","","1","41000","0","4100","0","45100","100000","01/06/2019","17:21","01/06/2019","18:01:46","ISU000004","tbl0007","CLOSED","1","","IATR190000512","","","","","IAT0106191008","NHO2018000007"),
("IATT190000540","","1","0","0","0","0","0","0","01/06/2019","17:21","01/06/2019","22:00:39","ISU000012","tbl0050","CANCELED","1","PERMINTAAN CUSTOMER","","","","","","IAT0106191008","NHO2018000007"),
("IATT190000541","","2","86000","0","8600","0","94600","100600","01/06/2019","17:22","01/06/2019","18:06:25","ISU000004","tbl0006","CLOSED","1","","IATR190000514","","","","","IAT0106191008","NHO2018000007"),
("IATT190000542","","4","485000","0","48500","0","533500","533500","01/06/2019","17:23","01/06/2019","19:23:25","ISU000004","tbl0022","CLOSED","1","","IATR190000541","","","","","IAT0106191008","NHO2018000007"),
("IATT190000543","","2","76000","0","7600","0","83600","83600","01/06/2019","17:28","01/06/2019","18:03:25","ISU000004","tbl0023","CLOSED","1","","IATR190000513","","","","","IAT0106191008","NHO2018000007"),
("IATT190000544","","2","128000","0","12800","0","140800","140800","01/06/2019","17:29","01/06/2019","18:11:28","ISU000004","tbl0013","CLOSED","1","","IATR190000517","","","","","IAT0106191008","NHO2018000007"),
("IATT190000545","","2","135000","0","13500","0","148500","148500","01/06/2019","17:30","01/06/2019","19:06:25","ISU000004","tbl0021","CLOSED","1","","IATR190000537","","","","","IAT0106191008","NHO2018000007"),
("IATT190000546","","3","139000","0","13900","0","152900","200000","01/06/2019","17:32","01/06/2019","18:32:28","ISU000004","tbl0001","CLOSED","1","","IATR190000526","","","","","IAT0106191008","NHO2018000007"),
("IATT190000547","","3","300000","0","30000","0","330000","350000","01/06/2019","17:32","01/06/2019","18:22:39","ISU000004","tbl0011","CLOSED","1","","IATR190000520","","","","","IAT0106191008","NHO2018000007"),
("IATT190000548","","0","0","0","0","0","0","0","01/06/2019","17:47","01/06/2019","22:00:45","ISU000012","tbl0003","CANCELED","1","PERMINTAAN CUSTOMER","","","","","","IAT0106191008","NHO2018000007"),
("IATT190000549","","2","120000","0","12000","0","132000","150000","01/06/2019","17:48","01/06/2019","19:01:17","ISU000004","tbl0008","CLOSED","1","","IATR190000535","","","","","IAT0106191008","NHO2018000007"),
("IATT190000550","","2","80000","0","8000","0","88000","88000","01/06/2019","17:49","01/06/2019","18:31:02","ISU000004","tbl0009","CLOSED","1","","IATR190000524","","","","","IAT0106191008","NHO2018000007"),
("IATT190000551","","2","93000","0","9300","0","102300","102300","01/06/2019","17:50","01/06/2019","18:24:07","ISU000004","tbl0048","CLOSED","1","","IATR190000521","","","","","IAT0106191008","NHO2018000007"),
("IATT190000552","","1","137000","0","13700","0","150700","150700","01/06/2019","17:51","01/06/2019","18:41:30","ISU000004","tbl0014","CLOSED","1","","IATR190000529","","","","","IAT0106191008","NHO2018000007"),
("IATT190000553","","2","126000","0","12600","0","138600","150000","01/06/2019","17:52","01/06/2019","18:33:48","ISU000004","tbl0002","CLOSED","1","","IATR190000527","","","","","IAT0106191008","NHO2018000007"),
("IATT190000554","","1","90000","0","9000","0","99000","100000","01/06/2019","18:14","01/06/2019","18:46:03","ISU000004","tbl0005","CLOSED","1","","IATR190000531","","","","","IAT0106191008","NHO2018000007"),
("IATT190000555","","0","0","0","0","0","0","0","01/06/2019","18:16","01/06/2019","18:16:31","ISU000004","tbl0006","CANCELED","1","PERMINTAAN CUSTOMER","","","","","","IAT0106191008","NHO2018000007"),
("IATT190000556","","2","121000","0","12100","0","133100","150000","01/06/2019","18:16","01/06/2019","18:38:42","ISU000004","tbl0006","CLOSED","1","","IATR190000528","","","","","IAT0106191008","NHO2018000007"),
("IATT190000557","","1","169000","0","16900","0","185900","200000","01/06/2019","18:19","01/06/2019","18:44:43","ISU000004","tbl0010","CLOSED","1","","IATR190000530","","","","","IAT0106191008","NHO2018000007"),
("IATT190000558","","2","142000","0","14200","0","156200","200200","01/06/2019","18:27","01/06/2019","18:56:11","ISU000004","tbl0013","CLOSED","1","","IATR190000533","","","","","IAT0106191008","NHO2018000007"),
("IATT190000559","","2","147000","0","14700","0","161700","161700","01/06/2019","18:28","01/06/2019","18:54:19","ISU000004","tbl0017","CLOSED","1","","IATR190000532","","","","","IAT0106191008","NHO2018000007"),
("IATT190000560","","2","114000","0","11400","0","125400","150000","01/06/2019","18:29","01/06/2019","19:12:59","ISU000004","tbl0012","CLOSED","1","","IATR190000539","","","","","IAT0106191008","NHO2018000007"),
("IATT190000561","","2","85000","0","8500","0","93500","100000","01/06/2019","18:35","01/06/2019","19:24:03","ISU000004","tbl0023","CLOSED","1","","IATR190000542","","","","","IAT0106191008","NHO2018000007"),
("IATT190000562","","2","68000","0","6800","0","74800","100000","01/06/2019","18:35","01/06/2019","19:00:19","ISU000004","tbl0024","CLOSED","1","","IATR190000534","","","","","IAT0106191008","NHO2018000007"),
("IATT190000563","","1","60000","0","6000","0","66000","100000","01/06/2019","18:37","01/06/2019","19:03:40","ISU000004","tbl0016","CLOSED","1","","IATR190000536","","","","","IAT0106191008","NHO2018000007"),
("IATT190000564","","2","86000","0","8600","0","94600","100000","01/06/2019","18:39","01/06/2019","19:25:09","ISU000004","tbl0009","CLOSED","1","","IATR190000543","","","","","IAT0106191008","NHO2018000007"),
("IATT190000565","","2","80000","0","8000","0","88000","100000","01/06/2019","18:46","01/06/2019","19:13:34","ISU000004","tbl0011","CLOSED","1","","IATR190000540","","","","","IAT0106191008","NHO2018000007"),
("IATT190000566","","2","144000","0","14400","0","158400","170400","01/06/2019","18:49","01/06/2019","19:40:37","ISU000004","tbl0020","CLOSED","1","","IATR190000546","","","","","IAT0106191008","NHO2018000007"),
("IATT190000567","","2","100000","0","10000","0","110000","110000","01/06/2019","18:51","01/06/2019","19:11:22","ISU000004","tbl0007","CLOSED","1","","IATR190000538","","","","","IAT0106191008","NHO2018000007"),
("IATT190000568","","0","144000","0","14400","0","158400","158400","01/06/2019","18:52","01/06/2019","19:47:49","ISU000004","tbl0010","CLOSED","1","","IATR190000548","","","","","IAT0106191008","NHO2018000007"),
("IATT190000569","","2","101000","0","10100","0","111100","112000","01/06/2019","19:06","01/06/2019","19:30:45","ISU000004","tbl0005","CLOSED","1","","IATR190000545","","","","","IAT0106191008","NHO2018000007"),
("IATT190000570","","2","134000","0","13400","0","147400","200000","01/06/2019","19:27","01/06/2019","19:29:03","ISU000004","tbl0024","CLOSED","1","","IATR190000544","","","","","IAT0106191008","NHO2018000007"),
("IATT190000571","","2","76000","0","7600","0","83600","100000","01/06/2019","19:31","01/06/2019","20:00:39","ISU000004","tbl0024","CLOSED","1","","IATR190000550","","","","","IAT0106191008","NHO2018000007"),
("IATT190000572","","2","46000","0","4600","0","50600","52000","01/06/2019","19:32","01/06/2019","19:50:35","ISU000004","tbl0017","CLOSED","1","","IATR190000549","","","","","IAT0106191008","NHO2018000007"),
("IATT190000573","","3","148000","0","14800","0","162800","200000","01/06/2019","19:43","01/06/2019","19:44:51","ISU000004","tbl0012","CLOSED","1","","IATR190000547","","","","","IAT0106191008","NHO2018000007"),
("IATT190000574","","2","85000","0","8500","0","93500","100500","01/06/2019","19:55","01/06/2019","20:22:30","ISU000004","tbl0011","CLOSED","1","","IATR190000551","","","","","IAT0106191008","NHO2018000007"),
("IATT190000575","","3","124000","0","12400","0","136400","136400","01/06/2019","19:58","01/06/2019","20:53:17","ISU000012","tbl0010","CLOSED","1","","IATR190000554","","","","","IAT0106191008","NHO2018000007"),
("IATT190000576","","1","49000","0","4900","0","53900","53900","01/06/2019","20:09","01/06/2019","20:24:49","ISU000004","tbl0018","CLOSED","1","","IATR190000552","","","","","IAT0106191008","NHO2018000007"),
("IATT190000577","","2","68000","0","6800","0","74800","74800","01/06/2019","20:39","01/06/2019","20:41:15","ISU000004","tbl0012","CLOSED","1","","IATR190000553","","","","","IAT0106191008","NHO2018000007"),
("IATT190000578","","2","78000","0","7800","0","85800","100900","01/06/2019","20:48","01/06/2019","21:19:08","ISU000012","tbl0011","CLOSED","1","","IATR190000555","","","","","IAT0106191008","NHO2018000007"),
("IATT190000579","","1","0","0","0","0","0","0","01/06/2019","21:34","01/06/2019","21:34:28","ISU000012","tbl0004","CLOSED","1","","IATR190000556","","","","","IAT0106191008","NHO2018000007");
INSERT INTO item_void VALUES("IATT190000548","IAT0106191008","NHO2018000007","193048","193048","1","8000","Before Send","Komplen Customer"),
("IATT190000553","IAT0106191008","NHO2018000007","193022","193022","1","30000","Before Send","Komplen Customer"),
("IATT190000553","IAT0106191008","NHO2018000007","193024","193024","1","30000","Before Send","Komplen Customer"),
("IATT190000556","IAT0106191008","NHO2018000007","193049","193049","1","10000","Before Send","Komplen Customer"),
("IATT190000552","IAT0106191008","NHO2018000007","193003","PEDAS","1","30000","Before Send","Komplen Customer");
INSERT INTO pos_paymenttemp VALUES("IATT190000525","CASH","CASH","74800","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000526","CASH","CASH","92400","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000529","CASH","CASH","91300","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000527","CASH","CASH","41800","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000530","CASH","CASH","165000","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000534","CASH","CASH","102300","104000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000531","CARD","VISA","515900","515900","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000539","CASH","CASH","45100","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000543","CARD","MASTER","83600","83600","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000541","CASH","CASH","94600","100600","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000532","CASH","CASH","212300","214000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000533","CASH","CASH","228800","250000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000544","CARD","VISA","140800","140800","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000537","CARD","DEBIT BCA","251900","251900","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000528","CASH","CASH","187000","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000547","CASH","CASH","330000","350000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000551","CARD","DEBIT BCA","102300","102300","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000535","CASH","CASH","124300","150000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000538","CASH","CASH","224400","250000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000550","CARD","DEBIT BCA","88000","88000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000536","CARD","DEBIT BCA","132000","132000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000546","CASH","CASH","152900","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000553","CASH","CASH","138600","150000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000556","CASH","CASH","133100","150000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000552","CARD","DEBIT BCA","150700","150700","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000557","CASH","CASH","185900","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000554","CASH","CASH","99000","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000559","CARD","MASTER","161700","161700","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000558","CASH","CASH","156200","200200","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000562","CASH","CASH","74800","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000549","CASH","CASH","132000","150000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000563","CASH","CASH","66000","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000545","CARD","MASTER","148500","148500","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000567","CASH","CASH","110000","110000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000560","CASH","CASH","125400","150000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000565","CASH","CASH","88000","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000542","CARD","MASTER","533500","533500","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000561","CASH","CASH","93500","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000564","CASH","CASH","94600","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000570","CASH","CASH","147400","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000569","CASH","CASH","111100","112000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000566","CASH","CASH","158400","170400","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000573","CASH","CASH","162800","200000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000568","CARD","MASTER","158400","158400","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000572","CASH","CASH","50600","52000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000571","CASH","CASH","83600","100000","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000574","CASH","CASH","93500","100500","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000576","CARD","MASTER","53900","53900","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000577","CARD","MASTER","74800","74800","ISU000004","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000575","CARD","VISA","136400","136400","ISU000012","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000578","CASH","CASH","85800","100900","ISU000012","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007"),
("IATT190000579","CASH","CASH","0","0","ISU000012","2019-06-01","","1","","CLOSED","IAT0106191008","NHO2018000007");
| 141.730942 | 240 | 0.616971 |
57b2af41775cc14ea02c3d0db95a50ba89df06e3 | 258 | go | Go | tests/disabled_vertices/plugin4/plugin4.go | spiral/endure | 047a8a29d230e5ff456f33e8e2d1b468127a5c0b | [
"MIT"
] | 22 | 2020-08-01T09:12:09.000Z | 2021-10-30T14:40:59.000Z | tests/disabled_vertices/plugin4/plugin4.go | spiral/endure | 047a8a29d230e5ff456f33e8e2d1b468127a5c0b | [
"MIT"
] | 61 | 2020-08-25T08:04:15.000Z | 2021-11-13T16:43:03.000Z | tests/disabled_vertices/plugin4/plugin4.go | spiral/endure | 047a8a29d230e5ff456f33e8e2d1b468127a5c0b | [
"MIT"
] | 2 | 2021-04-05T13:08:02.000Z | 2021-06-22T15:13:32.000Z | package plugin4
import "github.com/spiral/errors"
type Plugin4 struct {
}
func (p4 *Plugin4) Init() error {
return errors.E(errors.Op("plugin 4 init"), errors.Disabled)
}
func (p4 *Plugin4) FightWithEvil() string {
return "plugin4 is ready to fight"
}
| 17.2 | 61 | 0.717054 |
5bd23e07e17990d248d10abca2b9abc40d8a6b37 | 5,010 | cs | C# | RichardSzalay.MockHttp.Tests/Matchers/FormDataMatcherTests.cs | jozefizso/mockhttp | 5e6ddc84fe2d0d9a6eb77b0b78173f2786a3c992 | [
"MIT"
] | null | null | null | RichardSzalay.MockHttp.Tests/Matchers/FormDataMatcherTests.cs | jozefizso/mockhttp | 5e6ddc84fe2d0d9a6eb77b0b78173f2786a3c992 | [
"MIT"
] | null | null | null | RichardSzalay.MockHttp.Tests/Matchers/FormDataMatcherTests.cs | jozefizso/mockhttp | 5e6ddc84fe2d0d9a6eb77b0b78173f2786a3c992 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using RichardSzalay.MockHttp.Matchers;
using RichardSzalay.MockHttp.Tests.Infrastructure;
using Xunit;
namespace RichardSzalay.MockHttp.Tests.Matchers
{
public class FormDataMatcherTests
{
[Fact]
public void Should_match_in_order()
{
bool result = Test(
expected: "key1=value1&key2=value2",
actual: "key1=value1&key2=value2"
);
Assert.True(result);
}
[Fact]
public void Should_match_out_of_order()
{
bool result = Test(
expected: "key2=value2&key1=value1",
actual: "key1=value1&key2=value2"
);
Assert.True(result);
}
[Fact]
public void Should_match_multiple_values()
{
bool result = Test(
expected: "key1=value1&key1=value2",
actual: "key1=value2&key1=value1"
);
Assert.True(result);
}
[Fact]
public void Should_support_matching_empty_values()
{
bool result = Test(
expected: "key2=value2&key1",
actual: "key1&key2=value2"
);
Assert.True(result);
}
[Fact]
public void Should_fail_for_incorrect_values()
{
bool result = Test(
expected: "key1=value1&key2=value3",
actual: "key1=value1&key2=value2"
);
Assert.False(result);
}
[Fact]
public void Should_fail_for_missing_keys()
{
bool result = Test(
expected: "key2=value2&key1=value1",
actual: "key1=value1&key3=value3"
);
Assert.False(result);
}
[Fact]
public void Should_not_fail_for_additional_keys()
{
bool result = Test(
expected: "key1=value1&key2=value2",
actual: "key1=value1&key2=value2&key3=value3"
);
Assert.True(result);
}
private bool Test(string expected, string actual)
{
var sut = new FormDataMatcher(expected);
FormUrlEncodedContent content = new FormUrlEncodedContent(
HttpHelpers.ParseQueryString(actual)
);
return sut.Matches(new HttpRequestMessage(HttpMethod.Get,
"http://tempuri.org/home") { Content = content });
}
[Fact]
public void Should_fail_for_non_form_data()
{
var content = new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key=value"));
content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
var result = Test(
expected: "key=value",
actual: content
);
Assert.False(result);
}
[Fact]
public void Supports_multipart_formdata_content()
{
var content = new MultipartFormDataContent
{
new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key=value"))
};
var result = Test(
expected: "key=value",
actual: content
);
Assert.True(result);
}
[Fact]
public void Matches_form_data_across_multipart_entries()
{
var content = new MultipartFormDataContent
{
new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key1=value1")),
new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key2=value2"))
};
var result = Test(
expected: "key1=value1&key2=value2",
actual: content
);
Assert.True(result);
}
[Fact]
public void Does_not_match_form_data_on_non_form_data_multipart_entries()
{
var content = new MultipartFormDataContent
{
new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key1=value1")),
new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key2=value2"))
};
content.First().Headers.ContentType = new MediaTypeHeaderValue("text/plain");
var result = Test(
expected: "key1=value1&key2=value2",
actual: content
);
Assert.False(result);
}
private bool Test(string expected, HttpContent actual)
{
var sut = new FormDataMatcher(expected);
return sut.Matches(new HttpRequestMessage(HttpMethod.Get,
"http://tempuri.org/home") { Content = actual });
}
}
}
| 27.833333 | 95 | 0.533333 |
5bf10c102d3de7244942a2454c8d343e5129d662 | 3,595 | cs | C# | test/MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs | KKL1982/msgpack-cli | 825acdf1a8d4eb75fe9683f1410b2ee5855c6e21 | [
"Apache-2.0"
] | 677 | 2015-01-01T08:27:27.000Z | 2022-03-25T07:46:16.000Z | test/MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs | KKL1982/msgpack-cli | 825acdf1a8d4eb75fe9683f1410b2ee5855c6e21 | [
"Apache-2.0"
] | 276 | 2015-01-02T10:19:47.000Z | 2021-10-02T15:14:15.000Z | test/MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs | KKL1982/msgpack-cli | 825acdf1a8d4eb75fe9683f1410b2ee5855c6e21 | [
"Apache-2.0"
] | 172 | 2015-01-02T20:56:08.000Z | 2021-07-16T04:10:07.000Z | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
namespace MsgPack.Serialization
{
public class AppendableReadOnlyCollection<T> : IReadOnlyCollection<T>
{
private readonly List<T> _underlying;
public int Count
{
get { return this._underlying.Count; }
}
public AppendableReadOnlyCollection() : this( 0 ) { }
public AppendableReadOnlyCollection( int initialCapacity )
{
this._underlying = new List<T>( initialCapacity );
}
public void Add( T item )
{
this._underlying.Add( item );
}
public IEnumerator<T> GetEnumerator()
{
return this._underlying.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class AppendableReadOnlyList<T> : IReadOnlyList<T>
{
private readonly List<T> _underlying;
public T this[ int index ]
{
get { return this._underlying[ index ]; }
}
public int Count
{
get { return this._underlying.Count; }
}
public AppendableReadOnlyList() : this( 0 ) { }
public AppendableReadOnlyList( int initialCapacity )
{
this._underlying = new List<T>( initialCapacity );
}
public void Add( T item )
{
this._underlying.Add( item );
}
public IEnumerator<T> GetEnumerator()
{
return this._underlying.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class AppendableReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _underlying;
public IEnumerable<TKey> Keys
{
get { return this._underlying.Keys; }
}
public IEnumerable<TValue> Values
{
get { return this._underlying.Values; }
}
public TValue this[ TKey key ]
{
get { return this._underlying[ key ]; }
}
public int Count
{
get { return this._underlying.Count; }
}
public AppendableReadOnlyDictionary() : this( 0 ) { }
public AppendableReadOnlyDictionary( int initialCapacity )
{
this._underlying = new Dictionary<TKey, TValue>( initialCapacity );
}
public void Add( TKey key, TValue value )
{
this._underlying.Add( key, value );
}
public bool ContainsKey( TKey key )
{
return this._underlying.ContainsKey( key );
}
public bool TryGetValue( TKey key, out TValue value )
{
return this._underlying.TryGetValue( key, out value );
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return this._underlying.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| 22.753165 | 176 | 0.700695 |
7a531d56c568b37c181e80f2f25abf9a39460588 | 11,050 | rb | Ruby | app/pdfs/reporte_devolutions.rb | ShadowManu/SigulabRails | 9ce6d508ddae121d85c8bc1f4f9036fc79a1357e | [
"MIT"
] | null | null | null | app/pdfs/reporte_devolutions.rb | ShadowManu/SigulabRails | 9ce6d508ddae121d85c8bc1f4f9036fc79a1357e | [
"MIT"
] | null | null | null | app/pdfs/reporte_devolutions.rb | ShadowManu/SigulabRails | 9ce6d508ddae121d85c8bc1f4f9036fc79a1357e | [
"MIT"
] | null | null | null | # encoding: utf-8
class ReporteDevolutions < Prawn::Document
def initialize(devolution)
super()
@devolution = devolution
header
crear_tabla
contenido
pie_de_pagina
end
def header
#This inserts an image in the pdf file and sets the size of the image
image "#{Rails.root}/app/assets/images/coord.jpg", width: 180, height: 100, :position => 0
move_up 50
image "#{Rails.root}/app/assets/images/Logo_ULab.jpg", width: 50, height: 55, :position => 490
end
def pie_de_pagina
draw_text "Cod. Doc.: UL01-M01F09 Fecha: #{Time.now.strftime("%d-%m-%Y")}", :size => 6, :at => [1,20]
font("#{Prawn::DATADIR}/fonts/DejaVuSans.ttf") do
font_size 8
text_box "Universidad Simón Bolívar, Edif. Energética, Planta Baja. Valle de Sartenejas, Baruta, " +
"Caracas, Edo. Miranda, Venezuela, 89000", :at => [20,11], :height => 8
font_size 7
text_box "Telef.: +58 212 906-3708 / 3709 / 3710 / 3711 Fax: +58 212 906-3712", :at => [150,0], :height => 7
end
end
def crear_tabla
move_down 13
header = [[{:content => "NOTA DE DEVOLUCIÓN", :rowspan => 2, :width => 450, :size => 20, :background_color => "DDDDDD", :align => :center, :height => 20, :font_style => :bold},
{:content => "Registro No.", :background_color => "DDDDDD", :width => 90, :height => 18, :size => 9, :align => :center, :font_style => :bold}],
[{:content => "UL01/14-#{@devolution.numRegistro}", :background_color => "FFFFFF", :width => 90,:height => 18, :size => 9, :align => :center}],
]
cuerpo1 = [[{:width => 180, :height => 20},{:width => 180, :height => 20},{:width => 180, :height => 20}],
[{:width => 180, :height => 20},{:width => 180, :height => 20},{:width => 180, :height => 20}]
]
cuerpo2 = [[{:content => "UNIDAD SOLICITANTE", :align => :center, :size => 10, :height => 19, :font_style => :bold, :background_color => "959595", :width => 540}],
[{:content => "#{@devolution.unidadSolicitante}", :align => :center, :size => 10, :height => 19, :font_style => :bold, :background_color => "DDDDDD", :width => 540}],
[{:content => "CAUSA DE LA DEVOLUCIÓN", :align => :center, :size => 10, :height => 19, :font_style => :bold, :background_color => "959595", :width => 540}]
]
cuerpo3 = [[{:width => 290, :height => 180, :background_color => "DDDDDD"},{:content => "Carencia de Documentos:", :size => 10, :width => 250, :height => 180, :background_color => "DDDDDD"}]]
cuerpo4 = [[{:content => "OBSERVACIONES", :align => :center, :background_color => "959595", :height => 19, :width => 380, :size => 10, :font_style => :bold},
{:content => "Por la Coord. Adquisiciones:", :align => :center, :background_color => "959595", :height => 19, :width => 160, :size => 10, :font_style => :bold}]]
cuerpo5 = [[{:content => "#{@devolution.observaciones}", :align => :left, :size => 11, :height => 80, :width => 380},
{:align => :center, :height => 80, :width => 160}]]
table ([[header],[cuerpo1],[cuerpo2],[cuerpo3],[cuerpo4],[cuerpo5]])
end
def contenido
draw_text "Requisición No. #{@devolution.numRequisicion}", :size => 9, :at => [27,552]
draw_text "Autorización de Pago No. #{@devolution.numAutorizacion}", :size => 9, :at => [207,552]
draw_text "Certificación de servicio No. #{@devolution.numCertificacion}", :size => 9, :at => [387,552]
draw_text "Solicitud de servicio No. #{@devolution.numSolicitud}", :size => 9, :at => [27,534]
draw_text "Informe de recepción No. #{@devolution.numInforme}", :size => 9, :at => [207,534]
draw_text "Otro No. #{@devolution.numOtro}", :size => 9, :at => [387,534]
draw_text "Disponibilidad presupuestaria insuficiente", :size => 10, :at => [28,453]
draw_text "Registro en idioma distinto al español", :size => 10, :at => [28,433]
draw_text "Registro no discriminado por ítems", :size => 10, :at => [28,413]
draw_text "Registro sin la firma y/o sello de la Unidad Responsable", :size => 10, :at => [28,393]
draw_text "Carencia de información indispensable del proveedor", :size => 10, :at => [28,373]
draw_text " del bien o servicio:", :size => 10, :at => [26,360]
draw_text "Nombre", :at => [48,343], :size => 10
draw_text "Dirección Fiscal", :at => [48,323], :size => 10
draw_text "Datos Bancarios", :at => [48,303], :size => 10
draw_text "RIF", :at => [148,343], :size => 10
draw_text "Teléfonos", :at => [148,323], :size => 10
draw_text "Persona Contacto", :at => [148,303], :size => 10
draw_text "Otro", :at => [252,303], :size => 10
draw_text "Contrato Fonacit, si aplica", :at => [318,434], :size => 10
draw_text "Copia del Acta del Consejo Directo que autorice", :at => [318,414], :size => 10
draw_text "la Contratación Pública (Compras mayores de", :at => [318,401], :size => 10
draw_text "2.500 UT), si es aplicable", :at => [318,388], :size => 10
draw_text "Factura, Proforma o Cotización a nombre de la", :at => [318,368], :size => 10
draw_text "USB, indicando la condición de entrega.", :at => [318,355], :size => 10
draw_text "Foto Referencial del Material y/o Equipo", :at => [318,335], :size => 10
draw_text "solicitado", :at => [318,322], :size => 10
draw_text "Fecha: #{Time.now.strftime("%d-%m-%Y")}", :size => 9, :at => [423,200]
if @devolution.requisicion == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,564]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,564]
end
if @devolution.autorizacion == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [188,564]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [188,564]
end
if @devolution.certificacion == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [368,564]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [368,564]
end
if @devolution.solicitud == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,544]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,544]
end
if @devolution.informe == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [188,544]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [188,544]
end
if @devolution.otro == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [368,544]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [368,544]
end
##################################
if @devolution.disponibilidad == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,464]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,464]
end
if @devolution.idioma == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,444]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,444]
end
if @devolution.discriminado == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,424]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,424]
end
if @devolution.firma == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,404]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,404]
end
if @devolution.carencia == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [8,384]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [8,384]
end
if @devolution.nombre == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [28,354]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [28,354]
end
if @devolution.direccion == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [28,334]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [28,334]
end
if @devolution.datos == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [28,314]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [28,314]
end
if @devolution.rif == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [128,354]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [128,354]
end
if @devolution.telefonos == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [128,334]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [128,334]
end
if @devolution.persona == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [128,314]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [128,314]
end
if @devolution.otroCarencia == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [228,314]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [232,314]
end
if @devolution.contacto == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [298,444]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [298,444]
end
if @devolution.copia == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [298,424]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [298,424]
end
if @devolution.factura == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [298,378]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [298,378]
end
if @devolution.foto == true
image "#{Rails.root}/app/assets/images/marcado.png", :width => 15, :height => 15, :at => [298,345]
else
image "#{Rails.root}/app/assets/images/cuadrado.png", :width => 15, :height => 15, :at => [298,345]
end
end
end | 43.333333 | 194 | 0.600814 |
dc092b83001f8857d31c7d183657775132f469d8 | 1,503 | py | Python | queue_services/common/tests/integration/test_queue_connections.py | argush3/lear | 804820ea93a9ca44d1a474ce7a903bb0a808aacb | [
"Apache-2.0"
] | 8 | 2019-06-19T16:16:15.000Z | 2021-08-28T23:56:40.000Z | queue_services/common/tests/integration/test_queue_connections.py | argush3/lear | 804820ea93a9ca44d1a474ce7a903bb0a808aacb | [
"Apache-2.0"
] | 796 | 2019-03-07T19:25:50.000Z | 2022-03-31T20:32:57.000Z | queue_services/common/tests/integration/test_queue_connections.py | argush3/lear | 804820ea93a9ca44d1a474ce7a903bb0a808aacb | [
"Apache-2.0"
] | 82 | 2019-01-30T20:06:14.000Z | 2022-03-29T20:38:31.000Z | # Copyright © 2019 Province of British Columbia
#
# 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.
"""The Test Suite to ensure queue connections are working as expected."""
import pytest
from nats.aio.client import Client as Nats
from stan.aio.client import Client as Stan
from stan.aio.errors import StanError
@pytest.mark.asyncio
async def test_queue_connection(stan_server, event_loop, client_id):
"""Assert that we connect to the queue configuration used by the tests."""
nc = Nats()
await nc.connect(loop=event_loop)
sc = Stan()
await sc.connect('test-cluster', client_id, nats=nc)
assert sc._pub_prefix # pylint: disable=protected-access; sc does not expose a connection check
assert sc._conn_id # pylint: disable=protected-access; sc does not expose a connection check
await sc.close() # should not close the connection
assert nc.is_connected
with pytest.raises(StanError):
await sc.close()
await nc.close()
assert not nc.is_connected
| 36.658537 | 100 | 0.745176 |
de0ca0f887fce974b057103456f524473630baaf | 7,077 | lua | Lua | libs/string.lua | truemedian/lua-extensions | 657a67043742368e8917cf3cf0e6b10df595ee3a | [
"MIT"
] | null | null | null | libs/string.lua | truemedian/lua-extensions | 657a67043742368e8917cf3cf0e6b10df595ee3a | [
"MIT"
] | null | null | null | libs/string.lua | truemedian/lua-extensions | 657a67043742368e8917cf3cf0e6b10df595ee3a | [
"MIT"
] | null | null | null | ---Extensions to the Lua standard string library.
---@module extensions.string
---@alias ext_string
local byte, char, find, gsub, len = string.byte, string.char, string.find, string.gsub, string.len
local match, rep, sub, upper = string.match, string.rep, string.sub, string.upper
local concat, insert = table.concat, table.insert
local ceil, floor, min, random = math.ceil, math.floor, math.min, math.random
local ext_string = {}
for k, v in pairs(string) do
ext_string[k] = v
end
---Returns whether or not the string ends with `pattern`. Use `plain` if you want to match `pattern` literally.
---@param str string
---@param pattern string
---@param[opt] plain boolean
---@return boolean
function ext_string.endswith(str, pattern, plain)
return select(2, find(str, pattern, 1, plain)) == #str
end
local pattern_special = [[^$()%.[]*+-?]]
local pattern_match = '[' .. pattern_special:gsub('.', '%%%1') .. ']'
---Returns a new string with all Lua Pattern special characters escaped.
---@param str string
---@return boolean
function ext_string.patternescape(str)
return (gsub(str, pattern_match, '%%%1'))
end
---Returns whether or not the string starts with `pattern`. Use `plain` if you want to match `pattern` literally.
---@param str string
---@param pattern string
---@param[opt] plain boolean
---@return boolean
function ext_string.startswith(str, pattern, plain)
return find(str, pattern, 1, plain) == 1
end
---Returns a new string with all leading and trailing whitespace removed.
---@param str string
---@return string
function ext_string.trim(str)
return match(str, '^%s*(.-)%s*$')
end
---Returns a new string with the left padded with `pattern` or spaces until the string is `final_len` characters long.
---@param str string
---@param final_len number
---@param[opt] pattern string
---@return string
function ext_string.padright(str, final_len, pattern)
pattern = pattern or ' '
return rep(pattern, (final_len - #str) / #pattern) .. str
end
---Returns a new string with both sides padded with `pattern` or spaces until the string is `final_len` characters long.
---@param str string
---@param final_len number
---@param[opt] pattern string
---@return string
function ext_string.padcenter(str, final_len, pattern)
pattern = pattern or ' '
local pad = 0.5 * (final_len - #str) / #pattern
return rep(pattern, floor(pad)) .. str .. rep(pattern, ceil(pad))
end
---Returns a new string with the right padded with `pattern` or spaces until the string is `final_len` characters long.
---@param str string
---@param final_len number
---@param[opt] pattern string
---@return string
function ext_string.padleft(str, final_len, pattern)
pattern = pattern or ' '
return str .. rep(pattern, (final_len - #str) / #pattern)
end
---Returns a new string with the right, left, or both sides padded with `pattern` or spaces until the string is `final_len` characters long.
---The alignment parameter denotes where the original string should be after padding. (eg. "left" will pad the right side)
---@param str string
---@param final_len number
---@param align "right"|"left"|"center"
---@param[opt] pattern string
---@return string
function ext_string.pad(str, final_len, align, pattern)
if align == 'right' then
return ext_string.padright(str, final_len, pattern)
elseif align == 'center' then
return ext_string.padcenter(str, final_len, pattern)
else -- left
return ext_string.padleft(str, final_len, pattern)
end
end
---Returns a table of all elements of the string split on `delim`. Use `plain` if the delimiter provided is not a pattern.
---@param str string
---@param[opt] delim string
---@param[opt] plain boolean
---@return table
function ext_string.split(str, delim, plain)
local ret = {}
if not str or str == '' then
return ret
end
if not delim or delim == '' then
for i = 1, #str do
ret[i] = byte(str, i)
end
return ret
end
local p = 1
while true do
local i, j = find(str, delim, p, plain)
if not i then
break
end
insert(ret, sub(str, p, i - 1))
p = j + 1
end
insert(ret, sub(str, p))
return ret
end
---Returns a string of `final_len` random characters in the byte-range of `[mn, mx]`. By default `mn = 0` and `mx = 255`.
---@param final_len number
---@param[opt] mn number
---@param[opt] mx number
---@return string
function ext_string.random(final_len, mn, mx)
local ret = {}
mn = mn or 0
mx = mx or 255
for _ = 1, final_len do
insert(ret, char(random(mn, mx)))
end
return concat(ret)
end
---Returns the Levenshtein distance between the two strings. This is often referred as "edit distance".
---[Wikipedia "Levenshtein Distance"](https://en.wikipedia.org/wiki/Levenshtein_distance)
---@param str1 string
---@param str2 string
---@return number
function ext_string.levenshtein(str1, str2)
if str1 == str2 then
return 0
end
local len1 = len(str1)
local len2 = len(str2)
if len1 == 0 then
return len2
elseif len2 == 0 then
return len1
end
local matrix = {}
for i = 0, len1 do
matrix[i] = {[0] = i}
end
for j = 0, len2 do
matrix[0][j] = j
end
for i = 1, len1 do
for j = 1, len2 do
local cost = byte(str1, i) == byte(str2, j) and 0 or 1
matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
end
end
return matrix[len1][len2]
end
---Returns the Damerau-Levenshtein distance between the two strings. This is often referred as "edit distance".
---[Wikipedia "Damerau-Levenshtein Distance"](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
---@param str1 string
---@param str2 string
---@return number
function ext_string.dameraulevenshtein(str1, str2)
if str1 == str2 then
return 0
end
local len1 = len(str1)
local len2 = len(str2)
if len1 == 0 then
return len2
elseif len2 == 0 then
return len1
end
local matrix = {}
for i = 0, len1 do
matrix[i] = {[0] = i}
end
for j = 0, len2 do
matrix[0][j] = j
end
for i = 1, len1 do
for j = 1, len2 do
local cost = byte(str1, i) == byte(str2, j) and 0 or 1
matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
if i > 1 and j > 1 and byte(str1, i) == byte(str2, j - 1) and byte(str1, i - 1) == byte(str2, j) then
matrix[i][j] = min(matrix[i][j], matrix[i - 2][j - 2] + 1)
end
end
end
return matrix[len1][len2]
end
---Returns true if the subsequence can be found inside `str`.
---For example: `ggl` is a subsequence of `GooGLe`. (uppercase letters signify which letters form the subsequence).
---@param subseq string
---@param str string
---@return boolean
function ext_string.subsequencematch(subseq, str)
local matches = 0
for i = 1, len(str) do
if byte(subseq, matches + 1) == byte(str, i) then
matches = matches + 1
end
end
return matches == len(subseq)
end
---Returns a copy of this string with the first and every letter after a word boundary uppercased, and everything else lowercase
---@param str string
---@return string
function ext_string.title(str)
return str:sub(1, 1):upper() .. str:sub(2):lower():gsub('%W%w', upper)
end
return ext_string
| 27.752941 | 140 | 0.687297 |
62d13c8ef7e99f7f74a695b875e3692d87609bde | 63 | rs | Rust | src/internals/mod.rs | Lol3rrr/hc-vault | adbc35dc436be1c84edf76b3f47054d298454801 | [
"MIT"
] | 4 | 2021-02-10T14:36:54.000Z | 2021-10-03T21:30:19.000Z | src/internals/mod.rs | Lol3rrr/hc-vault | adbc35dc436be1c84edf76b3f47054d298454801 | [
"MIT"
] | 3 | 2020-12-20T12:01:55.000Z | 2020-12-30T01:17:07.000Z | src/internals/mod.rs | Lol3rrr/hc-vault | adbc35dc436be1c84edf76b3f47054d298454801 | [
"MIT"
] | null | null | null | mod token_container;
pub use token_container::TokenContainer;
| 15.75 | 40 | 0.84127 |
b927c40a38cdecd2977e2df3204f3c9bf2044eb7 | 208 | h | C | LWModuleDemo/BeeHive/RootModule.h | AloesLu/LWModuleDemo | a4de03e7330409ead3c2852f2a03df78ee3cd301 | [
"MIT"
] | null | null | null | LWModuleDemo/BeeHive/RootModule.h | AloesLu/LWModuleDemo | a4de03e7330409ead3c2852f2a03df78ee3cd301 | [
"MIT"
] | 1 | 2017-06-26T09:40:31.000Z | 2017-06-26T09:40:31.000Z | LWModuleDemo/BeeHive/RootModule.h | AloesLu/LWModuleDemo | a4de03e7330409ead3c2852f2a03df78ee3cd301 | [
"MIT"
] | null | null | null | //
// RootModule.h
// LWModuleDemo
//
// Created by AloesLu on 2016/10/24.
// Copyright © 2016年 AloesLu. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface RootModule : NSObject
@end
| 14.857143 | 51 | 0.692308 |
711912d573a740c198ece8f9b9df292358a5ea86 | 64,830 | asm | Assembly | src/strcvtf.asm | majioa/faststring | ec42f805116940b8effa0a3adc0db82318b540de | [
"MIT"
] | 1 | 2021-01-16T08:11:27.000Z | 2021-01-16T08:11:27.000Z | src/strcvtf.asm | majioa/faststring | ec42f805116940b8effa0a3adc0db82318b540de | [
"MIT"
] | null | null | null | src/strcvtf.asm | majioa/faststring | ec42f805116940b8effa0a3adc0db82318b540de | [
"MIT"
] | null | null | null | .386
.model flat
include constant.inc
PUBLIC @FastString@$oo$xqqrv
PUBLIC @FastString@$oc$xqqrv
PUBLIC @FastString@$ozc$xqqrv
PUBLIC @FastString@$ouc$xqqrv
PUBLIC @FastString@$os$xqqrv
PUBLIC @FastString@$ous$xqqrv
PUBLIC @FastString@$oi$xqqrv
PUBLIC @FastString@$ol$xqqrv
PUBLIC @FastString@$oui$xqqrv
PUBLIC @FastString@$oul$xqqrv
PUBLIC @FastString@$oj$xqqrv
PUBLIC @FastString@$ouj$xqqrv
PUBLIC @FastString@$of$xqqrv
PUBLIC @FastString@$od$xqqrv
PUBLIC @FastString@$og$xqqrv
PUBLIC @FastString@$opv$xqqrv
PUBLIC @FastString@$opb$qqrv
PUBLIC @FastString@$opc$qqrv
PUBLIC @FastString@$o17System@AnsiString$qqrv
PUBLIC @FastString@$o17System@WideString$qqrv
PUBLIC @FastString@ConvertTo$qqrul
PUBLIC @FastString@SetCodePage$qqrul
PUBLIC Floating_point_symbol
PUBLIC Positive_sign_symbol
PUBLIC Negative_sign_symbol
EXTRN decimal_constant:dword
; EXTRN GetDecimalSeparator:near
; EXTRN GetPositiveSign:near
; EXTRN GetNegativeSign:near
; PUBLIC StringBufferSize
; PUBLIC StringCopy
; PUBLIC OleStrBufferSize
; PUBLIC OleStrCopy
; PUBLIC ToString
; PUBLIC ToOleStr
PARAMETER_SYMBOL = 1
FUNCTION_SYMBOL = 2
;MINUS_SIGN = 80h
POS_VALUE = 40h
NEG_VALUE = 80h
;HEX_SIGN = 40h
FLOAT_VALUE = 1
EXP_VALUE = 2
HEX_VALUE = 3
OCTAL_VALUE = 4
BIN_VALUE = 5
;POSTFIX_FLAG = 1
SIGN_FLAG = 1
FLOAT_DOT_FLAG = 2
SEPARATOR_FLAG = 4
MODE_FLAG = 8
EXP_FLAG = 16
NUMBER_FLAG = 32
MODE_ZERO_FLAG = 64
ZERO_FLAG = 128
;CHECKSYMVALUE union
;Function dd ?
;Symbol dw ?
;CHECKSYMVALUE ends
;CHECKSYMBOL struc
;Symbol db ?
;Value CHECKSYMVALUE ?
;Value dd ?
;ExitCode db ?
;Flag db ?
;CHECKSYMBOL ends
SYMBOL struc
Byte db ? ;Symbol 8 bit
Byte_ru db ? ;Symbol 8 bit russian
Word db ? ;Symbol 16 bit
Rutf db ? ;Symbol Rutf
SYMBOL ends
CHECKSYMBOL struc
Ptr dd ? ;ptr to symbol for check
Value db ? ;value of symbol
SymType db ? ;type of symbol
Mask db ? ;mask allowing following symbols
Degree db ? ;degree of divider
CHECKSYMBOL ends
RUSSIAN_CP_COUNT = 6
.code
GetStrLenForConvert proc near
ConvertInit:
;in
;esi: buffer
;ecx: maximum strlen
;ebp: -1: signed value, 1: unsigned value
;out
;ecx: number length
;ebp: sign
;edx: destroyed
;ebx: 1
;df: true
;edi: 0
;eax: 0: end of string found, 1: floating point found
stc
rcl ebp, 1
xor ebx, ebx
push ecx
; call GetNegativeSign
cmp al, [esi]
jz short GetStrLenForConvert_loop1
GetStrLenForConvert_plus:
dec ebp
; call GetPositiveSign
cmp al, [esi]
jnz short GetStrLenForConvert_loop2
GetStrLenForConvert_loop1:
inc esi
GetStrLenForConvert_loop2:
; call GetDecimalSeparator
mov edx, eax
pop ecx
GetStrLenForConvert_loop:
lodsb
or al, al
jz short GetStrLenForConvert_loop_exit2
cmp al, 'e'
jz short GetStrLenForConvert_loop_exit
cmp al, 'E'
jz short GetStrLenForConvert_loop_exit
cmp al, dl
jz short GetStrLenForConvert_loop_exit1
cmp al, '9'
ja short GetStrLenForConvert_error
cmp al, '0'
jb short GetStrLenForConvert_error
GetStrLenForConvert_next:
inc ch
cmp cl, ch
jb short GetStrLenForConvert_error
jmp short GetStrLenForConvert_loop
GetStrLenForConvert_loop_exit:
inc ebx
GetStrLenForConvert_loop_exit1:
inc ebx
; xor eax, eax
; inc eax
; jmp short GetStrLenForConvert_loop_exit2
GetStrLenForConvert_loop_exit2:
; xor eax, eax
;GetStrLenForConvert_loop_exit3:
mov eax, ebx
xchg cl, ch
xor ch, ch
pushf
or byte ptr[esp+1], 4
popf
sub esi, 2
xor ebx, ebx
mov edi, ebx
inc ebx
ret
GetStrLenForConvert_error:
stc
ret
GetStrLenForConvert endp
InitFloatConvert proc near
ret
InitFloatConvert endp
StringToFloat proc near
;in
;eax: input string
;st(0): default value
pushf
push ebx
push esi
push edi
push ebp
mov esi, eax
xor eax, eax
sub esp, 12*4+4
lea ebp, [esp+12*4+4-12]
mov ecx, 3
StringToFloat_loop:
push ecx
push ebp
pushf
mov cl, 20
call ConvertInit
jnc short StringToFloat_init_ok
or eax, eax
jz short StringToFloat_error1
StringToFloat_init_ok:
push eax
call QwordConvert
pop ebx
jc short StringToFloat_error1
popf
pop ebp
mov [ebp],eax
mov [ebp+4],edx
mov [ebp+8],ecx
sub ebp, 12
pop ecx
mov [esp+ecx+12*4-1], bl
or ebx, ebx
loopz short StringToFloat_loop
jnz short StringToFloat_pop_exit
mov cl, 2
lea ebp, [esp+12*3]
fld qword ptr[ebp]
xor ebx, ebx
StringToFloat_loop1:
sub ebp, 12
mov bl, [esp+ecx+12*4-1]
or ebx, ebx
jz short StringToFloat_loop1_exit
dec ebx
jnz short StringToFloat_loop1_exp
fild qword ptr[ebp]
fild dword ptr[ebp+8]
fldl2t
fmulp
f2xm1
fdivp
faddp
jmp short StringToFloat_loop1_next
StringToFloat_loop1_exp:
fld qword ptr[ebp]
fscale
StringToFloat_loop1_next:
loop short StringToFloat_loop1
StringToFloat_loop1_exit:
;StringToFloat_pop_exit1:
; pop edx
; pop eax
ffree st(1)
StringToFloat_pop_exit:
add esp, 12*4+4
pop ebp
pop edi
pop esi
pop ebx
popf
ret
StringToFloat_error1:
popf
pop ebp
pop ecx
jmp short StringToFloat_pop_exit
;StringToFloat_floating_point:
; mov esi, eax
; mov ecx, 10
; call InitFloatConvert
; jc StringToInt_error
;StringToFloat_loop1:
; xor eax, eax
; lodsb
; sub al, '0'
; mul ebx
; or edx, edx
; jnz StringToInt_error
; add edi, eax
; dec ecx
; jecxz short StringToFloat_loop1_exit
; mov eax, 10
; mul ebx
; mov ebx, eax
; jmp short StringToFloat_loop1
;StringToFloat_loop1_exit:
; mov eax, edi
; or ebp, ebp
; jz short StringToInt_pop_exit
; neg eax
; jns short StringToInt_error;///??? comp to 0????
; jmp short StringToInt_pop_exit
StringToFloat endp
StringToQword proc near
;in
;eax: input string
;edx: ecx: default value
pushf
push ebx
push esi
push edi
push ebp
push edx
push ecx
mov esi, eax
mov ecx, 20
call ConvertInit
jc short StringToQword_pop_exit
call QwordConvert
jc short StringToQword_pop_exit
mov [esp], eax
mov [esp+4], edx
StringToQword_pop_exit:
pop eax
pop edx
pop ebp
pop edi
pop esi
pop ebx
popf
ret
StringToQword endp
StringToInt proc near
;in
;eax: input string
;edx: default value
pushf
push ebx
push esi
push edi
push edx
mov esi, eax
mov ecx, 10
call ConvertInit
jc short StringToInt_error
StringToInt_loop1:
xor eax, eax
lodsb
sub al, '0'
mul ebx
or edx, edx
jnz short StringToInt_error
add edi, eax
dec ecx
jecxz short StringToInt_loop1_exit
mov eax, [decimal_constant]
mul ebx
mov ebx, eax
jmp short StringToInt_loop1
StringToInt_loop1_exit:
mov eax, edi
test ebp, eax
js short StringToInt_error;///??? comp to 0????
shr ebp, 1
jnc short StringToInt_pop_exit
neg eax
jns short StringToInt_error;///??? comp to 0????
StringToInt_pop_exit:
mov [esp], eax
StringToInt_error:
pop eax
pop edi
pop esi
pop ebx
popf
ret
StringToInt endp
StringToWord proc near
;in
;eax: input string
;edx: default value
push esi
push edx
mov esi, eax
mov ecx, 5
call ConvertInit
jc short StringToWord_error
StringToWord_loop1:
xor eax, eax
lodsb
sub al, '0'
mul bx
or dx, dx
jnz short StringToWord_error
add di, ax
dec ecx
jecxz short StringToWord_loop1_exit
mov eax, [decimal_constant]
mul ebx
mov ebx, eax
jmp short StringToWord_loop1
StringToWord_loop1_exit:
mov ax, di
test bp, ax
js short StringToWord_error;///??? comp to 0????
shr ebp, 1
jnc short StringToWord_pop_exit
neg ax
jns short StringToWord_error;///??? comp to 0????
StringToWord_pop_exit:
mov [esp], eax
StringToWord_error:
pop eax
pop esi
ret
StringToWord endp
StringToByte proc near
;in
;eax: input string
;edx: default value
push esi
push edx
mov esi, eax
mov ecx, 3
call ConvertInit
jc short StringToWord_error
xor eax, eax
StringToByte_loop1:
lodsb
sub al, '0'
mul bl
or ah, ah
jnz short StringToWord_error
add edi, eax
dec ecx
jecxz short StringToByte_loop1_exit
mov al, byte ptr[decimal_constant]
mul bl
mov bl, al
jmp short StringToByte_loop1
StringToByte_loop1_exit:
mov eax, edi
mov ebx, ebp
test bl, al
js short StringToWord_error;///??? comp to 0????
shr ebp, 1
jnc StringToWord_pop_exit
neg al
jns StringToWord_error;///??? comp to 0????
jmp StringToWord_pop_exit
StringToByte endp
;convert long values
;ftol proc near
; fstcw [flags]
; mov al,byte ptr[flags+1]
; or byte ptr[flags+1],0ch
; fldcw [flags]
; fistp qword ptr[temp]
; mov byte ptr[flags+1],al
; fldcw [flags]
; mov eax, [temp]
; mov edx, [temp+4]
; ret
;ftol endp
;ftoqw proc near
; fstcw [flags]
; mov al,byte ptr[flags+1]
; or byte ptr[flags+1],0ch
; fldcw [flags]
; fistp qword ptr[temp]
; mov byte ptr[flags+1],al
; fldcw [flags]
; mov eax, [temp]
; mov edx, [temp+4]
; ret
;ftoqw endp
QwordConvert proc near
push ecx
push ebp
xor eax, eax
inc eax
push eax
dec eax
push eax
QwordConvert_loop:
xor eax, eax
lodsb
sub al, '0'
mov ebx, eax
mul dword ptr [esp+4]
push eax
push edx
mov eax, ebx
mul dword ptr [esp+8]
or edx, edx
jnz short QwordConvert_error2
add [esp], eax
pop edx
pop eax
add edi, eax
adc ebp, edx
jc short QwordConvert_error1
dec ecx
jecxz short QwordConvert_loop_exit
pop ebx
pop eax
mul dword ptr [decimal_constant]
push eax
or ebx, ebx
jz short QwordConvert_significant_zero
push edx
mov eax, [decimal_constant]
mul ebx
add [esp], eax
jmp short QwordConvert_loop
QwordConvert_significant_zero:
push edx
jmp short QwordConvert_loop
QwordConvert_loop_exit:
pop eax
pop eax
mov eax, edi
mov edx, ebp
pop ebp
test ebp, edx
js short QwordConvert_error;///??? comp to 0????
shr ebp, 1
jnc short QwordConvert_pop_exit
not edx
not eax
inc eax
adc edx, 0
jns short QwordConvert_error;///??? comp to 0????
QwordConvert_pop_exit:
ret
QwordConvert_error2:
pop eax
pop eax
QwordConvert_error1:
pop eax
pop eax
pop ebp
pop ecx
QwordConvert_error:
stc
ret
QwordConvert endp
OleStrToString proc near
;in
;esi: ole string
;edi: string buffer
;out
;eax: destroyed
push esi
push edi
xor eax, eax
OleStrToString_loop:
lodsw
stosb
loop short OleStrToString_loop
pop edi
pop esi
ret
OleStrToString endp
StringToOleStr proc near
;in
;esi: string
;edi: ole string buffer
;out
;eax: destroyed
push esi
push edi
xor eax, eax
StringToOleStr_loop:
lodsb
stosw
loop short StringToOleStr_loop
pop edi
pop esi
ret
StringToOleStr endp
FloatToString proc near
;in
;st[0]: float number
;edi: string buffer
;out
;eax: destroyed
push eax
push edx
fxtract
fistp qword ptr[esp]
mov eax,[esp]
mov edx,[esp+4]
clc
call Int64ToString
fistp qword ptr[esp]
mov eax,[esp]
mov edx,[esp+4]
stc
call Int64ToString
pop eax
pop eax
ret
FloatToString endp
Int64ToString proc near
;in
;edx:eax: int64
;edi: string buffer
;out
;edx, eax: destroyed
push eax
mov al,'-'
rcl edx,1
jc short Int64ToString_sign
test edx,1
jz short Int64ToString_calc
mov al,'+'
Int64ToString_sign:
stosb
Int64ToString_calc:
shr edx,1
pop eax
jmp short Qword_cvt
Int64ToString endp
QwordToString proc near
;in
;edx:eax: qword
;edi: string buffer
;out
;edx, eax: destroyed
jnc QwordToString_calc
mov byte ptr[edi],'+'
inc edi
QwordToString_calc:
jmp short Qword_cvt
QwordToString endp
Qword_cvt proc near
push ebx
push eax
mov eax, edx
mov ebx, 10
Qword_cvt_loop1:
xor edx, edx
div ebx
or eax, eax
jz short Qword_cvt_loop1_exit
add edx, '0'
mov [edi],dl
inc edi
jmp short Qword_cvt_loop1
Qword_cvt_loop1_exit:
pop eax
Qword_cvt_loop2:
xor edx, edx
div ebx
add edx, '0'
mov [edi],dl
inc edi
or eax, eax
jnz short Qword_cvt_loop2
stosb
pop ebx
ret
Qword_cvt endp
;StringToQword proc near
;in
;esi: string
;out
;edx:eax: qword
; jnc QwordToString_calc
; mov byte ptr[edi],'+'
; inc edi
;StringToQword_calc:
; jmp short StrQword_cvt
;StringToQword endp
StrQword_cvt proc near
push ebx
push ecx
push esi
cmp byte ptr[esi],'-'
jnz short StrQword_cvt_1
mov ebx, 80000001h
jmp short StrQword_cvt_2
StrQword_cvt_1:
mov ebx, 1
cmp byte ptr[esi],'+'
jnz short StrQword_cvt_3
StrQword_cvt_2:
inc esi
StrQword_cvt_3:
xor edx,edx
mov ebx, 10
StrQword_search:
lodsb
cmp al,'0'
jb StrQword_search_exit
cmp al,'9'
jbe StrQword_search
mul ebx
StrQword_search_exit:
StrQword_loop1:
dec esi
xor eax,eax
mov al,[esi]
mul ebx
or edx,edx
jnz short StrQword_loop1_exit
add ecx,eax
mul ebx
jmp StrQword_loop1
StrQword_loop1_exit:
StrQword_cvt endp
OleStrBufferSize proc near
;in
;edi: ole string
;out
;edi, edx: destroyed
;eax: buffer size
xor eax, eax
xor ecx, ecx
dec ecx
repnz scasw
neg ecx
dec ecx
mov eax, ecx
shl eax, 1
ret
OleStrBufferSize endp
StringBufferSize proc near
;in
;edi: string
;out
;edi, edx: destroyed
;eax: buffer size
xor eax, eax
xor ecx, ecx
dec ecx
repnz scasb
neg ecx
dec ecx
mov eax, ecx
ret
StringBufferSize endp
StringCopy proc near
;in
;esi: source string
;edi: destination buffer
;out
;eax, esi, edi: destroyed
; push esi
; push edi
StringCopy_loop:
lodsb
stosb
or al,al
jnz short StringCopy_loop
; pop edi
; pop esi
ret
StringCopy endp
OleStrCopy proc near
;in
;esi: source ole string
;edi: destination buffer
;out
;eax, esi, edi: destroyed
; push esi
; push edi
xor eax,eax
OleStrCopy_loop:
lodsw
stosw
or eax, eax
jnz short OleStrCopy_loop
; pop edi
; pop esi
ret
OleStrCopy endp
ToString proc near
;in
;ebx: this
;out
;eax(al): bool value
;c=1 if error
;edi, esi: destroyed
mov cl,[ebx]
cmp cl, mvNull
jbe ToString_error
cmp cl, mvString
jz ToString_exit
; cmp cl, mvOleStr;??
ja ToString_error
jb short ToString_tochar
push esi
push edi
mov edi, [ebx+MATHVAR_VALUE]
call OleStrBufferSize
cmp eax,[ebx+MATHVAR_VALUE+4]
jbe ToString_strcopy
resize edi, eax
mov [ebx+MATHVAR_VALUE+4], eax
ToString_strcopy:
mov esi, edi
call OleStrToString
pop edi
pop esi
jmp short ToString_exit
ToString_tochar:
cmp cl, mvChar
jnz short ToString_toshort
ToString_char:
movsx eax, byte ptr[ebx+MATHVAR_VALUE]
jmp short ToString_IntCvt
ToString_toshort:
cmp cl, mvShortInt
jnz short ToString_toint
ToString_short:
movsx eax, word ptr[ebx+MATHVAR_VALUE]
jmp short ToString_IntCvt
ToString_toint:
cmp cl, mvInteger
jnz short ToString_toint64
ToString_int:
mov eax,[ebx+MATHVAR_VALUE]
jmp short ToString_IntCvt
ToString_toint64:
cmp cl, mvInt64
jnz short ToString_tofloat
mov eax,[ebx+MATHVAR_VALUE]
mov edx,[ebx+MATHVAR_VALUE+4]
jmp short ToString_IntCvt
ToString_tofloat:
cmp cl, mvFloat
jnz short ToString_todouble
fld dword ptr[ebx+MATHVAR_VALUE]
jmp short ToString_FloatCvt
ToString_todouble:
cmp cl, mvDouble
jnz short ToString_toextended
fld qword ptr[ebx+MATHVAR_VALUE]
jmp short ToString_FloatCvt
ToString_toextended:
cmp cl, mvExtended
jnz short ToString_WordCvt
fld tbyte ptr [ebx+MATHVAR_VALUE]
ToString_FloatCvt:
call FloatToString
jmp short ToString_exit
ToString_IntCvt:
xor edx, edx
call Int64ToString
jmp short ToString_exit
ToString_WordCvt:
mov eax,[ebx+MATHVAR_VALUE]
mov edx,[ebx+MATHVAR_VALUE+4]
call QwordToString
ToString_exit:
mov dword ptr [ebx+MATHVAR_ERROR], ERROR_SUCCESS
clc
ret
ToString_error:
mov dword ptr [ebx+MATHVAR_ERROR], ERROR_MATH_VARIANT_CANNOT_BE_CONVERTED_TO_STRING
stc
ret
ToString endp
;ToString proc near
;in
;[edx:]eax | st[0]: input value
;out
;eax: string
;ToString endp
ToOleStr proc near
ToOleStr endp
;----------------------------------------------------new functions----------------------------------------------------------
;---------------------------------------------------------------------------------------------------------------------------
;---------------------------------------------------------------------------------------------------------------------------
CheckString proc near
;in
;esi: input string buffer
;out
;c: error
;bl: value type
;dl: value sign
;esi: output string buffer
;ecx: length of string buffer
;temporary
;bl: plus sign
;bh: minus sign
;ah: floating point sign
xor edx, edx
xor ebp, ebp
xor edi, edi
push edx
push ebp
cmp ecx, 255
ja CheckString_error
mov ah, MODE_ZERO_FLAG OR ZERO_FLAG OR NUMBER_FLAG OR MODE_FLAG OR SEPARATOR_FLAG OR FLOAT_DOT_FLAG OR SIGN_FLAG OR EXP_FLAG
CheckString_loop:
call GetSymbol
test ah, MODE_ZERO_FLAG OR ZERO_FLAG
jz CheckString_1
cmp al, '0'
jz CheckString_next
;CheckString_zero_flg:
; test ah, ZERO_FLAG
; test ah, NUMBER_FLAG
; jz CheckString_1
; cmp al, '0'
; jnz CheckString_1
; jz CheckString_next
; or ebp, ebp
; jz CheckString_next
; jmp CheckString_inc_next
CheckString_1:
test ah, NUMBER_FLAG
jz CheckString_error
mov ebx, offset CheckRange
CheckString_1_1:
cmp byte ptr [ebx], 0
jz CheckString_2
cmp al, [ebx]
jb CheckString_1_2
cmp al, [ebx + 1]
jbe CheckString_inc_next
CheckString_1_2:
add ebx, 4
jmp CheckString_1_1
; cmp al, '1'
; jb CheckString_2
; cmp al, '9'
; ja CheckString_2
; mov edi, esi
; jmp CheckString_inc_next
; jbe CheckString_inc_next
CheckString_2:
test ah, MODE_FLAG OR FLOAT_DOT_FLAG OR SIGN_FLAG OR EXP_FLAG
jz CheckString_error
mov ebx, offset CheckTable - 5
CheckString_2_1:
add ebx, 5
cmp byte ptr [ebx.Symbol], 0
jz CheckString_separator
cmp al, [ebx.Symbol]
jnz CheckString_2_1
test ah, [ebx.Type]
jz CheckString_error
mov ch, [ebx.Degree]
mov dl, [ebx.Value]
and ah, [ebx.Mask]
or dh, dh
jns CheckString_2_2
shl edi, 8
mov dh, 0
CheckString_2_2:
inc edi
; or ah, [ebx.Mask]
; test dh, byte ptr[ebx.Mask]
; jnz CheckString_error
; test byte ptr[ebx.Flags], POSTFIX_FLAG
; jz CheckString_2_2
; or dh, byte ptr[ebx.Value]
jmp CheckString_next
;CheckString_2_2:
; mov dl, [ebx.Value]
; and ah, [ebx.Flags]
; jmp CheckString_next
CheckString_separator:
test ah, SEPARATOR_FLAG
jz CheckString_error
dec esi
jmp CheckString_exit
; dec bl
; jnz CheckString_2_1
; cmp al, ah
; jz CheckString_float_exit
; or ebp, ebp
; jnz CheckString_2_1
; cmp al, bh
; jz CheckString_next
; cmp al, bl
; jnz CheckString_3
; or dl, MINUS_SIGN
; jmp CheckString_next
;CheckString_2_1:
;CheckString_3:
; cmp al, 'e'
; jz CheckString_exp_exit
; cmp al, 'E'
; jz CheckString_exp_exit
; cmp al, 'h'
; jz CheckString_hex_exit
; cmp al, 'H'
; jz CheckString_hex_exit
; cmp al, 'q'
; jz CheckString_octal_exit
; cmp al, 'Q'
; jz CheckString_octal_exit
; cmp al, 'b'
; jz CheckString_bin_exit
; cmp al, 'B'
; jz CheckString_bin_exit
; cmp al, 'x'
; jz CheckString_set_hex
; cmp al, 'X'
; jnz CheckString_error
;CheckString_set_hex:
; or dl, HEX_SIGN
; jmp CheckString_next
CheckString_inc_next:
or dh, dh
js CheckString_inc_next_1
shl ebp, 8
not dh
CheckString_inc_next_1:
inc ebp
mov ch, [ebx+2]
and ah, NOT (MODE_ZERO_FLAG OR ZERO_FLAG)
;; mov [esp], ebx
CheckString_next:
; loop CheckString_loop
dec cl
jnz CheckString_loop
;; test dl, HEX_SIGN
;; jz CheckString_exit
;; mov dh, HEX_VALUE
CheckString_exit:
mov ecx, ebp
test dh, dh
js CheckString_clear_break_sym
shrd edi, eax, 8
shr eax, 24
sub esi, eax
CheckString_clear_break_sym:
; mov ecx, ebp
; lea esi, [edi - 1]
dec esi
pushfd
or dword ptr [esp], 400h
popfd
mov [esp], dl
and dl, 80h
mov [esp+7], dl
pop ebx
pop ebp
ret
;CheckString_bin_exit:
; mov dh, BIN_VALUE
;CheckString_octal_exit:
; mov dh, OCTAL_VALUE
;CheckString_hex_exit:
; mov dh, HEX_VALUE
;CheckString_exp_exit:
; mov dh, EXP_VALUE
;CheckString_float_exit:
; mov dh, FLOAT_VALUE
; test dl, HEX_SIGN
; jz CheckString_exit
CheckString_error:
stc
pop ebx
pop ebp
ret
;in
;esi: input string buffer
;ebx: base
;edx: CheckTable
;ebp: exitcode
;edi: ??
;out
;c: error
;bl: value type
;dl: value sign
;esi: output string buffer
;ecx: length of string buffer
; xor ebx, ebx
; xor edx, edx
; xor ebp, ebp
; call TableConversion
;CheckString_loop:
; lodsb
; call CheckBase
; jnc ok
; call CheckSymbol
; jc error
; or al, al
; inc ebp
;CheckString_next:
; loop CheckString_loop
CheckString endp
;CheckBase proc near
;ebx: base
;eax: symbol
; cmp eax, '0'
; jb CheckBase_error
; cmp eax, '9'
; jbe CheckBase1
; cmp eax, 'A'
; jb CheckBase_error
;CheckBase1:
; cmp ebx, eax
;CheckBase_error:
; ret
;CheckBase endp
;ToUpperReg proc near
; cmp eax, 'a'
; jb ToUpperReg_exit
; cmp eax, 'z'
; ja ToUpperReg_exit
; sub eax, 20h
;ToUpperReg_exit:
; ret
;ToUpperReg endp
;CheckSymbol proc near
; ret
;CheckSymbol endp
GetSymbol8 proc near
;out
;eax: symbol
xor eax, eax
lodsb
; test al, al
; js
; sub al, '0'
ret
GetSymbol8 endp
GetSymbol16 proc near
;out
;eax: symbol
xor eax, eax
lodsw
; test ax, ax
; js
; sub al, '0'
ret
GetSymbol16 endp
GetSymbolRutf proc near
;out
;eax: symbol
xor eax, eax
lodsb
test al, al
jns GetSymbolRutf_exit
; shl eax, 8
ror eax, 7
lodsb
test al, al
jns GetSymbolRutf_exit1
; shr eax, 16
ror eax, 7
lodsw
ror eax, 18
jmp GetSymbolRutf_exit
GetSymbolRutf_exit1:
rol eax, 7
GetSymbolRutf_exit:
ret
GetSymbolRutf endp
HexString2Qword proc near
;in
;esi: pointer to string (in backward direction)
;ecx: string size
;ebp: sign check
;out
;edx:eax: number
;edi, ecx, ebx: destoryed
xor eax, eax
xor ebx, ebx
xor edx, edx
cmp ecx, 16
ja HexString2Qword_error
push ecx
HexString2Qword_next:
lodsb
sub al, 'A'
jc HexString2Qword_digit
sub al, 'a' - 'A' + 10
jnc HexString2Qword_write
add al, 'a' - 'A' + 10
jmp HexString2Qword_write
HexString2Qword_digit:
add al, 'A' - '0'
HexString2Qword_write:
shrd edx, ebx, 4
ror eax, 4
or edx, eax
loop HexString2Qword_next
pop ecx
lea ecx, [ecx * 4 ]
HexString2Qword_count_cvts:
xor cl, 1111111b
inc cl
shrd edx, ebx, cl
test cl, 100000b
jz HexString2Qword_32xcgh
xchg ebx, edx
HexString2Qword_32xcgh:
mov eax, ebx
jmp String2Int_sign_fix
HexString2Qword_error:
xor eax, eax
xor edx, edx
ret
HexString2Qword endp
BinString2Qword proc near
;in
;esi: pointer to string (in backward direction)
;ecx: string size
;ebp: sign check
;out
;edx:eax: number
;edi, ecx, ebx: destoryed
xor eax, eax
xor ecx, ecx
xor ebx, ebx
xor edx, edx
cmp ecx, 64
ja HexString2Qword_error
push ecx
BinString2Qword_next:
call GetSymbol
shr eax, 1
rcr edx, 1
rcr ebx, 1
loop BinString2Qword_next
pop ecx
jmp HexString2Qword_count_cvts
; xor cl, 1111111b
; shrd edx, ebx, cl
; test cl, 100000b
; jz HexString2Qword_32xcgh
; xchg ebx, edx
;HexString2Qword_32xcgh:
; mov eax, ebx
; jmp String2Int_sign_fix
BinString2Qword endp
OctalString2Qword proc near
xor eax, eax
xor ecx, ecx
xor ebx, ebx
xor edx, edx
cmp ecx, 22
ja HexString2Qword_error
push ecx
OctalString2Qword_next:
call GetSymbol
cmp edi, 22
jnz OctalString2Qword_signed_digit
pop ecx
cmp al, 1
ja HexString2Qword_error
shr eax, 1
rcr edx, 1
rcr ebx, 1
jmp HexString2Qword_count_cvts
OctalString2Qword_signed_digit:
shrd edx, ebx, 3
ror eax, 3
or edx, eax
loop OctalString2Qword_next
pop ecx
ja HexString2Qword_error
lea ecx, [ecx + ecx * 2]
jmp HexString2Qword_count_cvts
OctalString2Qword endp
IntString2Qword proc near
;in
;esi: pointer to string (in backward direction)
;cl(!ecx): string size
;eax: base
;ebp: sign check
push ebx
push ebp
push eax
xor eax, eax
push eax
push eax
mov edi, 1
xor ebp, ebp
String2Int_loop:
xor eax, eax
call GetSymbol
mov ebx, eax
mul edi
add [esp+4], eax
adc [esp], edx
jc String2Int_error
mov eax, ebx
mul ebp
or edx, edx
jnz String2Int_error
add [esp], eax
jc String2Int_error
dec cl
jz String2Int_loop_exit
mov eax, edi
mul dword ptr [esp+8]
mov edi, eax
xchg ebp, edx
or edx, edx
jz String2Int_loop
imul edx, dword ptr [esp+8]
add ebp, edx
jmp String2Int_loop
String2Int_loop_exit:
pop edx
pop eax
pop edi
pop ebp
pop ebx
String2Int_sign_fix:
test ebp, edx
js String2Int_error1;///??? comp to 0????
test ebp, ebp
jns String2Int_pop_exit
not edx
not eax
inc eax
adc edx, 0
jns String2Int_error1;///??? comp to 0????
String2Int_pop_exit:
ret
String2Int_error:
pop eax
pop edx
pop edi
pop ebp
pop ebx
String2Int_error1:
stc
ret
IntString2Qword endp
@FastString@$oo$xqqrv proc near
@FastString@$oo$xqqrv endp
@FastString@$oc$xqqrv proc near
@FastString@$ozc$xqqrv:
@FastString@$oc$xqqrv endp
@FastString@$ouc$xqqrv proc near
@FastString@$ouc$xqqrv endp
@FastString@$os$xqqrv proc near
@FastString@$os$xqqrv endp
@FastString@$ous$xqqrv proc near
@FastString@$ous$xqqrv endp
@FastString@$oi$xqqrv proc near
@FastString@$ol$xqqrv:
;in
;eax: this
;out
;eax: integer value
mov eax, [eax]
or eax, eax
jz @FastString@$oi$xqqrv_nullval
mov ecx, [eax - SIZEOF_FASTSTRING + FastString.Length]
or ecx, ecx
jz @FastString@$oi$xqqrv_nulllen
push ebx
push esi
push edi
push ebp
pushfd
mov esi, eax
call CheckString
jc @FastString@$oi$xqqrv_CheckString_error
jmp [ebx * 4 + ToIntTable]
@FastString@$oi$xqqrv_FromInt:
mov eax, [decimal_constant]
call IntString2Qword
jmp @FastString@$oi$xqqrv_exit
@FastString@$oi$xqqrv_FromExp:
mov eax, [decimal_constant]
call IntString2Qword
push ecx
push ebp
fild qword ptr[esp]
pop ecx
pop ecx
dec esi
fldl2t
fmulp
fstsw ax
test ah, 1000b
jz @FastString@$oi$xqqrv_FromExp_1
fchs
@FastString@$oi$xqqrv_FromExp_1:
fld st(0)
frndint
fsub st(1), st(0)
; fld1
; fscale
fxch
f2xm1
fld1
faddp
fscale
jz @FastString@$oi$xqqrv_FromExp_2
fld1
fdivrp st(1)
@FastString@$oi$xqqrv_FromExp_2:
; movzx eax, dh
; sub esi, eax
stc
@FastString@$oi$xqqrv_FromFloat:
pushfd
; movzx eax, bl
; sub esi, eax
push edi
mov edi, ebp
xor ebp, ebp
mov eax, [decimal_constant]
call IntString2Qword
push ebp
push edi
fild qword ptr[esp]
push edx
push eax
fild qword ptr[esp]
; and edi, 0ffh
; sub esi, edi
sub esi, [esp+16]
mov eax, [decimal_constant]
fdivrp
; dec esi
; movzx eax, bl
; sub esi, eax
mov ebp, ebx
; mov ebp, [esp+16]
shr ecx, 8
call IntString2Qword
push edx
push eax
fild qword ptr[esp]
faddp
add esp, 24
pop edi
popfd
jnc @FastString@$oi$xqqrv_exit
fmulp
jmp @FastString@$oi$xqqrv_exit
@FastString@$oi$xqqrv_FromHex:
call HexString2Qword
jmp @FastString@$oi$xqqrv_exit
@FastString@$oi$xqqrv_FromOctal:
call OctalString2Qword
jmp @FastString@$oi$xqqrv_exit
@FastString@$oi$xqqrv_FromBinary:
call BinString2Qword
@FastString@$oi$xqqrv_exit:
popfd
pop ebp
pop edi
pop esi
pop ebx
ret
@FastString@$oi$xqqrv_CheckString_error:
xor eax, eax
jmp @FastString@$oi$xqqrv_exit
@FastString@$oi$xqqrv_nulllen:
xor eax, eax
@FastString@$oi$xqqrv_nullval:
ret
@FastString@$oi$xqqrv endp
@FastString@$oui$xqqrv proc near
@FastString@$oul$xqqrv:
@FastString@$oui$xqqrv endp
@FastString@$oj$xqqrv proc near
@FastString@$oj$xqqrv endp
@FastString@$ouj$xqqrv proc near
@FastString@$ouj$xqqrv endp
@FastString@$of$xqqrv proc near
@FastString@$of$xqqrv endp
@FastString@$od$xqqrv proc near
@FastString@$od$xqqrv endp
@FastString@$og$xqqrv proc near
@FastString@$og$xqqrv endp
@FastString@$opv$xqqrv proc near
@FastString@$opv$xqqrv endp
@FastString@$opb$qqrv proc near
@FastString@$opb$qqrv endp
@FastString@$opc$qqrv proc near
@FastString@$opc$qqrv endp
@FastString@$o17System@AnsiString$qqrv proc near
@FastString@$o17System@AnsiString$qqrv endp
@FastString@$o17System@WideString$qqrv proc near
@FastString@$o17System@WideString$qqrv endp
;---------------------------------------------------------------------------------------------------------------------------
;---------------------------------------------------------------------------------------------------------------------------
;---------------------------------------------------------------------------------------------------------------------------
;@FastString@ConvertTo$qqrul:
@FastString@ConvertTo$qqrul proc near
@FastString@ChangeCodePage$qqrul:
;in
;eax: this
;edx: codepage
mov eax, [eax]
or eax, eax
jz @FastString@ConvertTo$qqrui_empty
;simple convert
push esi
push edi
mov esi, eax
mov edi, eax
mov ecx, [eax - SIZEOF_FASTSTRING + FastString.Length]
xchg dx, [eax - SIZEOF_FASTSTRING + FastString.CodePage.Page]
movzx eax, word ptr[eax - SIZEOF_FASTSTRING + FastString.CodePage.Page]
; movzx eax, word ptr[eax - SIZEOF_FASTSTRING + FastString.CodePage.Page]
; mov word ptr[eax - SIZEOF_FASTSTRING + FastString.CodePage.Page], dx
xchg eax, edx
cmp eax, edx
jz @FastString@ConvertTo$qqrui_dontcvt
test ah, dh
js @FastString@ConvertTo$qqrui_utf
call Convert8_8
@FastString@ConvertTo$qqrui_dontcvt:
pop edi
pop esi
@FastString@ConvertTo$qqrui_empty:
ret
@FastString@ConvertTo$qqrui_utf:
test ah, ah
js @FastString@ConvertTo$qqrui_ruft
test ah, 40h
jnz @FastString@ConvertTo$qqrui_uft16
test dh, dh
js @FastString@ConvertTo$qqrui_to_ruft
call Convert8_16
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrui_to_ruft:
call Convert8_8P
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrui_uft16:
test dh, dh
jnz @FastString@ConvertTo$qqrui_utf16_to_ruft
call Convert16_8
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrui_utf16_to_ruft:
call Convert16_8P
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrui_ruft:
test dh, 40h
jnz @FastString@ConvertTo$qqrui_rutf_to_uft16
call Convert8P_8
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrui_rutf_to_uft16:
call Convert8P_16
jmp @FastString@ConvertTo$qqrui_dontcvt
@FastString@ConvertTo$qqrul endp
;@FastString@SetCodePage$qqrul:
@FastString@SetCodePage$qqrul proc near
;in
;eax: this
;edx: codepage
mov eax, [eax]
or eax, eax
jz @FastString@SetCodePage$qqrui_empty
mov word ptr[eax - SIZEOF_FASTSTRING + FastString.CodePage.Page], dx
@FastString@SetCodePage$qqrui_empty:
ret
@FastString@SetCodePage$qqrul endp
Convert8_8:
;in
;eax: input codepage
;edx: output codepage
;esi: input string
;edi: output string
;ecx: input count
;out
;esi: new input string
;esi: new output string
;ecx, eax, edx: destroyed
push ebx
push ebp
imul eax, RUSSIAN_CP_COUNT * 4
; shl edx, 2
; lea esi, [RussianConvertTable8_8 + eax*4 + edx*4]
mov ebx, [RussianConvertTable8_8 + edx*4 + eax]
push ebx
xor eax, eax
mov ebp, ecx
Convert8_8_enter:
lodsb
mov ebx, [esp]
movzx ecx, byte ptr[ebx]
Convert8_8_a:
; lodsw
mov dx, [ebx+1]
cmp al, dl
jb Convert8_8_b
cmp al, dh
ja Convert8_8_b
sub al, dl
mov al, [ebx+eax+3]
jmp Convert8_8_next
Convert8_8_b:
sub dh, dl
shr edx, 8
lea ebx, [ebx+edx+3]
loop Convert8_8_a
Convert8_8_next:
stosb
dec ebp
jnz Convert8_8_enter
pop ebx
pop ebp
pop ebx
ret
Convert8_16:
;eax: input codepage
lea esi, [RussianConvertTable8_16 + eax*4]
ret
Convert8_8P:
Convert16_8:
;edx: output codepage
lea esi, [RussianConvertTable16_8 + edx*4]
ret
Convert16_8P:
Convert8P_8:
Convert8P_16:
.data
RussianConvertTable8_8 label dword
dd 0, Cp866_Cp1251_tbl, Cp866_Mac_tbl, Cp866_Koi8r_tbl, Cp866_Mac_tbl, Cp866_Cp8859_5_tbl
dd Cp1251_Cp866_tbl, 0, Cp1251_Cp10007_tbl, Cp1251_Koi8r_tbl, Cp1251_Mac_tbl, Cp1251_Cp8859_5_tbl
dd Cp10007_Cp866_tbl, Cp10007_Cp1251_tbl, 0, Cp10007_Koi8r_tbl, 0, Cp10007_Cp8859_5_tbl
dd Koi8r_Cp866_tbl, Koi8r_Cp1251_tbl, Koi8r_Cp10007_tbl, 0, Koi8r_Mac_tbl, Koi8r_Cp8859_5_tbl
dd Mac_Cp866_tbl, Mac_Cp1251_tbl, 0, Cp10007_Koi8r_tbl, 0, Cp10007_Cp8859_5_tbl
dd Cp8859_5_Cp866_tbl, Cp8859_5_Cp1251_tbl, Cp8859_5_Mac_tbl, Cp8859_5_Koi8r_tbl, Cp8859_5_Mac_tbl, 0
RussianConvertTable8_16 label dword
dd Cp866_Utf16_tbl, Cp1251_Utf16_tbl, Cp10007_Utf16_tbl, Koi8r_Utf16_tbl, Mac_Utf16_tbl, Cp8859_5_Utf16_tbl
RussianConvertTable8_8P label dword
; dd Cp866_Cutf_tbl, Cp1251_Cutf_tbl, Cp10007_Cutf_tbl, Koi8r_Cutf_tbl, Mac_Cutf_tbl, Cp8859_5_Cutf_tbl
RussianConvertTable16_8 label dword
dd Utf16_Cp866_tbl, Utf16_Cp1251_tbl, Utf16_Cp10007_tbl, Utf16_Koi8r_tbl, Utf16_Mac_tbl, Utf16_Cp8859_5_tbl
RussianConvertTable16_8P label dword
; dd Utf16_Cutf_tbl
RussianConvertTable8P_8 label dword
; dd Cutf_Cp866_tbl, Cutf_Cp1251_tbl, Cutf_Cp10007_tbl, Cutf_Koi8r_tbl, Cutf_Mac_tbl, Cutf_Cp8859_5_tbl
RussianConvertTable8P_16 label dword
; dd Cutf_Utf16_tbl
;0->1
Cp866_Cp1251_tbl:
db 5h
db 80h, 0afh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh
db 0e0h, 0f8h, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0ffh, 0a8h, 0b8h, 0aah, 0bah, 0afh, 0bfh, 0a1h, 0a2h, 0b0h
db 0fah, 0fah, 0b7h
db 0fch, 0fdh, 0b9h, 0a4h
db 0ffh, 0ffh, 0a0h
;0->2+4
Cp866_Mac_tbl:
db 4h
db 0a0h, 0afh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh
db 0e0h, 0f8h, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0dfh, 0ddh, 0deh, 0b8h, 0b9h, 0bah, 0bbh, 0d8h, 0d9h, 0a1h
db 0fbh, 0fdh, 0c3h, 0dch, 0ffh
db 0ffh, 0ffh, 0cah
;0->3
Cp866_Koi8r_tbl:
db 3h
db 80h, 0f1h, 0e1h, 0e2h, 0f7h, 0e7h, 0e4h, 0e5h, 0f6h, 0fah, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f2h, 0f3h, 0f4h, 0f5h, 0e6h, 0e8h, 0e3h, 0feh, 0fbh, 0fdh, 0ffh, 0f9h, 0f8h, 0fch, 0e0h, 0f1h, 0c1h, 0c2h, 0d7h, 0c7h, 0c4h, 0c5h, 0d6h, 0dah, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 090h, 091h, 092h, 081h, 087h, 0b2h, 0b4h, 0a7h, 0a6h, 0b5h, 0a1h, 0a8h, 0aeh, 0adh, 0ach, 083h, 084h, 089h, 088h, 086h, 080h, 08ah, 0afh, 0b0h, 0abh, 0a5h, 0bbh, 0b8h, 0b1h, 0a0h, 0beh, 0b9h, 0bah, 0b6h, 0b7h, 0aah, 0a9h, 0a2h, 0a4h, 0bdh, 0bch, 085h, 082h, 08dh, 08ch, 08eh, 08fh, 08bh, 0d2h, 0d3h, 0d4h, 0d5h, 0c6h, 0c8h, 0c3h, 0deh, 0dbh, 0ddh, 0dfh, 0d9h, 0d8h, 0dch, 0c0h, 0d1h, 0b3h, 0a3h
db 0f8h, 0fbh, 09ch, 095h, 09eh, 096h
db 0feh, 0ffh, 094h, 09ah
;0->5
Cp866_Cp8859_5_tbl:
db 5h
db 080h, 0afh, 0b0h, 0b1h, 0b2h, 0b3h, 0b4h, 0b5h, 0b6h, 0b7h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh, 0bfh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh
db 0f0h, 0f0h, 0a1h
db 0f2h, 0f7h, 0a4h, 0f4h, 0a7h, 0f7h, 0aeh, 0feh
db 0fch, 0fch, 0f0h
db 0ffh, 0ffh, 0a0h
;1->0
Cp1251_Cp866_tbl:
db 7h
db 0a0h, 0a2h, 0ffh, 0f6h, 0f7h
db 0a4h, 0a4h, 0fdh
db 0a8h, 0a8h, 0f0h
db 0aah, 0aah, 0f2h
db 0afh, 0b0h, 0f4h, 0f8h
db 0b7h, 0bah, 0fah, 0f1h, 0fch, 0f3h
db 0bfh, 0ffh, 0f5h, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0a0h, 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh
;1->2
Cp1251_Cp10007_tbl:
db 0ch
db 080h, 081h, 0abh, 0aeh
db 083h, 086h, 0afh, 0d7h, 0c9h, 0a0h
db 08ah, 08ah, 0bch
db 08ch, 09ah, 0beh, 0cdh, 0cbh, 0dah, 0ach, 0d4h, 0d5h, 0d2h, 0d3h, 0a5h, 0d0h, 0d1h, 0aah, 0bdh, 0h
db 09ch, 0a4h, 0bfh, 0ceh, 0cch, 0dbh, 0cah, 0d8h, 0d9h, 0b7h, 0ffh
db 0a7h, 0a8h, 0a4h, 0ddh
db 0aah, 0ach, 0b8h, 0c7h, 0c2h
db 0aeh, 0b0h, 0a8h, 0bah, 0a1h
db 0b2h, 0b3h, 0a7h, 0b4h
db 0b6h, 0b6h, 0a6h
db 0b8h, 0dfh, 0deh, 0dch, 0b9h, 0c8h, 0c0h, 0c1h, 0cfh, 0bbh, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh
db 0ffh, 0ffh, 0dfh
;1->3
Cp1251_Koi8r_tbl:
db 5h
db 0a0h, 0a0h, 09ah
db 0a8h, 0a9h, 0b3h, 0bfh
db 0b0h, 0b0h, 09ch
db 0b7h, 0b8h, 09eh, 0a3h
db 0c0h, 0ffh, 0e1h, 0e2h, 0f7h, 0e7h, 0e4h, 0e5h, 0f6h, 0fah, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f2h, 0f3h, 0f4h, 0f5h, 0e6h, 0e8h, 0e3h, 0feh, 0fbh, 0fdh, 0ffh, 0f9h, 0f8h, 0fch, 0e0h, 0f1h, 0c1h, 0c2h, 0d7h, 0c7h, 0c4h, 0c5h, 0d6h, 0dah, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d2h, 0d3h, 0d4h, 0d5h, 0c6h, 0c8h, 0c3h, 0deh, 0dbh, 0ddh, 0dfh, 0d9h, 0d8h, 0dch, 0c0h, 0d1h
;1->4
Cp1251_Mac_tbl:
db 0eh
db 080h, 081h, 0abh, 0aeh
db 083h, 086h, 0afh, 0d7h, 0c9h, 0a0h
db 088h, 088h, 0ffh
db 08ah, 08ah, 0bch
db 08ch, 09ah, 0beh, 0cdh, 0cbh, 0dah, 0ach, 0d4h, 0d5h, 0d2h, 0d3h, 0a5h, 0d0h, 0d1h, 0aah, 0bdh, 0efh
db 09ch, 0a3h, 0bfh, 0ceh, 0cch, 0dbh, 0cah, 0d8h, 0d9h, 0b7h
db 0a5h, 0a5h, 0a2h
db 0a7h, 0a8h, 0a4h, 0ddh
db 0aah, 0ach, 0b8h, 0c7h, 0c2h
db 0aeh, 0b0h, 0a8h, 0bah, 0a1h
db 0b2h, 0b4h, 0a7h, 0b4h, 0b6h
db 0b6h, 0b6h, 0a6h
db 0b8h, 0dfh, 0deh, 0dch, 0b9h, 0c8h, 0c0h, 0c1h, 0cfh, 0bbh, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh
db 0ffh, 0ffh, 0dfh
;1->5
Cp1251_Cp8859_5_tbl:
db 0dh
db 080h, 081h, 0a2h, 0a3h
db 083h, 083h, 0f3h
db 08ah, 08ah, 0a9h
db 08ch, 090h, 0aah, 0ach, 0abh, 0afh, 0f2h
db 09ah, 09ah, 0f9h
db 09ch, 09fh, 0fah, 0fch, 0fbh, 0ffh
db 0a1h, 0a3h, 0aeh, 0feh, 0a8h
db 0a7h, 0a8h, 0fdh, 0a1h
db 0aah, 0aah, 0a4h
db 0afh, 0afh, 0a7h
db 0b2h, 0b3h, 0a6h, 0f6h
db 0b8h, 0bah, 0f1h, 0f0h, 0f4h
db 0bch, 0ffh, 0f8h, 0a5h, 0f5h, 0f7h, 0b0h, 0b1h, 0b2h, 0b3h, 0b4h, 0b5h, 0b6h, 0b7h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh, 0bfh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh
;2->0
Cp10007_Cp866_tbl:
db 6h
db 0a1h, 0a1h, 0f8h
db 0b8h, 0bbh, 0f2h, 0f3h, 0f4h, 0f5h
db 0c3h, 0c3h, 0fbh
db 0cah, 0cah, 0ffh
db 0d8h, 0d9h, 0f6h, 0f7h
db 0dch, 0ffh, 0fch, 0f0h, 0f1h, 0efh, 0a0h, 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0fdh
;2->1
Cp10007_Cp1251_tbl:
db 9h
db 080h, 0a1h, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 086h, 0b0h
db 0a4h, 0a8h, 0a7h, 095h, 0b6h, 0b2h, 0aeh
db 0aah, 0ach, 099h, 080h, 090h
db 0aeh, 0afh, 081h, 083h
db 0b4h, 0b4h, 0b3h
db 0b7h, 0c2h, 0a3h, 0aah, 0bah, 0afh, 0bfh, 08ah, 09ah, 08ch, 09ch, 0bch, 0bdh, 0ach
db 0c7h, 0d5h, 0abh, 0bbh, 085h, 0a0h, 08eh, 09eh, 08dh, 09dh, 0beh, 096h, 098h, 093h, 094h, 091h, 092h
db 0d7h, 0dfh, 084h, 0a1h, 0a2h, 08fh, 09fh, 0b9h, 0a8h, 0b8h, 0ffh
db 0ffh, 0ffh, 0a4h
;2+4->3
Cp10007_Koi8r_tbl:
db 9h
db 080h, 09fh, 0e1h, 0e2h, 0f7h, 0e7h, 0e4h, 0e5h, 0f6h, 0fah, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f2h, 0f3h, 0f4h, 0f5h, 0e6h, 0e8h, 0e3h, 0feh, 0fbh, 0fdh, 0ffh, 0f9h, 0f8h, 0fch, 0e0h, 0f1h
db 0a1h, 0a1h, 09ch
db 0a9h, 0a9h, 0bfh
db 0b2h, 0b3h, 098h, 099h
db 0c3h, 0c3h, 096h
db 0c5h, 0c5h, 097h
db 0cah, 0cah, 09ah
db 0d6h, 0d6h, 09fh
db 0ddh, 0feh, 0b3h, 0a3h, 0d1h, 0c1h, 0c2h, 0d7h, 0c7h, 0c4h, 0c5h, 0d6h, 0dah, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d2h, 0d3h, 0d4h, 0d5h, 0c6h, 0c8h, 0c3h, 0deh, 0dbh, 0ddh, 0dfh, 0d9h, 0d8h, 0dch, 0c0h
;2+4->5
Cp10007_Cp8859_5_tbl:
db 9h
db 080h, 09fh, 0b0h, 0b1h, 0b2h, 0b3h, 0b4h, 0b5h, 0b6h, 0b7h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh, 0bfh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh
db 0a4h, 0a4h, 0fdh
db 0a7h, 0a7h, 0a6h
db 0abh, 0ach, 0a2h, 0f2h
db 0aeh, 0afh, 0a3h, 0f3h
db 0b4h, 0b4h, 0f6h
db 0b7h, 0c1h, 0a8h, 0a4h, 0f4h, 0a7h, 0f7h, 0a9h, 0f9h, 0aah, 0fah, 0f8h, 0a5h
db 0cah, 0cfh, 0a0h, 0abh, 0fbh, 0ach, 0fch, 0f5h
db 0d8h, 0feh, 0aeh, 0feh, 0afh, 0ffh, 0f0h, 0a1h, 0f1h, 0efh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh
;3->0
Koi8r_Cp866_tbl:
db 7h
db 080h, 092h, 0c4h, 0b3h, 0dah, 0bfh, 0c0h, 0d9h, 0c3h, 0b4h, 0c2h, 0c1h, 0c5h, 0dfh, 0dch, 0dbh, 0ddh, 0deh, 0b0h, 0b1h, 0b2h
db 094h, 096h, 0feh, 0f9h, 0fbh
db 09ah, 09ah, 0ffh
db 09ch, 09ch, 0f8h
db 09eh, 09eh, 0fah
db 0a0h, 0beh, 0cdh, 0bah, 0d5h, 0f1h, 0d6h, 0c9h, 0b8h, 0b7h, 0bbh, 0d4h, 0d3h, 0c8h, 0beh, 0bdh, 0bch, 0c6h, 0c7h, 0cch, 0b5h, 0f0h, 0b6h, 0b9h, 0d1h, 0d2h, 0cbh, 0cfh, 0d0h, 0cah, 0d8h, 0d7h, 0ceh
db 0c0h, 0ffh, 0eeh, 0a0h, 0a1h, 0e6h, 0a4h, 0a5h, 0e4h, 0a3h, 0e5h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0efh, 0e0h, 0e1h, 0e2h, 0e3h, 0a6h, 0a2h, 0ech, 0ebh, 0a7h, 0e8h, 0edh, 0e9h, 0e7h, 0eah, 09eh, 080h, 081h, 096h, 084h, 085h, 094h, 083h, 095h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 09fh, 090h, 091h, 092h, 093h, 086h, 082h, 09ch, 09bh, 087h, 098h, 09dh, 099h, 097h, 09ah
;3->1
Koi8r_Cp1251_tbl:
db 6h
db 09ah, 09ah, 0a0h
db 09ch, 09ch, 0b0h
db 09eh, 09eh, 0b7h
db 0a3h, 0a3h, 0b8h
db 0b3h, 0b3h, 0a8h
db 0bfh, 0ffh, 0a9h, 0feh, 0e0h, 0e1h, 0f6h, 0e4h, 0e5h, 0f4h, 0e3h, 0f5h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0ffh, 0f0h, 0f1h, 0f2h, 0f3h, 0e6h, 0e2h, 0fch, 0fbh, 0e7h, 0f8h, 0fdh, 0f9h, 0f7h, 0fah, 0deh, 0c0h, 0c1h, 0d6h, 0c4h, 0c5h, 0d4h, 0c3h, 0d5h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0dfh, 0d0h, 0d1h, 0d2h, 0d3h, 0c6h, 0c2h, 0dch, 0dbh, 0c7h, 0d8h, 0ddh, 0d9h, 0d7h, 0dah
;3->2
Koi8r_Cp10007_tbl:
db 6h
db 096h, 09ah, 0c3h, 0c5h, 0b2h, 0b3h, 0cah
db 09ch, 09ch, 0a1h
db 09fh, 09fh, 0d6h
db 0a3h, 0a3h, 0deh
db 0b3h, 0b3h, 0ddh
db 0bfh, 0ffh, 0a9h, 0feh, 0e0h, 0e1h, 0f6h, 0e4h, 0e5h, 0f4h, 0e3h, 0f5h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0dfh, 0f0h, 0f1h, 0f2h, 0f3h, 0e6h, 0e2h, 0fch, 0fbh, 0e7h, 0f8h, 0fdh, 0f9h, 0f7h, 0fah, 09eh, 080h, 081h, 096h, 084h, 085h, 094h, 083h, 095h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 09fh, 090h, 091h, 092h, 093h, 086h, 082h, 09ch, 09bh, 087h, 098h, 09dh, 099h, 097h, 09ah
;3->4
Koi8r_Mac_tbl:
db 6h
db 096h, 09ah, 0c3h, 0c5h, 0b2h, 0b3h, 0cah
db 09ch, 09ch, 0a1h
db 09fh, 09fh, 0d6h
db 0a3h, 0a3h, 0deh
db 0b3h, 0b3h, 0ddh
db 0bfh, 0ffh, 0a9h, 0feh, 0e0h, 0e1h, 0f6h, 0e4h, 0e5h, 0f4h, 0e3h, 0f5h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0dfh, 0f0h, 0f1h, 0f2h, 0f3h, 0e6h, 0e2h, 0fch, 0fbh, 0e7h, 0f8h, 0fdh, 0f9h, 0f7h, 0fah, 09eh, 080h, 081h, 096h, 084h, 085h, 094h, 083h, 095h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 09fh, 090h, 091h, 092h, 093h, 086h, 082h, 09ch, 09bh, 087h, 098h, 09dh, 099h, 097h, 09ah
;3->5
Koi8r_Cp8859_5_tbl:
db 5h
db 09ah, 09ah, 0a0h
db 0a3h, 0a3h, 0f1h
db 0b3h, 0b3h, 0a1h
db 0c0h, 0d5h, 0eeh, 0d0h, 0d1h, 0e6h, 0d4h, 0d5h, 0e4h, 0d3h, 0e5h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0efh, 0e0h, 0e1h, 0e2h, 0e3h
db 0d7h, 0ffh, 0d2h, 0ech, 0ebh, 0d7h, 0e8h, 0edh, 0e9h, 0e7h, 0eah, 0ceh, 0b0h, 0b1h, 0c6h, 0b4h, 0b5h, 0c4h, 0b3h, 0c5h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh, 0bfh, 0cfh, 0c0h, 0c1h, 0c2h, 0c3h, 0b6h, 0b2h, 0cch, 0cbh, 0b7h, 0c8h, 0cdh, 0c9h, 0c7h, 0cah
;4->0
Mac_Cp866_tbl:
db 6h
db 0a1h, 0a1h, 0f8h
db 0b8h, 0bbh, 0f2h, 0f3h, 0f4h, 0f5h
db 0c3h, 0c3h, 0fbh
db 0cah, 0cah, 0ffh
db 0d8h, 0d9h, 0f6h, 0f7h
db 0dch, 0feh, 0fch, 0f0h, 0f1h, 0efh, 0a0h, 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh
;4->1
Mac_Cp1251_tbl:
db 9h
db 080h, 0a2h, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 086h, 0b0h, 0a5h
db 0a4h, 0a8h, 0a7h, 095h, 0b6h, 0b2h, 0aeh
db 0aah, 0ach, 099h, 080h, 090h
db 0aeh, 0afh, 081h, 083h
db 0b4h, 0b4h, 0b3h
db 0b6h, 0c2h, 0b4h, 0a3h, 0aah, 0bah, 0afh, 0bfh, 08ah, 09ah, 08ch, 09ch, 0bch, 0bdh, 0ach
db 0c7h, 0d5h, 0abh, 0bbh, 085h, 0a0h, 08eh, 09eh, 08dh, 09dh, 0beh, 096h, 098h, 093h, 094h, 091h, 092h
db 0d7h, 0dfh, 084h, 0a1h, 0a2h, 08fh, 09fh, 0b9h, 0a8h, 0b8h, 0ffh
db 0ffh, 0ffh, 088h
;5->0
Cp8859_5_Cp866_tbl:
db 9h
db 0a0h, 0a1h, 0ffh, 0f0h
db 0a4h, 0a4h, 0f2h
db 0a7h, 0a7h, 0f4h
db 0aeh, 0aeh, 0f6h
db 0b0h, 0dfh, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0a0h, 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh
db 0f0h, 0f0h, 0fch
db 0f4h, 0f4h, 0f3h
db 0f7h, 0f7h, 0f5h
db 0feh, 0feh, 0f7h
;5->1
Cp8859_5_Cp1251_tbl:
db 2h
db 0a1h, 0ach, 0a8h, 080h, 081h, 0aah, 0bdh, 0b2h, 0afh, 0a3h, 08ah, 08ch, 08eh, 08dh
db 0aeh, 0ffh, 0a1h, 08fh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0ffh, 0b9h, 0b8h, 090h, 083h, 0bah, 0beh, 0b3h, 0bfh, 0bch, 09ah, 09ch, 09eh, 09dh, 0a7h, 0a2h, 09fh
;5->2+4
Cp8859_5_Mac_tbl:
db 2h
db 0a0h, 0ach, 0cah, 0ddh, 0abh, 0aeh, 0b8h, 0c1h, 0a7h, 0bah, 0b7h, 0bch, 0beh, 0cbh, 0cdh
db 0aeh, 0ffh, 0d8h, 0dah, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0dfh, 0dch, 0deh, 0ach, 0afh, 0b9h, 0cfh, 0b4h, 0bbh, 0c0h, 0bdh, 0bfh, 0cch, 0ceh, 0a4h, 0d9h, 0dbh
;5->3
Cp8859_5_Koi8r_tbl:
db 4h
db 0a0h, 0a1h, 09ah, 0b3h
db 0b0h, 0d5h, 0e1h, 0e2h, 0f7h, 0e7h, 0e4h, 0e5h, 0f6h, 0fah, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f2h, 0f3h, 0f4h, 0f5h, 0e6h, 0e8h, 0e3h, 0feh, 0fbh, 0fdh, 0ffh, 0f9h, 0f8h, 0fch, 0e0h, 0f1h, 0c1h, 0c2h, 0d7h, 0c7h, 0c4h, 0c5h
db 0d7h, 0efh, 0dah, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d2h, 0d3h, 0d4h, 0d5h, 0c6h, 0c8h, 0c3h, 0deh, 0dbh, 0ddh, 0dfh, 0d9h, 0d8h, 0dch, 0c0h, 0d1h
db 0f1h, 0f1h, 0a3h
;wchar->0
Utf16_Cp866_tbl:
db 01eh
dw 0a0h, 0a0h
db 0ffh
dw 0a4h, 0a4h
db 0fdh
dw 0b0h, 0b0h
db 0f8h
dw 0b7h, 0b7h
db 0fah
dw 0401h, 0401h
db 0f0h
dw 0404h, 0404h
db 0f2h
dw 0407h, 0407h
db 0f4h
dw 040eh, 0451h
db 0f6h, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0a0h, 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f1h, 0h, 0h
dw 0454h, 0454h
db 0f3h
dw 0457h, 0457h
db 0f5h
dw 045eh, 045eh
db 0f7h
dw 02116h, 02116h
db 0fch
dw 02219h, 0221ah
db 0f9h, 0fbh
dw 02500h, 02501h
db 0c4h, 0b3h
dw 0250ch, 0250ch
db 0dah
dw 02510h, 02510h
db 0bfh
dw 02514h, 02514h
db 0c0h
dw 02518h, 02518h
db 0d9h
dw 0251ch, 0251ch
db 0c3h
dw 02524h, 02524h
db 0b4h
dw 0252ch, 0252ch
db 0c2h
dw 02534h, 02534h
db 0c1h
dw 0253ch, 0253ch
db 0c5h
dw 02550h, 0256ch
db 0cdh, 0bah, 0d5h, 0d6h, 0c9h, 0b8h, 0b7h, 0bbh, 0d4h, 0d3h, 0c8h, 0beh, 0bdh, 0bch, 0c6h, 0c7h, 0cch, 0b5h, 0b6h, 0b9h, 0d1h, 0d2h, 0cbh, 0cfh, 0d0h, 0cah, 0d8h, 0d7h, 0ceh
dw 02580h, 02580h
db 0dfh
dw 02584h, 02584h
db 0dch
dw 02588h, 02588h
db 0dbh
dw 0258ch, 0258ch
db 0ddh
dw 02590h, 02593h
db 0deh, 0b0h, 0b1h, 0b2h
dw 025a0h, 025a0h
db 0feh
Utf16_Cp1251_tbl:
;wchar->1
db 0ch
dw 00401h, 045fh
db 0a8h, 080h, 081h, 0aah, 0bdh, 0b2h, 0afh, 0a3h, 08ah, 08ch, 08eh, 08dh, 0a1h, 08fh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0ffh, 0b8h, 090h, 083h, 0bah, 0beh, 0b3h, 0bfh, 0bch, 09ah, 09ch, 09eh, 09dh, 0a2h, 09fh, 0h, 0h, 0h
dw 0490h, 0491h
db 0a5h, 0b4h
dw 02013h, 02014h
db 096h, 098h
dw 02018h, 0201ah
db 091h, 092h, 082h
dw 0201ch, 0201eh
db 093h, 094h, 084h
dw 02020h, 02022h
db 086h, 087h, 095h
dw 02026h, 02026h
db 085h
dw 02030h, 02030h
db 089h
dw 02039h, 0203ah
db 08bh, 09bh
dw 020ach, 020ach
db 088h
dw 02116h, 02116h
db 0b9h
dw 02122h, 02122h
db 099h
;wchar->2
Utf16_Cp10007_tbl:
db 019h
dw 0a0h, 0a0h
db 0cah
dw 0a4h, 0a4h
db 0ffh
dw 0a7h, 0a7h
db 0a4h
dw 0abh, 0ach
db 0c7h, 0c2h
dw 0aeh, 0b0h
db 0a8h, 0a1h, 084h
dw 0b6h, 0b6h
db 0a6h
dw 0bbh, 0bbh
db 0c8h
dw 0f7h, 0f7h
db 0d6h
dw 0192h, 0192h
db 0c4h
dw 0401h, 045fh
db 0ddh, 0abh, 0aeh, 0b8h, 0c1h, 0a7h, 0bah, 0b7h, 0bch, 0beh, 0cbh, 0cdh, 0d8h, 0dah, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0dfh, 0deh, 0ach, 0afh, 0b9h, 0cfh, 0b4h, 0bbh, 0c0h, 0bdh, 0bfh, 0cch, 0ceh, 0d9h, 0dbh, 0h, 0h, 0h
dw 02013h, 02014h
db 0d0h, 0d1h
dw 02018h, 02019h
db 0d4h, 0d5h
dw 0201ch, 0201eh
db 0d2h, 0d3h, 0d7h
dw 02020h, 02020h
db 0a0h
dw 02022h, 02022h
db 0a5h
dw 02026h, 02026h
db 0c9h
dw 02116h, 02116h
db 0dch
dw 02122h, 02122h
db 0aah
dw 02202h, 02202h
db 0b6h
dw 02206h, 02206h
db 0c6h
dw 0221ah, 0221ah
db 0c3h
dw 0221eh, 0221eh
db 0b0h
dw 02248h, 02248h
db 0c5h
dw 02260h, 02260h
db 0adh
dw 02264h, 02265h
db 0b2h, 0b3h
;wchar->3
Utf16_Koi8r_tbl:
db 01dh
dw 0a0h, 0a0h
db 09ah
dw 0a9h, 0a9h
db 0bfh
dw 0b0h, 0b0h
db 09ch
dw 0b2h, 0b2h
db 09dh
dw 0b7h, 0b7h
db 09eh
dw 0f7h, 0f7h
db 09fh
dw 0401h, 0401h
db 0b3h
dw 0410h, 0451h
db 0e1h, 0e2h, 0f7h, 0e7h, 0e4h, 0e5h, 0f6h, 0fah, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f2h, 0f3h, 0f4h, 0f5h, 0e6h, 0e8h, 0e3h, 0feh, 0fbh, 0fdh, 0ffh, 0f9h, 0f8h, 0fch, 0e0h, 0f1h, 0c1h, 0c2h, 0d7h, 0c7h, 0c4h, 0c5h, 0d6h, 0dah, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d2h, 0d3h, 0d4h, 0d5h, 0c6h, 0c8h, 0c3h, 0deh, 0dbh, 0ddh, 0dfh, 0d9h, 0d8h, 0dch, 0c0h, 0d1h, 0a3h, 0f1h
dw 02219h, 0221ah
db 095h, 096h
dw 02248h, 02248h
db 097h
dw 02264h, 02265h
db 098h, 099h
dw 02320h, 02321h
db 093h, 09bh
dw 02500h, 02502h
db 080h, 081h, 0d7h
dw 0250ch, 0250ch
db 082h
dw 02510h, 02510h
db 083h
dw 02514h, 02514h
db 084h
dw 02518h, 02518h
db 085h
dw 0251ch, 0251ch
db 086h
dw 02524h, 02524h
db 087h
dw 0252ch, 0252ch
db 088h
dw 02534h, 02534h
db 089h
dw 0253ch, 0253ch
db 08ah
dw 02550h, 0256ch
db 0a0h, 0a1h, 0a2h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0adh, 0aeh, 0afh, 0b0h, 0b1h, 0b2h, 0b4h, 0b5h, 0b6h, 0b7h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh
dw 02580h, 02580h
db 08bh
dw 02584h, 02584h
db 08ch
dw 02588h, 02588h
db 08dh
dw 0258ch, 0258ch
db 08eh
dw 02590h, 02593h
db 08fh, 090h, 091h, 092h
dw 025a0h, 025a0h
db 094h
;wchar->4
Utf16_Mac_tbl:
db 019h
dw 0a0h, 0a0h
db 0cah
db 0a7h, 0a7h
dw 0a4h
dw 0abh, 0ach
db 0c7h, 0c2h
dw 0aeh, 0b0h
db 0a8h, 0a1h, 082h
dw 0b6h, 0b6h
db 0a6h
dw 0bbh, 0bbh
db 0c8h
dw 0f7h, 0f7h
db 0d6h
dw 0192h, 0192h
db 0c4h
dw 0401h, 045fh
db 0ddh, 0abh, 0aeh, 0b8h, 0c1h, 0a7h, 0bah, 0b7h, 0bch, 0beh, 0cbh, 0cdh, 0d8h, 0dah, 080h, 081h, 082h, 083h, 084h, 085h, 086h, 087h, 088h, 089h, 08ah, 08bh, 08ch, 08dh, 08eh, 08fh, 090h, 091h, 092h, 093h, 094h, 095h, 096h, 097h, 098h, 099h, 09ah, 09bh, 09ch, 09dh, 09eh, 09fh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f0h, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0fdh, 0feh, 0dfh, 0deh, 0ach, 0afh, 0b9h, 0cfh, 0b4h, 0bbh, 0c0h, 0bdh, 0bfh, 0cch, 0ceh, 0d9h, 0dbh, 0h, 0h, 0h
dw 0490h, 0491h
db 0a2h, 0b6h
dw 02013h, 02014h
db 0d0h, 0d1h
dw 02018h, 02019h
db 0d4h, 0d5h
dw 0201ch, 0201eh
db 0d2h, 0d3h, 0d7h
dw 02020h, 02020h
db 0a0h
dw 02022h, 02022h
db 0a5h
dw 02026h, 02026h
db 0c9h
dw 020ach, 020ach
db 0ffh
dw 02116h, 02116h
db 0dch
dw 02122h, 02122h
db 0aah
dw 02206h, 02206h
db 0c6h
dw 0221ah, 0221ah
db 0c3h
dw 0221eh, 0221eh
db 0b0h
dw 02248h, 02248h
db 0c5h
dw 02260h, 02260h
db 0adh
dw 02264h, 02265h
db 0b2h, 0b3h
;wchar->5
Utf16_Cp8859_5_tbl:
db 3h
dw 0a7h, 0a7h
db 0fdh
dw 0401h, 045fh
db 0a1h, 0a2h, 0a3h, 0a4h, 0a5h, 0a6h, 0a7h, 0a8h, 0a9h, 0aah, 0abh, 0ach, 0aeh, 0afh, 0b0h, 0b1h, 0b2h, 0b3h, 0b4h, 0b5h, 0b6h, 0b7h, 0b8h, 0b9h, 0bah, 0bbh, 0bch, 0bdh, 0beh, 0bfh, 0c0h, 0c1h, 0c2h, 0c3h, 0c4h, 0c5h, 0c6h, 0c7h, 0c8h, 0c9h, 0cah, 0cbh, 0cch, 0cdh, 0ceh, 0cfh, 0d0h, 0d1h, 0d2h, 0d3h, 0d4h, 0d5h, 0d6h, 0d7h, 0d8h, 0d9h, 0dah, 0dbh, 0dch, 0ddh, 0deh, 0dfh, 0e0h, 0e1h, 0e2h, 0e3h, 0e4h, 0e5h, 0e6h, 0e7h, 0e8h, 0e9h, 0eah, 0ebh, 0ech, 0edh, 0eeh, 0efh, 0f1h, 0f2h, 0f3h, 0f4h, 0f5h, 0f6h, 0f7h, 0f8h, 0f9h, 0fah, 0fbh, 0fch, 0feh, 0ffh, 0h, 0h, 0h
dw 02116h, 02116h
db 0f0h
;0->wchar
Cp866_Utf16_tbl:
db 1h
db 080h, 0ffh
dw 0410h, 0411h, 0412h, 0413h, 0414h, 0415h, 0416h, 0417h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 0420h, 0421h, 0422h, 0423h, 0424h, 0425h, 0426h, 0427h, 0428h, 0429h, 042ah, 042bh, 042ch, 042dh, 042eh, 042fh, 0430h, 0431h, 0432h, 0433h, 0434h, 0435h, 0436h, 0437h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 02591h, 02592h, 02593h, 02502h, 02524h, 02561h, 02562h, 02556h, 02555h, 02563h, 02551h, 02557h, 0255dh, 0255ch, 0255bh, 02510h, 02514h, 02534h, 0252ch, 0251ch, 02500h, 0253ch, 0255eh, 0255fh, 0255ah, 02554h, 02569h, 02566h, 02560h, 02550h, 0256ch, 02567h, 02568h, 02564h, 02565h, 02559h, 02558h, 02552h, 02553h, 0256bh, 0256ah, 02518h, 0250ch, 02588h, 02584h, 0258ch, 02590h, 02580h, 0440h, 0441h, 0442h, 0443h, 0444h, 0445h, 0446h, 0447h, 0448h, 0449h, 044ah, 044bh, 044ch, 044dh, 044eh, 044fh, 0401h, 0451h, 0404h, 0454h, 0407h, 0457h, 040eh, 045eh, 0b0h, 02219h, 0b7h, 0221ah, 02116h, 0a4h, 025a0h, 0a0h
;1->wchar
Cp1251_Utf16_tbl:
db 0ah
db 080h, 096h
dw 0402h, 0403h, 0201ah, 0453h, 0201eh, 02026h, 02020h, 02021h, 020ach, 02030h, 0409h, 02039h, 040ah, 040ch, 040bh, 040fh, 0452h, 02018h, 02019h, 0201ch, 0201dh, 02022h, 02013h
db 098h, 09fh
dw 02014h, 02122h, 0459h, 0203ah, 045ah, 045ch, 045bh, 045fh
db 0a1h, 0a3h
dw 040eh, 045eh, 0408h
db 0a5h, 0a5h
dw 0490h
db 0a8h, 0a8h
dw 0401h
db 0aah, 0aah
dw 0404h
db 0afh, 0afh
dw 0407h
db 0b2h, 0b4h
dw 0406h, 0456h, 0491h
db 0b8h, 0bah
dw 0451h, 02116h, 0454h
dw 0bch, 0ffh, 0458h, 0405h, 0455h, 0457h, 0410h, 0411h, 0412h, 0413h, 0414h, 0415h, 0416h, 0417h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 0420h, 0421h, 0422h, 0423h, 0424h, 0425h, 0426h, 0427h, 0428h, 0429h, 042ah, 042bh, 042ch, 042dh, 042eh, 042fh, 0430h, 0431h, 0432h, 0433h, 0434h, 0435h, 0436h, 0437h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 0440h, 0441h, 0442h, 0443h, 0444h, 0445h, 0446h, 0447h, 0448h, 0449h, 044ah, 044bh, 044ch, 044dh, 044eh, 044fh
;2->wchar
Cp10007_Utf16_tbl:
db 5h
db 080h, 0a1h
dw 0410h, 0411h, 0412h, 0413h, 0414h, 0415h, 0416h, 0417h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 0420h, 0421h, 0422h, 0423h, 0424h, 0425h, 0426h, 0427h, 0428h, 0429h, 042ah, 042bh, 042ch, 042dh, 042eh, 042fh, 02020h, 0b0h
db 0a4h, 0a8h
dw 0a7h, 02022h, 0b6h, 0406h, 0aeh
db 0aah, 0b0h
dw 02122h, 0402h, 0452h, 02260h, 0403h, 0453h, 0221eh
db 0b2h, 0b4h
dw 02264h, 02265h, 0456h
db 0b6h, 0ffh
dw 02202h, 0408h, 0404h, 0454h, 0407h, 0457h, 0409h, 0459h, 040ah, 045ah, 0458h, 0405h, 0ach, 0221ah, 0192h, 02248h, 02206h, 0abh, 0bbh, 02026h, 0a0h, 040bh, 045bh, 040ch, 045ch, 0455h, 02013h, 02014h, 0201ch, 0201dh, 02018h, 02019h, 0f7h, 0201eh, 040eh, 045eh, 040fh, 045fh, 02116h, 0401h, 0451h, 044fh, 0430h, 0431h, 0432h, 0433h, 0434h, 0435h, 0436h, 0437h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 0440h, 0441h, 0442h, 0443h, 0444h, 0445h, 0446h, 0447h, 0448h, 0449h, 044ah, 044bh, 044ch, 044dh, 044eh, 0a4h
;3->wchar
Koi8r_Utf16_tbl:
db 1h
db 080h, 0ffh
dw 02500h, 02502h, 0250ch, 02510h, 02514h, 02518h, 0251ch, 02524h, 0252ch, 02534h, 0253ch, 02580h, 02584h, 02588h, 0258ch, 02590h, 02591h, 02592h, 02593h, 02320h, 025a0h, 02219h, 0221ah, 02248h, 02264h, 02265h, 0a0h, 02321h, 0b0h, 0b2h, 0b7h, 0f7h, 02550h, 02551h, 02552h, 0451h, 02553h, 02554h, 02555h, 02556h, 02557h, 02558h, 02559h, 0255ah, 0255bh, 0255ch, 0255dh, 0255eh, 0255fh, 02560h, 02561h, 0401h, 02562h, 02563h, 02564h, 02565h, 02566h, 02567h, 02568h, 02569h, 0256ah, 0256bh, 0256ch, 0a9h, 044eh, 0430h, 0431h, 0446h, 0434h, 0435h, 0444h, 0433h, 0445h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 044fh, 0440h, 0441h, 0442h, 0443h, 0436h, 0432h, 044ch, 044bh, 0437h, 0448h, 044dh, 0449h, 0447h, 044ah, 042eh, 0410h, 0411h, 0426h, 0414h, 0415h, 0424h, 0413h, 0425h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 042fh, 0420h, 0421h, 0422h, 0423h, 0416h, 0412h, 042ch, 042bh, 0417h, 0428h, 042dh, 0429h, 0427h, 042ah
;4->wchar
Mac_Utf16_tbl:
db 5h
db 080h, 0a2h
dw 0410h, 0411h, 0412h, 0413h, 0414h, 0415h, 0416h, 0417h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 0420h, 0421h, 0422h, 0423h, 0424h, 0425h, 0426h, 0427h, 0428h, 0429h, 042ah, 042bh, 042ch, 042dh, 042eh, 042fh, 02020h, 0b0h, 0490h
db 0a4h, 0a8h
dw 0a7h, 02022h, 0b6h, 0406h, 0aeh
db 0aah, 0b0h
dw 02122h, 0402h, 0452h, 02260h, 0403h, 0453h, 0221eh
db 0b2h, 0b4h
dw 02264h, 02265h, 0456h
db 0b6h, 0ffh
dw 0491h, 0408h, 0404h, 0454h, 0407h, 0457h, 0409h, 0459h, 040ah, 045ah, 0458h, 0405h, 0ach, 0221ah, 0192h, 02248h, 02206h, 0abh, 0bbh, 02026h, 0a0h, 040bh, 045bh, 040ch, 045ch, 0455h, 02013h, 02014h, 0201ch, 0201dh, 02018h, 02019h, 0f7h, 0201eh, 040eh, 045eh, 040fh, 045fh, 02116h, 0401h, 0451h, 044fh, 0430h, 0431h, 0432h, 0433h, 0434h, 0435h, 0436h, 0437h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 0440h, 0441h, 0442h, 0443h, 0444h, 0445h, 0446h, 0447h, 0448h, 0449h, 044ah, 044bh, 044ch, 044dh, 044eh, 020ach
;5->wchar
Cp8859_5_Utf16_tbl:
db 2h
db 0a1h, 0ach
dw 0401h, 0402h, 0403h, 0404h, 0405h, 0406h, 0407h, 0408h, 0409h, 040ah, 040bh, 040ch
db 0aeh, 0ffh
dw 040eh, 040fh, 0410h, 0411h, 0412h, 0413h, 0414h, 0415h, 0416h, 0417h, 0418h, 0419h, 041ah, 041bh, 041ch, 041dh, 041eh, 041fh, 0420h, 0421h, 0422h, 0423h, 0424h, 0425h, 0426h, 0427h, 0428h, 0429h, 042ah, 042bh, 042ch, 042dh, 042eh, 042fh, 0430h, 0431h, 0432h, 0433h, 0434h, 0435h, 0436h, 0437h, 0438h, 0439h, 043ah, 043bh, 043ch, 043dh, 043eh, 043fh, 0440h, 0441h, 0442h, 0443h, 0444h, 0445h, 0446h, 0447h, 0448h, 0449h, 044ah, 044bh, 044ch, 044dh, 044eh, 044fh, 02116h, 0451h, 0452h, 0453h, 0454h, 0455h, 0456h, 0457h, 0458h, 0459h, 045ah, 045bh, 045ch, 0a7h, 045eh, 045fh
CheckRange label dword
db Range_0_9_8, Range_0_9_8r, Range_0_9_16, Range_0_9_rutf, 10, 0
db Range_a_f_8, Range_a_f_8r, Range_a_f_16, Range_a_f_rutf, 16, 10
db Range_A_F_8, Range_A_F_8r, Range_A_F_16, Range_A_F_rutf, 16, 10
db 0
CheckTable label dword
; CHECKSYMBOL <FUNCTION_SYMBOL,GetPlusSign,0,0>
; CHECKSYMBOL <FUNCTION_SYMBOL,GetMinusSign,0,MINUS_SIGN>
; CHECKSYMBOL <FUNCTION_SYMBOL,GetFloationPointSign,FLOAT_VALUE,0>
CHECKSYMBOL <Symbol_e, EXP_VALUE, EXP_FLAG, SIGN_FLAG OR NUMBER_FLAG, 10>
CHECKSYMBOL <Symbol_ec, EXP_VALUE, EXP_FLAG, SIGN_FLAG OR NUMBER_FLAG, 10>
CHECKSYMBOL <Symbol_h, HEX_VALUE, MODE_FLAG, SEPARATOR_FLAG, 16>
CHECKSYMBOL <Symbol_hc,HEX_VALUE, MODE_FLAG, SEPARATOR_FLAG, 16>
CHECKSYMBOL <Symbol_x, HEX_VALUE, MODE_FLAG, NUMBER_FLAG OR ZERO_FLAG, 16>
CHECKSYMBOL <Symbol_xc, HEX_VALUE, MODE_FLAG, NUMBER_FLAG OR ZERO_FLAG, 16>
CHECKSYMBOL <Symbol_q, OCTAL_VALUE, MODE_FLAG, SEPARATOR_FLAG, 8>
CHECKSYMBOL <Symbol_qc, OCTAL_VALUE, MODE_FLAG, SEPARATOR_FLAG, 8>
CHECKSYMBOL <Symbol_b, BIN_VALUE, MODE_FLAG, SEPARATOR_FLAG, 2>
CHECKSYMBOL <Symbol_bc, BIN_VALUE, MODE_FLAG, SEPARATOR_FLAG, 2>
Floating_point_symbol:
CHECKSYMBOL <Symbol_es, FLOAT_VALUE, FLOAT_DOT_FLAG, NUMBER_FLAG OR SEPARATOR_FLAG OR EXP_FLAG, 10>
Positive_sign_symbol:
CHECKSYMBOL <Symbol_ps, POS_VALUE, SIGN_FLAG, NUMBER_FLAG OR MODE_FLAG OR FLOAT_DOT_FLAG OR ZERO_FLAG OR MODE_ZERO_FLAG, 0>
Negative_sign_symbol:
CHECKSYMBOL <Symbol_ms, NEG_VALUE, SIGN_FLAG, NUMBER_FLAG OR MODE_FLAG OR FLOAT_DOT_FLAG OR ZERO_FLAG OR MODE_ZERO_FLAG, 0>
db 0
; CHECKSYMBOL <PARAMETER_SYMBOL,'E',FLOAT_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'E',FLOAT_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'e',FLOAT_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'H',HEX_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'h',HEX_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'X',HEX_VALUE,HEX_SIGN>
; CHECKSYMBOL <PARAMETER_SYMBOL,'x',HEX_VALUE,HEX_SIGN>
; CHECKSYMBOL <PARAMETER_SYMBOL,'Q',OCTAL_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'q',OCTAL_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'B',BIN_VALUE,0>
; CHECKSYMBOL <PARAMETER_SYMBOL,'b',BIN_VALUE,0>
db 0
;Range_0_9_8 label byte
; db '0', '9'
;Range_0_9_8r label byte
; db 26h, 2fh
;Range_0_9_16 label word
; dw '0', '9'
;Range_0_9_rutf label dword
; dd 26h, 2fh
Range_0_9 SYMBOL <>,<>
Range_a_f SYMBOL <>,<>
Range_ac_fc SYMBOL <>,<>
;Range_a_f_8 label byte
; db 'a', 'f'
;Range_a_f_8r label byte
; db 80h, 85h
;Range_a_f_16 label word
; dw 'a', 'f'
;Range_a_f_rutf label dword
; dd 80h, 85h
;Range_ac_fc_8 label byte
; db 'A', 'F'
;Range_ac_fc_8r label byte
; db 0a0h, 0a5h
;Range_ac_fc_16 label word
; dw 'A', 'F'
;Range_ac_fc_rutf label dword
; dd 0a0h, 0a5h
Symbol_e SYMBOL <'e', 084h, 'e', 084h>
Symbol_ec SYMBOL <'E', 0a4h, 'E', 0a4h>
Symbol_h SYMBOL <'h', 84h, 'h', 84h>
Symbol_hc SYMBOL <'H',0a4h,'H',0a4h>
Symbol_x SYMBOL <'x',84h,'x',84h>
Symbol_xc SYMBOL <'X',0a4h,'X',0a4h>
Symbol_q SYMBOL <'q',84h,'q',84h>
Symbol_qc SYMBOL <'Q',0a4h,'Q',0a4h>
Symbol_b SYMBOL <'b',81h,'b',81h>
Symbol_bc SYMBOL <'B',0a1h,'B',0a1h>
Symbol_ms SYMBOL <'-',0a1h,'-',0a1h>
Symbol_ps SYMBOL <'+',0a1h,'+',0a1h>
Symbol_es SYMBOL <',',0a1h,',',0a1h>
ToIntTable label dword
dd @FastString@$oi$xqqrv_FromInt
dd @FastString@$oi$xqqrv_FromFloat
dd @FastString@$oi$xqqrv_FromExp
dd @FastString@$oi$xqqrv_FromHex
dd @FastString@$oi$xqqrv_FromOctal
dd @FastString@$oi$xqqrv_FromBinary
end
| 26.504497 | 949 | 0.685439 |
3ba1a8556dc3e56fb2976854e794aa631d2a5fe4 | 4,856 | h | C | test/unit/set/test_set_data.h | gidabite/libcds | f10fef7ff8c9d1abb4af1cfbf9ae5c60f9911014 | [
"BSD-2-Clause"
] | 2,118 | 2015-01-01T00:30:42.000Z | 2022-03-30T12:47:38.000Z | test/unit/set/test_set_data.h | liangwens/libcds | b4d11539824bb91ae4604f47aa1416fdd7cc1ff1 | [
"BSL-1.0"
] | 113 | 2015-01-03T15:29:40.000Z | 2022-03-05T21:30:11.000Z | test/unit/set/test_set_data.h | liangwens/libcds | b4d11539824bb91ae4604f47aa1416fdd7cc1ff1 | [
"BSL-1.0"
] | 385 | 2015-01-01T21:51:48.000Z | 2022-03-25T12:51:30.000Z | // Copyright (c) 2006-2018 Maxim Khizhinsky
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef CDSUNIT_SET_TEST_SET_DATA_H
#define CDSUNIT_SET_TEST_SET_DATA_H
#include <cds_test/check_size.h>
#include <cds_test/fixture.h>
#include <cds/opt/hash.h>
// forward declaration
namespace cds { namespace container {}}
namespace cds_test {
namespace co = cds::opt;
class container_set_data : public fixture
{
public:
static size_t const kSize = 1000;
struct stat
{
unsigned int nFindCount;
unsigned int nUpdateNewCount;
unsigned int nUpdateCount;
mutable unsigned int nEraseCount;
stat()
{
clear_stat();
}
void clear_stat()
{
memset( this, 0, sizeof( *this ));
}
};
struct other_item {
int nKey;
explicit other_item( int k )
: nKey( k )
{}
int key() const
{
return nKey;
}
};
struct int_item: public stat
{
int nKey;
int nVal;
std::string strVal;
int_item()
: nKey( 0 )
, nVal( 0 )
{}
explicit int_item( int k )
: nKey( k )
, nVal( k * 2 )
{}
template <typename Q>
explicit int_item( Q const& src )
: nKey( src.key())
, nVal( 0 )
{}
int_item( int_item const& src )
: nKey( src.nKey )
, nVal( src.nVal )
, strVal( src.strVal )
{}
int_item( int_item&& src )
: nKey( src.nKey )
, nVal( src.nVal )
, strVal( std::move( src.strVal ))
{}
int_item( int k, std::string&& s )
: nKey( k )
, nVal( k * 2 )
, strVal( std::move( s ))
{}
explicit int_item( other_item const& s )
: nKey( s.key())
, nVal( s.key() * 2 )
{}
int key() const
{
return nKey;
}
};
struct hash_int {
size_t operator()( int i ) const
{
return co::v::hash<int>()(i);
}
template <typename Item>
size_t operator()( const Item& i ) const
{
return (*this)(i.key());
}
};
struct simple_item_counter {
size_t m_nCount;
simple_item_counter()
: m_nCount( 0 )
{}
size_t operator ++()
{
return ++m_nCount;
}
size_t operator --()
{
return --m_nCount;
}
void reset()
{
m_nCount = 0;
}
operator size_t() const
{
return m_nCount;
}
};
struct less
{
bool operator ()( int_item const& v1, int_item const& v2 ) const
{
return v1.key() < v2.key();
}
template <typename Q>
bool operator ()( int_item const& v1, const Q& v2 ) const
{
return v1.key() < v2;
}
template <typename Q>
bool operator ()( const Q& v1, int_item const& v2 ) const
{
return v1 < v2.key();
}
};
struct cmp {
int operator ()( int_item const& v1, int_item const& v2 ) const
{
if ( v1.key() < v2.key())
return -1;
return v1.key() > v2.key() ? 1 : 0;
}
template <typename T>
int operator ()( T const& v1, int v2 ) const
{
if ( v1.key() < v2 )
return -1;
return v1.key() > v2 ? 1 : 0;
}
template <typename T>
int operator ()( int v1, T const& v2 ) const
{
if ( v1 < v2.key())
return -1;
return v1 > v2.key() ? 1 : 0;
}
};
struct other_less {
template <typename Q, typename T>
bool operator()( Q const& lhs, T const& rhs ) const
{
return lhs.key() < rhs.key();
}
};
};
} // namespace cds_test
#endif // CDSUNIT_SET_TEST_SET_DATA_H
| 23.687805 | 79 | 0.401565 |
7d23b003b31775f1b4418d328519d7903bfb7a7f | 783 | swift | Swift | Sources/SDGSwiftSource/Syntax/Syntax Nodes/Types/AttributedTypeSyntax.swift | SDGGiesbrecht/SDGSwift | 5b9f76f26ae136a5d762b6fb51861bbd8aa4672e | [
"Apache-2.0"
] | 53 | 2018-04-23T03:03:33.000Z | 2022-03-31T23:09:35.000Z | Sources/SDGSwiftSource/Syntax/Syntax Nodes/Types/AttributedTypeSyntax.swift | SDGGiesbrecht/SDGSwift | 5b9f76f26ae136a5d762b6fb51861bbd8aa4672e | [
"Apache-2.0"
] | 28 | 2018-11-02T13:32:47.000Z | 2021-12-29T04:38:45.000Z | Sources/SDGSwiftSource/Syntax/Syntax Nodes/Types/AttributedTypeSyntax.swift | SDGGiesbrecht/SDGSwift | 5b9f76f26ae136a5d762b6fb51861bbd8aa4672e | [
"Apache-2.0"
] | null | null | null | /*
AttributedTypeSyntax.swift
This source file is part of the SDGSwift open source project.
https://sdggiesbrecht.github.io/SDGSwift
Copyright ©2018–2021 Jeremy David Giesbrecht and the SDGSwift project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
#if !PLATFORM_NOT_SUPPORTED_BY_SWIFT_SYNTAX
import SwiftSyntax
extension AttributedTypeSyntax {
internal func normalized() -> AttributedTypeSyntax {
return SyntaxFactory.makeAttributedType(
specifier: specifier?.generallyNormalized(trailingTrivia: .spaces(1)),
attributes: attributes?.normalizedForAPIDeclaration(),
baseType: baseType.normalized()
)
}
}
#endif
| 27 | 84 | 0.752235 |
2f78ba25d8a0f154f3b5a52b6b229b098a0b903b | 282 | cs | C# | src/SmtpPilot/ConsoleBehavior.cs | cmcquillan/SMTPileIt | 0b529e0bcef23ca6b665d1b058e0c5986799894c | [
"MIT"
] | 4 | 2021-01-26T18:19:29.000Z | 2021-07-20T11:59:45.000Z | src/SmtpPilot/ConsoleBehavior.cs | cmcquillan/SMTPileIt | 0b529e0bcef23ca6b665d1b058e0c5986799894c | [
"MIT"
] | 3 | 2021-02-20T23:19:31.000Z | 2021-02-22T04:14:14.000Z | src/SmtpPilot/ConsoleBehavior.cs | cmcquillan/SMTPileIt | 0b529e0bcef23ca6b665d1b058e0c5986799894c | [
"MIT"
] | null | null | null | using System;
namespace SmtpPilot
{
internal static class ConsoleBehavior
{
internal static void ExitWithError(string errorMessage, ExitCode code)
{
ConsoleHooks.LogInfo(errorMessage);
Environment.Exit((int)code);
}
}
}
| 20.142857 | 78 | 0.62766 |
d27c22fe943c6805e81b30f89049f8b237508458 | 2,223 | php | PHP | Mob/Conf/router.php | terrydeng/beimeibang1205 | 1893bb355aaa81ba8655e45c1ef3ad88a21fbdaf | [
"Apache-2.0"
] | null | null | null | Mob/Conf/router.php | terrydeng/beimeibang1205 | 1893bb355aaa81ba8655e45c1ef3ad88a21fbdaf | [
"Apache-2.0"
] | null | null | null | Mob/Conf/router.php | terrydeng/beimeibang1205 | 1893bb355aaa81ba8655e45c1ef3ad88a21fbdaf | [
"Apache-2.0"
] | null | null | null | <?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 14-8-27
* Time: 下午4:54
* @author 嘉兴想天信息科技有限公司-郑钟良<zzl@ourstu.com>
*/
return array(
/**
* 路由的key必须写全称,且必须全小写. 比如: 使用'wap/index/index', 而非'wap'.
*/
'router' => array(
//消息
/*轻博客*/
'Weibo/Index/weiboDetail' =>'Mob/Weibo/weiboDetail',
/*专辑*/
'Issue/Index/issueContentDetail' =>'/mob/issue/issuedetail',
/*资讯*/
'News/Index/detail' =>'mob/blog/blogdetail',
/*问答*/
'Question/Index/detail' =>'mob/question/questiondetail',
/*论坛*/
'Forum/Index/detail#' =>'mob/forum/postdetail',
/*活动*/
'Event/Index/member' =>'mob/event/detail',
/*问答*/
'Question/index/detail' =>'mob/question/questiondetail',
/*群组*/
'Group/index/detail' =>'mob/group/detail',
/*分类信息*/
'Cat/Center/rec' =>'mob/cat/detail',
/*积分商城*/
'Shop/Index/myGoods' =>'mob/shop/myorder',
/*微店*/
'store/center/sold' =>'mob/store/soldsell',
//入口
/*活动*/
'Event/index/index' =>'mob/event/index',
/*论坛*/
'Forum/index/index' =>'mob/forum/index',
/*专辑*/
'Issue/index/index' =>'mob/issue/index',
/*资讯*/
'News/index/index' =>'mob/blog/index',
/*会员*/
'People/index/index' =>'mob/people/index',
/*问答*/
'Question/index/index' =>'mob/question/index',
/*轻博客*/
'Weibo/index/index' =>'mob/weibo/index',
/*用户中心*/
'Ucenter/index/index' =>'mob/user/index',
/*群组*/
'Group/index/index' =>'mob/group/index',
/*分类信息 */
'Cat/index/index' =>'mob/cat/index',
/*积分商城*/
'Shop/index/index' =>'mob/shop/index',
/*商城*/
'Store/index/index' =>'mob/store/index',
),
); | 28.139241 | 80 | 0.420153 |
3bf3530ce5a26d3c8418af19c7e9f77ac991965d | 1,073 | html | HTML | project/LOL/jineng.html | shuaiyiji/KVO | aa77665de6f606143e2013d0c12155bd96e3753d | [
"MIT"
] | null | null | null | project/LOL/jineng.html | shuaiyiji/KVO | aa77665de6f606143e2013d0c12155bd96e3753d | [
"MIT"
] | null | null | null | project/LOL/jineng.html | shuaiyiji/KVO | aa77665de6f606143e2013d0c12155bd96e3753d | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title></title>
<link href="css.css" rel="stylesheet">
</head>
<body>
<!--238, 221, 204-->
<header>
<div id="banner_3"></div>
<nav>
<ul>
<li ><a href="index.html">主页</a></li>
<li><a href="jiqiao.html">技巧</a></li>
<li><a class="active">技能</a></li>
<li><a href="paihang.html">排行榜</a></li>
<li><a href="lianxi.html">联系作者</a></li>
</ul>
</nav>
</header>
<article>
<div class="container" id="jineng">
<h1>英雄的四个技能</h1>
<ul id=>
<li><a href="images/qq.jpg" title="天音波/回音击【快捷键Q"><img src="images/q.jpg" alt></a></li>
<li><a href="images/ww.jpg" title="金钟罩/铁布衫【快捷键W"><img src="images/w.jpg"></a></li>
<li><a href="images/ee.jpg" title="天雷破/摧筋断骨【快捷键E"><img src="images/e.jpg"></a></li>
<li><a href="images/rr.jpg" title="猛龙摆尾【快捷键R】"><img src="images/r.jpg"></a></li>
</ul>
</div>
</article>
<script src="add.js"></script>
</body>
</html> | 29 | 98 | 0.50233 |
57ba30d7a1665ad1251b76de89030a14ee4a91e2 | 4,170 | go | Go | codegen/plugin.go | kmacmcfarlane/goa | 9a06a898c5ab449143635c1b28be49aba9ee2cf9 | [
"MIT"
] | 4,468 | 2016-01-21T09:30:44.000Z | 2022-03-31T14:55:56.000Z | codegen/plugin.go | c-spider/Api-by-goa | 863186d31c4286265f950c5c740049fde3572917 | [
"MIT"
] | 1,928 | 2016-01-21T17:35:14.000Z | 2022-03-30T22:55:07.000Z | codegen/plugin.go | c-spider/Api-by-goa | 863186d31c4286265f950c5c740049fde3572917 | [
"MIT"
] | 600 | 2016-01-21T02:49:49.000Z | 2022-03-19T16:33:23.000Z | package codegen
import "goa.design/goa/v3/eval"
type (
// GenerateFunc makes it possible to modify the files generated by the
// goa code generators and other plugins. A GenerateFunc accepts the Go
// import path of the "gen" package, the design roots as well as the
// currently generated files (produced initially by the goa generators
// and potentially modified by previously run plugins) and returns a new
// set of files.
GenerateFunc func(genpkg string, roots []eval.Root, files []*File) ([]*File, error)
// PrepareFunc makes it possible to modify the design roots before
// the files being generated by the goa code generators or other plugins.
PrepareFunc func(genpkg string, roots []eval.Root) error
// plugin is a plugin that has been registered with a given command.
plugin struct {
// PrepareFunc is the plugin preparation function.
PrepareFunc
// GenerateFunc is the plugin generator function.
GenerateFunc
// name is the plugin name.
name string
// cmd is the name of cmd to run.
cmd string
// if first is set the plugin cmd must run before all other plugins.
first bool
// if last is set the plugin cmd must run after all other plugins.
last bool
}
)
// plugins keeps track of the registered plugins sorted by their first/last bools,
// names, or registration order.
var plugins []*plugin
// RegisterPlugin adds the plugin to the list of plugins to be invoked with the
// given command.
func RegisterPlugin(name string, cmd string, pre PrepareFunc, p GenerateFunc) {
np := &plugin{name: name, PrepareFunc: pre, GenerateFunc: p, cmd: cmd}
var inserted bool
for i, plgn := range plugins {
if plgn.last || (!plgn.first && np.name < plgn.name) {
plugins = append(plugins[:i], append([]*plugin{np}, plugins[i:]...)...)
inserted = true
break
}
}
if !inserted {
plugins = append(plugins, np)
}
}
// RegisterPluginFirst adds the plugin to the beginning of the list of plugins
// to be invoked with the given command. If more than one plugins are registered
// using this, the plugins will be sorted alphabetically by their names. If two
// plugins have same names, then they are sorted by registration order.
func RegisterPluginFirst(name string, cmd string, pre PrepareFunc, p GenerateFunc) {
np := &plugin{name: name, PrepareFunc: pre, GenerateFunc: p, cmd: cmd, first: true}
var inserted bool
for i, plgn := range plugins {
if !plgn.first || np.name < plgn.name {
plugins = append(plugins[:i], append([]*plugin{np}, plugins[i:]...)...)
inserted = true
break
}
}
if !inserted {
plugins = append(plugins, np)
}
}
// RegisterPluginLast adds the plugin to the end of the list of plugins
// to be invoked with the given command. If more than one plugins are registered
// using this, the plugins will be sorted alphabetically by their names. If two
// plugins have same names, then they are sorted by registration order.
func RegisterPluginLast(name string, cmd string, pre PrepareFunc, p GenerateFunc) {
np := &plugin{name: name, PrepareFunc: pre, GenerateFunc: p, cmd: cmd, last: true}
var inserted bool
for i := len(plugins) - 1; i >= 0; i-- {
plgn := plugins[i]
if !plgn.last || plgn.name < np.name {
plugins = append(plugins[:i+1], append([]*plugin{np}, plugins[i+1:]...)...)
inserted = true
break
}
}
if !inserted {
plugins = append(plugins, np)
}
}
// RunPluginsPrepare executes the plugins prepare functions in the order
// they were registered.
func RunPluginsPrepare(cmd, genpkg string, roots []eval.Root) error {
for _, plugin := range plugins {
if plugin.cmd != cmd {
continue
}
if plugin.PrepareFunc != nil {
err := plugin.PrepareFunc(genpkg, roots)
if err != nil {
return err
}
}
}
return nil
}
// RunPlugins executes the plugins registered with the given command in the order
// they were registered.
func RunPlugins(cmd, genpkg string, roots []eval.Root, genfiles []*File) ([]*File, error) {
for _, plugin := range plugins {
if plugin.cmd != cmd {
continue
}
gs, err := plugin.GenerateFunc(genpkg, roots, genfiles)
if err != nil {
return nil, err
}
genfiles = gs
}
return genfiles, nil
}
| 32.834646 | 91 | 0.704317 |
0a28d902527a39764092bff24d526b46cfec2006 | 1,860 | ts | TypeScript | src/interfaces/shopify-module-options.ts | visionarylab/nestjs-shopify-module | 42aafcb9ff89dd3d220377bd293a0cf96d657048 | [
"MIT"
] | 1 | 2022-02-15T23:01:50.000Z | 2022-02-15T23:01:50.000Z | src/interfaces/shopify-module-options.ts | visionarylab/nestjs-shopify-module | 42aafcb9ff89dd3d220377bd293a0cf96d657048 | [
"MIT"
] | null | null | null | src/interfaces/shopify-module-options.ts | visionarylab/nestjs-shopify-module | 42aafcb9ff89dd3d220377bd293a0cf96d657048 | [
"MIT"
] | null | null | null | import { IPlan } from '../charge/interfaces/plan';
import { Enums } from 'shopify-admin-api';
import * as redisStore from 'cache-manager-ioredis';
import { Resource } from './resource'
export interface ConfigApp {
root: string;
protocol: 'https' | 'http';
host: string;
port: number;
debug: boolean;
test: boolean;
environment: 'production' | 'development' | 'test';
}
export interface ConfigSync {
enabled: boolean;
/**
* Resources wich should be auto synced to the app's database, e.g. ['orders', 'blogs']
*/
autoSyncResources: Resource[];
}
export interface ConfigShopify {
/** client id / Api key */
clientID: string;
/** shared secret / client Secret / API secret key */
clientSecret: string;
/** callback url / redirect url */
callbackURL: string;
/** callback url used in shopify iframe */
iframeCallbackURL: string;
// successRedirectURL?: string;
// failureRedirectURL?: string;
scope: string[];
webhooks: {
autoSubscribe: Enums.WebhookTopic[];
};
}
export interface ConfigCharges {
plans: IPlan[];
frontend_return_url: string;
}
export interface ConfigCache {
store: 'memory' | typeof redisStore;
ttl: number;
max: number;
[Key: string]: any;
}
export interface ConfigRedis {
host?: string;
auth_pass?: string;
username?: string;
port?: number;
url?: string;
}
export interface ConfigMongoDB {
host?: string;
port?: number;
username?: string;
password?: string;
database?: string;
/** Optional MongoDB connection string */
url?: string;
}
export interface ShopifyModuleOptions {
app: ConfigApp;
sync: ConfigSync;
shopify: ConfigShopify;
charges: ConfigCharges;
/**
* Cache manager options
* @see https://github.com/BryanDonovan/node-cache-manager
*/
cache: ConfigCache;
redis?: ConfigRedis;
mongodb: ConfigMongoDB;
} | 20.43956 | 89 | 0.679032 |
29b0f2be7e83fe60ee894c20cd16ffd6b1b46a06 | 2,870 | dart | Dart | client/dart/lib/model/error_response.dart | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | null | null | null | client/dart/lib/model/error_response.dart | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | null | null | null | client/dart/lib/model/error_response.dart | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | null | null | null | //
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.0
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of projectname-client;
class ErrorResponse {
/// Returns a new [ErrorResponse] instance.
ErrorResponse({
@required this.message,
@required this.code,
this.error,
});
String message;
String code;
String error;
@override
bool operator ==(Object other) => identical(this, other) || other is ErrorResponse &&
other.message == message &&
other.code == code &&
other.error == error;
@override
int get hashCode =>
// ignore: unnecessary_parenthesis
(message == null ? 0 : message.hashCode) +
(code == null ? 0 : code.hashCode) +
(error == null ? 0 : error.hashCode);
@override
String toString() => 'ErrorResponse[message=$message, code=$code, error=$error]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'message'] = message;
json[r'code'] = code;
if (error != null) {
json[r'error'] = error;
}
return json;
}
/// Returns a new [ErrorResponse] instance and imports its values from
/// [value] if it's a [Map], null otherwise.
// ignore: prefer_constructors_over_static_methods
static ErrorResponse fromJson(dynamic value) {
if (value is Map) {
final json = value.cast<String, dynamic>();
return ErrorResponse(
message: mapValueOfType<String>(json, r'message'),
code: mapValueOfType<String>(json, r'code'),
error: mapValueOfType<String>(json, r'error'),
);
}
return null;
}
static List<ErrorResponse> listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) =>
json is List && json.isNotEmpty
? json.map(ErrorResponse.fromJson).toList(growable: true == growable)
: true == emptyIsNull ? null : <ErrorResponse>[];
static Map<String, ErrorResponse> mapFromJson(dynamic json) {
final map = <String, ErrorResponse>{};
if (json is Map && json.isNotEmpty) {
json
.cast<String, dynamic>()
.forEach((key, dynamic value) => map[key] = ErrorResponse.fromJson(value));
}
return map;
}
// maps a json object with a list of ErrorResponse-objects as value to a dart map
static Map<String, List<ErrorResponse>> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) {
final map = <String, List<ErrorResponse>>{};
if (json is Map && json.isNotEmpty) {
json
.cast<String, dynamic>()
.forEach((key, dynamic value) {
map[key] = ErrorResponse.listFromJson(
value,
emptyIsNull: emptyIsNull,
growable: growable,
);
});
}
return map;
}
}
| 28.415842 | 109 | 0.640767 |
8bcef631fffe4ce7b77843f0735458b5601f68ea | 1,339 | dart | Dart | state_managent/managing_states/lib/main.dart | shreyasSarve/FlutterBeginer | a84a91356590e1c9ca2f734565c2d1ece8000cdb | [
"Apache-2.0"
] | 1 | 2021-12-13T14:09:41.000Z | 2021-12-13T14:09:41.000Z | state_managent/managing_states/lib/main.dart | shreyasSarve/FlutterBeginer | a84a91356590e1c9ca2f734565c2d1ece8000cdb | [
"Apache-2.0"
] | null | null | null | state_managent/managing_states/lib/main.dart | shreyasSarve/FlutterBeginer | a84a91356590e1c9ca2f734565c2d1ece8000cdb | [
"Apache-2.0"
] | null | null | null | import 'package:flutter/material.dart';
import 'myStateful.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
Color _color = Colors.red;
Map<Color, int> myFavoColors = {};
int counter = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Managing State"),
),
body:
MyStateful(changeColor),
floatingActionButton: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _color,
),
width: 70,
height: 70,
child: IconButton(
icon: const Icon(
Icons.add,
color: Colors.amber,
size: 50,
),
onPressed: addToFavorite),
),
),
);
}
void changeColor(Color color) {
setState(() {
_color = color;
});
}
void addToFavorite() {
// if (!myFavoColors.containsKey(_color)) {
// counter++;
// myFavoColors[_color] = counter;
// }
// print(myFavoColors);
// }
}
}
| 20.6 | 49 | 0.528753 |
3b234e37f257e65d6b2f4bc6a44eb63d51c8cdc5 | 253 | ps1 | PowerShell | src/Scriptbook/Public/Scriptbook/Import-Parameters.ps1 | ehagen/Scriptbook | 884d7f37c754f285a216e312723fa94506ad603a | [
"MIT"
] | 2 | 2021-09-23T09:45:44.000Z | 2022-01-27T20:34:33.000Z | src/Scriptbook/Public/Scriptbook/Import-Parameters.ps1 | ehagen/Scriptbook | 884d7f37c754f285a216e312723fa94506ad603a | [
"MIT"
] | 7 | 2021-08-28T07:07:07.000Z | 2022-01-18T18:49:06.000Z | src/Scriptbook/Public/Scriptbook/Import-Parameters.ps1 | ehagen/Scriptbook | 884d7f37c754f285a216e312723fa94506ad603a | [
"MIT"
] | null | null | null | <#
.SYNOPSIS
Imports Parameters from File
.DESCRIPTION
Imports Parameters from File
.PARAMETER File
Name of the File
#>
function Import-Parameters
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
$File
)
. $File
} | 13.315789 | 34 | 0.660079 |
7e839eb7a6cc2f90b50f0608ca8914b8bcba6ee1 | 1,886 | lua | Lua | lua/wmChat/modules/anonyChat/anonyChat/baseChannel/channel_default.lua | Watermelon914/chatHTML | df9795b1df77be5cf054a96cefde7f1bd8a611e7 | [
"MIT"
] | null | null | null | lua/wmChat/modules/anonyChat/anonyChat/baseChannel/channel_default.lua | Watermelon914/chatHTML | df9795b1df77be5cf054a96cefde7f1bd8a611e7 | [
"MIT"
] | null | null | null | lua/wmChat/modules/anonyChat/anonyChat/baseChannel/channel_default.lua | Watermelon914/chatHTML | df9795b1df77be5cf054a96cefde7f1bd8a611e7 | [
"MIT"
] | null | null | null | CHANNEL.Name = "Default"
CHANNEL.isDefault = true
CHANNEL.Styles = { // Styles to implement when using messageSent
bold = {
["font-weight"] = "bold",
["font-size"] = "1em",
},
normal = {
["color"] = Color(255, 255, 255),
["font-size"] = "1em",
},
italic = {
["font-style"] = "italic",
["color"] = Color(255, 255, 255),
["font-size"] = "1em",
}
}
CHANNEL.canHearMessage = function(self, sender, listener, msg) return true end // Run a function for whether the player can hear this message or not
CHANNEL.shouldSend = function(self, ply, msg) return true end // Run a function for whether a message should go to this chat or not
CHANNEL.messageSent = function(self, ply, msg) return msg end
CHANNEL.messageReceivedByPlayer = function(self, ply, msg, args, chats) //This is called when the client receives the messages from another player
local tab = {}
local styles = table.Copy(self.Styles)
styles.bold["color"] = team.GetColor(ply:Team())
table.insert(tab, styles.bold)
table.insert(tab, ply:GetName())
table.insert(tab, styles.normal)
table.insert(tab, ": ")
if #chats > 1 then
table.insert(tab, styles.italic)
end
table.insert(tab, msg)
return tab
end
CHANNEL.messageReceived = function(self, msg, args, chats) //This is called when a client receives a message from a non-player entity (e.g. the world) or a null entity
local tab = {}
local styles = table.Copy(self.Styles)
table.insert(tab, styles.bold)
if args[1] then
table.insert(tab, args[1]..": ")
end
table.insert(tab, msg)
return tab
end
CHANNEL.priority = 0 //This'll prevent it from sending to other chats if this value is higher than other chat values. Keep at 0 if you don't know what you're doing
CHANNEL.orderPriority = 0 | 30.419355 | 167 | 0.645281 |
2a596563cbea3753d077e78aff2790774b9e1ea0 | 25,156 | sql | SQL | data/mysql/phanbook.sql | duythien/docker | d4485d78a7d82bfea5662d48727b6a248da02900 | [
"MIT"
] | 2 | 2017-06-01T08:12:24.000Z | 2017-08-17T03:16:43.000Z | data/mysql/phanbook.sql | phanbook/docker | d4485d78a7d82bfea5662d48727b6a248da02900 | [
"MIT"
] | null | null | null | data/mysql/phanbook.sql | phanbook/docker | d4485d78a7d82bfea5662d48727b6a248da02900 | [
"MIT"
] | null | null | null | -- MySQL dump 10.13 Distrib 5.7.15, for Linux (x86_64)
--
-- Host: localhost Database: phanbook
-- ------------------------------------------------------
-- Server version 5.7.15
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!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' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `activities`
--
DROP TABLE IF EXISTS `activities`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `activities` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`type` char(1) NOT NULL,
`postsId` int(10) unsigned DEFAULT NULL,
`createdAt` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `createdAt` (`createdAt`),
KEY `usersId` (`usersId`),
KEY `postsId` (`postsId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `activityNotifications`
--
DROP TABLE IF EXISTS `activityNotifications`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `activityNotifications` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`postsId` int(10) unsigned NOT NULL,
`postsReplyId` int(10) unsigned DEFAULT NULL,
`type` char(1) COLLATE utf8_unicode_ci NOT NULL,
`usersOriginId` int(10) unsigned DEFAULT NULL,
`createdAt` int(11) unsigned DEFAULT NULL,
`wasRead` char(1) COLLATE utf8_unicode_ci NOT NULL,
`extra` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`,`wasRead`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `audit`
--
DROP TABLE IF EXISTS `audit`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `audit` (
`id` char(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`userId` mediumint(8) unsigned NOT NULL,
`ipaddress` int(10) unsigned NOT NULL,
`type` char(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`createdAt` datetime NOT NULL,
`modelName` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `auditDetail`
--
DROP TABLE IF EXISTS `auditDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auditDetail` (
`id` char(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`auditId` char(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`fieldName` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`oldValue` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`newValue` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `categories`
--
DROP TABLE IF EXISTS `categories`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(10) unsigned NOT NULL,
`name` varchar(72) NOT NULL,
`description` text NOT NULL,
`slug` varchar(32) DEFAULT NULL,
`numberPosts` int(10) unsigned DEFAULT NULL,
`noBounty` char(1) NOT NULL DEFAULT 'N',
`noDigest` char(1) NOT NULL DEFAULT 'N',
PRIMARY KEY (`id`),
KEY `categoriesNumberPosts` (`numberPosts`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `comment`
--
DROP TABLE IF EXISTS `comment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comment` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userId` int(11) unsigned NOT NULL,
`objectId` int(11) unsigned NOT NULL,
`object` varchar(32) NOT NULL DEFAULT '',
`content` mediumtext NOT NULL,
`createdAt` int(11) NOT NULL,
`modifiedAt` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idUser` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `failedLogins`
--
DROP TABLE IF EXISTS `failedLogins`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `failedLogins` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`usersId` INT UNSIGNED DEFAULT NULL,
`ipAddress` INT UNSIGNED NOT NULL,
`attempted` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
KEY `failedLoginsAttempts` (`ipAddress`, `attempted`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `media`
--
DROP TABLE IF EXISTS `media`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `media` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`metaFile` longtext NOT NULL,
`createdAt` int(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mediaType`
--
DROP TABLE IF EXISTS `mediaType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mediaType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`code` varchar(255) NOT NULL,
`note` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notifications`
--
DROP TABLE IF EXISTS `notifications`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notifications` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`postsId` int(10) unsigned NOT NULL,
`postsReplyId` int(10) unsigned DEFAULT NULL,
`type` char(1) NOT NULL,
`createdAt` int(11) unsigned DEFAULT NULL,
`modifiedAt` int(11) unsigned DEFAULT NULL,
`messageId` char(60) DEFAULT NULL,
`sent` char(1) NOT NULL DEFAULT 'N',
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`),
KEY `postsId` (`postsId`),
KEY `sent` (`sent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notificationsBounces`
--
DROP TABLE IF EXISTS `notificationsBounces`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notificationsBounces` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(120) NOT NULL,
`status` varchar(10) DEFAULT NULL,
`diagnostic` varchar(120) DEFAULT NULL,
`createdAt` int(10) unsigned NOT NULL,
`reported` char(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `email` (`email`,`reported`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `posts`
--
DROP TABLE IF EXISTS `posts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`type` varchar(10) NOT NULL,
`title` varchar(128) NOT NULL,
`link` varchar(250) DEFAULT NULL,
`slug` varchar(64) NOT NULL,
`content` text,
`excerpt` text,
`thumbnail` varchar(200) DEFAULT NULL,
`numberViews` int(5) unsigned NOT NULL,
`numberReply` int(3) unsigned NOT NULL,
`sticked` char(1) DEFAULT 'N',
`createdAt` int(11) unsigned DEFAULT NULL,
`modifiedAt` int(11) unsigned DEFAULT NULL,
`editedAt` int(11) unsigned DEFAULT NULL,
`status` char(30) DEFAULT NULL,
`locked` char(1) DEFAULT 'N',
`deleted` int(3) DEFAULT '0',
`acceptedAnswer` char(1) DEFAULT 'N',
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`),
KEY `title` (`title`),
KEY `modifiedAt` (`modifiedAt`),
KEY `createdAt` (`createdAt`),
KEY `sticked` (`sticked`,`createdAt`),
KEY `deleted` (`deleted`),
KEY `numberReply` (`numberReply`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsBounties`
--
DROP TABLE IF EXISTS `postsBounties`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsBounties` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsId` int(10) unsigned NOT NULL,
`usersId` int(10) unsigned NOT NULL,
`postsReplyId` int(10) unsigned NOT NULL,
`points` int(10) unsigned NOT NULL,
`createdAt` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`,`postsReplyId`),
KEY `postsId` (`postsId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsHistory`
--
DROP TABLE IF EXISTS `postsHistory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsHistory` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsId` int(10) unsigned NOT NULL,
`usersId` int(10) unsigned NOT NULL,
`createdAt` int(11) unsigned NOT NULL,
`content` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
KEY `postsId` (`postsId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsNotifications`
--
DROP TABLE IF EXISTS `postsNotifications`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsNotifications` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`postsId` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`,`postsId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsReply`
--
DROP TABLE IF EXISTS `postsReply`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsReply` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsId` int(10) unsigned NOT NULL,
`usersId` int(10) unsigned NOT NULL,
`content` text,
`createdAt` int(11) unsigned DEFAULT NULL,
`modifiedAt` int(11) unsigned DEFAULT NULL,
`editedAt` int(11) unsigned DEFAULT NULL,
`deleted` int(11) NOT NULL DEFAULT '0',
`accepted` char(1) DEFAULT 'N',
PRIMARY KEY (`id`),
KEY `postsId` (`postsId`),
KEY `usersId` (`usersId`),
KEY `deleted` (`deleted`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsReplyHistory`
--
DROP TABLE IF EXISTS `postsReplyHistory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsReplyHistory` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsReplyId` int(10) unsigned NOT NULL,
`usersId` int(10) unsigned NOT NULL,
`createdAt` int(11) unsigned NOT NULL,
`content` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
KEY `postsReplyId` (`postsReplyId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsSubscribers`
--
DROP TABLE IF EXISTS `postsSubscribers`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsSubscribers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsId` int(10) unsigned NOT NULL,
`usersId` int(10) unsigned NOT NULL,
`createdAt` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `postsId` (`postsId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsTags`
--
DROP TABLE IF EXISTS `postsTags`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsTags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`postsId` int(11) NOT NULL,
`tagsId` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `postsViews`
--
DROP TABLE IF EXISTS `postsViews`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postsViews` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`postsId` int(10) unsigned NOT NULL,
`ipaddress` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `postsId` (`postsId`,`ipaddress`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `rememberTokens`
--
DROP TABLE IF EXISTS `rememberTokens`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rememberTokens` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(11) unsigned NOT NULL,
`token` varchar(32) NOT NULL,
`userAgent` varchar(250) NOT NULL,
`createdAt` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `settings`
--
DROP TABLE IF EXISTS `settings`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`value` varchar(1000) NOT NULL,
`note` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_setting_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `shortUrls`
--
DROP TABLE IF EXISTS `shortUrls`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shortUrls` (
`id` int(15) unsigned NOT NULL AUTO_INCREMENT,
`longUrl` varchar(255) NOT NULL,
`shortCode` varbinary(6) NOT NULL,
`createdAt` int(11) unsigned NOT NULL,
`counter` int(15) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `shortCode` (`shortCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `subscribe`
--
DROP TABLE IF EXISTS `subscribe`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `subscribe` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(40) NOT NULL,
`status` char(1) NOT NULL DEFAULT 'Y',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `successLogins`
--
DROP TABLE IF EXISTS `successLogins`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `successLogins` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`usersId` INT UNSIGNED NOT NULL,
`ipAddress` INT UNSIGNED NOT NULL,
`userAgent` VARCHAR(250) NOT NULL,
PRIMARY KEY (`id`),
KEY `successLoginsUserId` (`usersId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `tags`
--
DROP TABLE IF EXISTS `tags`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tags` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(72) NOT NULL,
`description` text NOT NULL,
`slug` varchar(32) DEFAULT NULL,
`numberPosts` int(10) unsigned DEFAULT NULL,
`noBounty` char(1) NOT NULL DEFAULT 'N',
`noDigest` char(1) NOT NULL DEFAULT 'N',
PRIMARY KEY (`id`),
KEY `numberPosts` (`numberPosts`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `template`
--
DROP TABLE IF EXISTS `template`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL DEFAULT '',
`key` varchar(64) NOT NULL DEFAULT '',
`subject` varchar(255) DEFAULT NULL,
`content` text,
PRIMARY KEY (`id`),
UNIQUE KEY `key` (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `topicTracking`
--
DROP TABLE IF EXISTS `topicTracking`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `topicTracking` (
`userId` int(11) NOT NULL,
`topicId` text NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `translations`
--
DROP TABLE IF EXISTS `translations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `translations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`language` varchar(5) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`key_name` varchar(48) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`value` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(72) DEFAULT NULL,
`email` varchar(70) DEFAULT NULL,
`firstname` varchar(50) DEFAULT NULL,
`lastname` varchar(40) DEFAULT NULL,
`tokenType` varchar(16) DEFAULT NULL,
`tokenGithub` char(100) DEFAULT NULL,
`tokenGoogle` char(100) DEFAULT NULL,
`tokenFacebook` char(100) DEFAULT NULL,
`uid` char(50) DEFAULT NULL,
`uuidFacebook` varchar(100) DEFAULT NULL,
`uuidGoogle` varchar(100) DEFAULT NULL,
`uuidGithub` varchar(100) DEFAULT NULL,
`createdAt` int(11) unsigned DEFAULT NULL,
`modifiedAt` int(11) unsigned DEFAULT NULL,
`notifications` char(1) DEFAULT 'N',
`digest` char(1) DEFAULT 'Y',
`timezone` varchar(48) DEFAULT NULL,
`karma` int(11) DEFAULT NULL,
`vote` int(10) unsigned DEFAULT NULL,
`votePoint` int(11) DEFAULT NULL,
`gender` int(1) NOT NULL DEFAULT '9',
`birthdate` date DEFAULT NULL,
`passwd` varchar(60) NOT NULL,
`registerHash` varchar(60) DEFAULT NULL,
`passwdForgotHash` varchar(60) DEFAULT NULL,
`lastPasswdReset` int(11) DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT '3',
`theme` char(1) DEFAULT 'D',
`bio` text,
`twitter` varchar(100) DEFAULT NULL,
`github` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `accessToken` (`tokenGithub`),
KEY `email` (`email`),
KEY `karma` (`karma`),
KEY `notifications` (`notifications`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT INTO `users` (`id`, `username`, `email`, `firstname`, `createdAt`, `passwd`, `status`) VALUES
(1,'admin','admin@phanbook.com','Admin', 1427816610, '$2a$12$wCpQq8iqKlKhFdwh7SgKVeEmjkuriZYje20RKq5/lN3HuNKAvb.i2', 1);
--
-- Table structure for table `roles`
--
DROP TABLE IF EXISTS `roles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roles` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL,
`description` TEXT,
`type` VARCHAR(32) NOT NULL,
`is_special` BOOLEAN DEFAULT FALSE,
`is_default` BOOLEAN DEFAULT FALSE,
PRIMARY KEY(`id`),
UNIQUE KEY `role_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT INTO `roles` (`id`, `name`, `description`, `type`, `is_special`, `is_default`) VALUES
(1, 'Admins', 'Administrative user, has access to everything.', 'admin', true, false),
(2, 'Moderators', 'The regular members with moderation privileges.', 'moderator', true, false),
(3, 'Users', 'Member privileges, granted after account confirmation.', 'user', true, true),
(4, 'Anonymous', 'Guests can only view content. Anyone browsing the site who is not signed in is considered to be a "Guest".', 'guest', true, false);
--
-- Table structure for table `roles_users`
--
DROP TABLE IF EXISTS `roles_users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roles_users` (
`users_id` BIGINT UNSIGNED NOT NULL,
`roles_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`users_id`, `roles_id`),
KEY `roles_users_users_id` (`users_id`),
KEY `roles_users_roles_id` (`roles_id`),
FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`roles_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT INTO `roles_users` (`users_id`, `roles_id`) VALUES
(1, 1),
(1, 2),
(1, 3);
--
-- Table structure for table `access`
--
DROP TABLE IF EXISTS `access`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `access` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`object` VARCHAR(64) NOT NULL,
`action` VARCHAR(255) NOT NULL,
`role_id` INT UNSIGNED NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
INSERT INTO `access` (`id`, `object`, `action`, `role_id`, `value`) VALUES
(1, 'AdminArea', 'access', 1, 'allow'),
(2, 'AdminArea', 'access', 2, 'deny'),
(3, 'AdminArea', 'access', 3, 'deny');
--
-- Table structure for table `usersBadges`
--
DROP TABLE IF EXISTS `usersBadges`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usersBadges` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(10) unsigned NOT NULL,
`badge` varchar(24) COLLATE utf8_unicode_ci NOT NULL,
`type` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
`code1` int(10) unsigned DEFAULT NULL,
`code2` int(10) unsigned DEFAULT NULL,
`code3` int(1) DEFAULT NULL,
`createdAt` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `usersId` (`usersId`,`badge`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vote`
--
DROP TABLE IF EXISTS `vote`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vote` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`usersId` int(11) unsigned NOT NULL,
`objectId` int(11) unsigned NOT NULL,
`object` varchar(32) NOT NULL DEFAULT '',
`positive` int(11) NOT NULL DEFAULT '0',
`negative` int(11) NOT NULL DEFAULT '0',
`createdAt` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `objectId` (`objectId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2016-11-10 18:07:26
| 34.22585 | 153 | 0.702894 |
6cd90258e0fea8b61ea3066d399644ee365924a1 | 31,516 | go | Go | cpsAsicdClnt/asicdExtObjClnt.go | learnopx/opx-flxcps | def0f7da34d7a9616092fd088bcb7bf1e9ab5bd7 | [
"Apache-2.0"
] | null | null | null | cpsAsicdClnt/asicdExtObjClnt.go | learnopx/opx-flxcps | def0f7da34d7a9616092fd088bcb7bf1e9ab5bd7 | [
"Apache-2.0"
] | null | null | null | cpsAsicdClnt/asicdExtObjClnt.go | learnopx/opx-flxcps | def0f7da34d7a9616092fd088bcb7bf1e9ab5bd7 | [
"Apache-2.0"
] | null | null | null | //
//Copyright [2016] [SnapRoute 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.
//
// _______ __ __________ ___ _______.____ __ ____ __ .___________. ______ __ __
// | ____|| | | ____\ \ / / / |\ \ / \ / / | | | | / || | | |
// | |__ | | | |__ \ V / | (----` \ \/ \/ / | | `---| |----`| ,----'| |__| |
// | __| | | | __| > < \ \ \ / | | | | | | | __ |
// | | | `----.| |____ / . \ .----) | \ /\ / | | | | | `----.| | | |
// |__| |_______||_______/__/ \__\ |_______/ \__/ \__/ |__| |__| \______||__| |__|
//
package cpsAsicdClnt
import (
"errors"
"fmt"
"models/objects"
"net"
"sync"
"utils/clntUtils/clntDefs/asicdClntDefs"
)
/*
#include <stdint.h>
#include <stdlib.h>
#include <cps.h>
#cgo CFLAGS: -I. -I/usr/include/
#cgo LDFLAGS: -L/usr/lib/x86_64-linux-gnu/ -lopx_common -lopx_cps_api_common
*/
import "C"
var cpsAsicdMutex *sync.Mutex = &sync.Mutex{}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkAsicGlobalState(fromIndex int, count int) (*asicdClntDefs.AsicGlobalStateGetInfo, error) {
var retObj asicdClntDefs.AsicGlobalStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetAsicGlobalState(ModuleId uint8) (*objects.AsicGlobalState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAsicGlobalPM(cfg *objects.AsicGlobalPM) (bool, error) {
return false, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAsicGlobalPM(origCfg, newCfg *objects.AsicGlobalPM, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAsicGlobalPM(cfg *objects.AsicGlobalPM) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkAsicGlobalPM(fromIndex int, count int) (*asicdClntDefs.AsicGlobalPMGetInfo, error) {
var retObj asicdClntDefs.AsicGlobalPMGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetAsicGlobalPM(ModuleId uint8, Resource string) (*objects.AsicGlobalPM, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkAsicGlobalPMState(fromIndex int, count int) (*asicdClntDefs.AsicGlobalPMStateGetInfo, error) {
var retObj asicdClntDefs.AsicGlobalPMStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetAsicGlobalPMState(ModuleId uint8, Resource string) (*objects.AsicGlobalPMState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateEthernetPM(cfg *objects.EthernetPM) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateEthernetPM(origCfg, newCfg *objects.EthernetPM, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteEthernetPM(cfg *objects.EthernetPM) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkEthernetPM(fromIndex int, count int) (*asicdClntDefs.EthernetPMGetInfo, error) {
var retObj asicdClntDefs.EthernetPMGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetEthernetPM(IntfRef string, Resource string) (*objects.EthernetPM, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkEthernetPMState(fromIndex int, count int) (*asicdClntDefs.EthernetPMStateGetInfo, error) {
var retObj asicdClntDefs.EthernetPMStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetEthernetPMState(IntfRef string, Resource string) (*objects.EthernetPMState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkAsicSummaryState(fromIndex int, count int) (*asicdClntDefs.AsicSummaryStateGetInfo, error) {
var retObj asicdClntDefs.AsicSummaryStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetAsicSummaryState(ModuleId uint8) (*objects.AsicSummaryState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateVlan(cfg *objects.Vlan) (bool, error) {
var tagPortIfIdx, untagPortIfIdx []int32
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
Logger.Info("Calling CPS CreateVlan:", cfg)
tagPorts := C.MakeCharArray(C.int(len(cfg.IntfList)))
defer C.FreeCharArray(tagPorts, C.int(len(cfg.IntfList)))
for idx, intf := range cfg.IntfList {
C.SetArrayString(tagPorts, C.CString(intf), C.int(idx))
}
untagPorts := C.MakeCharArray(C.int(len(cfg.UntagIntfList)))
defer C.FreeCharArray(untagPorts, C.int(len(cfg.UntagIntfList)))
for idx, intf := range cfg.UntagIntfList {
C.SetArrayString(untagPorts, C.CString(intf), C.int(idx))
}
rv := int(C.CPSCreateVlan(C.uint32_t(cfg.VlanId), C.uint32_t(len(cfg.IntfList)), tagPorts, C.uint32_t(len(cfg.UntagIntfList)), untagPorts))
if rv != 0 {
return false, errors.New("Error Creating Vlan")
}
vlanName := fmt.Sprintf("br%d", cfg.VlanId)
intf, err := net.InterfaceByName(vlanName)
if err != nil {
Logger.Err("1 Error Create Vlan, Unable to get vlanName", vlanName)
return false, errors.New("Error CreateVlan, Unable to get interface vlanName")
}
ifIdx := int32(intf.Index)
vlanEnt, _ := asicdClientMgr.VlanDB[cfg.VlanId]
vlanEnt.VlanName = vlanName
vlanEnt.OperState = "UP"
vlanEnt.AdminState = "UP"
vlanEnt.IfIndex = ifIdx
vlanEnt.IntfList = make(map[int32]bool)
for _, tagIntf := range cfg.IntfList {
intf, err := net.InterfaceByName(tagIntf)
if err != nil {
Logger.Err("Error Create Vlan, Unable to get vlanName", tagIntf)
continue
}
vlanEnt.IntfList[int32(intf.Index)] = true
tagPortIfIdx = append(tagPortIfIdx, int32(intf.Index))
}
vlanEnt.UntagIntfList = make(map[int32]bool)
for _, untagIntf := range cfg.UntagIntfList {
intf, err := net.InterfaceByName(untagIntf)
if err != nil {
Logger.Info("Error Create Vlan, Unable to get vlanName", untagIntf)
continue
}
vlanEnt.UntagIntfList[int32(intf.Index)] = true
untagPortIfIdx = append(untagPortIfIdx, int32(intf.Index))
}
asicdClientMgr.VlanDB[cfg.VlanId] = vlanEnt
asicdClientMgr.VlanList = append(asicdClientMgr.VlanList, cfg.VlanId)
asicdClientMgr.IfIdxToIfIdMap[ifIdx] = cfg.VlanId
asicdClientMgr.IfIdxToIfTypeMap[ifIdx] = asicdClntDefs.IfTypeVlan
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteVlan(cfg *objects.Vlan) (bool, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
Logger.Info("Calling CPS DeleteVlan:", cfg)
vlanName := fmt.Sprintf("br%d", cfg.VlanId)
intf, err := net.InterfaceByName(vlanName)
if err != nil {
Logger.Info("Error Create Vlan, Unable to get vlanName", vlanName)
return false, errors.New("Error CreateVlan, Unable to get interface vlanName")
}
ifIdx := int32(intf.Index)
rv := int(C.CPSDeleteVlan(C.uint32_t(cfg.VlanId)))
if rv != 0 {
return false, errors.New("Error Delete Vlan")
}
delete(asicdClientMgr.VlanDB, cfg.VlanId)
var vlanList []int32
for idx := 0; idx < len(asicdClientMgr.VlanList); idx++ {
if cfg.VlanId != asicdClientMgr.VlanList[idx] {
vlanList = append(vlanList, cfg.VlanId)
}
}
asicdClientMgr.VlanList = asicdClientMgr.VlanList[:0]
asicdClientMgr.VlanList = nil
asicdClientMgr.VlanList = append(asicdClientMgr.VlanList, vlanList...)
delete(asicdClientMgr.IfIdxToIfIdMap, ifIdx)
delete(asicdClientMgr.IfIdxToIfTypeMap, ifIdx)
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateVlan(origCfg, newCfg *objects.Vlan, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkVlanState(fromIdx, count int) (*asicdClntDefs.VlanStateGetInfo, error) {
var retObj asicdClntDefs.VlanStateGetInfo
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var idx, numEntries int
if (fromIdx > len(asicdClientMgr.VlanList)) || (fromIdx < 0) {
Logger.Err("Invalid fromIdx vlan argument in get bulk vlan state")
return nil, errors.New("Invalid fromIdx vlan argument in get bulk vlan state")
}
if count < 0 {
Logger.Err("Invalid count in get bulk port config")
return nil, errors.New("Invalid count int get bulk port config")
}
for idx = fromIdx; idx < len(asicdClientMgr.VlanList); idx++ {
if numEntries == count {
retObj.More = true
break
}
var vlanState objects.VlanState
vlanState.VlanId = asicdClientMgr.VlanList[idx]
vlanState.VlanName = asicdClientMgr.VlanDB[vlanState.VlanId].VlanName
vlanState.IfIndex = asicdClientMgr.VlanDB[vlanState.VlanId].IfIndex
vlanState.OperState = asicdClientMgr.VlanDB[vlanState.VlanId].OperState
retObj.VlanStateList = append(retObj.VlanStateList, &vlanState)
numEntries++
}
retObj.EndIdx = int32(idx)
retObj.Count = int32(numEntries)
if idx == len(asicdClientMgr.VlanDB) {
retObj.More = false
}
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetVlanState(VlanId int32) (*objects.VlanState, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
vlanEnt, exist := asicdClientMgr.VlanDB[VlanId]
if !exist {
return nil, errors.New("Invalid VlanId")
}
var retObj objects.VlanState
retObj.VlanId = VlanId
retObj.VlanName = vlanEnt.VlanName
retObj.IfIndex = vlanEnt.IfIndex
retObj.OperState = vlanEnt.OperState
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateIPv4Intf(cfg *objects.IPv4Intf) (bool, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
Logger.Info("Calling CPS CreateIPv4Intf:", cfg)
ipAddr, ipNet, err := net.ParseCIDR(cfg.IpAddr)
if err != nil {
return false, errors.New(fmt.Sprintln("Invalid IP Address", err))
}
prefixLen, _ := ipNet.Mask.Size()
if err != nil {
return false, errors.New(fmt.Sprintln("Invalid IP Address", err))
}
rv := int(C.CPSCreateIPv4Intf(C.CString(cfg.IntfRef), C.CString(ipAddr.String()), C.uint32_t(prefixLen)))
if rv != 0 {
return false, errors.New("Error Creating IPv4 Intf")
}
intf, err := net.InterfaceByName(cfg.IntfRef)
if err != nil {
Logger.Info("Error Create IPv4Intf, Unable to get interface details", cfg.IntfRef)
return false, errors.New(fmt.Sprintln("Error Create IPv4Intf, Unable to get interface details", cfg.IntfRef))
}
ipv4IntfEnt, _ := asicdClientMgr.IPv4IntfDB[cfg.IntfRef]
ipv4IntfEnt.IpAddr = cfg.IpAddr
ipv4IntfEnt.AdminState = "UP"
ipv4IntfEnt.IfIdx = int32(intf.Index)
ipv4IntfEnt.OperState = "UP"
asicdClientMgr.IPv4IntfDB[cfg.IntfRef] = ipv4IntfEnt
asicdClientMgr.IPv4IntfList = append(asicdClientMgr.IPv4IntfList, cfg.IntfRef)
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteIPv4Intf(cfg *objects.IPv4Intf) (bool, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
Logger.Info("Calling CPS DeleteIPv4Intf:", cfg)
ipAddr, ipNet, err := net.ParseCIDR(cfg.IpAddr)
if err != nil {
return false, errors.New(fmt.Sprintln("Invalid IP Address", err))
}
prefixLen, _ := ipNet.Mask.Size()
if err != nil {
return false, errors.New(fmt.Sprintln("Invalid IP Address", err))
}
rv := int(C.CPSDeleteIPv4Intf(C.CString(cfg.IntfRef), C.CString(ipAddr.String()), C.uint32_t(prefixLen)))
if rv != 0 {
return false, errors.New("Error Creating IPv4 Intf")
}
delete(asicdClientMgr.IPv4IntfDB, cfg.IntfRef)
var ipv4IntfList []string
for idx := 0; idx < len(asicdClientMgr.IPv4IntfList); idx++ {
if asicdClientMgr.IPv4IntfList[idx] != cfg.IntfRef {
ipv4IntfList = append(ipv4IntfList, asicdClientMgr.IPv4IntfList[idx])
}
}
asicdClientMgr.IPv4IntfList = asicdClientMgr.IPv4IntfList[:0]
asicdClientMgr.IPv4IntfList = nil
asicdClientMgr.IPv4IntfList = append(asicdClientMgr.IPv4IntfList, ipv4IntfList...)
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateIPv4Intf(origCfg, newCfg *objects.IPv4Intf, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkIPv4IntfState(fromIdx, count int) (*asicdClntDefs.IPv4IntfStateGetInfo, error) {
var retObj asicdClntDefs.IPv4IntfStateGetInfo
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var idx, numEntries int
if (fromIdx > len(asicdClientMgr.IPv4IntfList)) || (fromIdx < 0) {
Logger.Err("Invalid fromIdx ipv4Intf argument in get bulk ipv4Intf state")
return nil, errors.New("Invalid fromIdx ipv4Intf argument in get bulk ipv4Intf state")
}
if count < 0 {
Logger.Err("Invalid count in get bulk IPv4IntfList")
return nil, errors.New("Invalid count int get bulk IPv4IntList")
}
for idx = fromIdx; idx < len(asicdClientMgr.IPv4IntfList); idx++ {
if numEntries == count {
retObj.More = true
break
}
var ipv4IntfState objects.IPv4IntfState
intfRef := asicdClientMgr.IPv4IntfList[idx]
ipv4IntfState.IntfRef = intfRef
ipv4IntfState.IfIndex = asicdClientMgr.IPv4IntfDB[intfRef].IfIdx
ipv4IntfState.IpAddr = asicdClientMgr.IPv4IntfDB[intfRef].IpAddr
ipv4IntfState.OperState = asicdClientMgr.IPv4IntfDB[intfRef].OperState
ipv4IntfState.L2IntfId = int32(asicdClientMgr.GetIntfIdFromIfIndex(ipv4IntfState.IfIndex))
ifType := asicdClientMgr.GetIntfTypeFromIfIndex(ipv4IntfState.IfIndex)
switch ifType {
case asicdClntDefs.IfTypePort:
ipv4IntfState.L2IntfType = "Port"
case asicdClntDefs.IfTypeVlan:
ipv4IntfState.L2IntfType = "Vlan"
}
retObj.IPv4IntfStateList = append(retObj.IPv4IntfStateList, &ipv4IntfState)
numEntries++
}
retObj.EndIdx = int32(idx)
retObj.Count = int32(numEntries)
if idx == len(asicdClientMgr.IPv4IntfList) {
retObj.More = false
}
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetIPv4IntfState(IntfRef string) (*objects.IPv4IntfState, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
ipv4Ent, exist := asicdClientMgr.IPv4IntfDB[IntfRef]
if !exist {
return nil, errors.New("Invalid IntfRef")
}
var retObj objects.IPv4IntfState
retObj.IntfRef = IntfRef
retObj.IfIndex = ipv4Ent.IfIdx
retObj.IpAddr = ipv4Ent.IpAddr
retObj.OperState = ipv4Ent.OperState
retObj.L2IntfId = int32(asicdClientMgr.GetIntfIdFromIfIndex(retObj.IfIndex))
ifType := asicdClientMgr.GetIntfTypeFromIfIndex(retObj.IfIndex)
switch ifType {
case asicdClntDefs.IfTypePort:
retObj.L2IntfType = "Port"
case asicdClntDefs.IfTypeVlan:
retObj.L2IntfType = "Vlan"
}
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreatePort(cfg *objects.Port) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdatePort(origCfg, newCfg *objects.Port, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var mask uint32
var idx int
for idx, val := range attrset {
if val {
switch idx {
case 0:
//Object Key IntfRef
case 1:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_IF_INDEX
case 2:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_DESCRIPTION
case 3:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_PHY_INTF_TYPE
case 4:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_ADMIN_STATE
case 5:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_MAC_ADDR
case 6:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_SPEED
case 7:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_DUPLEX
case 8:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_AUTONEG
case 9:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_MEDIA_TYPE
case 10:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_MTU
case 11:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_BREAK_OUT_MODE
case 12:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_LOOPBACK_MODE
case 13:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_ENABLE_FEC
case 14:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_PRBS_TX_ENABLE
case 15:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_PRBS_RX_ENABLE
case 16:
mask |= asicdClntDefs.PORT_UPDATE_ATTR_PRBS_POLYNOMIAL
}
}
}
for idx = 0; idx < len(asicdClientMgr.PortDB); idx++ {
if asicdClientMgr.PortDB[idx].IntfRef == newCfg.IntfRef {
break
}
}
if idx == len(asicdClientMgr.PortDB) {
return false, errors.New(fmt.Sprintln("Error Invalid IntfRef", newCfg.IntfRef))
}
if (((mask & asicdClntDefs.PORT_UPDATE_ATTR_ADMIN_STATE) == asicdClntDefs.PORT_UPDATE_ATTR_ADMIN_STATE) ||
((mask & asicdClntDefs.PORT_UPDATE_ATTR_AUTONEG) == asicdClntDefs.PORT_UPDATE_ATTR_AUTONEG)) {
var val uint8
var an uint8
if newCfg.AdminState == "UP" {
val = 1
} else {
val = 0
}
if newCfg.Autoneg == "ON" {
an = 1
} else {
an = 0
}
rv := int(C.CPSSetPortAdminState(C.CString(newCfg.IntfRef), C.uint8_t(val), C.uint8_t(an)))
if rv != 0 {
return false, errors.New("Error Setting Port AdminState")
}
asicdClientMgr.PortDB[idx].AdminState = newCfg.AdminState
asicdClientMgr.PortDB[idx].OperState = newCfg.AdminState
}
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeletePort(cfg *objects.Port) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkPort(fromIdx, count int) (*asicdClntDefs.PortGetInfo, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var retObj asicdClntDefs.PortGetInfo
var idx, numEntries int
if (fromIdx > len(asicdClientMgr.PortDB)) || (fromIdx < 0) {
Logger.Err("Invalid fromIdx port argument in get bulk port config")
return nil, errors.New("Invalid fromIdx port argument in get bulk port config")
}
if count < 0 {
Logger.Err("Invalid count in get bulk port config")
return nil, errors.New("Invalid count int get bulk port config")
}
for idx = fromIdx; idx < len(asicdClientMgr.PortDB); idx++ {
if numEntries == count {
retObj.More = true
break
}
var portCfg objects.Port
portCfg.IntfRef = asicdClientMgr.PortDB[idx].IntfRef
portCfg.IfIndex = asicdClientMgr.PortDB[idx].IfIndex
portCfg.MacAddr = asicdClientMgr.PortDB[idx].MacAddr
portCfg.AdminState = asicdClientMgr.PortDB[idx].AdminState
retObj.PortList = append(retObj.PortList, &portCfg)
numEntries++
}
retObj.EndIdx = int32(idx)
if idx == len(asicdClientMgr.PortDB) {
retObj.More = false
}
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetPort(IntfRef string) (*objects.Port, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var flag bool
var idx int
for idx = 0; idx < len(asicdClientMgr.PortDB); idx++ {
if asicdClientMgr.PortDB[idx].IntfRef == IntfRef {
flag = true
break
}
}
if flag == false {
return nil, errors.New("Invalid IntfRef")
}
var retObj objects.Port
retObj.IntfRef = asicdClientMgr.PortDB[idx].IntfRef
retObj.IfIndex = asicdClientMgr.PortDB[idx].IfIndex
retObj.MacAddr = asicdClientMgr.PortDB[idx].MacAddr
retObj.AdminState = asicdClientMgr.PortDB[idx].AdminState
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkPortState(fromIdx, count int) (*asicdClntDefs.PortStateGetInfo, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var retObj asicdClntDefs.PortStateGetInfo
var idx, numEntries int
if (fromIdx > len(asicdClientMgr.PortDB)) || (fromIdx < 0) {
Logger.Err("Invalid fromIdx port argument in get bulk port config")
return nil, errors.New("Invalid fromIdx port argument in get bulk port config")
}
if count < 0 {
Logger.Err("Invalid count in get bulk port config")
return nil, errors.New("Invalid count int get bulk port config")
}
for idx = fromIdx; idx < len(asicdClientMgr.PortDB); idx++ {
if numEntries == count {
retObj.More = true
break
}
var portState objects.PortState
var pState C.PortState_t
portState.IntfRef = asicdClientMgr.PortDB[idx].IntfRef
portState.IfIndex = asicdClientMgr.PortDB[idx].IfIndex
portState.Name = asicdClientMgr.PortDB[idx].IntfRef
portState.OperState = asicdClientMgr.PortDB[idx].OperState
C.CPSGetPortState(C.CString(portState.IntfRef), &pState)
portState.IfInOctets = int64(pState.IfInOctets)
portState.IfInUcastPkts = int64(pState.IfInUcastPkts)
portState.IfInDiscards = int64(pState.IfInDiscards)
portState.IfInErrors = int64(pState.IfInErrors)
portState.IfInUnknownProtos = int64(pState.IfInUnknownProtos)
portState.IfOutOctets = int64(pState.IfOutOctets)
portState.IfOutUcastPkts = int64(pState.IfOutUcastPkts)
portState.IfOutDiscards = int64(pState.IfOutDiscards)
portState.IfOutErrors = int64(pState.IfOutErrors)
portState.IfEtherUnderSizePktCnt = int64(pState.IfEtherUnderSizePktCnt)
portState.IfEtherOverSizePktCnt = int64(pState.IfEtherOverSizePktCnt)
portState.IfEtherFragments = int64(pState.IfEtherFragments)
portState.IfEtherCRCAlignError = int64(pState.IfEtherCRCAlignError)
portState.IfEtherJabber = int64(pState.IfEtherJabber)
portState.IfEtherPkts = int64(pState.IfEtherPkts)
portState.IfEtherMCPkts = int64(pState.IfEtherMCPkts)
portState.IfEtherBcastPkts = int64(pState.IfEtherBcastPkts)
retObj.PortStateList = append(retObj.PortStateList, &portState)
numEntries++
}
retObj.EndIdx = int32(idx)
if idx == len(asicdClientMgr.PortDB) {
retObj.More = false
}
retObj.Count = int32(numEntries)
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetPortState(IntfRef string) (*objects.PortState, error) {
cpsAsicdMutex.Lock()
defer cpsAsicdMutex.Unlock()
var flag bool
var idx int
for idx = 0; idx < len(asicdClientMgr.PortDB); idx++ {
if asicdClientMgr.PortDB[idx].IntfRef == IntfRef {
flag = true
break
}
}
if flag == false {
return nil, errors.New("Invalid IntfRef")
}
var retObj objects.PortState
var pState C.PortState_t
retObj.IntfRef = asicdClientMgr.PortDB[idx].IntfRef
retObj.IfIndex = asicdClientMgr.PortDB[idx].IfIndex
retObj.Name = asicdClientMgr.PortDB[idx].IntfRef
retObj.OperState = asicdClientMgr.PortDB[idx].OperState
C.CPSGetPortState(C.CString(retObj.IntfRef), &pState)
retObj.IfInOctets = int64(pState.IfInOctets)
retObj.IfInUcastPkts = int64(pState.IfInUcastPkts)
retObj.IfInDiscards = int64(pState.IfInDiscards)
retObj.IfInErrors = int64(pState.IfInErrors)
retObj.IfInUnknownProtos = int64(pState.IfInUnknownProtos)
retObj.IfOutOctets = int64(pState.IfOutOctets)
retObj.IfOutUcastPkts = int64(pState.IfOutUcastPkts)
retObj.IfOutDiscards = int64(pState.IfOutDiscards)
retObj.IfOutErrors = int64(pState.IfOutErrors)
retObj.IfEtherUnderSizePktCnt = int64(pState.IfEtherUnderSizePktCnt)
retObj.IfEtherOverSizePktCnt = int64(pState.IfEtherOverSizePktCnt)
retObj.IfEtherFragments = int64(pState.IfEtherFragments)
retObj.IfEtherCRCAlignError = int64(pState.IfEtherCRCAlignError)
retObj.IfEtherJabber = int64(pState.IfEtherJabber)
retObj.IfEtherPkts = int64(pState.IfEtherPkts)
retObj.IfEtherMCPkts = int64(pState.IfEtherMCPkts)
retObj.IfEtherBcastPkts = int64(pState.IfEtherBcastPkts)
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkMacTableEntryState(fromIndex int, count int) (*asicdClntDefs.MacTableEntryStateGetInfo, error) {
var retObj asicdClntDefs.MacTableEntryStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetMacTableEntryState(MacAddr string) (*objects.MacTableEntryState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkIPv4RouteHwState(fromIndex int, count int) (*asicdClntDefs.IPv4RouteHwStateGetInfo, error) {
var retObj asicdClntDefs.IPv4RouteHwStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetIPv4RouteHwState(DestinationNw string) (*objects.IPv4RouteHwState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkIPv6RouteHwState(fromIndex int, count int) (*asicdClntDefs.IPv6RouteHwStateGetInfo, error) {
var retObj asicdClntDefs.IPv6RouteHwStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetIPv6RouteHwState(DestinationNw string) (*objects.IPv6RouteHwState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkArpEntryHwState(fromIndex int, count int) (*asicdClntDefs.ArpEntryHwStateGetInfo, error) {
var retObj asicdClntDefs.ArpEntryHwStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetArpEntryHwState(IpAddr string) (*objects.ArpEntryHwState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkNdpEntryHwState(fromIndex int, count int) (*asicdClntDefs.NdpEntryHwStateGetInfo, error) {
var retObj asicdClntDefs.NdpEntryHwStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetNdpEntryHwState(IpAddr string) (*objects.NdpEntryHwState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateLogicalIntf(cfg *objects.LogicalIntf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateLogicalIntf(origCfg, newCfg *objects.LogicalIntf, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteLogicalIntf(cfg *objects.LogicalIntf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkLogicalIntfState(fromIndex int, count int) (*asicdClntDefs.LogicalIntfStateGetInfo, error) {
var retObj asicdClntDefs.LogicalIntfStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetLogicalIntfState(Name string) (*objects.LogicalIntfState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateSubIPv4Intf(cfg *objects.SubIPv4Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateSubIPv4Intf(origCfg, newCfg *objects.SubIPv4Intf, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteSubIPv4Intf(cfg *objects.SubIPv4Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkSubIPv4IntfState(fromIndex int, count int) (*asicdClntDefs.SubIPv4IntfStateGetInfo, error) {
var retObj asicdClntDefs.SubIPv4IntfStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetSubIPv4IntfState(IntfRef string, Type string) (*objects.SubIPv4IntfState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateIPv6Intf(cfg *objects.IPv6Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateIPv6Intf(origCfg, newCfg *objects.IPv6Intf, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteIPv6Intf(cfg *objects.IPv6Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkIPv6IntfState(fromIndex int, count int) (*asicdClntDefs.IPv6IntfStateGetInfo, error) {
var retObj asicdClntDefs.IPv6IntfStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetIPv6IntfState(IntfRef string) (*objects.IPv6IntfState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateSubIPv6Intf(cfg *objects.SubIPv6Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateSubIPv6Intf(origCfg, newCfg *objects.SubIPv6Intf, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteSubIPv6Intf(cfg *objects.SubIPv6Intf) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkSubIPv6IntfState(fromIndex int, count int) (*asicdClntDefs.SubIPv6IntfStateGetInfo, error) {
var retObj asicdClntDefs.SubIPv6IntfStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetSubIPv6IntfState(IntfRef string, Type string) (*objects.SubIPv6IntfState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkBufferPortStatState(fromIndex int, count int) (*asicdClntDefs.BufferPortStatStateGetInfo, error) {
var retObj asicdClntDefs.BufferPortStatStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBufferPortStatState(IntfRef string) (*objects.BufferPortStatState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkBufferGlobalStatState(fromIndex int, count int) (*asicdClntDefs.BufferGlobalStatStateGetInfo, error) {
var retObj asicdClntDefs.BufferGlobalStatStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBufferGlobalStatState(DeviceId uint32) (*objects.BufferGlobalStatState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAclGlobal(cfg *objects.AclGlobal) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAclGlobal(origCfg, newCfg *objects.AclGlobal, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAclGlobal(cfg *objects.AclGlobal) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAcl(cfg *objects.Acl) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAcl(origCfg, newCfg *objects.Acl, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAcl(cfg *objects.Acl) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAclIpv4Filter(cfg *objects.AclIpv4Filter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAclIpv4Filter(origCfg, newCfg *objects.AclIpv4Filter, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAclIpv4Filter(cfg *objects.AclIpv4Filter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAclMacFilter(cfg *objects.AclMacFilter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAclMacFilter(origCfg, newCfg *objects.AclMacFilter, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAclMacFilter(cfg *objects.AclMacFilter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) CreateAclIpv6Filter(cfg *objects.AclIpv6Filter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) UpdateAclIpv6Filter(origCfg, newCfg *objects.AclIpv6Filter, attrset []bool, op []*objects.PatchOpInfo) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) DeleteAclIpv6Filter(cfg *objects.AclIpv6Filter) (bool, error) {
return true, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkAclState(fromIndex int, count int) (*asicdClntDefs.AclStateGetInfo, error) {
var retObj asicdClntDefs.AclStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetAclState(AclName string) (*objects.AclState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkLinkScopeIpState(fromIndex int, count int) (*asicdClntDefs.LinkScopeIpStateGetInfo, error) {
var retObj asicdClntDefs.LinkScopeIpStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetLinkScopeIpState(LinkScopeIp string) (*objects.LinkScopeIpState, error) {
return nil, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetBulkCoppStatState(fromIndex int, count int) (*asicdClntDefs.CoppStatStateGetInfo, error) {
var retObj asicdClntDefs.CoppStatStateGetInfo
return &retObj, nil
}
func (asicdClientMgr *CPSAsicdClntMgr) GetCoppStatState(Protocol string) (*objects.CoppStatState, error) {
return nil, nil
}
| 36.266974 | 157 | 0.75606 |
04633a100cc85bf6806c6364255b3fad106106d7 | 4,179 | java | Java | app/src/main/java/com/zqf/talkpoint/util/SettingUtil.java | eternityzqf/TalkPoint | 323eccb15c56b31dcc0d034e94e2d562263f4831 | [
"Apache-2.0"
] | 2 | 2018-09-18T08:51:11.000Z | 2018-09-29T04:01:12.000Z | app/src/main/java/com/zqf/talkpoint/util/SettingUtil.java | eternityzqf/TalkPoint | 323eccb15c56b31dcc0d034e94e2d562263f4831 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zqf/talkpoint/util/SettingUtil.java | eternityzqf/TalkPoint | 323eccb15c56b31dcc0d034e94e2d562263f4831 | [
"Apache-2.0"
] | null | null | null | package com.zqf.talkpoint.util;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import com.zqf.talkpoint.R;
import com.zqf.talkpoint.app.MyApp;
/**
* Created by Meiji on 2017/2/20.
*/
public class SettingUtil {
private SharedPreferences setting = PreferenceManager.getDefaultSharedPreferences(MyApp.getContext());
public static SettingUtil getInstance() {
return SettingsUtilInstance.instance;
}
/**
* 获取是否开启无图模式
*/
public boolean getIsNoPhotoMode() {
return setting.getBoolean("switch_noPhotoMode", false) && NetWorkUtil.isMobileConnected(MyApp.getContext());
}
/**
* 获取主题颜色
*/
public int getColor() {
int defaultColor = MyApp.getContext().getResources().getColor(R.color.colorPrimary);
int color = setting.getInt("color", defaultColor);
if ((color != 0) && Color.alpha(color) != 255) {
return defaultColor;
}
return color;
}
/**
* 设置主题颜色
*/
public void setColor(int color) {
setting.edit().putInt("color", color).apply();
}
/**
* 获取是否开启夜间模式
*/
public boolean getIsNightMode() {
return setting.getBoolean("switch_nightMode", false);
}
/**
* 设置夜间模式
*/
public void setIsNightMode(boolean flag) {
setting.edit().putBoolean("switch_nightMode", flag).apply();
}
/**
* 获取是否开启自动切换夜间模式
*/
public boolean getIsAutoNightMode() {
return setting.getBoolean("auto_nightMode", false);
}
/**
* 获取是否开启自动切换夜间模式
*/
public void setIsAutoNightMode(boolean flag) {
setting.edit().putBoolean("auto_nightMode", flag).apply();
}
public String getNightStartHour() {
return setting.getString("night_startHour", "22");
}
public void setNightStartHour(String nightStartHour) {
setting.edit().putString("night_startHour", nightStartHour).apply();
}
public String getNightStartMinute() {
return setting.getString("night_startMinute", "00");
}
public void setNightStartMinute(String nightStartMinute) {
setting.edit().putString("night_startMinute", nightStartMinute).apply();
}
public String getDayStartHour() {
return setting.getString("day_startHour", "06");
}
public void setDayStartHour(String dayStartHour) {
setting.edit().putString("day_startHour", dayStartHour).apply();
}
public String getDayStartMinute() {
return setting.getString("day_startMinute", "00");
}
public void setDayStartMinute(String dayStartMinute) {
setting.edit().putString("day_startMinute", dayStartMinute).apply();
}
/**
* 获取是否开启导航栏上色
*/
public boolean getNavBar() {
return setting.getBoolean("nav_bar", false);
}
/**
* 获取是否开启视频强制横屏
*/
public boolean getIsVideoForceLandscape() {
return setting.getBoolean("video_force_landscape", false);
}
/**
* 获取图标值
*/
public int getCustomIconValue() {
String s = setting.getString("custom_icon", "0");
return Integer.parseInt(s);
}
/**
* 获取滑动返回值
*/
public int getSlidable() {
String s = setting.getString("slidable", "1");
return Integer.parseInt(s);
}
/**
* 获取是否开启视频自动播放
*/
public boolean getIsVideoAutoPlay() {
return setting.getBoolean("video_auto_play", false) && NetWorkUtil.isWifiConnected(MyApp.getContext());
}
/**
* 获取字体大小
*/
public int getTextSize() {
return setting.getInt("textsize", 16);
}
/**
* 设置字体大小
*/
public void setTextSize(int textSize) {
setting.edit().putInt("textsize", textSize).apply();
}
public boolean getIsFirstTime() {
return setting.getBoolean("first_time", true);
}
public void setIsFirstTime(boolean flag) {
setting.edit().putBoolean("first_time", flag).apply();
}
private static final class SettingsUtilInstance {
private static final SettingUtil instance = new SettingUtil();
}
}
| 24.582353 | 116 | 0.625508 |
bcd44d0cd57aa916bdb8a72432c3f23b646461b9 | 3,221 | js | JavaScript | web_client/routes.js | data-exp-lab/girder_ythub | 81e908db56271f5ac0bebd55e9badacbe428f6d1 | [
"BSD-3-Clause"
] | 3 | 2016-04-22T13:48:35.000Z | 2019-03-11T14:15:39.000Z | web_client/routes.js | data-exp-lab/girder_ythub | 81e908db56271f5ac0bebd55e9badacbe428f6d1 | [
"BSD-3-Clause"
] | 5 | 2016-08-15T15:13:07.000Z | 2018-02-15T22:41:22.000Z | web_client/routes.js | data-exp-lab/girder_ythub | 81e908db56271f5ac0bebd55e9badacbe428f6d1 | [
"BSD-3-Clause"
] | 5 | 2016-08-02T23:29:47.000Z | 2018-12-20T21:56:40.000Z | /* eslint-disable import/first */
import router from 'girder/router';
import events from 'girder/events';
import { exposePluginConfig } from 'girder/utilities/PluginUtils';
import ItemModel from 'girder/models/ItemModel';
import { Layout } from 'girder/constants';
import ConfigView from './views/ConfigView';
import NotebookListWidget from './views/NotebookListWidget';
import RaftListView from './views/RaftListView';
import RaftRunView from './views/RaftRunView';
import CreateRaftView from './views/body/CreateRaftView';
import FrontendModel from './models/FrontendModel';
import RunNotebookView from './views/RunNotebookView';
exposePluginConfig('ythub', 'plugins/ythub/config');
router.route('plugins/ythub/config', 'ythubConfig', function () {
events.trigger('g:navigateTo', ConfigView);
});
router.route('notebook/user/:id', 'notebookList', function (id) {
events.trigger('g:navigateTo', NotebookListWidget, {
filter: {userId: id}
});
});
router.route('rafts', 'raftList', () => {
events.trigger('g:navigateTo', RaftListView);
});
router.route('newraft', 'newRaft', () => {
events.trigger('g:navigateTo', CreateRaftView);
});
router.route('raft/:id/run', (id, params) => {
const item = new ItemModel({_id: id});
const promises = [item.fetch()];
$.when.apply($, promises).done(() => {
events.trigger('g:navigateTo', RaftRunView, {
model: item
}, {
renderNow: true
});
}).fail(() => {
router.navigate('rafts', {trigger: true});
});
});
router.route('raft/:id/edit', 'newRaft', (id, params) => {
const itemTask = new ItemModel({_id: id});
let frontend = null;
const promises = [itemTask.fetch()];
if (params.frontendId) {
frontend = new FrontendModel({_id: params.frontendId});
promises.push(frontend.fetch());
}
$.when(...promises).done(() => {
let raftSpec = itemTask.get('meta').raftSpec;
let initialValues = {
data: raftSpec.data,
frontendId: raftSpec.frontend,
frontendName: frontend.get('description'),
scripts: raftSpec.scripts
};
events.trigger('g:navigateTo', CreateRaftView, {
model: itemTask,
initialValues: initialValues
}, {
renderNow: true
});
}).fail(() => {
router.navigate('rafts', {trigger: true, replace: true});
});
});
router.route('frontend/:id/:folderId', 'runNotebook', function (id, folderId) {
events.trigger('g:navigateTo', RunNotebookView, {
frontendId: id,
folderId: folderId
}, {
layout: Layout.EMPTY
});
});
router.route('raft/:id', (id, params) => {
const item = new ItemModel({_id: id});
const promises = [item.fetch()];
$.when.apply($, promises).done(() => {
let raftSpec = item.get('meta').raftSpec;
events.trigger('g:navigateTo', RunNotebookView, {
frontendId: raftSpec.frontend,
folderId: raftSpec.data,
scripts: raftSpec.scripts
}, {
layout: Layout.EMPTY
});
}).fail(() => {
router.navigate('rafts', {trigger: true});
});
});
| 29.824074 | 79 | 0.606644 |
86138a846ac6d6e5637ac1ee33e3b2ab5649892f | 695 | java | Java | smart-cloud-starter/smart-cloud-starter-core/src/test/java/org/smartframework/cloud/starter/common/test/unit/ReflectionUtilUnitTest.java | cwj3000/smart-cloud | 972ee8b8c13191de8357577af623e74e21ed5212 | [
"Apache-2.0"
] | null | null | null | smart-cloud-starter/smart-cloud-starter-core/src/test/java/org/smartframework/cloud/starter/common/test/unit/ReflectionUtilUnitTest.java | cwj3000/smart-cloud | 972ee8b8c13191de8357577af623e74e21ed5212 | [
"Apache-2.0"
] | null | null | null | smart-cloud-starter/smart-cloud-starter-core/src/test/java/org/smartframework/cloud/starter/common/test/unit/ReflectionUtilUnitTest.java | cwj3000/smart-cloud | 972ee8b8c13191de8357577af623e74e21ed5212 | [
"Apache-2.0"
] | 1 | 2021-04-27T10:15:18.000Z | 2021-04-27T10:15:18.000Z | package org.smartframework.cloud.starter.common.test.unit;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.smartframework.cloud.starter.common.SuiteTest;
import org.smartframework.cloud.starter.core.business.util.ReflectionUtil;
import org.smartframework.cloud.starter.core.constants.PackageConfig;
import junit.framework.TestCase;
public class ReflectionUtilUnitTest extends TestCase {
public void testGetSubTypesOf() {
PackageConfig.setBasePackages(new String[]{SuiteTest.class.getPackage().getName()});
Set<Class<? extends TestCase>> set = ReflectionUtil.getSubTypesOf(TestCase.class);
Assertions.assertThat(set).isNotEmpty();
}
} | 34.75 | 87 | 0.785612 |
40609f67b8dd3c78caba433f6989c5acf7164888 | 10,437 | lua | Lua | game_scripts/levels/contributed/psychlab/visuospatial_suite/factories/visual_match_factory.lua | jadedragon-mrm/deepmind-lab-pub | b9f163800577d398aa01a99e20e01272d9210c76 | [
"CC-BY-4.0"
] | null | null | null | game_scripts/levels/contributed/psychlab/visuospatial_suite/factories/visual_match_factory.lua | jadedragon-mrm/deepmind-lab-pub | b9f163800577d398aa01a99e20e01272d9210c76 | [
"CC-BY-4.0"
] | null | null | null | game_scripts/levels/contributed/psychlab/visuospatial_suite/factories/visual_match_factory.lua | jadedragon-mrm/deepmind-lab-pub | b9f163800577d398aa01a99e20e01272d9210c76 | [
"CC-BY-4.0"
] | null | null | null | --[[ Copyright (C) 2019 Google LLC
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.
]]
local game = require 'dmlab.system.game'
local log = require 'common.log'
local psychlab_factory = require 'factories.psychlab.factory'
local psychlab_helpers = require 'factories.psychlab.helpers'
local helpers = require 'common.helpers'
local image = require 'dmlab.system.image'
local point_and_click = require 'factories.psychlab.point_and_click'
local random = require 'common.random'
local tensor = require 'dmlab.system.tensor'
local defaults = require 'levels.contributed.psychlab.visuospatial_suite.factories.defaults'
--[[ A visual match task.
The subject is presented with a small number (2, 3, or 4) of pairs of shapes.
In one pair, the shapes are the same, in the others, they are different.
The subject must indicate which pair are the same using a button.
The intention of the task is that in order to solve it, the agent needs
to look closely at the shapes. Hence it is a task that requires gaze control,
but not by directly rewarding it.
]]
local SHAPE_SIZES = {5, 6, 7, 8, 9}
local factory = {}
function factory.createLevelApi(kwargs)
kwargs.episodeLengthSeconds = kwargs.episodeLengthSeconds or
defaults.EPISODE_LENGTH_SECONDS
kwargs.trialsPerEpisodeCap = kwargs.trialsPerEpisodeCap or
defaults.TRIALS_PER_EPISODE_CAP
kwargs.bgColor = kwargs.bgColor or defaults.BG_COLOR
kwargs.colors = kwargs.colors or defaults.COLORS
kwargs.shapeSizes = kwargs.shapeSizes or SHAPE_SIZES
kwargs.incorrectReward = kwargs.incorrectReward or defaults.INCORRECT_REWARD
kwargs.correctReward = kwargs.correctReward or defaults.CORRECT_REWARD
kwargs.maxStepsOffScreen = kwargs.maxStepsOffScreen or
defaults.MAX_STEPS_OFF_SCREEN
-- Class definition for odd_one_out psychlab environment.
local env = {}
env.__index = env
setmetatable(env, {
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:_init(...)
return self
end
})
-- 'init' gets called at the start of each episode.
function env:_init(pac, opts)
log.info('opts passed to _init:\n' .. helpers.tostring(opts))
self.screenSize = opts.screenSize
self:setupImages()
-- Store a copy of the 'point_and_click' api.
self.pac = pac
end
--[[ Reset is called after init. It is called only once per episode.
Note: the episodeId passed to this function may not be correct if the job
has resumed from a checkpoint after preemption.
]]
function env:reset(episodeId, seed)
random:seed(seed)
self.pac:setBackgroundColor(kwargs.bgColor)
self.pac:clearWidgets()
self.pac:clearTimers()
psychlab_helpers.addFixation(self, defaults.FIXATION_SIZE)
self.currentTrial = {}
psychlab_helpers.setTrialsPerEpisodeCap(self, kwargs.trialsPerEpisodeCap)
-- blockId groups together all rows written during the same episode
self.blockId = random:uniformInt(1, 2 ^ 32)
self.trialId = 1
end
-- Creates image tensor for fixation.
function env:setupImages()
self.images = {}
self.images.fixation = psychlab_helpers.getFixationImage(
self.screenSize, kwargs.bgColor, defaults.FIXATION_COLOR,
defaults.FIXATION_SIZE)
local h = defaults.BUTTON_SIZE * self.screenSize.height
local w = defaults.BUTTON_SIZE * self.screenSize.width
self.images.greenImage = tensor.ByteTensor(h, w, 3):fill{100, 255, 100}
self.images.redImage = tensor.ByteTensor(h, w, 3):fill{255, 100, 100}
end
function env:finishTrial(delay)
self.currentTrial.blockId = self.blockId
self.currentTrial.reactionTime =
game:episodeTimeSeconds() - self._currentTrialStartTime
self.currentTrial.stepCount = self.pac:elapsedSteps()
psychlab_helpers.publishTrialData(self.currentTrial, kwargs.schema)
self.pac:clearTimers()
psychlab_helpers.finishTrialCommon(self, delay, defaults.FIXATION_SIZE)
end
function env:fixationCallback(name, mousePos, hoverTime, userData)
if hoverTime == defaults.TIME_TO_FIXATE_CROSS then
self.pac:addReward(defaults.FIXATION_REWARD)
self.pac:removeWidget('fixation')
self.pac:removeWidget('center_of_fixation')
self.currentTrial.reward = 0
self.currentTrial.trialId = self.trialId
self.trialId = self.trialId + 1
self:addArray()
self.pac:addTimer{
name = 'trial_timeout',
timeout = defaults.TRIAL_TIMEOUT,
callback = function(...) return self:trialTimeoutCallback() end
}
-- Measure reaction time since the trial started.
self._currentTrialStartTime = game:episodeTimeSeconds()
self.pac:resetSteps()
end
end
function env:onHoverEndCorrect(name, mousePos, hoverTime, userData)
-- Reward if this is the first "hoverEnd" event for this trial.
self.currentTrial.response = name
self.currentTrial.correct = 1
self.currentTrial.reward = kwargs.correctReward
self.pac:addReward(self.currentTrial.reward)
self:finishTrial(defaults.FAST_INTER_TRIAL_INTERVAL)
end
function env:onHoverEndIncorrect(name, mousePos, hoverTime, userData)
-- Reward if this is the first "hoverEnd" event for this trial.
self.currentTrial.response = name
self.currentTrial.correct = 0
self.currentTrial.reward = kwargs.incorrectReward
self.pac:addReward(self.currentTrial.reward)
self:finishTrial(defaults.FAST_INTER_TRIAL_INTERVAL)
end
function env:correctResponseCallback(name, mousePos, hoverTime, userData)
self.pac:updateWidget(name, self.images.greenImage)
end
function env:incorrectResponseCallback(name, mousePos, hoverTime, userData)
self.pac:updateWidget(name, self.images.redImage)
end
function env:trialTimeoutCallback()
-- Trial times out if agent does not fixate on odd one out.
self.currentTrial.correct = 0
self.currentTrial.reward = kwargs.incorrectReward
self.pac:addReward(self.currentTrial.reward)
self:finishTrial(defaults.FAST_INTER_TRIAL_INTERVAL)
end
function env:addArray()
local numPairs = psychlab_helpers.randomFrom{2, 3, 4}
local shapeSize = psychlab_helpers.randomFrom(kwargs.shapeSizes)
local setSize = 2 * numPairs
local objectHeight = defaults.SCREEN_SIZE.height * 0.125
local objectWidth = objectHeight
self.currentTrial.numPairs = numPairs
self.currentTrial.shapeSize = shapeSize
local size = {objectWidth / defaults.SCREEN_SIZE.width,
objectHeight / defaults.SCREEN_SIZE.height}
local shapes = self:createShapes(setSize, shapeSize, 0.75)
local radius = 0.5 -- random:uniformReal(0.5, 0.75)
local radiansOffset = -2 * math.pi / setSize / 2
local shuffleGen = random:shuffledIndexGenerator(setSize - 2)
local correctPair = random:uniformInt(1, numPairs)
for i = 1, setSize do
local pair = math.ceil(i / 2)
local radians = radiansOffset + 2 * math.pi * i / setSize
local pos = {
0.5 * (1 + radius * math.sin(radians)),
0.5 * (1 - radius * math.cos(radians))
}
pos = psychlab_helpers.getUpperLeftFromCenter(pos, size)
local j
if pair == correctPair then
j = setSize - 1
else
j = shuffleGen()
end
local shape = shapes[j]
local color = kwargs.colors[pair]
local image = self:createImage(
shape, color, objectHeight, objectWidth)
self.pac:addWidget{
name = 'image_' .. i,
pos = pos,
size = size,
image = image,
}
end
-- Add buttons
local h = defaults.BUTTON_SIZE * self.screenSize.height
local w = defaults.BUTTON_SIZE * self.screenSize.width
for i = 1, numPairs do
local color = kwargs.colors[i]
local buttonImage = tensor.ByteTensor(h, w, 3):fill(color)
local buttonPosX = 0.5 +
(0.5 * numPairs - i) * defaults.BUTTON_SIZE * 1.5 +
defaults.BUTTON_SIZE * 0.25
local responseCallback, hoverEndCallback
if i == correctPair then
responseCallback = self.correctResponseCallback
hoverEndCallback = self.onHoverEndCorrect
else
responseCallback = self.incorrectResponseCallback
hoverEndCallback = self.onHoverEndIncorrect
end
self.pac:addWidget{
name = 'button_' .. tostring(i),
image = buttonImage,
pos = {buttonPosX, 1 - defaults.BUTTON_SIZE},
size = {defaults.BUTTON_SIZE, defaults.BUTTON_SIZE},
mouseHoverCallback = responseCallback,
mouseHoverEndCallback = hoverEndCallback,
}
end
end
function env:removeArray()
self.pac:clearWidgets()
end
function env:createShapes(numShapes, shapeSize, p)
local shapes = {}
for n = 1, numShapes do
local grid = {}
for i = 1, shapeSize do
local row = {}
for j = 1, shapeSize do
local value = random:uniformReal(0, 1) < p and 1 or 0
table.insert(row, value)
end
table.insert(grid, row)
end
table.insert(shapes, grid)
end
return shapes
end
function env:createImage(shape, color, objectHeight, objectWidth)
local shapeSize = #shape
local unscaled = tensor.ByteTensor(shapeSize, shapeSize, 3)
for k = 1, 3 do
local plane = unscaled:select(3, k)
plane:val(shape)
plane:mul(color[k])
end
local scaled = image.scale(
unscaled, objectHeight, objectWidth, 'nearest')
return scaled
end
local screenSize = defaults.SCREEN_SIZE
return psychlab_factory.createLevelApi{
env = point_and_click,
envOpts = {environment = env, screenSize = screenSize,
maxStepsOffScreen = kwargs.maxStepsOffScreen},
episodeLengthSeconds = kwargs.episodeLengthSeconds
}
end
return factory
| 34.559603 | 92 | 0.706333 |
02a546a678291078330fdeb78800dad0181a008c | 1,395 | swift | Swift | PrivacyManager/UIViewController+PM.swift | cp3hnu/PrivacyManager | 76c74b2add712afa024a0bb77bafceb8e064f37e | [
"MIT"
] | 56 | 2017-09-22T01:49:28.000Z | 2019-03-30T00:04:45.000Z | PrivacyManager/UIViewController+PM.swift | cp3hnu/PrivacyManager | 76c74b2add712afa024a0bb77bafceb8e064f37e | [
"MIT"
] | null | null | null | PrivacyManager/UIViewController+PM.swift | cp3hnu/PrivacyManager | 76c74b2add712afa024a0bb77bafceb8e064f37e | [
"MIT"
] | null | null | null | //
// UIViewController.swift
// PrivacyManagerDemo
//
// Created by CP3 on 2017/4/13.
// Copyright © 2017年 CP3. All rights reserved.
//
import UIKit
public typealias PrivacyClosure = () -> Void
// MARK: - Present Alert Controller
public extension UIViewController {
func presentPrivacySetting(type: PermissionType, desc: String? = nil, cancelBlock: PrivacyClosure? = nil, settingBlock: PrivacyClosure? = nil) {
let appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? ""
let title = "\"\(appName)\"没有获得\(type.description)的访问权限"
let message = desc ?? "请允许\"\(appName)\"访问您的\(type.description),以便下一步操作。"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { _ in
cancelBlock?()
}
let settingAction = UIAlertAction(title: "设置", style: UIAlertAction.Style.default) { _ in
settingBlock?()
if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsUrl)
}
}
alert.addAction(cancelAction)
alert.addAction(settingAction)
alert.preferredAction = settingAction
present(alert, animated: true, completion: nil)
}
}
| 38.75 | 148 | 0.661649 |
9c5340f87d38023f59408dc40575ba375407acbc | 2,742 | hpp | C++ | libs/functional/include/hpx/functional/detail/vtable/function_vtable.hpp | jokteur/hpx | 689ce9b586322c90f966ef84aa6eba190f037dd7 | [
"BSL-1.0"
] | 1,822 | 2015-01-03T11:22:37.000Z | 2022-03-31T14:49:59.000Z | libs/functional/include/hpx/functional/detail/vtable/function_vtable.hpp | jokteur/hpx | 689ce9b586322c90f966ef84aa6eba190f037dd7 | [
"BSL-1.0"
] | 3,288 | 2015-01-05T17:00:23.000Z | 2022-03-31T18:49:41.000Z | libs/functional/include/hpx/functional/detail/vtable/function_vtable.hpp | jokteur/hpx | 689ce9b586322c90f966ef84aa6eba190f037dd7 | [
"BSL-1.0"
] | 431 | 2015-01-07T06:22:14.000Z | 2022-03-31T14:50:04.000Z | // Copyright (c) 2011 Thomas Heller
// Copyright (c) 2013 Hartmut Kaiser
// Copyright (c) 2014-2019 Agustin Berge
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/config.hpp>
#include <hpx/functional/detail/vtable/callable_vtable.hpp>
#include <hpx/functional/detail/vtable/copyable_vtable.hpp>
#include <hpx/functional/detail/vtable/vtable.hpp>
#include <type_traits>
namespace hpx { namespace util { namespace detail {
struct function_base_vtable
: vtable
, copyable_vtable
, callable_info_vtable
{
template <typename T>
constexpr function_base_vtable(
construct_vtable<T>, std::integral_constant<bool, true>) noexcept
: vtable(construct_vtable<T>())
, copyable_vtable(construct_vtable<T>())
, callable_info_vtable(construct_vtable<T>())
{
}
template <typename T>
constexpr function_base_vtable(
construct_vtable<T>, std::integral_constant<bool, false>) noexcept
: vtable(construct_vtable<T>())
, copyable_vtable(nullptr)
, callable_info_vtable(construct_vtable<T>())
{
}
};
///////////////////////////////////////////////////////////////////////
template <typename Sig, bool Copyable = true>
struct function_vtable;
template <typename Sig>
struct function_vtable<Sig, /*Copyable*/ false>
: function_base_vtable
, callable_vtable<Sig>
{
using copyable_tag = std::integral_constant<bool, false>;
template <typename T>
constexpr function_vtable(construct_vtable<T>) noexcept
: function_base_vtable(construct_vtable<T>(), copyable_tag{})
, callable_vtable<Sig>(construct_vtable<T>())
{
}
template <typename T, typename CopyableTag>
constexpr function_vtable(construct_vtable<T>, CopyableTag) noexcept
: function_base_vtable(construct_vtable<T>(), CopyableTag{})
, callable_vtable<Sig>(construct_vtable<T>())
{
}
};
template <typename Sig>
struct function_vtable<Sig, /*Copyable*/ true> : function_vtable<Sig, false>
{
using copyable_tag = std::integral_constant<bool, true>;
template <typename T>
constexpr function_vtable(construct_vtable<T>) noexcept
: function_vtable<Sig, false>(construct_vtable<T>(), copyable_tag{})
{
}
};
template <typename Sig>
using unique_function_vtable = function_vtable<Sig, false>;
}}} // namespace hpx::util::detail
| 32.642857 | 80 | 0.63895 |
985f50e0f19839226ebbc2902083081068d2255e | 634 | html | HTML | src/app/components/main-layout/main-layout.component.html | denpalrius/bespoke-inventory | 6ca231a1ee1b134ea21bba728c2c007c331c6c4a | [
"MIT"
] | null | null | null | src/app/components/main-layout/main-layout.component.html | denpalrius/bespoke-inventory | 6ca231a1ee1b134ea21bba728c2c007c331c6c4a | [
"MIT"
] | null | null | null | src/app/components/main-layout/main-layout.component.html | denpalrius/bespoke-inventory | 6ca231a1ee1b134ea21bba728c2c007c331c6c4a | [
"MIT"
] | null | null | null | <div class="main-container" [class.is-mobile]="mobileQuery.matches">
<app-top-nav (toggleSideNav)="toggleSideNav()"></app-top-nav>
<mat-sidenav-container class="sidenav-container" [style.marginTop.px]="mobileQuery.matches ? 0 : 0">
<mat-sidenav class="app-side-nav" #sideNav opened [mode]="mobileQuery.matches ? 'over' : 'side'" [fixedInViewport]="mobileQuery.matches"
[fixedTopGap]="56">
<app-side-nav (selectNavItem)="navSelect()"></app-side-nav>
</mat-sidenav>
<mat-sidenav-content class="content-view">
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>
| 48.769231 | 140 | 0.684543 |
162fe341c06c4e17188b586348c7895086dbbccc | 249 | ts | TypeScript | src/services/index.ts | tbarlow12/projector-cli | 37fcc6c6cd318cf29097e6189df59c50679130de | [
"MIT"
] | 2 | 2021-07-26T16:56:00.000Z | 2021-10-10T03:05:12.000Z | src/services/index.ts | tbarlow12/projector-cli | 37fcc6c6cd318cf29097e6189df59c50679130de | [
"MIT"
] | 31 | 2021-07-26T17:00:54.000Z | 2021-12-02T23:56:30.000Z | src/services/index.ts | tbarlow12/projector-cli | 37fcc6c6cd318cf29097e6189df59c50679130de | [
"MIT"
] | 1 | 2022-01-19T06:32:35.000Z | 2022-01-19T06:32:35.000Z | export * from "./agile";
export * from "./configuration";
export * from "./input";
export * from "./interpolate";
export * from "./logger";
export * from "./metrics";
export * from "./playbook";
export * from "./project";
export * from "./storage";
| 24.9 | 32 | 0.638554 |
373b793ea98e534e043f3103326c2ef31cadd08c | 595 | asm | Assembly | programs/oeis/310/A310704.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/310/A310704.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/310/A310704.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A310704: Coordination sequence Gal.3.2.2 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,4,7,10,15,19,21,24,30,34,35,38,45,49,49,52,60,64,63,66,75,79,77,80,90,94,91,94,105,109,105,108,120,124,119,122,135,139,133,136,150,154,147,150,165,169,161,164,180,184
mov $4,$0
add $0,1
mov $5,$0
lpb $0
add $0,4
div $5,2
add $5,$0
div $0,$5
mov $1,2
add $1,$0
div $0,10
sub $2,$5
gcd $2,$1
add $2,1
sub $5,4
add $5,$1
lpe
div $5,$2
mov $1,$5
sub $1,1
mov $3,$4
mul $3,3
add $1,$3
mov $0,$1
| 21.25 | 175 | 0.630252 |
f03920b0bb303e84585b5301156f60537211cfe6 | 3,011 | lua | Lua | Server/TriggerCreation.lua | Falaxir/nanos-world_boss-vs-players | 58eea8b7884a768d9b4c948072fe7608c5789edc | [
"Apache-2.0"
] | null | null | null | Server/TriggerCreation.lua | Falaxir/nanos-world_boss-vs-players | 58eea8b7884a768d9b4c948072fe7608c5789edc | [
"Apache-2.0"
] | null | null | null | Server/TriggerCreation.lua | Falaxir/nanos-world_boss-vs-players | 58eea8b7884a768d9b4c948072fe7608c5789edc | [
"Apache-2.0"
] | 1 | 2021-07-01T12:30:42.000Z | 2021-07-01T12:30:42.000Z | --[[
.______ ______ _______. _______. ____ ____ _______. .______ __ ___ ____ ____ _______ .______ _______.
| _ \ / __ \ / | / | \ \ / / / | | _ \ | | / \ \ \ / / | ____|| _ \ / |
| |_) | | | | | | (----` | (----` \ \/ / | (----` | |_) | | | / ^ \ \ \/ / | |__ | |_) | | (----`
| _ < | | | | \ \ \ \ \ / \ \ | ___/ | | / /_\ \ \_ _/ | __| | / \ \
| |_) | | `--' | .----) | .----) | \ / .----) | | | | `----./ _____ \ | | | |____ | |\ \----.----) |
|______/ \______/ |_______/ |_______/ \__/ |_______/ | _| |_______/__/ \__\ |__| |_______|| _| `._____|_______/
.______ ____ ____ _______ ___ __ ___ ___ ___ __ .______
| _ \ \ \ / / | ____| / \ | | / \ \ \ / / | | | _ \
| |_) | \ \/ / | |__ / ^ \ | | / ^ \ \ V / | | | |_) |
| _ < \_ _/ | __| / /_\ \ | | / /_\ \ > < | | | /
| |_) | | | | | / _____ \ | `----./ _____ \ / . \ | | | |\ \----.
|______/ |__| |__| /__/ \__\ |_______/__/ \__\ /__/ \__\ |__| | _| `._____|
--]]
function SpawnNewAmmoRessuply(location)
local ressuplyTrigger = Trigger(location, Rotator(), Vector(200), TriggerType.Sphere, true, Color(0, 1, 0))
ressuplyTrigger:SetValue("CanResupply", true)
ressuplyTrigger:Subscribe("BeginOverlap", function(trigger, actor_triggering)
if NanosUtils.IsA(actor_triggering, Character) then
if actor_triggering:GetTeam() == 1 then return end
if trigger:GetValue("CanResupply") then
local entityChar = actor_triggering:GetPicked()
if entityChar ~= nil then
if NanosUtils.IsA(entityChar, Weapon) then
if entityChar:GetAmmoBag() >= 400 then return end
entityChar:SetAmmoBag(400)
trigger:SetValue("CanResupply", false)
trigger:SetVisibility(false)
local playerChar = actor_triggering:GetPlayer()
if playerChar ~= nil then
Events.CallRemote("BVP_Client_SendPrivateChatMessage", playerChar, "CHAT_AmmoResupplied", nil)
end
Timer.SetTimeout(function(triggy)
triggy:SetValue("CanResupply", true)
triggy:SetVisibility(true)
return false
end, BVP_CONFIG.ResupplyTimeSeconds * 1000, trigger)
end
end
end
end
end)
end | 64.06383 | 152 | 0.376619 |
11cc442957a7df808260a2ac7a84d240c6eb3b5f | 298 | swift | Swift | WeatherAppDemo/Extensions/NSNotificationName+Custom.swift | brkyvrkn/WeatherApp | 82b9d556512956151a64f9c109e5ba4893c4ea50 | [
"MIT"
] | null | null | null | WeatherAppDemo/Extensions/NSNotificationName+Custom.swift | brkyvrkn/WeatherApp | 82b9d556512956151a64f9c109e5ba4893c4ea50 | [
"MIT"
] | null | null | null | WeatherAppDemo/Extensions/NSNotificationName+Custom.swift | brkyvrkn/WeatherApp | 82b9d556512956151a64f9c109e5ba4893c4ea50 | [
"MIT"
] | null | null | null | //
// NSNotificationName+Custom.swift
// WeatherAppDemo
//
// Created by Berkay Vurkan on 6.12.2020.
//
import Foundation
extension NSNotification.Name {
public static let settingsDidUpdate: NSNotification.Name = {
return NSNotification.Name("ForecastSettingsDidUpdate")
}()
}
| 19.866667 | 64 | 0.721477 |
179bb86501f7892ac5a7fc71d6d9d1f19c65cb2f | 403 | cs | C# | SampleMR/Models/Response.cs | mahdishahbazi/CQRS_Sample | a852ed8fe85a0d0f456e3f6800f0803ffea62b74 | [
"Apache-2.0"
] | 2 | 2020-06-18T01:00:42.000Z | 2021-06-04T08:03:12.000Z | SampleMR/Models/Response.cs | mahdishahbazi/CQRS_Sample | a852ed8fe85a0d0f456e3f6800f0803ffea62b74 | [
"Apache-2.0"
] | null | null | null | SampleMR/Models/Response.cs | mahdishahbazi/CQRS_Sample | a852ed8fe85a0d0f456e3f6800f0803ffea62b74 | [
"Apache-2.0"
] | null | null | null | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleMR.Models
{
public class ApiResponse<T> : ApiResponse
{
public T Result { get; set; }
}
public class ApiResponse
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
}
}
| 20.15 | 68 | 0.679901 |
dc143150a9a6bd448b4a46b8ec2cfeb284a7dc3c | 1,803 | py | Python | fakergen.py | KevCui/Fakergen | 0e329302e8e15e6f5d7430e796eeb30cf6436946 | [
"MIT"
] | 1 | 2020-12-16T08:37:53.000Z | 2020-12-16T08:37:53.000Z | fakergen.py | KevCui/jsonFaker | 0e329302e8e15e6f5d7430e796eeb30cf6436946 | [
"MIT"
] | null | null | null | fakergen.py | KevCui/jsonFaker | 0e329302e8e15e6f5d7430e796eeb30cf6436946 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import argparse
def printError(message):
if not _quiet:
print('\033[91m[ERROR]\033[0m ' + str(message))
exit(1)
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument('template', help='template file')
parser.add_argument('-q', '--quiet', action='store_true', help='be quiet, no error message')
parser.add_argument('-s', '--seed', type=int, help='set seed value')
return parser.parse_args()
def fetchContent(templateFile):
try:
with open(templateFile) as f:
return f.read().splitlines()
except FileNotFoundError as err:
printError(err)
def generateData(templateContent):
from faker import Faker
fake = Faker()
if _seed:
fake.seed_instance(_seed)
try:
from customprovider import CustomProvider
fake.add_provider(CustomProvider)
except (ModuleNotFoundError, ImportError):
pass
pattern = r'\{\{\w+\([\w=,\s?#\'\":-]*\)\}\}'
for line in templateContent:
num = len(re.findall(pattern, line))
if num != 0:
newline = line
for i in range(1, num+1):
item = re.findall(pattern, newline)
try:
newline = newline.replace(item[0], str(eval('fake.' + re.sub(r'[\{\}]', '', item[0]))), 1)
except AttributeError as err:
printError(err)
print(newline)
else:
print(line)
def main():
args = parseArgs()
global _quiet
global _seed
_seed = args.seed or 0
_quiet = args.quiet or False
template = str(args.template)
content = fetchContent(template)
generateData(content)
if __name__ == '__main__':
main()
| 24.69863 | 110 | 0.583472 |
06dfa0f3afa5a8f446a7d12da4977ccb8cd46d6b | 5,525 | cpp | C++ | src/Match.cpp | Gegel85/ChallongeLib | 15e7372a574282143b4ff928f261701d331ab7e8 | [
"MIT"
] | null | null | null | src/Match.cpp | Gegel85/ChallongeLib | 15e7372a574282143b4ff928f261701d331ab7e8 | [
"MIT"
] | null | null | null | src/Match.cpp | Gegel85/ChallongeLib | 15e7372a574282143b4ff928f261701d331ab7e8 | [
"MIT"
] | null | null | null | //
// Created by PinkySmile on 18/01/2021.
//
#include "Match.hpp"
#include "Tournament.hpp"
#include "JsonUtils.hpp"
namespace ChallongeAPI
{
Match::Match(Client &client, const Tournament &tournament, const json &val)
{
auto &value = val["match"];
getFromJson(this->_attachmentCount, "attachment_count", value);
getFromJson(this->_completedAt, "completed_at", value);
getFromJson(this->_createdAt, "created_at", value);
getFromJson(this->_forfeited, "forfeited", value);
getFromJson(this->_groupId, "group_id", value);
getFromJson(this->_hasAttachment, "has_attachment", value);
getFromJson(this->_id, "id", value);
getFromJson(this->_identifier, "identifier", value);
getFromJson(this->_location, "location", value);
getFromJson(this->_openGraphImageContentType, "open_graph_image_content_type", value);
getFromJson(this->_openGraphImageFileName, "open_graph_image_file_name", value);
getFromJson(this->_openGraphImageFileSize, "open_graph_image_file_size", value);
getFromJson(this->_optional, "optional", value);
getFromJson(this->_player1IsPrereqMatchLoser, "player1_is_prereq_match_loser", value);
getFromJson(this->_player1PrereqMatchId, "player1_prereq_match_id", value);
getFromJson(this->_player1Votes, "player1_votes", value);
getFromJson(this->_player2IsPrereqMatchLoser, "player2_is_prereq_match_loser", value);
getFromJson(this->_player2PrereqMatchId, "player2_prereq_match_id", value);
getFromJson(this->_player2Votes, "player2_votes", value);
getFromJson(this->_round, "round", value);
getFromJson(this->_rushbId, "rushb_id", value);
getFromJson(this->_scheduledTime, "scheduled_time", value);
getFromJson(this->_startedAt, "started_at", value);
getFromJson(this->_state, "state", value);
getFromJson(this->_suggestedPlayOrder, "suggested_play_order", value);
getFromJson(this->_tournamentId, "tournament_id", value);
getFromJson(this->_underwayAt, "underway_at", value);
getFromJson(this->_updatedAt, "updated_at", value);
getFromJson(this->_player1Id, "player1_id", value);
getFromJson(this->_player2Id, "player2_id", value);
getFromJson(this->_loserId, "loser_id", value);
getFromJson(this->_winnerId, "winner_id", value);
getFromJson(this->_prerequisiteMatchIds, "prerequisite_match_ids_csv", value);
getFromJson(this->_scores, "scores_csv", value);
}
const std::optional<json> &Match::getAttachmentCount() const
{
return this->_attachmentCount;
}
const std::optional<Time> &Match::getCompletedAt() const
{
return this->_completedAt;
}
const Time &Match::getCreatedAt() const
{
return this->_createdAt;
}
const std::optional<json> &Match::getForfeited() const
{
return this->_forfeited;
}
const std::optional<size_t> &Match::getGroupId() const
{
return this->_groupId;
}
bool Match::hasAttachment() const
{
return this->_hasAttachment;
}
size_t Match::getId() const
{
return this->_id;
}
const std::string &Match::getIdentifier() const
{
return this->_identifier;
}
const std::optional<json> &Match::getLocation() const
{
return this->_location;
}
const std::optional<json> &Match::getOpenGraphImageContentType() const
{
return this->_openGraphImageContentType;
}
const std::optional<json> &Match::getOpenGraphImageFileName() const
{
return this->_openGraphImageFileName;
}
const std::optional<json> &Match::getOpenGraphImageFileSize() const
{
return this->_openGraphImageFileSize;
}
const std::optional<bool> &Match::getOptional() const
{
return this->_optional;
}
bool Match::isPlayer1IsPrereqMatchLoser() const
{
return this->_player1IsPrereqMatchLoser;
}
const std::optional<size_t> &Match::getPlayer1PrereqMatchId() const
{
return this->_player1PrereqMatchId;
}
const std::optional<json> &Match::getPlayer1Votes() const
{
return this->_player1Votes;
}
bool Match::isPlayer2IsPrereqMatchLoser() const
{
return this->_player2IsPrereqMatchLoser;
}
const std::optional<size_t> &Match::getPlayer2PrereqMatchId() const
{
return this->_player2PrereqMatchId;
}
const std::optional<json> &Match::getPlayer2Votes() const
{
return this->_player2Votes;
}
const std::vector<size_t> &Match::getPrerequisiteMatchIds() const
{
return this->_prerequisiteMatchIds;
}
int Match::getRound() const
{
return this->_round;
}
const std::optional<json> &Match::getRushbId() const
{
return this->_rushbId;
}
const std::optional<Time> &Match::getScheduledTime() const
{
return this->_scheduledTime;
}
const std::optional<std::pair<int, int>> &Match::getScores() const
{
return this->_scores;
}
const std::optional<Time> &Match::getStartedAt() const
{
return this->_startedAt;
}
const std::string &Match::getState() const
{
return this->_state;
}
unsigned int Match::getSuggestedPlayOrder() const
{
if (!this->_suggestedPlayOrder)
return 0;
return *this->_suggestedPlayOrder;
}
size_t Match::getTournamentId() const
{
return this->_tournamentId;
}
const std::optional<json> &Match::getUnderwayAt() const
{
return this->_underwayAt;
}
const Time &Match::getUpdatedAt() const
{
return this->_updatedAt;
}
const std::optional<size_t> &Match::getLoserId() const
{
return this->_loserId;
}
const std::optional<size_t> &Match::getWinnerId() const
{
return this->_winnerId;
}
const std::optional<size_t> &Match::getPlayer1Id() const
{
return this->_player1Id;
}
const std::optional<size_t> &Match::getPlayer2Id() const
{
return this->_player2Id;
}
} | 24.775785 | 88 | 0.732489 |
0fae6ba00955fb1bec3478745ab262d737e4d7d4 | 2,930 | go | Go | pkg/blockchain/genesis.go | peerbridge/peerbridge | fcf42dc3673c451cfd01c9d2a8e2f06aab499263 | [
"MIT"
] | 3 | 2020-06-11T11:48:58.000Z | 2021-05-14T21:38:39.000Z | pkg/blockchain/genesis.go | peerbridge/peerbridge | fcf42dc3673c451cfd01c9d2a8e2f06aab499263 | [
"MIT"
] | 16 | 2020-06-11T14:23:57.000Z | 2021-04-29T10:01:33.000Z | pkg/blockchain/genesis.go | peerbridge/peerbridge | fcf42dc3673c451cfd01c9d2a8e2f06aab499263 | [
"MIT"
] | null | null | null | package blockchain
import (
"crypto/sha256"
"encoding/hex"
"time"
"github.com/peerbridge/peerbridge/pkg/encryption"
"github.com/peerbridge/peerbridge/pkg/encryption/secp256k1"
)
var (
// The initial block height.
GenesisHeight uint64 = 0
// The initial block target in the network.
GenesisTarget uint64 = 100_000
// The initial block difficulty in the network.
GenesisDifficulty uint64 = 0
// The initial block creation time in the network.
GenesisTimeUnixNano int64 = time.Unix(0, 0).UnixNano()
// The genesis account that created the genesis block.
GenesisKeyPair = &secp256k1.KeyPair{
PublicKey: "0308f3ee0280f67151bd0d1a468205279d7df016805213be6c89f7bb8168835d0c",
PrivateKey: "484ff6fe0382d9f0c201d3f7a7e65e2a4f86845ccc47bc5b8617b31666ddf408",
}
// The initial transactions in the genesis block.
GenesisTransactions = []Transaction{}
GenesisChallenge encryption.SHA256HexString = encryption.ZeroSHA256HexString()
GenesisAddress encryption.SHA256HexString = encryption.ZeroSHA256HexString()
// The genesis block.
GenesisBlock *Block
Stakeholders = map[string]uint64{
// Alice
"0372689db204d56d9bb7122497eef4732cce308b73f3923fc076aed3c2dfa4ad04": uint64(100_000),
// Bob
"03f1f2fbd80b49b8ffc8194ac0a0e0b7cf0c7e21bca2482c5fba7adf67db41dec5": uint64(100_000),
}
)
func init() {
for publicKeyHex, stake := range Stakeholders {
// Generate the genesis transaction ids in a consistent way so that
// every node has the same starting point
publicKeyBytes, err := hex.DecodeString(publicKeyHex)
if err != nil {
panic(err)
}
hasher := sha256.New()
hasher.Write(publicKeyBytes)
var id [encryption.SHA256ByteLength]byte
copy(id[:], hasher.Sum(nil)[:encryption.SHA256ByteLength])
idHex := hex.EncodeToString(id[:])
t := &Transaction{
ID: idHex,
Sender: GenesisKeyPair.PublicKey,
Receiver: publicKeyHex,
Balance: stake,
TimeUnixNano: time.Unix(0, 0).UnixNano(),
Data: nil,
Fee: 0,
BlockID: &GenesisAddress, // Genesis block
// Part of the signing process
Signature: nil,
}
signature, err := secp256k1.ComputeSignature(t, GenesisKeyPair.PrivateKey)
if err != nil {
panic(err)
}
t.Signature = signature
GenesisTransactions = append(GenesisTransactions, *t)
}
g := &Block{
ID: GenesisAddress,
ParentID: nil,
Height: GenesisHeight,
TimeUnixNano: time.Unix(0, 0).UnixNano(),
Transactions: GenesisTransactions,
Creator: GenesisKeyPair.PublicKey,
Target: GenesisTarget,
Challenge: GenesisChallenge,
CumulativeDifficulty: GenesisDifficulty,
// Part of the signature calculation
Signature: nil,
}
signature, err := secp256k1.ComputeSignature(g, GenesisKeyPair.PrivateKey)
if err != nil {
panic(err)
}
g.Signature = signature
GenesisBlock = g
}
| 27.383178 | 88 | 0.71058 |
47600d41181d547b3d83b630ca25252b6a080ef5 | 24,734 | swift | Swift | MaltMall/CabageShop/CabbageShop/Classess/首页/controllers/推荐/SZYMainViewController.swift | mengzhihun6/JGTaoMall | 4cbd161fa5092c212edfd9a3c184bbb9cd91c079 | [
"MIT"
] | 116 | 2019-09-30T03:44:22.000Z | 2021-11-22T05:54:53.000Z | MaltMall/CabageShop/CabbageShop/Classess/首页/controllers/推荐/SZYMainViewController.swift | mengzhihun6/JGTaoMall | 4cbd161fa5092c212edfd9a3c184bbb9cd91c079 | [
"MIT"
] | null | null | null | MaltMall/CabageShop/CabbageShop/Classess/首页/controllers/推荐/SZYMainViewController.swift | mengzhihun6/JGTaoMall | 4cbd161fa5092c212edfd9a3c184bbb9cd91c079 | [
"MIT"
] | 54 | 2019-09-30T02:21:45.000Z | 2021-12-08T07:48:17.000Z | //
// SZYMainViewController.swift
// CabbageShop
//
// Created by 宋宗宇 on 2019/3/19.
// Copyright © 2019 付耀辉. All rights reserved.
//
import UIKit
import SwiftyJSON
import MJRefresh
import SwiftyUserDefaults
@objc public protocol SZYMainViewControllerDelegate: NSObjectProtocol {
@objc func delegateScroll(_ offSetY: CGFloat)
}
class SZYMainViewController: LNBaseViewController {
var headBottomImage: UIImageView? //接收外界变换视图
let identyfierTable1 = "identyfierTable1"
let identyfierTable2 = "identyfierTable2"
let identyfierTable3 = "identyfierTable3"
let identyfierTable4 = "identyfierTable4"
let identyfierTable5 = "identyfierTable5"
let identyfierTable6 = "identyfierTable6"
let JGHomeDiyGoodsTCellId = "JGHomeDiyGoodsTCellId"
// 一定要weak,防止循环引用
weak var superViewController : LNPageViewController?
var scrollDelegate : SZYMainViewControllerDelegate?
var homeDiyModel : JTHHomeDiyModel?
var newCouponsSource = [SZYGoodsInformationModel]()
var newIndexCouponsSource = [SZYGoodsInformationModel]()
var homeNewGoods = [NSMutableArray]()
//精品
private lazy var homeDiyGoods : NSMutableArray = {
return NSMutableArray()
}()
// 时间选择View
// fileprivate var topView = LNTopScrollView3_1()
fileprivate var selectIndex1 = 0
var topBun = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addFooterRefresh()
let head = mainTableView.mj_header as! MJRefreshNormalHeader
head.lastUpdatedTimeLabel.textColor = UIColor.white
head.stateLabel.textColor = UIColor.white
// diy 数据获取
requestForLayout()
}
override func configSubViews() {
navigaView.isHidden = true
titleLabel.textColor = UIColor.white
let top = CGFloat(105)
mainTableView = getTableView(frame: CGRect(x: 0, y: top, width: kDeviceWidth, height: kDeviceHight - top), style: .grouped, vc: self)
// 两列 四列 四个按钮
mainTableView.register(UINib(nibName: "SZYSecondFourTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable1)
// 横向滑动
mainTableView.register(UINib(nibName: "SZYCollectionViewTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable2)
// banner
mainTableView.register(UINib(nibName: "SZYBannerTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable3)
// 九宫格
mainTableView.register(UINib(nibName: "SZYScratchableIatexTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable4)
// 情报局
mainTableView.register(UINib(nibName: "SZYCiaTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable5)
// 商品
mainTableView.register(UINib(nibName: "SZYDiyGoodsTableViewCell", bundle: nil), forCellReuseIdentifier: identyfierTable6)
// mainTableView.register(UINib(nibName: "JGHomeDiyGoodsTCell", bundle: nil), forCellReuseIdentifier: JGHomeDiyGoodsTCellId)
mainTableView.register(JGHomeDiyGoodsTCell.self, forCellReuseIdentifier: JGHomeDiyGoodsTCellId)
// 商品信息
mainTableView.register(UINib(nibName: "LNMainLayoutCell3", bundle: nil), forCellReuseIdentifier: identyfierTable)
// 一定要将所有的背景设为透明,否则看不到后面的东西
mainTableView.backgroundColor = UIColor.clear
self.view.backgroundColor = UIColor.clear
mainTableView.separatorStyle = .none
self.view.addSubview(mainTableView)
// topView = LNTopScrollView3_1.init(frame: CGRect(x: 0, y: 10, width: kSCREEN_WIDTH, height: 60))
//// setTopView()
// weak var weakSelf = self
// topView.callBackBlock { (index, title) in
// weakSelf?.selectIndex1 = index + 1
// weakSelf?.currentPage = 1
// weakSelf?.requestData()
// kDeBugPrint(item: "index \(index) title \(title) ")
// }
topBun = UIButton.init(frame: CGRect.init(x: kSCREEN_WIDTH - 55, y: kSCREEN_HEIGHT - 165, width: 45, height: 45));
topBun.backgroundColor = UIColor.red
topBun.setImage(UIImage.init(named: "返回顶部"), for: .normal)
topBun.addTarget(self, action: #selector(topBunClick), for: .touchUpInside)
topBun.cornerRadius = topBun.height / 2.0
topBun.clipsToBounds = true
topBun.isHidden = true
self.view.addSubview(topBun)
}
@objc func topBunClick() {
let indexPat = IndexPath.init(row: 0, section: 0)
mainTableView.scrollToRow(at: indexPat as IndexPath, at: .bottom, animated: true)
}
// func setTopView() {
// var selectIndex = 0
// let dateFamater = DateFormatter.init()
// dateFamater.dateFormat = "HH"
// let time = Int(dateFamater.string(from: Date.init()))
//
//// 判断当前时间属于哪一个阶段
// if time! >= 0 && time! < 10 {
// selectIndex = 5
// }
// if time! >= 10 && time! < 12 {
// selectIndex = 6
// }
// if time! >= 12 && time! < 15 {
// selectIndex = 7
// }
// if time! >= 15 && time! < 20 {
// selectIndex = 8
// }
// if time! >= 20 {
// selectIndex = 9
// }
// selectIndex1 = selectIndex + 1
// topView.lineColor = kGaryColor(num: 255)//kGaryColor
// topView.setTopView(titles: [ "00:00", "10:00", "12:00", "15:00", "20:00", "00:00", "10:00", "12:00", "15:00", "20:00", "00:00", "10:00", "12:00", "15:00", "20:00" ], selectIndex: selectIndex)
//
// topView.setSelectIndex(index: selectIndex, animation: true)
//
// }
override func refreshHeaderAction() {
currentPage = 1
requestForLayout()
requestData()
}
override func refreshFooterAction() {
currentPage = currentPage + 1
requestData()
}
// 请求布局 diy
func requestForLayout() {
let request = SKRequest.init()
weak var weakSelf = self
request.callGET(withUrl: LNUrls().JTHHomdeDiy) { (response) in
kDeBugPrint(item: response?.data)
DispatchQueue.main.async {
if !(response?.success)! {
return
}
let datas = JSON((response?.data["data"])!)
weakSelf?.homeDiyModel = JTHHomeDiyModel.setUpModel(json: datas)
weakSelf?.mainTableView.reloadData()
}
}
}
override func requestData() {
let request = SKRequest.init()
weak var weakSelf = self
request.setParam(String(currentPage) as NSObject, forKey: "page")
request.setParam("type:1;tag:2" as NSObject, forKey: "search")
request.setParam("and" as NSObject, forKey: "searchJoin")
request.setParam("id" as NSObject, forKey: "orderBy")
request.setParam("desc" as NSObject, forKey: "sortedBy")
request.setParam("10" as NSObject, forKey: "limit")
request.callGET(withUrl: LNUrls().kSwhow_coupon) { (response) in
LQLoadingView().SVPHide()
DispatchQueue.main.async {
if !(response?.success)! {
weakSelf?.mainTableView.mj_footer.endRefreshing()
weakSelf?.mainTableView.mj_header.endRefreshing()
return
}
let datas = JSON((response?.data["data"])!)["data"].arrayValue
if datas.count >= 0 {
let pages = JSON((response?.data["data"])!)["meta"]["pagination"]["total_pages"].intValue
if weakSelf?.currentPage == 1 {
weakSelf?.newCouponsSource.removeAll()
if weakSelf?.currentPage == pages {
weakSelf?.mainTableView.mj_footer.endRefreshingWithNoMoreData()
} else {
weakSelf?.mainTableView.mj_footer.resetNoMoreData()
}
} else {
if (weakSelf?.currentPage)! >= pages {
weakSelf?.mainTableView.mj_footer.endRefreshingWithNoMoreData()
} else {
weakSelf?.mainTableView.mj_footer.endRefreshing()
}
}
for index in 0..<datas.count{
let json = datas[index]
weakSelf?.newCouponsSource.append(SZYGoodsInformationModel.setupValues(json: json))
}
if (weakSelf?.newCouponsSource.count)! > 0{
var randomNumber:Int = Int(arc4random() % UInt32((weakSelf?.newCouponsSource.count)!)) - 1
if randomNumber < 0 {
randomNumber = 0
}
if randomNumber + 1 <= (weakSelf?.newCouponsSource.count)! {
Defaults[kGetTheRandomItemId] = weakSelf?.newCouponsSource[randomNumber].item_id
}
}
if (weakSelf?.mainTableView.mj_header.isRefreshing)! {
weakSelf?.mainTableView.mj_header.endRefreshing()
}
} else {
if weakSelf?.mainTableView.mj_footer != nil {
weakSelf?.mainTableView.mj_footer.endRefreshingWithNoMoreData()
}
}
//SZYGoodsInformationModel
weakSelf?.homeNewGoods.removeAll()
let arrM = NSMutableArray.init();
for (index , mo) in (weakSelf!.newCouponsSource.enumerated()) {
arrM.add(mo)
if (index + 1) % 2 == 0 {
var arrMN = NSMutableArray.init();
arrMN = arrM.mutableCopy() as! NSMutableArray
weakSelf?.homeNewGoods.append(arrMN)
arrM.removeAllObjects()
}else if index == ((weakSelf?.newCouponsSource.count)! - 1) {
var arrMN = NSMutableArray.init();
arrMN = arrM.mutableCopy() as! NSMutableArray
weakSelf?.homeNewGoods.append(arrMN)
}
}
weakSelf?.mainTableView.reloadData()
}
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// if scrollView.mj_offsetY > 600 {
// topBun.isHidden = false
// } else {
// topBun.isHidden = true
// }
if scrollDelegate != nil {
scrollDelegate?.delegateScroll(scrollView.mj_offsetY)
}
}
}
extension SZYMainViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if homeDiyModel == nil {
return 0
} else {
return 3 + (homeDiyModel?.home.goods.count)!
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 3 + homeDiyModel!.home.goods.count - 1 {
// //热销商品
// return newCouponsSource.count
return homeNewGoods.count
} else {
if section > 1 {
let goods: goodsDiyModel = homeDiyModel!.home.goods[section - 2]
if goods.type == "special" && goods.theme == "4" {
//精选宝贝
// return goods.list.count
return 0
}
if goods.type == "special" && (goods.theme == "1" || goods.theme == "2" || goods.theme == "3") {
return 0
}
}
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable3, for: indexPath) as! SZYBannerTableViewCell
cell.headBottomImage = headBottomImage
cell.selectionStyle = .none
cell.backgroundColor = kSetRGBAColor(r: 0, g: 0, b: 0, a: 0)
cell.superViewController = superViewController
if homeDiyModel?.home.banner != nil {
cell.setUpValues(model: (homeDiyModel?.home.banner)!)
}
return cell
} else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable4, for: indexPath) as! SZYScratchableIatexTableViewCell
cell.selectionStyle = .none
cell.superViewController = superViewController
cell.serUpModel(model: (homeDiyModel?.home.entrance)!)
return cell
} else if indexPath.section > 1 && indexPath.section < (3 + homeDiyModel!.home.goods.count - 1) {
let goods: goodsDiyModel = homeDiyModel!.home.goods[indexPath.section - 2]
if goods.type == "topic" { //专题
let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable1, for: indexPath) as! SZYSecondFourTableViewCell
cell.selectionStyle = .none
cell.superViewController = superViewController
if goods.theme == "1" { // 两列并排
cell.setModel(model: goods.data)
} else if goods.theme == "2" { // 四列并排
cell.setModelFour(model: goods.data)
} else if goods.theme == "3" { //单独一张图
cell.setOneModel(model: goods.data)
} else if goods.theme == "4" { //四个固定图
cell.setFourModel(model: goods.data)
}
return cell
} else if goods.type == "special" { //商品
kDeBugPrint(item: "输出goods.list \(goods.list)")
if goods.theme == "1" || goods.theme == "2" || goods.theme == "3" {
let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable2, for: indexPath) as! SZYCollectionViewTableViewCell
cell.superViewController = superViewController
cell.selectionStyle = .none
cell.typeString = goods.theme
// cell.titleLable.text = goods.title
// cell.setUpValues(model: goods.list)
cell.setUpValues(model: goods)
return cell
} else { //单个横排商品 goods.theme == "4"
// let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable6, for: indexPath) as! SZYDiyGoodsTableViewCell
// cell.selectionStyle = .none
//
// cell.setUpModel(model: goods.list[indexPath.row])
//
// return cell
let cell = tableView.dequeueReusableCell(withIdentifier: JGHomeDiyGoodsTCellId, for: indexPath) as! JGHomeDiyGoodsTCell
return cell
}
}
}
// let cell = tableView.dequeueReusableCell(withIdentifier: identyfierTable, for: indexPath) as! LNMainLayoutCell3
// cell.setValues2(model: newCouponsSource[indexPath.row], type: "")
// cell.selectionStyle = .none
// return cell
let cell = tableView.dequeueReusableCell(withIdentifier: JGHomeDiyGoodsTCellId, for: indexPath) as! JGHomeDiyGoodsTCell
cell.setUpArrM(arrM: homeNewGoods[indexPath.row])
cell.superViewController = superViewController
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section > 1 {
if indexPath.section < (3 + homeDiyModel!.home.goods.count - 1) {
let goods: goodsDiyModel = homeDiyModel!.home.goods[indexPath.section - 2]
if goods.type == "special" && goods.theme == "4" { // 完成显示 操作
let detailVc = SZYGoodsViewController()
detailVc.good_item_id = goods.list[indexPath.row].item_id
detailVc.coupone_type = goods.list[indexPath.row].type
detailVc.goodsUrl = goods.list[indexPath.row].pic_url
detailVc.GoodsInformationModel = goods.list[indexPath.row]
superViewController?.navigationController?.pushViewController(detailVc, animated: true)
}
} else if indexPath.section == (3 + homeDiyModel!.home.goods.count - 1) { // 最后商品 区头 完成区头样式
// let detailVc = SZYGoodsViewController()
// detailVc.good_item_id = newCouponsSource[indexPath.row].item_id
// detailVc.coupone_type = newCouponsSource[indexPath.row].type
// detailVc.goodsUrl = newCouponsSource[indexPath.row].pic_url
// detailVc.GoodsInformationModel = newCouponsSource[indexPath.row]
// superViewController?.navigationController?.pushViewController(detailVc, animated: true)
}
}
}
// 表头
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionHead = UIView.init()
sectionHead.contentMode = .scaleToFill
sectionHead.backgroundColor = kSetRGBColor(r: 246, g: 246, b: 246)
if section > 1 {
if section < (3 + homeDiyModel!.home.goods.count - 1) {
let goods: goodsDiyModel = homeDiyModel!.home.goods[section - 2]
if goods.type == "special" && goods.theme == "4" { // 完成显示 操作
// let beijingView = UIView.init(frame: CGRect.init(x: 0, y: 10, width: kSCREEN_WIDTH, height: 45))
// beijingView.backgroundColor = UIColor.white
// sectionHead.addSubview(beijingView)
//
// let nameLab = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: 150, height: 45))
// nameLab.text = goods.title
// nameLab.textColor = kSetRGBColor(r: 55, g: 55, b: 55)
// nameLab.font = UIFont.systemFont(ofSize: 15)
// beijingView.addSubview(nameLab)
//
// let bun = UIButton.init(frame: CGRect.init(x: kSCREEN_WIDTH - 80, y: 0, width: 70, height: 45))
// bun.setImage(UIImage.init(named: "首页更多"), for: .normal)
// bun.setTitle("更多", for: .normal)
// bun.setTitleColor(kSetRGBColor(r: 153, g: 153, b: 153), for: .normal)
// bun.titleLabel?.font = UIFont.systemFont(ofSize: 13)
// bun.addTarget(self, action: #selector(shangPinBunClick(bun:)), for: .touchUpInside)
// bun.tag = 50
// beijingView.addSubview(bun)
// bun.layoutButton(with: .right, imageTitleSpace: 10)
}
} else if section == (3 + homeDiyModel!.home.goods.count - 1) { // 最后商品 区头 完成区头样式
// let beijingView = UIView.init(frame: CGRect.init(x: 0, y: 10, width: kSCREEN_WIDTH, height: 45))
// beijingView.backgroundColor = UIColor.white
// sectionHead.addSubview(beijingView)
//
// let nameLab = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: 150, height: 50))
// nameLab.text = "热销商品"
// nameLab.textColor = kSetRGBColor(r: 55, g: 55, b: 55)
// nameLab.font = UIFont.systemFont(ofSize: 15)
// beijingView.addSubview(nameLab)
// sectionHead.addSubview(topView)
}
}
return sectionHead
}
@objc func shangPinBunClick(bun: UIButton) {
for index in 0..<homeDiyModel!.home.goods.count {
let goods: goodsDiyModel = (homeDiyModel?.home.goods[index])!
if goods.type == "special" && goods.theme == "4" {
let dataUrl = goods.data[0].url
if dataUrl.contains("list") {
let arr1 = dataUrl.components(separatedBy: "?")
let viewC = SZYModuleViewController()
viewC.titleString = goods.title
viewC.typeInt = 2
if arr1.count > 1 {
viewC.SZYTypeString = arr1[1]
}
superViewController?.navigationController?.pushViewController(viewC, animated: true)
} else if dataUrl.contains("webview") {
var pageUrl = dataUrl.replacingOccurrences(of: "hongtang://webview?url=", with: "")
if Defaults[kUserToken] != nil && Defaults[kUserToken] != "" {
if !pageUrl.contains(Defaults[kUserToken]!) {
if !pageUrl.contains("?") {
pageUrl = "\(pageUrl)?token=\(Defaults[kUserToken]!)"
} else {
pageUrl = "\(pageUrl)&token=\(Defaults[kUserToken]!)"
}
}
}
let page = AlibcTradePageFactory.page(pageUrl)
let taoKeParams = AlibcTradeTaokeParams.init()
taoKeParams.pid = nil
let showParam = AlibcTradeShowParams.init()
showParam.openType = .auto
let myView = SZYwebViewViewController.init()
myView.webTitle = goods.title
// let ret = AlibcTradeSDK.sharedInstance()?.tradeService()?.show(myView, webView: myView.webView, page: page, showParams: showParam, taoKeParams: taoKeParams, trackParam: nil, tradeProcessSuccessCallback: { (ls) in
// kDeBugPrint(item: "======11111=======")
// }, tradeProcessFailedCallback: { (error) in
// kDeBugPrint(item: error)
// })
// if (ret == 1) {
// superViewController?.navigationController?.pushViewController(myView, animated: true)
// }
let ret = AlibcTradeSDK.sharedInstance().tradeService()?.open(byUrl: pageUrl, identity: "trade", webView: myView.webView, parentController: myView, showParams: showParam, taoKeParams: self.getTaokeParam(), trackParam: ALiTradeSDKShareParam.sharedInstance().customParams as? [AnyHashable : Any], tradeProcessSuccessCallback: { (back) in
}, tradeProcessFailedCallback: { (error) in
})
if (ret == 1) {
superViewController?.navigationController?.pushViewController(myView, animated: true)
}
}
break
}
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// if section > 1 {
// if section < (3 + homeDiyModel!.home.goods.count - 1) {
// let goods: goodsDiyModel = homeDiyModel!.home.goods[section - 2]
// if goods.type == "special" && goods.theme == "4" {
// return 0.01
// }
//
// } else if section == (3 + homeDiyModel!.home.goods.count - 1) { // 最后商品 区头
// return 0.01
// }
//
// return 10
// }
return 0.01
}
// 表尾
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let foot = UIView.init()
foot.backgroundColor = kBGColor()
return foot
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
| 43.165794 | 355 | 0.543665 |
f547f8fef46ec505d69b6ef7e6e43be8efc8fea3 | 3,249 | cpp | C++ | test/forestmodelchoice-ks-test.cpp | vitorpavinato/abcranger | 71f950817bedeebed12d13610d8747c6dcc75a72 | [
"MIT"
] | 1 | 2020-07-29T13:31:43.000Z | 2020-07-29T13:31:43.000Z | test/forestmodelchoice-ks-test.cpp | vitorpavinato/abcranger | 71f950817bedeebed12d13610d8747c6dcc75a72 | [
"MIT"
] | null | null | null | test/forestmodelchoice-ks-test.cpp | vitorpavinato/abcranger | 71f950817bedeebed12d13610d8747c6dcc75a72 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "readstatobs.hpp"
#include "readreftable.hpp"
#include "csv-eigen.hpp"
#include "cxxopts.hpp"
#include "ModelChoice.hpp"
#include "ks.hpp"
#include "various.hpp"
#include "tqdm.hpp"
#include "range/v3/all.hpp"
using namespace ranges;
TEST_CASE("ModelChoice KS test")
{
size_t nref = 3000;
std::string headerfile,reftablefile,statobsfile;
MatrixXd E = read_matrix_file("modelchoice_runs.csv",',');
std::vector<double> postprobasR = E.col(0) | to_vector;
try {
std::vector<std::string> args{"ModelChoice","-t","500","-n","3000"};
std::vector<char *> argv;
for(std::string &s: args) argv.push_back(&s[0]);
argv.push_back(NULL);
cxxopts::Options options("", "");
options
.positional_help("[optional args]")
.show_positional_help();
options.add_options()
("h,header","Header file",cxxopts::value<std::string>()->default_value("headerRF.txt"))
("r,reftable","Reftable file",cxxopts::value<std::string>()->default_value("reftableRF.bin"))
("b,statobs","Statobs file",cxxopts::value<std::string>()->default_value("statobsRF.txt"))
("o,output","Prefix output",cxxopts::value<std::string>()->default_value("modelchoice_out"))
("n,nref","Number of samples, 0 means all",cxxopts::value<size_t>()->default_value("0"))
("m,minnodesize","Minimal node size. 0 means 1 for classification or 5 for regression",cxxopts::value<size_t>()->default_value("0"))
("t,ntree","Number of trees",cxxopts::value<size_t>()->default_value("500"))
("j,threads","Number of threads, 0 means all",cxxopts::value<size_t>()->default_value("0"))
("s,seed","Seed, 0 means generated",cxxopts::value<size_t>()->default_value("0"))
("c,noisecolumns","Number of noise columns",cxxopts::value<size_t>()->default_value("5"))
("nolinear","Disable LDA",cxxopts::value<bool>()->default_value("false"))
("help", "Print help")
;
int argc = argv.size()-1;
char ** argvc = argv.data();
const auto opts = options.parse(argc,argvc);
size_t nrun = 100;
std::vector<double> postprobas(nrun);
headerfile = opts["h"].as<std::string>();
reftablefile = opts["r"].as<std::string>();
statobsfile = opts["b"].as<std::string>();
auto myread = readreftable(headerfile, reftablefile, 3000,true);
const auto statobs = readStatObs(statobsfile);
tqdm bar;
for(auto i = 0; i < nrun; i++) {
bar.progress(i,nrun);
auto res = ModelChoice_fun(myread,statobs,opts,true);
postprobas[i] = res.post_proba;
}
std::cout << std::endl;
double D, pvalue;
std::cout << "postprobas" << std::endl;
std::cout << (postprobas | views::all) << std::endl;
D = KSTest(postprobasR,postprobas);
pvalue = 1-psmirnov2x(D,E.rows(),nrun);
CHECK( pvalue >= 0.05);
} catch (const cxxopts::OptionException& e)
{
std::cout << "error parsing options: " << e.what() << std::endl;
exit(1);
}
} | 37.77907 | 144 | 0.595568 |
8bd87b944ccc51baa132378abcfc304267fd8d2f | 1,867 | swift | Swift | TwitterDemo/Twitter+Prefetching.swift | faviomob/TwitterDemo | ebd3bda936a3bddaefe9c731b49909271f226244 | [
"MIT"
] | null | null | null | TwitterDemo/Twitter+Prefetching.swift | faviomob/TwitterDemo | ebd3bda936a3bddaefe9c731b49909271f226244 | [
"MIT"
] | null | null | null | TwitterDemo/Twitter+Prefetching.swift | faviomob/TwitterDemo | ebd3bda936a3bddaefe9c731b49909271f226244 | [
"MIT"
] | null | null | null | //
// Twitter+Prefetching.swift
// TwitterDemo
//
// Created by Marat on 06/02/2017.
// Copyright © 2017 Favio Mobile. All rights reserved.
//
import Groot
extension Twitter {
func prefetchHomeTweets() {
get("1.1/statuses/home_timeline.json",
parameters: ["count": "5"],
progress: nil,
success: { (_: URLSessionDataTask, response: Any?) -> Void in
if let tweetsArr = response as? [JSONDictionary] {
for tweetJson in tweetsArr {
let tweetId = tweetJson["id_str"] as! String
let tweet = NSManagedObject.objects(ofEntity: "\(Tweet.self)", with: NSPredicate(format: "SELF.tweetId = %@", tweetId), in: self.moc)?.first
if tweet == nil {
self.prefetchedTweets[tweetId] = tweetJson
}
}
if self.prefetchedTweets.count > 0 {
NotificationCenter.default.post(name: .prefetchedTweetsAvailable, object: nil)
}
print("Prefetched tweets count: \(self.prefetchedTweets.count)")
}
}, failure: { (task: URLSessionDataTask?, error: Error) in
print(error.localizedDescription)
self.handleError(error, inTask: task, withNotification: .tweetsPrefetchingError)
})
}
func showPrefetchedHomeTweets() {
if self.prefetchedTweets.count > 0 {
let tweets = try? Groot.objects(fromJSONArray: Array(self.prefetchedTweets.values), inContext: self.moc) as [Tweet]
NotificationCenter.default.post(name: .moreTweetsAvailable, object: nil)
self.prefetchedTweets.removeAll()
print("Tweets shown count: \(tweets?.count)")
}
}
}
| 39.723404 | 164 | 0.558115 |
7080343379a4a77530bd4a1d5d0fc675d49945e6 | 93 | cshtml | C# | 12. Internet Programming/2020/09. Template Language/CHUSHKA/Pages/_ViewImports.cshtml | dimitarminchev/ITCareer | 0e36aa85e5f1c12de186bbe402f8c66042ce84a2 | [
"MIT"
] | 50 | 2018-09-22T07:18:13.000Z | 2022-03-04T12:31:04.000Z | 12. Internet Programming/2020/09. Template Language/CHUSHKA/Pages/_ViewImports.cshtml | dimitarminchev/ITCareer | 0e36aa85e5f1c12de186bbe402f8c66042ce84a2 | [
"MIT"
] | null | null | null | 12. Internet Programming/2020/09. Template Language/CHUSHKA/Pages/_ViewImports.cshtml | dimitarminchev/ITCareer | 0e36aa85e5f1c12de186bbe402f8c66042ce84a2 | [
"MIT"
] | 30 | 2019-03-22T21:48:16.000Z | 2022-02-14T08:48:52.000Z | @using CHUSHKA
@namespace CHUSHKA.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
| 23.25 | 52 | 0.827957 |
31083119f6c46c15946cf4732ad56af6ac5a76ab | 1,526 | sql | SQL | Questionario/questionario.sql | rpatricio-souza/Programacao_de_Banco_de_Dados | 5de539979544dcb59046980ac331337e02181b16 | [
"MIT"
] | null | null | null | Questionario/questionario.sql | rpatricio-souza/Programacao_de_Banco_de_Dados | 5de539979544dcb59046980ac331337e02181b16 | [
"MIT"
] | null | null | null | Questionario/questionario.sql | rpatricio-souza/Programacao_de_Banco_de_Dados | 5de539979544dcb59046980ac331337e02181b16 | [
"MIT"
] | null | null | null | --01
select pes_nro_matricula, count(emp_cod) "quantidade"
from aluno join emprestimo using(pes_cod)
where emp_data_emprestimo='03/11/15'
group by pes_nro_matricula;
--02
select liv_titulo, count(exe_cod)
from livro join exemplar using(liv_cod)
group by rollup(liv_titulo);
--03
select liv_cod, emp_data_emprestimo, count(*) "quantidade"
from exemplar join item_emprestimo using(exe_cod) join emprestimo using(emp_cod)
group by cube(liv_cod, emp_data_emprestimo)
order by liv_cod;
--04
select edi_cod, edi_descricao, liv_cod
from editora left join livro using(edi_cod);
select e.edi_cod, e.edi_descricao, l.liv_cod
from editora e,livro l
where e.edi_cod=l.edi_cod(+);
--05
create view view_emp_atrasadados as
select distinct(pes_nome) "Pessoas com atraso"
from pessoa join emprestimo using(pes_cod)
where emp_cod is not null and emp_cod not in(select distinct(emp_cod)
from pessoa join emprestimo using(pes_cod) join devolucao using(emp_cod)
where emp_data_prevdev<=data_dev);
--drop view view_emp_atrasadados;
select * from view_emp_atrasadados;
--06
create table emp_log(
data date,
user_log varchar2(30),
emp_cod number
);
create or replace trigger trg_log_emprestimo
after update on emprestimo
for each row
declare
user user_users.username%type;
begin
select Username into user
FROM USER_USERS;
insert into emp_log
values(sysdate, user, :new.emp_cod);
end trg_log_emprestimo;
/
update emprestimo set emp_data_emprestimo=sysdate where emp_cod=1;
select * from emp_log;
| 22.776119 | 80 | 0.783748 |
a9d2c5bf85625de6eb7f95916376a8ecce7af7dd | 695 | sql | SQL | Ch08/ex08-10.sql | NoMan2000/sql_func_and_procs | 18673c4b914b92b7d0d790b4758038bb5110421f | [
"MIT"
] | null | null | null | Ch08/ex08-10.sql | NoMan2000/sql_func_and_procs | 18673c4b914b92b7d0d790b4758038bb5110421f | [
"MIT"
] | null | null | null | Ch08/ex08-10.sql | NoMan2000/sql_func_and_procs | 18673c4b914b92b7d0d790b4758038bb5110421f | [
"MIT"
] | null | null | null | CREATE PROCEDURE tfer_funds4
(from_account int, to_account int,tfer_amount numeric(10,2),
OUT status int, OUT message VARCHAR(30))
BEGIN
DECLARE from_account_balance NUMERIC(10,2);
SELECT balance
INTO from_account_balance
FROM account_balance
WHERE account_id=from_account;
IF from_account_balance >= tfer_amount THEN
START TRANSACTION;
UPDATE account_balance
SET balance=balance-tfer_amount
WHERE account_id=from_account;
UPDATE account_balance
SET balance=balance+tfer_amount
WHERE account_id=to_account;
COMMIT;
SET status=0;
SET message='OK';
ELSE
SET status=-1;
SET message='Insufficient funds';
END IF;
END;
| 21.71875 | 67 | 0.735252 |
49e9e593c8c36daa15cedb1fa18b87ba6aea86ff | 875 | sql | SQL | src/StoreLake.Test/SQL/Tables/hlspinstance.sql | benhauman/storelake | 216581c7236f0c9d5285e89d04a0be24e2c72a69 | [
"MIT"
] | 1 | 2021-06-18T19:58:44.000Z | 2021-06-18T19:58:44.000Z | src/StoreLake.Test/SQL/Tables/hlspinstance.sql | benhauman/storelake | 216581c7236f0c9d5285e89d04a0be24e2c72a69 | [
"MIT"
] | null | null | null | src/StoreLake.Test/SQL/Tables/hlspinstance.sql | benhauman/storelake | 216581c7236f0c9d5285e89d04a0be24e2c72a69 | [
"MIT"
] | null | null | null | CREATE TABLE [dbo].[hlspinstance]
(
[spinstanceid] INT NOT NULL IDENTITY(1,1),
[processinstanceid] UNIQUEIDENTIFIER NOT NULL,
[spdefinitionid] INT NOT NULL,
[creationtime] DATETIME NOT NULL
CONSTRAINT DF_hlspinstance_creationtime DEFAULT(GETUTCDATE())
,
[lastmodified] DATETIME NOT NULL
CONSTRAINT DF_hlspinstance_lastmodified DEFAULT(GETUTCDATE())
,
[version] INT NOT NULL
CONSTRAINT CK_hlspinstance_version CHECK ([version] > 0)
CONSTRAINT DF_hlspinstance_version DEFAULT(1)
,
CONSTRAINT [PK_hlspinstance] PRIMARY KEY ([spinstanceid] ASC),
CONSTRAINT [FK_hlspinstance_spdefinitionid] FOREIGN KEY ([spdefinitionid]) REFERENCES [dbo].[hlspdefinition] ([spdefinitionid]),
CONSTRAINT [UQ_hlspinstance_spiddefid] UNIQUE NONCLUSTERED ([spinstanceid], [spdefinitionid]),
CONSTRAINT [UQ_hlspinstance_procinstid] UNIQUE NONCLUSTERED ([processinstanceid])
)
| 41.666667 | 129 | 0.794286 |
5a6641c70bc244949ad3cb064ba47037781a1f9d | 349,937 | html | HTML | work/lua-5.4/doc/manual.html | RussellHaley/PUC-Lua-VS2017 | b6287727f0d4db4347b6ab4e8dce7040f971fea0 | [
"OpenSSL",
"MIT"
] | 45 | 2020-01-30T16:22:43.000Z | 2022-03-30T23:17:45.000Z | PrivateBuild/src/lua-5.4.0-beta/doc/manual.html | xun-yxkf/LuaBuilds | 906011b97850d0fd9129c7ecd9360d97eb322f79 | [
"MIT"
] | 14 | 2020-02-21T06:18:32.000Z | 2020-12-24T05:52:10.000Z | PrivateBuild/src/lua-5.4.0-beta/doc/manual.html | xun-yxkf/LuaBuilds | 906011b97850d0fd9129c7ecd9360d97eb322f79 | [
"MIT"
] | 3 | 2021-08-02T02:47:01.000Z | 2021-09-30T14:26:39.000Z | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Lua 5.4 Reference Manual</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
<LINK REL="stylesheet" TYPE="text/css" HREF="manual.css">
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>
<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A>
Lua 5.4 Reference Manual
</H1>
<P>
by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
<P>
<SMALL>
Copyright © 2019 Lua.org, PUC-Rio.
Freely available under the terms of the
<a href="http://www.lua.org/license.html">Lua license</a>.
</SMALL>
<DIV CLASS="menubar">
<A HREF="contents.html#contents">contents</A>
·
<A HREF="contents.html#index">index</A>
·
<A HREF="http://www.lua.org/manual/">other versions</A>
</DIV>
<!-- ====================================================================== -->
<p>
<!-- $Id: manual.of $ -->
<h1>1 – <a name="1">Introduction</a></h1>
<p>
Lua is a powerful, efficient, lightweight, embeddable scripting language.
It supports procedural programming,
object-oriented programming, functional programming,
data-driven programming, and data description.
<p>
Lua combines simple procedural syntax with powerful data description
constructs based on associative arrays and extensible semantics.
Lua is dynamically typed,
runs by interpreting bytecode with a register-based
virtual machine,
and has automatic memory management with
a generational garbage collection,
making it ideal for configuration, scripting,
and rapid prototyping.
<p>
Lua is implemented as a library, written in <em>clean C</em>,
the common subset of Standard C and C++.
The Lua distribution includes a host program called <code>lua</code>,
which uses the Lua library to offer a complete,
standalone Lua interpreter,
for interactive or batch use.
Lua is intended to be used both as a powerful, lightweight,
embeddable scripting language for any program that needs one,
and as a powerful but lightweight and efficient stand-alone language.
<p>
As an extension language, Lua has no notion of a "main" program:
it works <em>embedded</em> in a host client,
called the <em>embedding program</em> or simply the <em>host</em>.
(Frequently, this host is the stand-alone <code>lua</code> program.)
The host program can invoke functions to execute a piece of Lua code,
can write and read Lua variables,
and can register C functions to be called by Lua code.
Through the use of C functions, Lua can be augmented to cope with
a wide range of different domains,
thus creating customized programming languages sharing a syntactical framework.
<p>
Lua is free software,
and is provided as usual with no guarantees,
as stated in its license.
The implementation described in this manual is available
at Lua's official web site, <code>www.lua.org</code>.
<p>
Like any other reference manual,
this document is dry in places.
For a discussion of the decisions behind the design of Lua,
see the technical papers available at Lua's web site.
For a detailed introduction to programming in Lua,
see Roberto's book, <em>Programming in Lua</em>.
<h1>2 – <a name="2">Basic Concepts</a></h1>
<p>
This section describes the basic concepts of the language.
<h2>2.1 – <a name="2.1">Values and Types</a></h2>
<p>
Lua is a dynamically typed language.
This means that
variables do not have types; only values do.
There are no type definitions in the language.
All values carry their own type.
<p>
All values in Lua are first-class values.
This means that all values can be stored in variables,
passed as arguments to other functions, and returned as results.
<p>
There are eight basic types in Lua:
<em>nil</em>, <em>boolean</em>, <em>number</em>,
<em>string</em>, <em>function</em>, <em>userdata</em>,
<em>thread</em>, and <em>table</em>.
The type <em>nil</em> has one single value, <b>nil</b>,
whose main property is to be different from any other value;
it often represents the absence of a useful value.
The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>.
Both <b>nil</b> and <b>false</b> make a condition false;
any other value makes it true.
<p>
The type <em>number</em> represents both
integer numbers and real (floating-point) numbers,
using two subtypes: <em>integer</em> and <em>float</em>.
Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
but you can also compile Lua so that it
uses 32-bit integers and/or single-precision (32-bit) floats.
The option with 32 bits for both integers and floats
is particularly attractive
for small machines and embedded systems.
(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
<p>
Lua has explicit rules about when each subtype is used,
but it also converts between them automatically as needed (see <a href="#3.4.3">§3.4.3</a>).
Therefore,
the programmer may choose to mostly ignore the difference
between integers and floats
or to assume complete control over the representation of each number.
<p>
The type <em>string</em> represents immutable sequences of bytes.
Lua is 8-bit clean:
strings can contain any 8-bit value,
including embedded zeros ('<code>\0</code>').
Lua is also encoding-agnostic;
it makes no assumptions about the contents of a string.
The length of any string in Lua must fit in a Lua integer.
<p>
Lua can call (and manipulate) functions written in Lua and
functions written in C (see <a href="#3.4.10">§3.4.10</a>).
Both are represented by the type <em>function</em>.
<p>
The type <em>userdata</em> is provided to allow arbitrary C data to
be stored in Lua variables.
A userdata value represents a block of raw memory.
There are two kinds of userdata:
<em>full userdata</em>,
which is an object with a block of memory managed by Lua,
and <em>light userdata</em>,
which is simply a C pointer value.
Userdata has no predefined operations in Lua,
except assignment and identity test.
By using <em>metatables</em>,
the programmer can define operations for full userdata values
(see <a href="#2.4">§2.4</a>).
Userdata values cannot be created or modified in Lua,
only through the C API.
This guarantees the integrity of data owned by
the host program and C libraries.
<p>
The type <em>thread</em> represents independent threads of execution
and it is used to implement coroutines (see <a href="#2.6">§2.6</a>).
Lua threads are not related to operating-system threads.
Lua supports coroutines on all systems,
even those that do not support threads natively.
<p>
The type <em>table</em> implements associative arrays,
that is, arrays that can have as indices not only numbers,
but any Lua value except <b>nil</b> and NaN.
(<em>Not a Number</em> is a special floating-point value
used by the IEEE 754 standard to represent
undefined numerical results, such as <code>0/0</code>.)
Tables can be <em>heterogeneous</em>;
that is, they can contain values of all types (except <b>nil</b>).
Any key associated to the value <b>nil</b> is not considered part of the table.
Conversely, any key that is not part of a table has
an associated value <b>nil</b>.
<p>
Tables are the sole data-structuring mechanism in Lua;
they can be used to represent ordinary arrays, lists,
symbol tables, sets, records, graphs, trees, etc.
To represent records, Lua uses the field name as an index.
The language supports this representation by
providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
There are several convenient ways to create tables in Lua
(see <a href="#3.4.9">§3.4.9</a>).
<p>
Like indices,
the values of table fields can be of any type.
In particular,
because functions are first-class values,
table fields can contain functions.
Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">§3.4.11</a>).
<p>
The indexing of tables follows
the definition of raw equality in the language.
The expressions <code>a[i]</code> and <code>a[j]</code>
denote the same table element
if and only if <code>i</code> and <code>j</code> are raw equal
(that is, equal without metamethods).
In particular, floats with integral values
are equal to their respective integers
(e.g., <code>1.0 == 1</code>).
To avoid ambiguities,
any float used as a key that is equal to an integer
is converted to that integer.
For instance, if you write <code>a[2.0] = true</code>,
the actual key inserted into the table will be the integer <code>2</code>.
<p>
Tables, functions, threads, and (full) userdata values are <em>objects</em>:
variables do not actually <em>contain</em> these values,
only <em>references</em> to them.
Assignment, parameter passing, and function returns
always manipulate references to such values;
these operations do not imply any kind of copy.
<p>
The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
of a given value (see <a href="#pdf-type"><code>type</code></a>).
<h2>2.2 – <a name="2.2">Environments and the Global Environment</a></h2>
<p>
As we will discuss further in <a href="#3.2">§3.2</a> and <a href="#3.3.3">§3.3.3</a>,
any reference to a free name
(that is, a name not bound to any declaration) <code>var</code>
is syntactically translated to <code>_ENV.var</code>.
Moreover, every chunk is compiled in the scope of
an external local variable named <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>),
so <code>_ENV</code> itself is never a free name in a chunk.
<p>
Despite the existence of this external <code>_ENV</code> variable and
the translation of free names,
<code>_ENV</code> is a completely regular name.
In particular,
you can define new variables and parameters with that name.
Each reference to a free name uses the <code>_ENV</code> that is
visible at that point in the program,
following the usual visibility rules of Lua (see <a href="#3.5">§3.5</a>).
<p>
Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
<p>
Lua keeps a distinguished environment called the <em>global environment</em>.
This value is kept at a special index in the C registry (see <a href="#4.5">§4.5</a>).
In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
(<a href="#pdf-_G"><code>_G</code></a> is never used internally,
so changing its value will affect only your own code.)
<p>
When Lua loads a chunk,
the default value for its <code>_ENV</code> variable
is the global environment (see <a href="#pdf-load"><code>load</code></a>).
Therefore, by default,
free names in Lua code refer to entries in the global environment
and, therefore, they are also called <em>global variables</em>.
Moreover, all standard libraries are loaded in the global environment
and some functions there operate on that environment.
You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
to load a chunk with a different environment.
(In C, you have to load the chunk and then change the value
of its first upvalue; see <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.)
<h2>2.3 – <a name="2.3">Error Handling</a></h2>
<p>
Because Lua is an embedded extension language,
all Lua actions start from C code in the host program
calling a function from the Lua library.
(When you use Lua standalone,
the <code>lua</code> application is the host program.)
Whenever an error occurs during
the compilation or execution of a Lua chunk,
control returns to the host,
which can take appropriate measures
(such as printing an error message).
<p>
Lua code can explicitly generate an error by calling the
<a href="#pdf-error"><code>error</code></a> function.
If you need to catch errors in Lua,
you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
to call a given function in <em>protected mode</em>.
<p>
Whenever there is an error,
an <em>error object</em> (also called an <em>error message</em>)
is propagated with information about the error.
Lua itself only generates errors whose error object is a string,
but programs may generate errors with
any value as the error object.
It is up to the Lua program or its host to handle such error objects.
<p>
When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
you may give a <em>message handler</em>
to be called in case of errors.
This function is called with the original error object
and returns a new error object.
It is called before the error unwinds the stack,
so that it can gather more information about the error,
for instance by inspecting the stack and creating a stack traceback.
This message handler is still protected by the protected call;
so, an error inside the message handler
will call the message handler again.
If this loop goes on for too long,
Lua breaks it and returns an appropriate message.
(The message handler is called only for regular runtime errors.
It is not called for memory-allocation errors
nor for errors while running finalizers.)
<p>
Lua also offers a system of <em>warnings</em> (see <a href="#pdf-warn"><code>warn</code></a>).
Unlike errors, warnings do not interfere
in any way with program execution.
They typically only generate a message to the user,
although this behavior can be adapted from C (see <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>).
<h2>2.4 – <a name="2.4">Metatables and Metamethods</a></h2>
<p>
Every value in Lua can have a <em>metatable</em>.
This <em>metatable</em> is an ordinary Lua table
that defines the behavior of the original value
under certain events.
You can change several aspects of the behavior
of a value by setting specific fields in its metatable.
For instance, when a non-numeric value is the operand of an addition,
Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
If it finds one,
Lua calls this function to perform the addition.
<p>
The key for each event in a metatable is a string
with the event name prefixed by two underscores;
the corresponding values are called <em>metamethods</em>.
In the previous example, the key is the string "<code>__add</code>"
and the metamethod is the function that performs the addition.
Unless stated otherwise,
metamethods should be function values.
<p>
You can query the metatable of any value
using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>).
<p>
You can replace the metatable of tables
using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
You cannot change the metatable of other types from Lua code,
except by using the debug library (<a href="#6.10">§6.10</a>).
<p>
Tables and full userdata have individual metatables,
although multiple tables and userdata can share their metatables.
Values of all other types share one single metatable per type;
that is, there is one single metatable for all numbers,
one for all strings, etc.
By default, a value has no metatable,
but the string library sets a metatable for the string type (see <a href="#6.4">§6.4</a>).
<p>
A detailed list of operations controlled by metatables is given next.
Each event is identified by its corresponding key.
By convention, all metatable keys used by Lua are composed by
two underscores followed by lowercase Latin letters.
<ul>
<li><b><code>__add</code>: </b>
the addition (<code>+</code>) operation.
If any operand for an addition is not a number,
Lua will try to call a metamethod.
It starts by checking the first operand (even if it is a number);
if that operand does not define a metamethod for <code>__add</code>,
then Lua will check the second operand.
If Lua can find a metamethod,
it calls the metamethod with the two operands as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
Otherwise, if no metamethod is found,
Lua raises an error.
</li>
<li><b><code>__sub</code>: </b>
the subtraction (<code>-</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__mul</code>: </b>
the multiplication (<code>*</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__div</code>: </b>
the division (<code>/</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__mod</code>: </b>
the modulo (<code>%</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__pow</code>: </b>
the exponentiation (<code>^</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__unm</code>: </b>
the negation (unary <code>-</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__idiv</code>: </b>
the floor division (<code>//</code>) operation.
Behavior similar to the addition operation.
</li>
<li><b><code>__band</code>: </b>
the bitwise AND (<code>&</code>) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod
if any operand is neither an integer
nor a float coercible to an integer (see <a href="#3.4.3">§3.4.3</a>).
</li>
<li><b><code>__bor</code>: </b>
the bitwise OR (<code>|</code>) operation.
Behavior similar to the bitwise AND operation.
</li>
<li><b><code>__bxor</code>: </b>
the bitwise exclusive OR (binary <code>~</code>) operation.
Behavior similar to the bitwise AND operation.
</li>
<li><b><code>__bnot</code>: </b>
the bitwise NOT (unary <code>~</code>) operation.
Behavior similar to the bitwise AND operation.
</li>
<li><b><code>__shl</code>: </b>
the bitwise left shift (<code><<</code>) operation.
Behavior similar to the bitwise AND operation.
</li>
<li><b><code>__shr</code>: </b>
the bitwise right shift (<code>>></code>) operation.
Behavior similar to the bitwise AND operation.
</li>
<li><b><code>__concat</code>: </b>
the concatenation (<code>..</code>) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod
if any operand is neither a string nor a number
(which is always coercible to a string).
</li>
<li><b><code>__len</code>: </b>
the length (<code>#</code>) operation.
If the object is not a string,
Lua will try its metamethod.
If there is a metamethod,
Lua calls it with the object as argument,
and the result of the call
(always adjusted to one value)
is the result of the operation.
If there is no metamethod but the object is a table,
then Lua uses the table length operation (see <a href="#3.4.7">§3.4.7</a>).
Otherwise, Lua raises an error.
</li>
<li><b><code>__eq</code>: </b>
the equal (<code>==</code>) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod only when the values
being compared are either both tables or both full userdata
and they are not primitively equal.
The result of the call is always converted to a boolean.
</li>
<li><b><code>__lt</code>: </b>
the less than (<code><</code>) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod only when the values
being compared are neither both numbers nor both strings.
Moreover, the result of the call is always converted to a boolean.
</li>
<li><b><code>__le</code>: </b>
the less equal (<code><=</code>) operation.
Behavior similar to the less than operation.
</li>
<li><b><code>__index</code>: </b>
The indexing access operation <code>table[key]</code>.
This event happens when <code>table</code> is not a table or
when <code>key</code> is not present in <code>table</code>.
The metamethod is looked up in <code>table</code>.
<p>
Despite the name,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with <code>table</code> and <code>key</code> as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
If it is a table,
the final result is the result of indexing this table with <code>key</code>.
This indexing is regular, not raw,
and therefore can trigger another metamethod.
</li>
<li><b><code>__newindex</code>: </b>
The indexing assignment <code>table[key] = value</code>.
Like the index event,
this event happens when <code>table</code> is not a table or
when <code>key</code> is not present in <code>table</code>.
The metamethod is looked up in <code>table</code>.
<p>
Like with indexing,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
If it is a table,
Lua does an indexing assignment to this table with the same key and value.
This assignment is regular, not raw,
and therefore can trigger another metamethod.
<p>
Whenever there is a <code>__newindex</code> metamethod,
Lua does not perform the primitive assignment.
If needed,
the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
to do the assignment.
</li>
<li><b><code>__call</code>: </b>
The call operation <code>func(args)</code>.
This event happens when Lua tries to call a non-function value
(that is, <code>func</code> is not a function).
The metamethod is looked up in <code>func</code>.
If present,
the metamethod is called with <code>func</code> as its first argument,
followed by the arguments of the original call (<code>args</code>).
All results of the call
are the results of the operation.
This is the only metamethod that allows multiple results.
</li>
</ul>
<p>
In addition to the previous list,
the interpreter also respects the following keys in metatables:
<code>__gc</code> (see <a href="#2.5.3">§2.5.3</a>),
<code>__close</code> (see <a href="#3.3.8">§3.3.8</a>),
<code>__mode</code> (see <a href="#2.5.4">§2.5.4</a>),
and <code>__name</code>.
(The entry <code>__name</code>,
when it contains a string,
is used by some error-reporting functions to build error messages.)
<p>
For the unary operators (negation, length, and bitwise NOT),
the metamethod is computed and called with a dummy second operand,
equal to the first one.
This extra operand is only to simplify Lua's internals
(by making these operators behave like a binary operation)
and may be removed in future versions.
For most uses this extra operand is irrelevant.
<p>
Because metatables are regular tables,
they can contain arbitrary fields,
not only the event names defined above.
Some functions in the standard library
(e.g., <a href="#pdf-tostring"><code>tostring</code></a>)
use other fields in metatables for their own purposes.
<p>
It is a good practice to add all needed metamethods to a table
before setting it as a metatable of some object.
In particular, the <code>__gc</code> metamethod works only when this order
is followed (see <a href="#2.5.3">§2.5.3</a>).
It is also a good practice to set the metatable of an object
right after its creation.
<h2>2.5 – <a name="2.5">Garbage Collection</a></h2>
<p>
Lua performs automatic memory management.
This means that
you do not have to worry about allocating memory for new objects
or freeing it when the objects are no longer needed.
Lua manages memory automatically by running
a <em>garbage collector</em> to collect all <em>dead objects</em>
(that is, objects that are no longer accessible from Lua).
All memory used by Lua is subject to automatic management:
strings, tables, userdata, functions, threads, internal structures, etc.
<p>
The garbage collector (GC) in Lua can work in two modes:
incremental and generational.
<p>
The default GC mode with the default parameters
are adequate for most uses.
However, programs that waste a large proportion of their time
allocating and freeing memory can benefit from other settings.
Keep in mind that the GC behavior is non-portable
both across platforms and across different Lua releases;
therefore, optimal settings are also non-portable.
<p>
You can change the GC mode and parameters by calling
<a href="#lua_gc"><code>lua_gc</code></a> in C
or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
You can also use these functions to control
the collector directly (e.g., to stop and restart it).
<h3>2.5.1 – <a name="2.5.1">Incremental Garbage Collection</a></h3>
<p>
In incremental mode,
each GC cycle performs a mark-and-sweep collection in small steps
interleaved with the program's execution.
In this mode,
the collector uses three numbers to control its garbage-collection cycles:
the <em>garbage-collector pause</em>,
the <em>garbage-collector step multiplier</em>,
and the <em>garbage-collector step size</em>.
<p>
The garbage-collector pause
controls how long the collector waits before starting a new cycle.
The collector starts a new cycle when the use of memory
hits <em>n%</em> of the use after the previous collection.
Larger values make the collector less aggressive.
Values equal to or less than 100 mean the collector will not wait to
start a new cycle.
A value of 200 means that the collector waits for the total memory in use
to double before starting a new cycle.
The default value is 200; the maximum value is 1000.
<p>
The garbage-collector step multiplier
controls the speed of the collector relative to
memory allocation,
that is,
how many elements it marks or sweeps for each
kilobyte of memory allocated.
Larger values make the collector more aggressive but also increase
the size of each incremental step.
You should not use values less than 100,
because they make the collector too slow and
can result in the collector never finishing a cycle.
The default value is 100; the maximum value is 1000.
<p>
The garbage-collector step size controls the
size of each incremental step,
specifically how many bytes the interpreter allocates
before performing a step.
This parameter is logarithmic:
A value of <em>n</em> means the interpreter will allocate <em>2<sup>n</sup></em>
bytes between steps and perform equivalent work during the step.
A large value (e.g., 60) makes the collector a stop-the-world
(non-incremental) collector.
The default value is 13,
which means steps of approximately 8 Kbytes.
<h3>2.5.2 – <a name="2.5.2">Generational Garbage Collection</a></h3>
<p>
In generational mode,
the collector does frequent <em>minor</em> collections,
which traverses only objects recently created.
If after a minor collection the use of memory is still above a limit,
the collector does a <em>major</em> collection,
which traverses all objects.
The generational mode uses two parameters:
the <em>minor multiplier</em> and the <em>the major multiplier</em>.
<p>
The minor multiplier controls the frequency of minor collections.
For a minor multiplier <em>x</em>,
a new minor collection will be done when memory
grows <em>x%</em> larger than the memory in use after the previous major
collection.
For instance, for a multiplier of 20,
the collector will do a minor collection when the use of memory
gets 20% larger than the use after the previous major collection.
The default value is 20; the maximum value is 200.
<p>
The major multiplier controls the frequency of major collections.
For a major multiplier <em>x</em>,
a new major collection will be done when memory
grows <em>x%</em> larger than the memory in use after the previous major
collection.
For instance, for a multiplier of 100,
the collector will do a major collection when the use of memory
gets larger than twice the use after the previous collection.
The default value is 100; the maximum value is 1000.
<h3>2.5.3 – <a name="2.5.3">Garbage-Collection Metamethods</a></h3>
<p>
You can set garbage-collector metamethods for tables
and, using the C API,
for full userdata (see <a href="#2.4">§2.4</a>).
These metamethods, called <em>finalizers</em>,
are called when the garbage collector detects that the
corresponding table or userdata is unreachable.
Finalizers allow you to coordinate Lua's garbage collection
with external resource management such as closing files,
network or database connections,
or freeing your own memory.
<p>
For an object (table or userdata) to be finalized when collected,
you must <em>mark</em> it for finalization.
You mark an object for finalization when you set its metatable
and the metatable has a field indexed by the string "<code>__gc</code>".
Note that if you set a metatable without a <code>__gc</code> field
and later create that field in the metatable,
the object will not be marked for finalization.
<p>
When a marked object becomes unreachable,
it is not collected immediately by the garbage collector.
Instead, Lua puts it in a list.
After the collection,
Lua goes through that list.
For each object in the list,
it checks the object's <code>__gc</code> metamethod:
If it is present,
Lua calls it with the object as its single argument.
<p>
At the end of each garbage-collection cycle,
the finalizers are called in
the reverse order that the objects were marked for finalization,
among those collected in that cycle;
that is, the first finalizer to be called is the one associated
with the object marked last in the program.
The execution of each finalizer may occur at any point during
the execution of the regular code.
<p>
Because the object being collected must still be used by the finalizer,
that object (and other objects accessible only through it)
must be <em>resurrected</em> by Lua.
Usually, this resurrection is transient,
and the object memory is freed in the next garbage-collection cycle.
However, if the finalizer stores the object in some global place
(e.g., a global variable),
then the resurrection is permanent.
Moreover, if the finalizer marks a finalizing object for finalization again,
its finalizer will be called again in the next cycle where the
object is unreachable.
In any case,
the object memory is freed only in a GC cycle where
the object is unreachable and not marked for finalization.
<p>
When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
Lua calls the finalizers of all objects marked for finalization,
following the reverse order that they were marked.
If any finalizer marks objects for collection during that phase,
these marks have no effect.
<p>
Finalizers cannot yield.
Except for that, they can do anything,
such as raise errors, create new objects,
or even run the garbage collector.
However, because they can run in unpredictable times,
it is good practice to restrict each finalizer
to the minimum necessary to properly release
its associated resource.
<p>
Any error while running a finalizer generates a warning;
the error is not propagated.
<h3>2.5.4 – <a name="2.5.4">Weak Tables</a></h3>
<p>
A <em>weak table</em> is a table whose elements are
<em>weak references</em>.
A weak reference is ignored by the garbage collector.
In other words,
if the only references to an object are weak references,
then the garbage collector will collect that object.
<p>
A weak table can have weak keys, weak values, or both.
A table with weak values allows the collection of its values,
but prevents the collection of its keys.
A table with both weak keys and weak values allows the collection of
both keys and values.
In any case, if either the key or the value is collected,
the whole pair is removed from the table.
The weakness of a table is controlled by the
<code>__mode</code> field of its metatable.
This field, if present, must be one of the following strings:
"<code>k</code>", for a table with weak keys;
"<code>v</code>", for a table with weak values;
or "<code>kv</code>", for a table with both weak keys and values.
<p>
A table with weak keys and strong values
is also called an <em>ephemeron table</em>.
In an ephemeron table,
a value is considered reachable only if its key is reachable.
In particular,
if the only reference to a key comes through its value,
the pair is removed.
<p>
Any change in the weakness of a table may take effect only
at the next collect cycle.
In particular, if you change the weakness to a stronger mode,
Lua may still collect some items from that table
before the change takes effect.
<p>
Only objects that have an explicit construction
are removed from weak tables.
Values, such as numbers and light C functions,
are not subject to garbage collection,
and therefore are not removed from weak tables
(unless their associated values are collected).
Although strings are subject to garbage collection,
they do not have an explicit construction and
their equality is by value;
they behave more like values than like objects.
Therefore, they are not removed from weak tables.
<p>
Resurrected objects
(that is, objects being finalized
and objects accessible only through objects being finalized)
have a special behavior in weak tables.
They are removed from weak values before running their finalizers,
but are removed from weak keys only in the next collection
after running their finalizers, when such objects are actually freed.
This behavior allows the finalizer to access properties
associated with the object through weak tables.
<p>
If a weak table is among the resurrected objects in a collection cycle,
it may not be properly cleared until the next cycle.
<h2>2.6 – <a name="2.6">Coroutines</a></h2>
<p>
Lua supports coroutines,
also called <em>collaborative multithreading</em>.
A coroutine in Lua represents an independent thread of execution.
Unlike threads in multithread systems, however,
a coroutine only suspends its execution by explicitly calling
a yield function.
<p>
You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
Its sole argument is a function
that is the main function of the coroutine.
The <code>create</code> function only creates a new coroutine and
returns a handle to it (an object of type <em>thread</em>);
it does not start the coroutine.
<p>
You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
passing as its first argument
a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
the coroutine starts its execution by
calling its main function.
Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
as arguments to that function.
After the coroutine starts running,
it runs until it terminates or <em>yields</em>.
<p>
A coroutine can terminate its execution in two ways:
normally, when its main function returns
(explicitly or implicitly, after the last instruction);
and abnormally, if there is an unprotected error.
In case of normal termination,
<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
plus any values returned by the coroutine main function.
In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
plus the error object.
In this case, the coroutine does not unwind its stack,
so that it is possible to inspect it after the error
with the debug API.
<p>
A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
When a coroutine yields,
the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
even if the yield happens inside nested function calls
(that is, not in the main function,
but in a function directly or indirectly called by the main function).
In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
The next time you resume the same coroutine,
it continues its execution from the point where it yielded,
with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
<p>
Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
but instead of returning the coroutine itself,
it returns a function that, when called, resumes the coroutine.
Any arguments passed to this function
go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
except the first one (the boolean error code).
Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
the function created by <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>
propagates any error to the caller.
In this case,
the function also closes the coroutine (see <a href="#pdf-coroutine.close"><code>coroutine.close</code></a>).
<p>
As an example of how coroutines work,
consider the following code:
<pre>
function foo (a)
print("foo", a)
return coroutine.yield(2*a)
end
co = coroutine.create(function (a,b)
print("co-body", a, b)
local r = foo(a+1)
print("co-body", r)
local r, s = coroutine.yield(a+b, a-b)
print("co-body", r, s)
return b, "end"
end)
print("main", coroutine.resume(co, 1, 10))
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))
</pre><p>
When you run it, it produces the following output:
<pre>
co-body 1 10
foo 2
main true 4
co-body r
main true 11 -9
co-body x y
main true 10 end
main false cannot resume dead coroutine
</pre>
<p>
You can also create and manipulate coroutines through the C API:
see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
and <a href="#lua_yield"><code>lua_yield</code></a>.
<h1>3 – <a name="3">The Language</a></h1>
<p>
This section describes the lexis, the syntax, and the semantics of Lua.
In other words,
this section describes
which tokens are valid,
how they can be combined,
and what their combinations mean.
<p>
Language constructs will be explained using the usual extended BNF notation,
in which
{<em>a</em>} means 0 or more <em>a</em>'s, and
[<em>a</em>] means an optional <em>a</em>.
Non-terminals are shown like non-terminal,
keywords are shown like <b>kword</b>,
and other terminal symbols are shown like ‘<b>=</b>’.
The complete syntax of Lua can be found in <a href="#9">§9</a>
at the end of this manual.
<h2>3.1 – <a name="3.1">Lexical Conventions</a></h2>
<p>
Lua is a free-form language.
It ignores spaces and comments between lexical elements (tokens),
except as delimiters between two tokens.
In source code,
Lua recognizes as spaces the standard ASCII white-space
characters space, form feed, newline,
carriage return, horizontal tab, and vertical tab.
<p>
<em>Names</em>
(also called <em>identifiers</em>)
in Lua can be any string of Latin letters,
Arabic-Indic digits, and underscores,
not beginning with a digit and
not being a reserved word.
Identifiers are used to name variables, table fields, and labels.
<p>
The following <em>keywords</em> are reserved
and cannot be used as names:
<pre>
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while
</pre>
<p>
Lua is a case-sensitive language:
<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
are two different, valid names.
As a convention,
programs should avoid creating
names that start with an underscore followed by
one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
<p>
The following strings denote other tokens:
<pre>
+ - * / % ^ #
& ~ | << >> //
== ~= <= >= < > =
( ) { } [ ] ::
; : , . .. ...
</pre>
<p>
A <em>short literal string</em>
can be delimited by matching single or double quotes,
and can contain the following C-like escape sequences:
'<code>\a</code>' (bell),
'<code>\b</code>' (backspace),
'<code>\f</code>' (form feed),
'<code>\n</code>' (newline),
'<code>\r</code>' (carriage return),
'<code>\t</code>' (horizontal tab),
'<code>\v</code>' (vertical tab),
'<code>\\</code>' (backslash),
'<code>\"</code>' (quotation mark [double quote]),
and '<code>\'</code>' (apostrophe [single quote]).
A backslash followed by a line break
results in a newline in the string.
The escape sequence '<code>\z</code>' skips the following span
of white-space characters,
including line breaks;
it is particularly useful to break and indent a long literal string
into multiple lines without adding the newlines and spaces
into the string contents.
A short literal string cannot contain unescaped line breaks
nor escapes not forming a valid escape sequence.
<p>
We can specify any byte in a short literal string,
including embedded zeros,
by its numeric value.
This can be done
with the escape sequence <code>\x<em>XX</em></code>,
where <em>XX</em> is a sequence of exactly two hexadecimal digits,
or with the escape sequence <code>\<em>ddd</em></code>,
where <em>ddd</em> is a sequence of up to three decimal digits.
(Note that if a decimal escape sequence is to be followed by a digit,
it must be expressed using exactly three digits.)
<p>
The UTF-8 encoding of a Unicode character
can be inserted in a literal string with
the escape sequence <code>\u{<em>XXX</em>}</code>
(with mandatory enclosing braces),
where <em>XXX</em> is a sequence of one or more hexadecimal digits
representing the character code point.
This code point can be any value less than <em>2<sup>31</sup></em>.
(Lua uses the original UTF-8 specification here,
which is not restricted to valid Unicode code points.)
<p>
Literal strings can also be defined using a long format
enclosed by <em>long brackets</em>.
We define an <em>opening long bracket of level <em>n</em></em> as an opening
square bracket followed by <em>n</em> equal signs followed by another
opening square bracket.
So, an opening long bracket of level 0 is written as <code>[[</code>,
an opening long bracket of level 1 is written as <code>[=[</code>,
and so on.
A <em>closing long bracket</em> is defined similarly;
for instance,
a closing long bracket of level 4 is written as <code>]====]</code>.
A <em>long literal</em> starts with an opening long bracket of any level and
ends at the first closing long bracket of the same level.
It can contain any text except a closing bracket of the same level.
Literals in this bracketed form can run for several lines,
do not interpret any escape sequences,
and ignore long brackets of any other level.
Any kind of end-of-line sequence
(carriage return, newline, carriage return followed by newline,
or newline followed by carriage return)
is converted to a simple newline.
When the opening long bracket is immediately followed by a newline,
the newline is not included in the string.
<p>
As an example, in a system using ASCII
(in which '<code>a</code>' is coded as 97,
newline is coded as 10, and '<code>1</code>' is coded as 49),
the five literal strings below denote the same string:
<pre>
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
</pre>
<p>
Any byte in a literal string not
explicitly affected by the previous rules represents itself.
However, Lua opens files for parsing in text mode,
and the system's file functions may have problems with
some control characters.
So, it is safer to represent
binary data as a quoted literal with
explicit escape sequences for the non-text characters.
<p>
A <em>numeric constant</em> (or <em>numeral</em>)
can be written with an optional fractional part
and an optional decimal exponent,
marked by a letter '<code>e</code>' or '<code>E</code>'.
Lua also accepts hexadecimal constants,
which start with <code>0x</code> or <code>0X</code>.
Hexadecimal constants also accept an optional fractional part
plus an optional binary exponent,
marked by a letter '<code>p</code>' or '<code>P</code>'.
<p>
A numeric constant with a radix point or an exponent
denotes a float;
otherwise,
if its value fits in an integer or it is a hexadecimal constant,
it denotes an integer;
otherwise (that is, a decimal integer numeral that overflows),
it denotes a float.
(Hexadecimal integer numerals that overflow <em>wrap around</em>;
they always denote an integer value.)
Examples of valid integer constants are
<pre>
3 345 0xff 0xBEBADA
</pre><p>
Examples of valid float constants are
<pre>
3.0 3.1416 314.16e-2 0.31416E1 34e1
0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
</pre>
<p>
A <em>comment</em> starts with a double hyphen (<code>--</code>)
anywhere outside a string.
If the text immediately after <code>--</code> is not an opening long bracket,
the comment is a <em>short comment</em>,
which runs until the end of the line.
Otherwise, it is a <em>long comment</em>,
which runs until the corresponding closing long bracket.
<h2>3.2 – <a name="3.2">Variables</a></h2>
<p>
Variables are places that store values.
There are three kinds of variables in Lua:
global variables, local variables, and table fields.
<p>
A single name can denote a global variable or a local variable
(or a function's formal parameter,
which is a particular kind of local variable):
<pre>
var ::= Name
</pre><p>
Name denotes identifiers (see <a href="#3.1">§3.1</a>).
<p>
Any variable name is assumed to be global unless explicitly declared
as a local (see <a href="#3.3.7">§3.3.7</a>).
Local variables are <em>lexically scoped</em>:
local variables can be freely accessed by functions
defined inside their scope (see <a href="#3.5">§3.5</a>).
<p>
Before the first assignment to a variable, its value is <b>nil</b>.
<p>
Square brackets are used to index a table:
<pre>
var ::= prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’
</pre><p>
The meaning of accesses to table fields can be changed via metatables
(see <a href="#2.4">§2.4</a>).
<p>
The syntax <code>var.Name</code> is just syntactic sugar for
<code>var["Name"]</code>:
<pre>
var ::= prefixexp ‘<b>.</b>’ Name
</pre>
<p>
An access to a global variable <code>x</code>
is equivalent to <code>_ENV.x</code>.
Due to the way that chunks are compiled,
the variable <code>_ENV</code> itself is never global (see <a href="#2.2">§2.2</a>).
<h2>3.3 – <a name="3.3">Statements</a></h2>
<p>
Lua supports an almost conventional set of statements,
similar to those in other conventional languages.
This set includes
blocks, assignments, control structures, function calls,
and variable declarations.
<h3>3.3.1 – <a name="3.3.1">Blocks</a></h3>
<p>
A block is a list of statements,
which are executed sequentially:
<pre>
block ::= {stat}
</pre><p>
Lua has <em>empty statements</em>
that allow you to separate statements with semicolons,
start a block with a semicolon
or write two semicolons in sequence:
<pre>
stat ::= ‘<b>;</b>’
</pre>
<p>
Both function calls and assignments
can start with an open parenthesis.
This possibility leads to an ambiguity in Lua's grammar.
Consider the following fragment:
<pre>
a = b + c
(print or io.write)('done')
</pre><p>
The grammar could see this fragment in two ways:
<pre>
a = b + c(print or io.write)('done')
a = b + c; (print or io.write)('done')
</pre><p>
The current parser always sees such constructions
in the first way,
interpreting the open parenthesis
as the start of the arguments to a call.
To avoid this ambiguity,
it is a good practice to always precede with a semicolon
statements that start with a parenthesis:
<pre>
;(print or io.write)('done')
</pre>
<p>
A block can be explicitly delimited to produce a single statement:
<pre>
stat ::= <b>do</b> block <b>end</b>
</pre><p>
Explicit blocks are useful
to control the scope of variable declarations.
Explicit blocks are also sometimes used to
add a <b>return</b> statement in the middle
of another block (see <a href="#3.3.4">§3.3.4</a>).
<h3>3.3.2 – <a name="3.3.2">Chunks</a></h3>
<p>
The unit of compilation of Lua is called a <em>chunk</em>.
Syntactically,
a chunk is simply a block:
<pre>
chunk ::= block
</pre>
<p>
Lua handles a chunk as the body of an anonymous function
with a variable number of arguments
(see <a href="#3.4.11">§3.4.11</a>).
As such, chunks can define local variables,
receive arguments, and return values.
Moreover, such anonymous function is compiled as in the
scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">§2.2</a>).
The resulting function always has <code>_ENV</code> as its only external variable,
even if it does not use that variable.
<p>
A chunk can be stored in a file or in a string inside the host program.
To execute a chunk,
Lua first <em>loads</em> it,
precompiling the chunk's code into instructions for a virtual machine,
and then Lua executes the compiled code
with an interpreter for the virtual machine.
<p>
Chunks can also be precompiled into binary form;
see the program <code>luac</code> and the function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
Programs in source and compiled forms are interchangeable;
Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
<h3>3.3.3 – <a name="3.3.3">Assignment</a></h3>
<p>
Lua allows multiple assignments.
Therefore, the syntax for assignment
defines a list of variables on the left side
and a list of expressions on the right side.
The elements in both lists are separated by commas:
<pre>
stat ::= varlist ‘<b>=</b>’ explist
varlist ::= var {‘<b>,</b>’ var}
explist ::= exp {‘<b>,</b>’ exp}
</pre><p>
Expressions are discussed in <a href="#3.4">§3.4</a>.
<p>
Before the assignment,
the list of values is <em>adjusted</em> to the length of
the list of variables.
If there are more values than needed,
the excess values are thrown away.
If there are fewer values than needed,
the list is extended with <b>nil</b>'s.
If the list of expressions ends with a function call,
then all values returned by that call enter the list of values,
before the adjustment
(except when the call is enclosed in parentheses; see <a href="#3.4">§3.4</a>).
<p>
The assignment statement first evaluates all its expressions
and only then the assignments are performed.
Thus the code
<pre>
i = 3
i, a[i] = i+1, 20
</pre><p>
sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
before it is assigned 4.
Similarly, the line
<pre>
x, y = y, x
</pre><p>
exchanges the values of <code>x</code> and <code>y</code>,
and
<pre>
x, y, z = y, z, x
</pre><p>
cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
<p>
An assignment to a global name <code>x = val</code>
is equivalent to the assignment
<code>_ENV.x = val</code> (see <a href="#2.2">§2.2</a>).
<p>
The meaning of assignments to table fields and
global variables (which are actually table fields, too)
can be changed via metatables (see <a href="#2.4">§2.4</a>).
<h3>3.3.4 – <a name="3.3.4">Control Structures</a></h3><p>
The control structures
<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
familiar syntax:
<pre>
stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
stat ::= <b>repeat</b> block <b>until</b> exp
stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
</pre><p>
Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">§3.3.5</a>).
<p>
The condition expression of a
control structure can return any value.
Both <b>false</b> and <b>nil</b> test false.
All values different from <b>nil</b> and <b>false</b> test true.
In particular, the number 0 and the empty string also test true.
<p>
In the <b>repeat</b>–<b>until</b> loop,
the inner block does not end at the <b>until</b> keyword,
but only after the condition.
So, the condition can refer to local variables
declared inside the loop block.
<p>
The <b>goto</b> statement transfers the program control to a label.
For syntactical reasons,
labels in Lua are considered statements too:
<pre>
stat ::= <b>goto</b> Name
stat ::= label
label ::= ‘<b>::</b>’ Name ‘<b>::</b>’
</pre>
<p>
A label is visible in the entire block where it is defined,
except inside nested functions.
A goto may jump to any visible label as long as it does not
enter into the scope of a local variable.
A label should not be declared
where a label with the same name is visible,
even if this other label has been declared in an enclosing block.
<p>
Labels and empty statements are called <em>void statements</em>,
as they perform no actions.
<p>
The <b>break</b> statement terminates the execution of a
<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
skipping to the next statement after the loop:
<pre>
stat ::= <b>break</b>
</pre><p>
A <b>break</b> ends the innermost enclosing loop.
<p>
The <b>return</b> statement is used to return values
from a function or a chunk
(which is handled as an anonymous function).
Functions can return more than one value,
so the syntax for the <b>return</b> statement is
<pre>
stat ::= <b>return</b> [explist] [‘<b>;</b>’]
</pre>
<p>
The <b>return</b> statement can only be written
as the last statement of a block.
If it is necessary to <b>return</b> in the middle of a block,
then an explicit inner block can be used,
as in the idiom <code>do return end</code>,
because now <b>return</b> is the last statement in its (inner) block.
<h3>3.3.5 – <a name="3.3.5">For Statement</a></h3>
<p>
The <b>for</b> statement has two forms:
one numerical and one generic.
<h4>The numerical <b>for</b> loop</h4>
<p>
The numerical <b>for</b> loop repeats a block of code while a
control variable goes through an arithmetic progression.
It has the following syntax:
<pre>
stat ::= <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b>
</pre><p>
The given identifier (Name) defines the control variable,
which is local to the loop body (<em>block</em>).
<p>
The loop starts by evaluating once the three control expressions;
they must all result in numbers.
Their values are called respectively
the <em>initial value</em>, the <em>limit</em>, and the <em>step</em>.
If the step is absent, it defaults to 1.
<p>
If both the initial value and the step are integers,
the loop is done with integers;
note that the limit may not be an integer.
Otherwise, the loop is done with floats.
(Beware of floating-point accuracy in this case.)
<p>
After that initialization,
the loop body is repeated with the value of the control variable
going through an arithmetic progression,
starting at the initial value,
with a common difference given by the step.
A negative step makes a decreasing sequence;
a step equal to zero raises an error.
The loop continues while the value is less than
or equal to the limit
(greater than or equal to for a negative step).
If the initial value is already greater than the limit
(or less than, if the step is negative),
the body is not executed.
<p>
For integer loops,
the control variable never wraps around;
instead, the loop ends in case of an overflow.
<p>
You should not change the value of the control variable
during the loop.
If you need its value after the loop,
assign it to another variable before exiting the loop.
<h4>The generic <b>for</b> loop</h4>
<p>
The generic <b>for</b> statement works over functions,
called <em>iterators</em>.
On each iteration, the iterator function is called to produce a new value,
stopping when this new value is <b>nil</b>.
The generic <b>for</b> loop has the following syntax:
<pre>
stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
namelist ::= Name {‘<b>,</b>’ Name}
</pre><p>
A <b>for</b> statement like
<pre>
for <em>var_1</em>, ···, <em>var_n</em> in <em>explist</em> do <em>body</em> end
</pre><p>
works as follows.
<p>
The names <em>var_i</em> declare loop variables local to the loop body.
The first of these variables is the <em>control variable</em>.
<p>
The loop starts by evaluating <em>explist</em>
to produce four values:
an <em>iterator function</em>,
a <em>state</em>,
an initial value for the control variable,
and a <em>closing value</em>.
<p>
Then, at each iteration,
Lua calls the iterator function with two arguments:
the state and the control variable.
The results from this call are then assigned to the loop variables,
following the rules of multiple assignments (see <a href="#3.3.3">§3.3.3</a>).
If the control variable becomes <b>nil</b>,
the loop terminates.
Otherwise, the body is executed and the loop goes
to the next iteration.
<p>
The closing value behaves like a
to-be-closed variable (see <a href="#3.3.8">§3.3.8</a>),
which can be used to release resources when the loop ends.
Otherwise, it does not interfere with the loop.
<p>
You should not change the value of the control variable
during the loop.
<h3>3.3.6 – <a name="3.3.6">Function Calls as Statements</a></h3><p>
To allow possible side-effects,
function calls can be executed as statements:
<pre>
stat ::= functioncall
</pre><p>
In this case, all returned values are thrown away.
Function calls are explained in <a href="#3.4.10">§3.4.10</a>.
<h3>3.3.7 – <a name="3.3.7">Local Declarations</a></h3><p>
Local variables can be declared anywhere inside a block.
The declaration can include an initialization:
<pre>
stat ::= <b>local</b> attnamelist [‘<b>=</b>’ explist]
attnamelist ::= Name attrib {‘<b>,</b>’ Name attrib}
</pre><p>
If present, an initial assignment has the same semantics
of a multiple assignment (see <a href="#3.3.3">§3.3.3</a>).
Otherwise, all variables are initialized with <b>nil</b>.
<p>
Each variable name may be postfixed by an attribute
(a name between angle brackets):
<pre>
attrib ::= [‘<b><</b>’ Name ‘<b>></b>’]
</pre><p>
There are two possible attributes:
<code>const</code>, which declares a constant variable,
that is, a variable that cannot be assigned to
after its initialization;
and <code>close</code>, which declares a to-be-closed variable (see <a href="#3.3.8">§3.3.8</a>).
A list of variables can contain at most one to-be-closed variable.
<p>
A chunk is also a block (see <a href="#3.3.2">§3.3.2</a>),
and so local variables can be declared in a chunk outside any explicit block.
<p>
The visibility rules for local variables are explained in <a href="#3.5">§3.5</a>.
<h3>3.3.8 – <a name="3.3.8">To-be-closed Variables</a></h3>
<p>
A to-be-closed variable behaves like a constant local variable,
except that its value is <em>closed</em> whenever the variable
goes out of scope, including normal block termination,
exiting its block by <b>break</b>/<b>goto</b>/<b>return</b>,
or exiting by an error.
<p>
Here, to <em>close</em> a value means
to call its <code>__close</code> metamethod.
When calling the metamethod,
the value itself is passed as the first argument
and the error object that caused the exit (if any)
is passed as a second argument;
if there was no error, the second argument is <b>nil</b>.
<p>
The value assigned to a to-be-closed variable
must have a <code>__close</code> metamethod
or be a false value.
(<b>nil</b> and <b>false</b> are ignored as to-be-closed values.)
<p>
If several to-be-closed variables go out of scope at the same event,
they are closed in the reverse order that they were declared.
<p>
If there is any error while running a closing method,
that error is handled like an error in the regular code
where the variable was defined.
However, Lua may call the method one more time.
<p>
After an error,
the other pending closing methods will still be called.
Errors in these methods
interrupt the respective method and generate a warning,
but are otherwise ignored;
the error reported is only the original one.
<p>
If a coroutine yields and is never resumed again,
some variables may never go out of scope,
and therefore they will never be closed.
(These variables are the ones created inside the coroutine
and in scope at the point where the coroutine yielded.)
Similarly, if a coroutine ends with an error,
it does not unwind its stack,
so it does not close any variable.
In both cases,
you can either use finalizers
or call <a href="#pdf-coroutine.close"><code>coroutine.close</code></a> to close the variables.
However, if the coroutine was created
through <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>,
then its corresponding function will close the coroutine
in case of errors.
<h2>3.4 – <a name="3.4">Expressions</a></h2>
<p>
The basic expressions in Lua are the following:
<pre>
exp ::= prefixexp
exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
exp ::= Numeral
exp ::= LiteralString
exp ::= functiondef
exp ::= tableconstructor
exp ::= ‘<b>...</b>’
exp ::= exp binop exp
exp ::= unop exp
prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’
</pre>
<p>
Numerals and literal strings are explained in <a href="#3.1">§3.1</a>;
variables are explained in <a href="#3.2">§3.2</a>;
function definitions are explained in <a href="#3.4.11">§3.4.11</a>;
function calls are explained in <a href="#3.4.10">§3.4.10</a>;
table constructors are explained in <a href="#3.4.9">§3.4.9</a>.
Vararg expressions,
denoted by three dots ('<code>...</code>'), can only be used when
directly inside a vararg function;
they are explained in <a href="#3.4.11">§3.4.11</a>.
<p>
Binary operators comprise arithmetic operators (see <a href="#3.4.1">§3.4.1</a>),
bitwise operators (see <a href="#3.4.2">§3.4.2</a>),
relational operators (see <a href="#3.4.4">§3.4.4</a>), logical operators (see <a href="#3.4.5">§3.4.5</a>),
and the concatenation operator (see <a href="#3.4.6">§3.4.6</a>).
Unary operators comprise the unary minus (see <a href="#3.4.1">§3.4.1</a>),
the unary bitwise NOT (see <a href="#3.4.2">§3.4.2</a>),
the unary logical <b>not</b> (see <a href="#3.4.5">§3.4.5</a>),
and the unary <em>length operator</em> (see <a href="#3.4.7">§3.4.7</a>).
<p>
Both function calls and vararg expressions can result in multiple values.
If a function call is used as a statement (see <a href="#3.3.6">§3.3.6</a>),
then its return list is adjusted to zero elements,
thus discarding all returned values.
If an expression is used as the last (or the only) element
of a list of expressions,
then no adjustment is made
(unless the expression is enclosed in parentheses).
In all other contexts,
Lua adjusts the result list to one element,
either discarding all values except the first one
or adding a single <b>nil</b> if there are no values.
<p>
Here are some examples:
<pre>
f() -- adjusted to 0 results
g(f(), x) -- f() is adjusted to 1 result
g(x, f()) -- g gets x plus all results from f()
a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
a,b = ... -- a gets the first vararg argument, b gets
-- the second (both a and b can get nil if there
-- is no corresponding vararg argument)
a,b,c = x, f() -- f() is adjusted to 2 results
a,b,c = f() -- f() is adjusted to 3 results
return f() -- returns all results from f()
return ... -- returns all received vararg arguments
return x,y,f() -- returns x, y, and all results from f()
{f()} -- creates a list with all results from f()
{...} -- creates a list with all vararg arguments
{f(), nil} -- f() is adjusted to 1 result
</pre>
<p>
Any expression enclosed in parentheses always results in only one value.
Thus,
<code>(f(x,y,z))</code> is always a single value,
even if <code>f</code> returns several values.
(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
or <b>nil</b> if <code>f</code> does not return any values.)
<h3>3.4.1 – <a name="3.4.1">Arithmetic Operators</a></h3><p>
Lua supports the following arithmetic operators:
<ul>
<li><b><code>+</code>: </b>addition</li>
<li><b><code>-</code>: </b>subtraction</li>
<li><b><code>*</code>: </b>multiplication</li>
<li><b><code>/</code>: </b>float division</li>
<li><b><code>//</code>: </b>floor division</li>
<li><b><code>%</code>: </b>modulo</li>
<li><b><code>^</code>: </b>exponentiation</li>
<li><b><code>-</code>: </b>unary minus</li>
</ul>
<p>
With the exception of exponentiation and float division,
the arithmetic operators work as follows:
If both operands are integers,
the operation is performed over integers and the result is an integer.
Otherwise, if both operands are numbers,
then they are converted to floats,
the operation is performed following the machine's rules
for floating-point arithmetic
(usually the IEEE 754 standard),
and the result is a float.
(The string library coerces strings to numbers in
arithmetic operations; see <a href="#3.4.3">§3.4.3</a> for details.)
<p>
Exponentiation and float division (<code>/</code>)
always convert their operands to floats
and the result is always a float.
Exponentiation uses the ISO C function <code>pow</code>,
so that it works for non-integer exponents too.
<p>
Floor division (<code>//</code>) is a division
that rounds the quotient towards minus infinity,
resulting in the floor of the division of its operands.
<p>
Modulo is defined as the remainder of a division
that rounds the quotient towards minus infinity (floor division).
<p>
In case of overflows in integer arithmetic,
all operations <em>wrap around</em>,
according to the usual rules of two-complement arithmetic.
(In other words,
they return the unique representable integer
that is equal modulo <em>2<sup>n</sup></em> to the mathematical result,
where <em>n</em> is the number of bits of the integer type.)
<h3>3.4.2 – <a name="3.4.2">Bitwise Operators</a></h3><p>
Lua supports the following bitwise operators:
<ul>
<li><b><code>&</code>: </b>bitwise AND</li>
<li><b><code>|</code>: </b>bitwise OR</li>
<li><b><code>~</code>: </b>bitwise exclusive OR</li>
<li><b><code>>></code>: </b>right shift</li>
<li><b><code><<</code>: </b>left shift</li>
<li><b><code>~</code>: </b>unary bitwise NOT</li>
</ul>
<p>
All bitwise operations convert its operands to integers
(see <a href="#3.4.3">§3.4.3</a>),
operate on all bits of those integers,
and result in an integer.
<p>
Both right and left shifts fill the vacant bits with zeros.
Negative displacements shift to the other direction;
displacements with absolute values equal to or higher than
the number of bits in an integer
result in zero (as all bits are shifted out).
<h3>3.4.3 – <a name="3.4.3">Coercions and Conversions</a></h3><p>
Lua provides some automatic conversions between some
types and representations at run time.
Bitwise operators always convert float operands to integers.
Exponentiation and float division
always convert integer operands to floats.
All other arithmetic operations applied to mixed numbers
(integers and floats) convert the integer operand to a float.
The C API also converts both integers to floats and
floats to integers, as needed.
Moreover, string concatenation accepts numbers as arguments,
besides strings.
<p>
In a conversion from integer to float,
if the integer value has an exact representation as a float,
that is the result.
Otherwise,
the conversion gets the nearest higher or
the nearest lower representable value.
This kind of conversion never fails.
<p>
The conversion from float to integer
checks whether the float has an exact representation as an integer
(that is, the float has an integral value and
it is in the range of integer representation).
If it does, that representation is the result.
Otherwise, the conversion fails.
<p>
Several places in Lua coerce strings to numbers when necessary.
A string is converted to an integer or a float
following its syntax and the rules of the Lua lexer.
(The string may have also leading and trailing spaces and a sign.)
All conversions from strings to numbers
accept both a dot and the current locale mark
as the radix character.
(The Lua lexer, however, accepts only a dot.)
If the string is not a valid numeral,
the conversion fails.
If necessary, the result of this first step is then converted
to the required number subtype following the previous rules
for conversions between floats and integers.
<p>
The string library uses metamethods that try to coerce
strings to numbers in all arithmetic operations.
If the conversion fails,
the library calls the metamethod of the other operand
(if present) or it raises an error.
<p>
The conversion from numbers to strings uses a
non-specified human-readable format.
To convert numbers to strings in any specific way,
use the function <a href="#pdf-string.format"><code>string.format</code></a>.
<h3>3.4.4 – <a name="3.4.4">Relational Operators</a></h3><p>
Lua supports the following relational operators:
<ul>
<li><b><code>==</code>: </b>equality</li>
<li><b><code>~=</code>: </b>inequality</li>
<li><b><code><</code>: </b>less than</li>
<li><b><code>></code>: </b>greater than</li>
<li><b><code><=</code>: </b>less or equal</li>
<li><b><code>>=</code>: </b>greater or equal</li>
</ul><p>
These operators always result in <b>false</b> or <b>true</b>.
<p>
Equality (<code>==</code>) first compares the type of its operands.
If the types are different, then the result is <b>false</b>.
Otherwise, the values of the operands are compared.
Strings are equal if they have the same byte content.
Numbers are equal if they denote the same mathematical value.
<p>
Tables, userdata, and threads
are compared by reference:
two objects are considered equal only if they are the same object.
Every time you create a new object
(a table, a userdata, or a thread),
this new object is different from any previously existing object.
A function is always equal to itself.
Functions with any detectable difference
(different behavior, different definition) are always different.
Functions created at different times but with no detectable differences
may be classified as equal or not
(depending on internal caching details).
<p>
You can change the way that Lua compares tables and userdata
by using the <code>__eq</code> metamethod (see <a href="#2.4">§2.4</a>).
<p>
Equality comparisons do not convert strings to numbers
or vice versa.
Thus, <code>"0"==0</code> evaluates to <b>false</b>,
and <code>t[0]</code> and <code>t["0"]</code> denote different
entries in a table.
<p>
The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
<p>
The order operators work as follows.
If both arguments are numbers,
then they are compared according to their mathematical values,
regardless of their subtypes.
Otherwise, if both arguments are strings,
then their values are compared according to the current locale.
Otherwise, Lua tries to call the <code>__lt</code> or the <code>__le</code>
metamethod (see <a href="#2.4">§2.4</a>).
A comparison <code>a > b</code> is translated to <code>b < a</code>
and <code>a >= b</code> is translated to <code>b <= a</code>.
<p>
Following the IEEE 754 standard,
the special value NaN is considered neither less than,
nor equal to, nor greater than any value, including itself.
<h3>3.4.5 – <a name="3.4.5">Logical Operators</a></h3><p>
The logical operators in Lua are
<b>and</b>, <b>or</b>, and <b>not</b>.
Like the control structures (see <a href="#3.3.4">§3.3.4</a>),
all logical operators consider both <b>false</b> and <b>nil</b> as false
and anything else as true.
<p>
The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
The conjunction operator <b>and</b> returns its first argument
if this value is <b>false</b> or <b>nil</b>;
otherwise, <b>and</b> returns its second argument.
The disjunction operator <b>or</b> returns its first argument
if this value is different from <b>nil</b> and <b>false</b>;
otherwise, <b>or</b> returns its second argument.
Both <b>and</b> and <b>or</b> use short-circuit evaluation;
that is,
the second operand is evaluated only if necessary.
Here are some examples:
<pre>
10 or 20 --> 10
10 or error() --> 10
nil or "a" --> "a"
nil and 10 --> nil
false and error() --> false
false and nil --> false
false or nil --> nil
10 and 20 --> 20
</pre>
<h3>3.4.6 – <a name="3.4.6">Concatenation</a></h3><p>
The string concatenation operator in Lua is
denoted by two dots ('<code>..</code>').
If both operands are strings or numbers,
then the numbers are converted to strings
in a non-specified format (see <a href="#3.4.3">§3.4.3</a>).
Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">§2.4</a>).
<h3>3.4.7 – <a name="3.4.7">The Length Operator</a></h3>
<p>
The length operator is denoted by the unary prefix operator <code>#</code>.
<p>
The length of a string is its number of bytes.
(That is the usual meaning of string length when each
character is one byte.)
<p>
The length operator applied on a table
returns a border in that table.
A <em>border</em> in a table <code>t</code> is any natural number
that satisfies the following condition:
<pre>
(border == 0 or t[border] ~= nil) and t[border + 1] == nil
</pre><p>
In words,
a border is any (natural) index present in the table
that is followed by an absent index
(or zero, when index 1 is absent).
<p>
A table with exactly one border is called a <em>sequence</em>.
For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
as it has only one border (5).
The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
and therefore it is not a sequence.
(The <b>nil</b> at index 4 is called a <em>hole</em>.)
The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
has three borders (0, 3, and 6) and three holes
(at indices 1, 4, and 5),
so it is not a sequence, too.
The table <code>{}</code> is a sequence with border 0.
Note that non-natural keys do not interfere
with whether a table is a sequence.
<p>
When <code>t</code> is a sequence,
<code>#t</code> returns its only border,
which corresponds to the intuitive notion of the length of the sequence.
When <code>t</code> is not a sequence,
<code>#t</code> can return any of its borders.
(The exact one depends on details of
the internal representation of the table,
which in turn can depend on how the table was populated and
the memory addresses of its non-numeric keys.)
<p>
The computation of the length of a table
has a guaranteed worst time of <em>O(log n)</em>,
where <em>n</em> is the largest natural key in the table.
<p>
A program can modify the behavior of the length operator for
any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">§2.4</a>).
<h3>3.4.8 – <a name="3.4.8">Precedence</a></h3><p>
Operator precedence in Lua follows the table below,
from lower to higher priority:
<pre>
or
and
< > <= >= ~= ==
|
~
&
<< >>
..
+ -
* / // %
unary operators (not # - ~)
^
</pre><p>
As usual,
you can use parentheses to change the precedences of an expression.
The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
operators are right associative.
All other binary operators are left associative.
<h3>3.4.9 – <a name="3.4.9">Table Constructors</a></h3><p>
Table constructors are expressions that create tables.
Every time a constructor is evaluated, a new table is created.
A constructor can be used to create an empty table
or to create a table and initialize some of its fields.
The general syntax for constructors is
<pre>
tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp
fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’
</pre>
<p>
Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
with key <code>exp1</code> and value <code>exp2</code>.
A field of the form <code>name = exp</code> is equivalent to
<code>["name"] = exp</code>.
Fields of the form <code>exp</code> are equivalent to
<code>[i] = exp</code>, where <code>i</code> are consecutive integers
starting with 1;
fields in the other formats do not affect this counting.
For example,
<pre>
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
</pre><p>
is equivalent to
<pre>
do
local t = {}
t[f(1)] = g
t[1] = "x" -- 1st exp
t[2] = "y" -- 2nd exp
t.x = 1 -- t["x"] = 1
t[3] = f(x) -- 3rd exp
t[30] = 23
t[4] = 45 -- 4th exp
a = t
end
</pre>
<p>
The order of the assignments in a constructor is undefined.
(This order would be relevant only when there are repeated keys.)
<p>
If the last field in the list has the form <code>exp</code>
and the expression is a function call or a vararg expression,
then all values returned by this expression enter the list consecutively
(see <a href="#3.4.10">§3.4.10</a>).
<p>
The field list can have an optional trailing separator,
as a convenience for machine-generated code.
<h3>3.4.10 – <a name="3.4.10">Function Calls</a></h3><p>
A function call in Lua has the following syntax:
<pre>
functioncall ::= prefixexp args
</pre><p>
In a function call,
first prefixexp and args are evaluated.
If the value of prefixexp has type <em>function</em>,
then this function is called
with the given arguments.
Otherwise, if present,
the prefixexp <code>__call</code> metamethod is called:
its first argument is the value of prefixexp,
followed by the original call arguments
(see <a href="#2.4">§2.4</a>).
<p>
The form
<pre>
functioncall ::= prefixexp ‘<b>:</b>’ Name args
</pre><p>
can be used to emulate methods.
A call <code>v:name(<em>args</em>)</code>
is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
except that <code>v</code> is evaluated only once.
<p>
Arguments have the following syntax:
<pre>
args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’
args ::= tableconstructor
args ::= LiteralString
</pre><p>
All argument expressions are evaluated before the call.
A call of the form <code>f{<em>fields</em>}</code> is
syntactic sugar for <code>f({<em>fields</em>})</code>;
that is, the argument list is a single new table.
A call of the form <code>f'<em>string</em>'</code>
(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
is syntactic sugar for <code>f('<em>string</em>')</code>;
that is, the argument list is a single literal string.
<p>
A call of the form <code>return <em>functioncall</em></code> not in the
scope of a to-be-closed variable is called a <em>tail call</em>.
Lua implements <em>proper tail calls</em>
(or <em>proper tail recursion</em>):
in a tail call,
the called function reuses the stack entry of the calling function.
Therefore, there is no limit on the number of nested tail calls that
a program can execute.
However, a tail call erases any debug information about the
calling function.
Note that a tail call only happens with a particular syntax,
where the <b>return</b> has one single function call as argument,
and it is outside the scope of any to-be-closed variable.
This syntax makes the calling function return exactly
the returns of the called function,
without any intervening action.
So, none of the following examples are tail calls:
<pre>
return (f(x)) -- results adjusted to 1
return 2 * f(x) -- result multiplied by 2
return x, f(x) -- additional results
f(x); return -- results discarded
return x or f(x) -- results adjusted to 1
</pre>
<h3>3.4.11 – <a name="3.4.11">Function Definitions</a></h3>
<p>
The syntax for function definition is
<pre>
functiondef ::= <b>function</b> funcbody
funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b>
</pre>
<p>
The following syntactic sugar simplifies function definitions:
<pre>
stat ::= <b>function</b> funcname funcbody
stat ::= <b>local</b> <b>function</b> Name funcbody
funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name]
</pre><p>
The statement
<pre>
function f () <em>body</em> end
</pre><p>
translates to
<pre>
f = function () <em>body</em> end
</pre><p>
The statement
<pre>
function t.a.b.c.f () <em>body</em> end
</pre><p>
translates to
<pre>
t.a.b.c.f = function () <em>body</em> end
</pre><p>
The statement
<pre>
local function f () <em>body</em> end
</pre><p>
translates to
<pre>
local f; f = function () <em>body</em> end
</pre><p>
not to
<pre>
local f = function () <em>body</em> end
</pre><p>
(This only makes a difference when the body of the function
contains references to <code>f</code>.)
<p>
A function definition is an executable expression,
whose value has type <em>function</em>.
When Lua precompiles a chunk,
all its function bodies are precompiled too,
but they are not created yet.
Then, whenever Lua executes the function definition,
the function is <em>instantiated</em> (or <em>closed</em>).
This function instance, or <em>closure</em>,
is the final value of the expression.
<p>
Parameters act as local variables that are
initialized with the argument values:
<pre>
parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’
</pre><p>
When a Lua function is called,
it adjusts its list of arguments to
the length of its list of parameters,
unless the function is a <em>vararg function</em>,
which is indicated by three dots ('<code>...</code>')
at the end of its parameter list.
A vararg function does not adjust its argument list;
instead, it collects all extra arguments and supplies them
to the function through a <em>vararg expression</em>,
which is also written as three dots.
The value of this expression is a list of all actual extra arguments,
similar to a function with multiple results.
If a vararg expression is used inside another expression
or in the middle of a list of expressions,
then its return list is adjusted to one element.
If the expression is used as the last element of a list of expressions,
then no adjustment is made
(unless that last expression is enclosed in parentheses).
<p>
As an example, consider the following definitions:
<pre>
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
</pre><p>
Then, we have the following mapping from arguments to parameters and
to the vararg expression:
<pre>
CALL PARAMETERS
f(3) a=3, b=nil
f(3, 4) a=3, b=4
f(3, 4, 5) a=3, b=4
f(r(), 10) a=1, b=10
f(r()) a=1, b=2
g(3) a=3, b=nil, ... --> (nothing)
g(3, 4) a=3, b=4, ... --> (nothing)
g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
g(5, r()) a=5, b=1, ... --> 2 3
</pre>
<p>
Results are returned using the <b>return</b> statement (see <a href="#3.3.4">§3.3.4</a>).
If control reaches the end of a function
without encountering a <b>return</b> statement,
then the function returns with no results.
<p>
There is a system-dependent limit on the number of values
that a function may return.
This limit is guaranteed to be greater than 1000.
<p>
The <em>colon</em> syntax
is used to emulate <em>methods</em>,
adding an implicit extra parameter <code>self</code> to the function.
Thus, the statement
<pre>
function t.a.b.c:f (<em>params</em>) <em>body</em> end
</pre><p>
is syntactic sugar for
<pre>
t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
</pre>
<h2>3.5 – <a name="3.5">Visibility Rules</a></h2>
<p>
Lua is a lexically scoped language.
The scope of a local variable begins at the first statement after
its declaration and lasts until the last non-void statement
of the innermost block that includes the declaration.
Consider the following example:
<pre>
x = 10 -- global variable
do -- new block
local x = x -- new 'x', with value 10
print(x) --> 10
x = x+1
do -- another block
local x = x+1 -- another 'x'
print(x) --> 12
end
print(x) --> 11
end
print(x) --> 10 (the global one)
</pre>
<p>
Notice that, in a declaration like <code>local x = x</code>,
the new <code>x</code> being declared is not in scope yet,
and so the second <code>x</code> refers to the outside variable.
<p>
Because of the lexical scoping rules,
local variables can be freely accessed by functions
defined inside their scope.
A local variable used by an inner function is called an <em>upvalue</em>
(or <em>external local variable</em>, or simply <em>external variable</em>)
inside the inner function.
<p>
Notice that each execution of a <b>local</b> statement
defines new local variables.
Consider the following example:
<pre>
a = {}
local x = 20
for i = 1, 10 do
local y = 0
a[i] = function () y = y + 1; return x + y end
end
</pre><p>
The loop creates ten closures
(that is, ten instances of the anonymous function).
Each of these closures uses a different <code>y</code> variable,
while all of them share the same <code>x</code>.
<h1>4 – <a name="4">The Application Program Interface</a></h1>
<p>
This section describes the C API for Lua, that is,
the set of C functions available to the host program to communicate
with Lua.
All API functions and related types and constants
are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
<p>
Even when we use the term "function",
any facility in the API may be provided as a macro instead.
Except where stated otherwise,
all such macros use each of their arguments exactly once
(except for the first argument, which is always a Lua state),
and so do not generate any hidden side-effects.
<p>
As in most C libraries,
the Lua API functions do not check their arguments
for validity or consistency.
However, you can change this behavior by compiling Lua
with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
<p>
The Lua library is fully reentrant:
it has no global variables.
It keeps all information it needs in a dynamic structure,
called the <em>Lua state</em>.
<p>
Each Lua state has one or more threads,
which correspond to independent, cooperative lines of execution.
The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
(Indirectly, through the thread, it also refers to the
Lua state associated to the thread.)
<p>
A pointer to a thread must be passed as the first argument to
every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
which creates a Lua state from scratch and returns a pointer
to the <em>main thread</em> in the new state.
<h2>4.1 – <a name="4.1">The Stack</a></h2>
<p>
Lua uses a <em>virtual stack</em> to pass values to and from C.
Each element in this stack represents a Lua value
(<b>nil</b>, number, string, etc.).
Functions in the API can access this stack through the
Lua state parameter that they receive.
<p>
Whenever Lua calls C, the called function gets a new stack,
which is independent of previous stacks and of stacks of
C functions that are still active.
This stack initially contains any arguments to the C function
and it is where the C function can store temporary
Lua values and must push its results
to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
<p>
For convenience,
most query operations in the API do not follow a strict stack discipline.
Instead, they can refer to any element in the stack
by using an <em>index</em>:
A positive index represents an absolute stack position,
starting at 1 as the bottom of the stack;
a negative index represents an offset relative to the top of the stack.
More specifically, if the stack has <em>n</em> elements,
then index 1 represents the first element
(that is, the element that was pushed onto the stack first)
and
index <em>n</em> represents the last element;
index -1 also represents the last element
(that is, the element at the top)
and index <em>-n</em> represents the first element.
<h2>4.2 – <a name="4.2">Stack Size</a></h2>
<p>
When you interact with the Lua API,
you are responsible for ensuring consistency.
In particular,
<em>you are responsible for controlling stack overflow</em>.
You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
to ensure that the stack has enough space for pushing new elements.
<p>
Whenever Lua calls C,
it ensures that the stack has space for
at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
<code>LUA_MINSTACK</code> is defined as 20,
so that usually you do not have to worry about stack space
unless your code has loops pushing elements onto the stack.
<p>
When you call a Lua function
without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
Lua ensures that the stack has enough space for all results,
but it does not ensure any extra space.
So, before pushing anything in the stack after such a call
you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
<h2>4.3 – <a name="4.3">Valid and Acceptable Indices</a></h2>
<p>
Any function in the API that receives stack indices
works only with <em>valid indices</em> or <em>acceptable indices</em>.
<p>
A <em>valid index</em> is an index that refers to a
position that stores a modifiable Lua value.
It comprises stack indices between 1 and the stack top
(<code>1 ≤ abs(index) ≤ top</code>)
plus <em>pseudo-indices</em>,
which represent some positions that are accessible to C code
but that are not in the stack.
Pseudo-indices are used to access the registry (see <a href="#4.5">§4.5</a>)
and the upvalues of a C function (see <a href="#4.4">§4.4</a>).
<p>
Functions that do not need a specific mutable position,
but only a value (e.g., query functions),
can be called with acceptable indices.
An <em>acceptable index</em> can be any valid index,
but it also can be any positive index after the stack top
within the space allocated for the stack,
that is, indices up to the stack size.
(Note that 0 is never an acceptable index.)
Indices to upvalues (see <a href="#4.4">§4.4</a>) greater than the real number
of upvalues in the current C function are also acceptable (but invalid).
Except when noted otherwise,
functions in the API work with acceptable indices.
<p>
Acceptable indices serve to avoid extra tests
against the stack top when querying the stack.
For instance, a C function can query its third argument
without the need to check whether there is a third argument,
that is, without the need to check whether 3 is a valid index.
<p>
For functions that can be called with acceptable indices,
any non-valid index is treated as if it
contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
which behaves like a nil value.
<h2>4.4 – <a name="4.4">C Closures</a></h2>
<p>
When a C function is created,
it is possible to associate some values with it,
thus creating a <em>C closure</em>
(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
these values are called <em>upvalues</em> and are
accessible to the function whenever it is called.
<p>
Whenever a C function is called,
its upvalues are located at specific pseudo-indices.
These pseudo-indices are produced by the macro
<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
The first upvalue associated with a function is at index
<code>lua_upvalueindex(1)</code>, and so on.
Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
where <em>n</em> is greater than the number of upvalues of the
current function
(but not greater than 256,
which is one plus the maximum number of upvalues in a closure),
produces an acceptable but invalid index.
<p>
A C closure can also change the values
of its corresponding upvalues.
<h2>4.5 – <a name="4.5">Registry</a></h2>
<p>
Lua provides a <em>registry</em>,
a predefined table that can be used by any C code to
store whatever Lua values it needs to store.
The registry table is always accessible at pseudo-index
<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
Any C library can store data into this table,
but it must take care to choose keys
that are different from those used
by other libraries, to avoid collisions.
Typically, you should use as key a string containing your library name,
or a light userdata with the address of a C object in your code,
or any Lua object created by your code.
As with variable names,
string keys starting with an underscore followed by
uppercase letters are reserved for Lua.
<p>
The integer keys in the registry are used
by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
and by some predefined values.
Therefore, integer keys in the registry
must not be used for other purposes.
<p>
When you create a new Lua state,
its registry comes with some predefined values.
These predefined values are indexed with integer keys
defined as constants in <code>lua.h</code>.
The following constants are defined:
<ul>
<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
the main thread of the state.
(The main thread is the one created together with the state.)
</li>
<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
the global environment.
</li>
</ul>
<h2>4.6 – <a name="4.6">Error Handling in C</a></h2>
<p>
Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
(Lua will use exceptions if you compile it as C++;
search for <code>LUAI_THROW</code> in the source code for details.)
When Lua faces any error,
such as a memory allocation error or a type error,
it <em>raises</em> an error;
that is, it does a long jump.
A <em>protected environment</em> uses <code>setjmp</code>
to set a recovery point;
any error jumps to the most recent active recovery point.
<p>
Inside a C function you can raise an error explicitly
by calling <a href="#lua_error"><code>lua_error</code></a>.
<p>
Most functions in the API can raise an error,
for instance due to a memory allocation error.
The documentation for each function indicates whether
it can raise errors.
<p>
If an error happens outside any protected environment,
Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
and then calls <code>abort</code>,
thus exiting the host application.
Your panic function can avoid this exit by
never returning
(e.g., doing a long jump to your own recovery point outside Lua).
<p>
The panic function,
as its name implies,
is a mechanism of last resort.
Programs should avoid it.
As a general rule,
when a C function is called by Lua with a Lua state,
it can do whatever it wants on that Lua state,
as it should be already protected.
However,
when C code operates on other Lua states
(e.g., a Lua-state argument to the function,
a Lua state stored in the registry, or
the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
it should use them only in API calls that cannot raise errors.
<p>
The panic function runs as if it were a message handler (see <a href="#2.3">§2.3</a>);
in particular, the error object is on the top of the stack.
However, there is no guarantee about stack space.
To push anything on the stack,
the panic function must first check the available space (see <a href="#4.2">§4.2</a>).
<h2>4.7 – <a name="4.7">Handling Yields in C</a></h2>
<p>
Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
Therefore, if a C function <code>foo</code> calls an API function
and this API function yields
(directly or indirectly by calling another function that yields),
Lua cannot return to <code>foo</code> any more,
because the <code>longjmp</code> removes its frame from the C stack.
<p>
To avoid this kind of problem,
Lua raises an error whenever it tries to yield across an API call,
except for three functions:
<a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
All those functions receive a <em>continuation function</em>
(as a parameter named <code>k</code>) to continue execution after a yield.
<p>
We need to set some terminology to explain continuations.
We have a C function called from Lua which we will call
the <em>original function</em>.
This original function then calls one of those three functions in the C API,
which we will call the <em>callee function</em>,
that then yields the current thread.
This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a>
and the function called by them yields.
<p>
Suppose the running thread yields while executing the callee function.
After the thread resumes,
it eventually will finish running the callee function.
However,
the callee function cannot return to the original function,
because its frame in the C stack was destroyed by the yield.
Instead, Lua calls a <em>continuation function</em>,
which was given as an argument to the callee function.
As the name implies,
the continuation function should continue the task
of the original function.
<p>
As an illustration, consider the following function:
<pre>
int original_function (lua_State *L) {
... /* code 1 */
status = lua_pcall(L, n, m, h); /* calls Lua */
... /* code 2 */
}
</pre><p>
Now we want to allow
the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
First, we can rewrite our function like here:
<pre>
int k (lua_State *L, int status, lua_KContext ctx) {
... /* code 2 */
}
int original_function (lua_State *L) {
... /* code 1 */
return k(L, lua_pcall(L, n, m, h), ctx);
}
</pre><p>
In the above code,
the new function <code>k</code> is a
<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
which should do all the work that the original function
was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
Now, we must inform Lua that it must call <code>k</code> if the Lua code
being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
(errors or yielding),
so we rewrite the code as here,
replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
<pre>
int original_function (lua_State *L) {
... /* code 1 */
return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
}
</pre><p>
Note the external, explicit call to the continuation:
Lua will call the continuation only if needed, that is,
in case of errors or resuming after a yield.
If the called function returns normally without ever yielding,
<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
(Of course, instead of calling the continuation in that case,
you can do the equivalent work directly inside the original function.)
<p>
Besides the Lua state,
the continuation function has two other parameters:
the final status of the call and the context value (<code>ctx</code>) that
was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
Lua does not use this context value;
it only passes this value from the original function to the
continuation function.
For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
(For these two functions,
Lua will not call the continuation in case of errors,
because they do not handle errors.)
Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
you should call the continuation function
with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
directly the continuation function,
because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
<p>
Lua treats the continuation function as if it were the original function.
The continuation function receives the same Lua stack
from the original function,
in the same state it would be if the callee function had returned.
(For instance,
after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
removed from the stack and replaced by the results from the call.)
It also has the same upvalues.
Whatever it returns is handled by Lua as if it were the return
of the original function.
<h2>4.8 – <a name="4.8">Functions and Types</a></h2>
<p>
Here we list all functions and types from the C API in
alphabetical order.
Each function has an indicator like this:
<span class="apii">[-o, +p, <em>x</em>]</span>
<p>
The first field, <code>o</code>,
is how many elements the function pops from the stack.
The second field, <code>p</code>,
is how many elements the function pushes onto the stack.
(Any function always pushes its results after popping its arguments.)
A field in the form <code>x|y</code> means the function can push (or pop)
<code>x</code> or <code>y</code> elements,
depending on the situation;
an interrogation mark '<code>?</code>' means that
we cannot know how many elements the function pops/pushes
by looking only at its arguments.
(For instance, they may depend on what is on the stack.)
The third field, <code>x</code>,
tells whether the function may raise errors:
'<code>-</code>' means the function never raises any error;
'<code>m</code>' means the function may raise only out-of-memory errors;
'<code>v</code>' means the function may raise the errors explained in the text;
'<code>e</code>' means the function can run arbitrary Lua code,
either directly or through metamethods,
and therefore may raise any errors.
<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_absindex (lua_State *L, int idx);</pre>
<p>
Converts the acceptable index <code>idx</code>
into an equivalent absolute index
(that is, one that does not depend on the stack top).
<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
<pre>typedef void * (*lua_Alloc) (void *ud,
void *ptr,
size_t osize,
size_t nsize);</pre>
<p>
The type of the memory-allocation function used by Lua states.
The allocator function must provide a
functionality similar to <code>realloc</code>,
but not exactly the same.
Its arguments are
<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
<code>osize</code>, the original size of the block or some code about what
is being allocated;
and <code>nsize</code>, the new size of the block.
<p>
When <code>ptr</code> is not <code>NULL</code>,
<code>osize</code> is the size of the block pointed by <code>ptr</code>,
that is, the size given when it was allocated or reallocated.
<p>
When <code>ptr</code> is <code>NULL</code>,
<code>osize</code> encodes the kind of object that Lua is allocating.
<code>osize</code> is any of
<a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
<a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when)
Lua is creating a new object of that type.
When <code>osize</code> is some other value,
Lua is allocating memory for something else.
<p>
Lua assumes the following behavior from the allocator function:
<p>
When <code>nsize</code> is zero,
the allocator must behave like <code>free</code>
and then return <code>NULL</code>.
<p>
When <code>nsize</code> is not zero,
the allocator must behave like <code>realloc</code>.
In particular, the allocator returns <code>NULL</code>
if and only if it cannot fulfill the request.
<p>
Here is a simple implementation for the allocator function.
It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
<pre>
static void *l_alloc (void *ud, void *ptr, size_t osize,
size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return NULL;
}
else
return realloc(ptr, nsize);
}
</pre><p>
Note that Standard C ensures
that <code>free(NULL)</code> has no effect and that
<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
<span class="apii">[-(2|1), +1, <em>e</em>]</span>
<pre>void lua_arith (lua_State *L, int op);</pre>
<p>
Performs an arithmetic or bitwise operation over the two values
(or one, in the case of negations)
at the top of the stack,
with the value on the top being the second operand,
pops these values, and pushes the result of the operation.
The function follows the semantics of the corresponding Lua operator
(that is, it may call metamethods).
<p>
The value of <code>op</code> must be one of the following constants:
<ul>
<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&</code>)</li>
<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code><<</code>)</li>
<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>>></code>)</li>
</ul>
<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
<p>
Sets a new panic function and returns the old one (see <a href="#4.6">§4.6</a>).
<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
<p>
Calls a function.
<p>
To do a call you must use the following protocol:
first, the value to be called is pushed onto the stack;
then, the arguments to the call are pushed
in direct order;
that is, the first argument is pushed first.
Finally you call <a href="#lua_call"><code>lua_call</code></a>;
<code>nargs</code> is the number of arguments that you pushed onto the stack.
When the function returns,
all arguments and the function value are popped
and the function results are pushed onto the stack.
The number of results is adjusted to <code>nresults</code>,
unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
In this case, all results from the function are pushed;
Lua takes care that the returned values fit into the stack space,
but it does not ensure any extra space in the stack.
The function results are pushed onto the stack in direct order
(the first result is pushed first),
so that after the call the last result is on the top of the stack.
<p>
Any error while calling and running the function is propagated upwards
(with a <code>longjmp</code>).
Like regular Lua calls,
this function respects the <code>__call</code> metamethod.
<p>
The following example shows how the host program can do the
equivalent to this Lua code:
<pre>
a = f("how", t.x, 14)
</pre><p>
Here it is in C:
<pre>
lua_getglobal(L, "f"); /* function to be called */
lua_pushliteral(L, "how"); /* 1st argument */
lua_getglobal(L, "t"); /* table to be indexed */
lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
lua_remove(L, -2); /* remove 't' from the stack */
lua_pushinteger(L, 14); /* 3rd argument */
lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
lua_setglobal(L, "a"); /* set global 'a' */
</pre><p>
Note that the code above is <em>balanced</em>:
at its end, the stack is back to its original configuration.
This is considered good programming practice.
<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
<pre>void lua_callk (lua_State *L,
int nargs,
int nresults,
lua_KContext ctx,
lua_KFunction k);</pre>
<p>
This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
but allows the called function to yield (see <a href="#4.7">§4.7</a>).
<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
<p>
Type for C functions.
<p>
In order to communicate properly with Lua,
a C function must use the following protocol,
which defines the way parameters and results are passed:
a C function receives its arguments from Lua in its stack
in direct order (the first argument is pushed first).
So, when the function starts,
<code>lua_gettop(L)</code> returns the number of arguments received by the function.
The first argument (if any) is at index 1
and its last argument is at index <code>lua_gettop(L)</code>.
To return values to Lua, a C function just pushes them onto the stack,
in direct order (the first result is pushed first),
and returns in C the number of results.
Any other value in the stack below the results will be properly
discarded by Lua.
Like a Lua function, a C function called by Lua can also return
many results.
<p>
As an example, the following function receives a variable number
of numeric arguments and returns their average and their sum:
<pre>
static int foo (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number sum = 0.0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushliteral(L, "incorrect argument");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n); /* first result */
lua_pushnumber(L, sum); /* second result */
return 2; /* number of results */
}
</pre>
<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_checkstack (lua_State *L, int n);</pre>
<p>
Ensures that the stack has space for at least <code>n</code> extra slots,
that is, that you can safely push up to <code>n</code> values into it.
It returns false if it cannot fulfill the request,
either because it would cause the stack
to be greater than a fixed maximum size
(typically at least several thousand elements) or
because it cannot allocate memory for the extra space.
This function never shrinks the stack;
if the stack already has space for the extra slots,
it is left unchanged.
<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_close (lua_State *L);</pre>
<p>
Close all active to-be-closed variables in the main thread,
release all objects in the given Lua state
(calling the corresponding garbage-collection metamethods, if any),
and frees all dynamic memory used by this state.
<p>
On several platforms, you may not need to call this function,
because all resources are naturally released when the host program ends.
On the other hand, long-running programs that create multiple states,
such as daemons or web servers,
will probably need to close states as soon as they are not needed.
<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
<span class="apii">[-0, +0, <em>e</em>]</span>
<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
<p>
Compares two Lua values.
Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
when compared with the value at index <code>index2</code>,
following the semantics of the corresponding Lua operator
(that is, it may call metamethods).
Otherwise returns 0.
Also returns 0 if any of the indices is not valid.
<p>
The value of <code>op</code> must be one of the following constants:
<ul>
<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code><</code>)</li>
<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code><=</code>)</li>
</ul>
<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
<span class="apii">[-n, +1, <em>e</em>]</span>
<pre>void lua_concat (lua_State *L, int n);</pre>
<p>
Concatenates the <code>n</code> values at the top of the stack,
pops them, and leaves the result on the top.
If <code>n</code> is 1, the result is the single value on the stack
(that is, the function does nothing);
if <code>n</code> is 0, the result is the empty string.
Concatenation is performed following the usual semantics of Lua
(see <a href="#3.4.6">§3.4.6</a>).
<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
<p>
Copies the element at index <code>fromidx</code>
into the valid index <code>toidx</code>,
replacing the value at that position.
Values at other positions are not affected.
<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
<p>
Creates a new empty table and pushes it onto the stack.
Parameter <code>narr</code> is a hint for how many elements the table
will have as a sequence;
parameter <code>nrec</code> is a hint for how many other elements
the table will have.
Lua may use these hints to preallocate memory for the new table.
This preallocation may help performance when you know in advance
how many elements the table will have.
Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_dump (lua_State *L,
lua_Writer writer,
void *data,
int strip);</pre>
<p>
Dumps a function as a binary chunk.
Receives a Lua function on the top of the stack
and produces a binary chunk that,
if loaded again,
results in a function equivalent to the one dumped.
As it produces parts of the chunk,
<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
with the given <code>data</code>
to write them.
<p>
If <code>strip</code> is true,
the binary representation may not include all debug information
about the function,
to save space.
<p>
The value returned is the error code returned by the last
call to the writer;
0 means no errors.
<p>
This function does not pop the Lua function from the stack.
<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
<span class="apii">[-1, +0, <em>v</em>]</span>
<pre>int lua_error (lua_State *L);</pre>
<p>
Generates a Lua error,
using the value on the top of the stack as the error object.
This function does a long jump,
and therefore never returns
(see <a href="#luaL_error"><code>luaL_error</code></a>).
<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_gc (lua_State *L, int what, ...);</pre>
<p>
Controls the garbage collector.
<p>
This function performs several tasks,
according to the value of the parameter <code>what</code>.
For options that need extra arguments,
they are listed after the option.
<ul>
<li><b><code>LUA_GCCOLLECT</code>: </b>
Performs a full garbage-collection cycle.
</li>
<li><b><code>LUA_GCSTOP</code>: </b>
Stops the garbage collector.
</li>
<li><b><code>LUA_GCRESTART</code>: </b>
Restarts the garbage collector.
</li>
<li><b><code>LUA_GCCOUNT</code>: </b>
Returns the current amount of memory (in Kbytes) in use by Lua.
</li>
<li><b><code>LUA_GCCOUNTB</code>: </b>
Returns the remainder of dividing the current amount of bytes of
memory in use by Lua by 1024.
</li>
<li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
Performs an incremental step of garbage collection,
corresponding to the allocation of <code>stepsize</code> Kbytes.
</li>
<li><b><code>LUA_GCISRUNNING</code>: </b>
Returns a boolean that tells whether the collector is running
(i.e., not stopped).
</li>
<li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
Changes the collector to incremental mode
with the given parameters (see <a href="#2.5.1">§2.5.1</a>).
Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
</li>
<li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
Changes the collector to generational mode
with the given parameters (see <a href="#2.5.2">§2.5.2</a>).
Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
</li>
</ul><p>
For more details about these options,
see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
<p>
Returns the memory-allocation function of a given state.
If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
opaque pointer given when the memory-allocator function was set.
<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
<p>
Pushes onto the stack the value <code>t[k]</code>,
where <code>t</code> is the value at the given index.
As in Lua, this function may trigger a metamethod
for the "index" event (see <a href="#2.4">§2.4</a>).
<p>
Returns the type of the pushed value.
<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void *lua_getextraspace (lua_State *L);</pre>
<p>
Returns a pointer to a raw memory area associated with the
given Lua state.
The application can use this area for any purpose;
Lua does not use it for anything.
<p>
Each new thread has this area initialized with a copy
of the area of the main thread.
<p>
By default, this area has the size of a pointer to void,
but you can recompile Lua with a different size for this area.
(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
<p>
Pushes onto the stack the value of the global <code>name</code>.
Returns the type of that value.
<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
<p>
Pushes onto the stack the value <code>t[i]</code>,
where <code>t</code> is the value at the given index.
As in Lua, this function may trigger a metamethod
for the "index" event (see <a href="#2.4">§2.4</a>).
<p>
Returns the type of the pushed value.
<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
<span class="apii">[-0, +(0|1), –]</span>
<pre>int lua_getmetatable (lua_State *L, int index);</pre>
<p>
If the value at the given index has a metatable,
the function pushes that metatable onto the stack and returns 1.
Otherwise,
the function returns 0 and pushes nothing on the stack.
<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
<span class="apii">[-1, +1, <em>e</em>]</span>
<pre>int lua_gettable (lua_State *L, int index);</pre>
<p>
Pushes onto the stack the value <code>t[k]</code>,
where <code>t</code> is the value at the given index
and <code>k</code> is the value on the top of the stack.
<p>
This function pops the key from the stack,
pushing the resulting value in its place.
As in Lua, this function may trigger a metamethod
for the "index" event (see <a href="#2.4">§2.4</a>).
<p>
Returns the type of the pushed value.
<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_gettop (lua_State *L);</pre>
<p>
Returns the index of the top element in the stack.
Because indices start at 1,
this result is equal to the number of elements in the stack;
in particular, 0 means an empty stack.
<hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
<p>
Pushes onto the stack the <code>n</code>-th user value associated with the
full userdata at the given index and
returns the type of the pushed value.
<p>
If the userdata does not have that value,
pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
<span class="apii">[-1, +1, –]</span>
<pre>void lua_insert (lua_State *L, int index);</pre>
<p>
Moves the top element into the given valid index,
shifting up the elements above this index to open space.
This function cannot be called with a pseudo-index,
because a pseudo-index is not an actual stack position.
<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
<pre>typedef ... lua_Integer;</pre>
<p>
The type of integers in Lua.
<p>
By default this type is <code>long long</code>,
(usually a 64-bit two-complement integer),
but that can be changed to <code>long</code> or <code>int</code>
(usually a 32-bit two-complement integer).
(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
<p>
Lua also defines the constants
<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
with the minimum and the maximum values that fit in this type.
<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isboolean (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a boolean,
and 0 otherwise.
<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_iscfunction (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a C function,
and 0 otherwise.
<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isfunction (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a function
(either C or Lua), and 0 otherwise.
<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isinteger (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is an integer
(that is, the value is a number and is represented as an integer),
and 0 otherwise.
<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a light userdata,
and 0 otherwise.
<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isnil (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is <b>nil</b>,
and 0 otherwise.
<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isnone (lua_State *L, int index);</pre>
<p>
Returns 1 if the given index is not valid,
and 0 otherwise.
<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
<p>
Returns 1 if the given index is not valid
or if the value at this index is <b>nil</b>,
and 0 otherwise.
<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isnumber (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a number
or a string convertible to a number,
and 0 otherwise.
<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isstring (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a string
or a number (which is always convertible to a string),
and 0 otherwise.
<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_istable (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a table,
and 0 otherwise.
<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isthread (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a thread,
and 0 otherwise.
<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isuserdata (lua_State *L, int index);</pre>
<p>
Returns 1 if the value at the given index is a userdata
(either full or light), and 0 otherwise.
<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_isyieldable (lua_State *L);</pre>
<p>
Returns 1 if the given coroutine can yield,
and 0 otherwise.
<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
<pre>typedef ... lua_KContext;</pre>
<p>
The type for continuation-function contexts.
It must be a numeric type.
This type is defined as <code>intptr_t</code>
when <code>intptr_t</code> is available,
so that it can store pointers too.
Otherwise, it is defined as <code>ptrdiff_t</code>.
<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
<p>
Type for continuation functions (see <a href="#4.7">§4.7</a>).
<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>void lua_len (lua_State *L, int index);</pre>
<p>
Returns the length of the value at the given index.
It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>) and
may trigger a metamethod for the "length" event (see <a href="#2.4">§2.4</a>).
The result is pushed on the stack.
<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int lua_load (lua_State *L,
lua_Reader reader,
void *data,
const char *chunkname,
const char *mode);</pre>
<p>
Loads a Lua chunk without running it.
If there are no errors,
<code>lua_load</code> pushes the compiled chunk as a Lua
function on top of the stack.
Otherwise, it pushes an error message.
<p>
The return values of <code>lua_load</code> are:
<ul>
<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
syntax error during precompilation;</li>
<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
memory allocation (out-of-memory) error;</li>
</ul>
<p>
The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
The <code>data</code> argument is an opaque value passed to the reader function.
<p>
The <code>chunkname</code> argument gives a name to the chunk,
which is used for error messages and in debug information (see <a href="#4.9">§4.9</a>).
<p>
<code>lua_load</code> automatically detects whether the chunk is text or binary
and loads it accordingly (see program <code>luac</code>).
The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
with the addition that
a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
<p>
<code>lua_load</code> uses the stack internally,
so the reader function must always leave the stack
unmodified when returning.
<p>
If the resulting function has upvalues,
its first upvalue is set to the value of the global environment
stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">§4.5</a>).
When loading main chunks,
this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>).
Other upvalues are initialized with <b>nil</b>.
<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
<p>
Creates a new independent state and returns its main thread.
Returns <code>NULL</code> if it cannot create the state
(due to lack of memory).
The argument <code>f</code> is the allocator function;
Lua will do all memory allocation for this state
through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
The second argument, <code>ud</code>, is an opaque pointer that Lua
passes to the allocator in every call.
<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void lua_newtable (lua_State *L);</pre>
<p>
Creates a new empty table and pushes it onto the stack.
It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>lua_State *lua_newthread (lua_State *L);</pre>
<p>
Creates a new thread, pushes it on the stack,
and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
The new thread returned by this function shares with the original thread
its global environment,
but has an independent execution stack.
<p>
Threads are subject to garbage collection,
like any Lua object.
<hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
<p>
This function creates and pushes on the stack a new full userdata,
with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
plus an associated block of raw memory with <code>size</code> bytes.
(The user values can be set and read with the functions
<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
<p>
The function returns the address of the block of memory.
<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
<span class="apii">[-1, +(2|0), <em>v</em>]</span>
<pre>int lua_next (lua_State *L, int index);</pre>
<p>
Pops a key from the stack,
and pushes a key–value pair from the table at the given index,
the "next" pair after the given key.
If there are no more elements in the table,
then <a href="#lua_next"><code>lua_next</code></a> returns 0 and pushes nothing.
<p>
A typical table traversal looks like this:
<pre>
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
</pre>
<p>
While traversing a table,
avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
unless you know that the key is actually a string.
Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
the value at the given index;
this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
<p>
This function may raise an error if the given key
is neither <b>nil</b> nor present in the table.
See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
the table during its traversal.
<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
<pre>typedef ... lua_Number;</pre>
<p>
The type of floats in Lua.
<p>
By default this type is double,
but that can be changed to a single float or a long double.
(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
<p>
Tries to convert a Lua float to a Lua integer;
the float <code>n</code> must have an integral value.
If that value is within the range of Lua integers,
it is converted to an integer and assigned to <code>*p</code>.
The macro results in a boolean indicating whether the
conversion was successful.
(Note that this range test can be tricky to do
correctly without this macro, due to rounding.)
<p>
This macro may evaluate its arguments more than once.
<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
<span class="apii">[-(nargs + 1), +(nresults|1), –]</span>
<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
<p>
Calls a function (or a callable object) in protected mode.
<p>
Both <code>nargs</code> and <code>nresults</code> have the same meaning as
in <a href="#lua_call"><code>lua_call</code></a>.
If there are no errors during the call,
<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
However, if there is any error,
<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
pushes a single value on the stack (the error object),
and returns an error code.
Like <a href="#lua_call"><code>lua_call</code></a>,
<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
and its arguments from the stack.
<p>
If <code>msgh</code> is 0,
then the error object returned on the stack
is exactly the original error object.
Otherwise, <code>msgh</code> is the stack index of a
<em>message handler</em>.
(This index cannot be a pseudo-index.)
In case of runtime errors,
this handler will be called with the error object
and its return value will be the object
returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
<p>
Typically, the message handler is used to add more debug
information to the error object, such as a stack traceback.
Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
since by then the stack has unwound.
<p>
The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
(defined in <code>lua.h</code>):
<ul>
<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
success.</li>
<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
a runtime error.
</li>
<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
memory allocation error.
For such errors, Lua does not call the message handler.
</li>
<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
error while running the message handler.
</li>
</ul>
<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
<span class="apii">[-(nargs + 1), +(nresults|1), –]</span>
<pre>int lua_pcallk (lua_State *L,
int nargs,
int nresults,
int msgh,
lua_KContext ctx,
lua_KFunction k);</pre>
<p>
This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
but allows the called function to yield (see <a href="#4.7">§4.7</a>).
<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
<span class="apii">[-n, +0, –]</span>
<pre>void lua_pop (lua_State *L, int n);</pre>
<p>
Pops <code>n</code> elements from the stack.
<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushboolean (lua_State *L, int b);</pre>
<p>
Pushes a boolean value with value <code>b</code> onto the stack.
<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
<span class="apii">[-n, +1, <em>m</em>]</span>
<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
<p>
Pushes a new C closure onto the stack.
This function receives a pointer to a C function
and pushes onto the stack a Lua value of type <code>function</code> that,
when called, invokes the corresponding C function.
The parameter <code>n</code> tells how many upvalues this function will have
(see <a href="#4.4">§4.4</a>).
<p>
Any function to be callable by Lua must
follow the correct protocol to receive its parameters
and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
<p>
When a C function is created,
it is possible to associate some values with it,
the so called upvalues;
these upvalues are then accessible to the function whenever it is called.
This association is called a C closure (see <a href="#4.4">§4.4</a>).
To create a C closure,
first the initial values for its upvalues must be pushed onto the stack.
(When there are multiple upvalues, the first value is pushed first.)
Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
is called to create and push the C function onto the stack,
with the argument <code>n</code> telling how many values will be
associated with the function.
<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
<p>
The maximum value for <code>n</code> is 255.
<p>
When <code>n</code> is zero,
this function creates a <em>light C function</em>,
which is just a pointer to the C function.
In that case, it never raises a memory error.
<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
<p>
Pushes a C function onto the stack.
This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
<span class="apii">[-0, +1, <em>v</em>]</span>
<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
<p>
Pushes onto the stack a formatted string
and returns a pointer to this string.
It is similar to the ISO C function <code>sprintf</code>,
but has two important differences.
First,
you do not have to allocate space for the result;
the result is a Lua string and Lua takes care of memory allocation
(and deallocation, through garbage collection).
Second,
the conversion specifiers are quite restricted.
There are no flags, widths, or precisions.
The conversion specifiers can only be
'<code>%%</code>' (inserts the character '<code>%</code>'),
'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
'<code>%p</code>' (inserts a pointer),
'<code>%d</code>' (inserts an <code>int</code>),
'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
<p>
This function may raise errors due to memory overflow
or an invalid conversion specifier.
<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushglobaltable (lua_State *L);</pre>
<p>
Pushes the global environment onto the stack.
<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
<p>
Pushes an integer with value <code>n</code> onto the stack.
<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
<p>
Pushes a light userdata onto the stack.
<p>
Userdata represent C values in Lua.
A <em>light userdata</em> represents a pointer, a <code>void*</code>.
It is a value (like a number):
you do not create it, it has no individual metatable,
and it is not collected (as it was never created).
A light userdata is equal to "any"
light userdata with the same C address.
<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
<p>
This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
but should be used only when <code>s</code> is a literal string.
(Lua may optimize this case.)
<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
<p>
Pushes the string pointed to by <code>s</code> with size <code>len</code>
onto the stack.
Lua will make or reuse an internal copy of the given string,
so the memory at <code>s</code> can be freed or reused immediately after
the function returns.
The string can contain any binary data,
including embedded zeros.
<p>
Returns a pointer to the internal copy of the string.
<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushnil (lua_State *L);</pre>
<p>
Pushes a nil value onto the stack.
<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
<p>
Pushes a float with value <code>n</code> onto the stack.
<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
<p>
Pushes the zero-terminated string pointed to by <code>s</code>
onto the stack.
Lua will make or reuse an internal copy of the given string,
so the memory at <code>s</code> can be freed or reused immediately after
the function returns.
<p>
Returns a pointer to the internal copy of the string.
<p>
If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int lua_pushthread (lua_State *L);</pre>
<p>
Pushes the thread represented by <code>L</code> onto the stack.
Returns 1 if this thread is the main thread of its state.
<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>void lua_pushvalue (lua_State *L, int index);</pre>
<p>
Pushes a copy of the element at the given index
onto the stack.
<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
<span class="apii">[-0, +1, <em>v</em>]</span>
<pre>const char *lua_pushvfstring (lua_State *L,
const char *fmt,
va_list argp);</pre>
<p>
Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
instead of a variable number of arguments.
<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
<p>
Returns 1 if the two values in indices <code>index1</code> and
<code>index2</code> are primitively equal
(that is, equal without calling the <code>__eq</code> metamethod).
Otherwise returns 0.
Also returns 0 if any of the indices are not valid.
<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
<span class="apii">[-1, +1, –]</span>
<pre>int lua_rawget (lua_State *L, int index);</pre>
<p>
Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
(i.e., without metamethods).
<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
<p>
Pushes onto the stack the value <code>t[n]</code>,
where <code>t</code> is the table at the given index.
The access is raw,
that is, it does not invoke the <code>__index</code> metamethod.
<p>
Returns the type of the pushed value.
<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
<p>
Pushes onto the stack the value <code>t[k]</code>,
where <code>t</code> is the table at the given index and
<code>k</code> is the pointer <code>p</code> represented as a light userdata.
The access is raw;
that is, it does not invoke the <code>__index</code> metamethod.
<p>
Returns the type of the pushed value.
<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
<p>
Returns the raw "length" of the value at the given index:
for strings, this is the string length;
for tables, this is the result of the length operator ('<code>#</code>')
with no metamethods;
for userdata, this is the size of the block of memory allocated
for the userdata.
For other values, this call returns 0.
<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
<span class="apii">[-2, +0, <em>m</em>]</span>
<pre>void lua_rawset (lua_State *L, int index);</pre>
<p>
Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
(i.e., without metamethods).
<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
<span class="apii">[-1, +0, <em>m</em>]</span>
<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
<p>
Does the equivalent of <code>t[i] = v</code>,
where <code>t</code> is the table at the given index
and <code>v</code> is the value on the top of the stack.
<p>
This function pops the value from the stack.
The assignment is raw,
that is, it does not invoke the <code>__newindex</code> metamethod.
<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
<span class="apii">[-1, +0, <em>m</em>]</span>
<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
<p>
Does the equivalent of <code>t[p] = v</code>,
where <code>t</code> is the table at the given index,
<code>p</code> is encoded as a light userdata,
and <code>v</code> is the value on the top of the stack.
<p>
This function pops the value from the stack.
The assignment is raw,
that is, it does not invoke <code>__newindex</code> metamethod.
<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
<pre>typedef const char * (*lua_Reader) (lua_State *L,
void *data,
size_t *size);</pre>
<p>
The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
it calls the reader,
passing along its <code>data</code> parameter.
The reader must return a pointer to a block of memory
with a new piece of the chunk
and set <code>size</code> to the block size.
The block must exist until the reader function is called again.
To signal the end of the chunk,
the reader must return <code>NULL</code> or set <code>size</code> to zero.
The reader function may return pieces of any size greater than zero.
<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
<span class="apii">[-0, +0, <em>e</em>]</span>
<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
<p>
Sets the C function <code>f</code> as the new value of global <code>name</code>.
It is defined as a macro:
<pre>
#define lua_register(L,n,f) \
(lua_pushcfunction(L, f), lua_setglobal(L, n))
</pre>
<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
<span class="apii">[-1, +0, –]</span>
<pre>void lua_remove (lua_State *L, int index);</pre>
<p>
Removes the element at the given valid index,
shifting down the elements above this index to fill the gap.
This function cannot be called with a pseudo-index,
because a pseudo-index is not an actual stack position.
<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
<span class="apii">[-1, +0, –]</span>
<pre>void lua_replace (lua_State *L, int index);</pre>
<p>
Moves the top element into the given valid index
without shifting any element
(therefore replacing the value at that given index),
and then pops the top element.
<hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
<span class="apii">[-0, +?, –]</span>
<pre>int lua_resetthread (lua_State *L);</pre>
<p>
Resets a thread, cleaning its call stack and closing all pending
to-be-closed variables.
Returns a status code:
<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in closing methods,
or an error status otherwise.
In case of error,
leaves the error object on the top of the stack,
<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
<span class="apii">[-?, +?, –]</span>
<pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
int *nresults);</pre>
<p>
Starts and resumes a coroutine in the given thread <code>L</code>.
<p>
To start a coroutine,
you push onto the thread stack the main function plus any arguments;
then you call <a href="#lua_resume"><code>lua_resume</code></a>,
with <code>nargs</code> being the number of arguments.
This call returns when the coroutine suspends or finishes its execution.
When it returns,
<code>*nresults</code> is updated and
the top of the stack contains
the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
or returned by the body function.
<a href="#lua_resume"><code>lua_resume</code></a> returns
<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
without errors,
or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
In case of errors,
the error object is on the top of the stack.
<p>
To resume a coroutine, you clear its stack,
push only the values to be passed as results from <code>yield</code>,
and then call <a href="#lua_resume"><code>lua_resume</code></a>.
<p>
The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
If there is no such coroutine,
this parameter can be <code>NULL</code>.
<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
<p>
Rotates the stack elements between the valid index <code>idx</code>
and the top of the stack.
The elements are rotated <code>n</code> positions in the direction of the top,
for a positive <code>n</code>,
or <code>-n</code> positions in the direction of the bottom,
for a negative <code>n</code>.
The absolute value of <code>n</code> must not be greater than the size
of the slice being rotated.
This function cannot be called with a pseudo-index,
because a pseudo-index is not an actual stack position.
<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
<p>
Changes the allocator function of a given state to <code>f</code>
with user data <code>ud</code>.
<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
<span class="apii">[-1, +0, <em>e</em>]</span>
<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
<p>
Does the equivalent to <code>t[k] = v</code>,
where <code>t</code> is the value at the given index
and <code>v</code> is the value on the top of the stack.
<p>
This function pops the value from the stack.
As in Lua, this function may trigger a metamethod
for the "newindex" event (see <a href="#2.4">§2.4</a>).
<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
<span class="apii">[-1, +0, <em>e</em>]</span>
<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
<p>
Pops a value from the stack and
sets it as the new value of global <code>name</code>.
<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
<span class="apii">[-1, +0, <em>e</em>]</span>
<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
<p>
Does the equivalent to <code>t[n] = v</code>,
where <code>t</code> is the value at the given index
and <code>v</code> is the value on the top of the stack.
<p>
This function pops the value from the stack.
As in Lua, this function may trigger a metamethod
for the "newindex" event (see <a href="#2.4">§2.4</a>).
<hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
<span class="apii">[-1, +0, –]</span>
<pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
<p>
Pops a value from the stack and sets it as
the new <code>n</code>-th user value associated to the
full userdata at the given index.
Returns 0 if the userdata does not have that value.
<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
<span class="apii">[-1, +0, –]</span>
<pre>int lua_setmetatable (lua_State *L, int index);</pre>
<p>
Pops a table from the stack and
sets it as the new metatable for the value at the given index.
<p>
(For historical reasons, this function returns an <code>int</code>,
which now is always 1.)
<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
<span class="apii">[-2, +0, <em>e</em>]</span>
<pre>void lua_settable (lua_State *L, int index);</pre>
<p>
Does the equivalent to <code>t[k] = v</code>,
where <code>t</code> is the value at the given index,
<code>v</code> is the value on the top of the stack,
and <code>k</code> is the value just below the top.
<p>
This function pops both the key and the value from the stack.
As in Lua, this function may trigger a metamethod
for the "newindex" event (see <a href="#2.4">§2.4</a>).
<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
<span class="apii">[-?, +?, –]</span>
<pre>void lua_settop (lua_State *L, int index);</pre>
<p>
Accepts any index, or 0,
and sets the stack top to this index.
If the new top is greater than the old one,
then the new elements are filled with <b>nil</b>.
If <code>index</code> is 0, then all stack elements are removed.
<hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
<p>
Sets the warning function to be used by Lua to emit warnings
(see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
The <code>ud</code> parameter sets the value <code>ud</code> passed to
the warning function.
<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
<pre>typedef struct lua_State lua_State;</pre>
<p>
An opaque structure that points to a thread and indirectly
(through the thread) to the whole state of a Lua interpreter.
The Lua library is fully reentrant:
it has no global variables.
All information about a state is accessible through this structure.
<p>
A pointer to this structure must be passed as the first argument to
every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
which creates a Lua state from scratch.
<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_status (lua_State *L);</pre>
<p>
Returns the status of the thread <code>L</code>.
<p>
The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
an error code if the thread finished the execution
of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
<p>
You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
(to resume a coroutine).
<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
<p>
Converts the zero-terminated string <code>s</code> to a number,
pushes that number into the stack,
and returns the total size of the string,
that is, its length plus one.
The conversion can result in an integer or a float,
according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>).
The string may have leading and trailing spaces and a sign.
If the string is not a valid numeral,
returns 0 and pushes nothing.
(Note that the result can be used as a boolean,
true if the conversion succeeds.)
<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_toboolean (lua_State *L, int index);</pre>
<p>
Converts the Lua value at the given index to a C boolean
value (0 or 1).
Like all tests in Lua,
<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
different from <b>false</b> and <b>nil</b>;
otherwise it returns false.
(If you want to accept only actual boolean values,
use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
<p>
Converts a value at the given index to a C function.
That value must be a C function;
otherwise, returns <code>NULL</code>.
<hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void lua_toclose (lua_State *L, int index);</pre>
<p>
Marks the given index in the stack as a
to-be-closed "variable" (see <a href="#3.3.8">§3.3.8</a>).
Like a to-be-closed variable in Lua,
the value at that index in the stack will be closed
when it goes out of scope.
Here, in the context of a C function,
to go out of scope means that the running function returns to Lua,
there is an error,
or the index is removed from the stack through
<a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>.
An index marked as to-be-closed should not be removed from the stack
by any other function in the API except <a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>.
<p>
This function should not be called for an index
that is equal to or below an active to-be-closed index.
<p>
This function can raise an out-of-memory error.
In that case, the value in the given index is immediately closed,
as if it was already marked.
<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
<p>
Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
<p>
Converts the Lua value at the given index
to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
The Lua value must be an integer,
or a number or string convertible to an integer (see <a href="#3.4.3">§3.4.3</a>);
otherwise, <code>lua_tointegerx</code> returns 0.
<p>
If <code>isnum</code> is not <code>NULL</code>,
its referent is assigned a boolean value that
indicates whether the operation succeeded.
<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
<span class="apii">[-0, +0, <em>m</em>]</span>
<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
<p>
Converts the Lua value at the given index to a C string.
If <code>len</code> is not <code>NULL</code>,
it sets <code>*len</code> with the string length.
The Lua value must be a string or a number;
otherwise, the function returns <code>NULL</code>.
If the value is a number,
then <code>lua_tolstring</code> also
<em>changes the actual value in the stack to a string</em>.
(This change confuses <a href="#lua_next"><code>lua_next</code></a>
when <code>lua_tolstring</code> is applied to keys during a table traversal.)
<p>
<code>lua_tolstring</code> returns a pointer
to a string inside the Lua state.
This string always has a zero ('<code>\0</code>')
after its last character (as in C),
but can contain other zeros in its body.
<p>
Because Lua has garbage collection,
there is no guarantee that the pointer returned by <code>lua_tolstring</code>
will be valid after the corresponding Lua value is removed from the stack.
<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
<p>
Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
<p>
Converts the Lua value at the given index
to the C type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
The Lua value must be a number or a string convertible to a number
(see <a href="#3.4.3">§3.4.3</a>);
otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns 0.
<p>
If <code>isnum</code> is not <code>NULL</code>,
its referent is assigned a boolean value that
indicates whether the operation succeeded.
<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>const void *lua_topointer (lua_State *L, int index);</pre>
<p>
Converts the value at the given index to a generic
C pointer (<code>void*</code>).
The value can be a userdata, a table, a thread, a string, or a function;
otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
Different objects will give different pointers.
There is no way to convert the pointer back to its original value.
<p>
Typically this function is used only for hashing and debug information.
<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
<span class="apii">[-0, +0, <em>m</em>]</span>
<pre>const char *lua_tostring (lua_State *L, int index);</pre>
<p>
Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
<p>
Converts the value at the given index to a Lua thread
(represented as <code>lua_State*</code>).
This value must be a thread;
otherwise, the function returns <code>NULL</code>.
<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void *lua_touserdata (lua_State *L, int index);</pre>
<p>
If the value at the given index is a full userdata,
returns its memory-block address.
If the value is a light userdata,
returns its value (a pointer).
Otherwise, returns <code>NULL</code>.
<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_type (lua_State *L, int index);</pre>
<p>
Returns the type of the value in the given valid index,
or <code>LUA_TNONE</code> for a non-valid but acceptable index.
The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
defined in <code>lua.h</code>:
<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
and
<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>const char *lua_typename (lua_State *L, int tp);</pre>
<p>
Returns the name of the type encoded by the value <code>tp</code>,
which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
<pre>typedef ... lua_Unsigned;</pre>
<p>
The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_upvalueindex (int i);</pre>
<p>
Returns the pseudo-index that represents the <code>i</code>-th upvalue of
the running function (see <a href="#4.4">§4.4</a>).
<code>i</code> must be in the range <em>[1,256]</em>.
<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Number lua_version (lua_State *L);</pre>
<p>
Returns the version number of this core.
<hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
<pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
<p>
The type of warning functions, called by Lua to emit warnings.
The first parameter is an opaque pointer
set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
The second parameter is the warning message.
The third parameter is a boolean that
indicates whether the message is
to be continued by the message in the next call.
<p>
See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
<hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
<p>
Emits a warning with the given message.
A message in a call with <code>tocont</code> true should be
continued in another call to this function.
<p>
See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
<pre>typedef int (*lua_Writer) (lua_State *L,
const void* p,
size_t sz,
void* ud);</pre>
<p>
The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
it calls the writer,
passing along the buffer to be written (<code>p</code>),
its size (<code>sz</code>),
and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
<p>
The writer returns an error code:
0 means no errors;
any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
calling the writer again.
<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
<span class="apii">[-?, +?, –]</span>
<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
<p>
Exchange values between different threads of the same state.
<p>
This function pops <code>n</code> values from the stack <code>from</code>,
and pushes them onto the stack <code>to</code>.
<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
<span class="apii">[-?, +?, <em>v</em>]</span>
<pre>int lua_yield (lua_State *L, int nresults);</pre>
<p>
This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
but it has no continuation (see <a href="#4.7">§4.7</a>).
Therefore, when the thread resumes,
it continues the function that called
the function calling <code>lua_yield</code>.
To avoid surprises,
this function should be called only in a tail call.
<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
<span class="apii">[-?, +?, <em>v</em>]</span>
<pre>int lua_yieldk (lua_State *L,
int nresults,
lua_KContext ctx,
lua_KFunction k);</pre>
<p>
Yields a coroutine (thread).
<p>
When a C function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
the running coroutine suspends its execution,
and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
The parameter <code>nresults</code> is the number of values from the stack
that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
<p>
When the coroutine is resumed again,
Lua calls the given continuation function <code>k</code> to continue
the execution of the C function that yielded (see <a href="#4.7">§4.7</a>).
This continuation function receives the same stack
from the previous function,
with the <code>n</code> results removed and
replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
Moreover,
the continuation function receives the value <code>ctx</code>
that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
<p>
Usually, this function does not return;
when the coroutine eventually resumes,
it continues executing the continuation function.
However, there is one special case,
which is when this function is called
from inside a line or a count hook (see <a href="#4.9">§4.9</a>).
In that case, <code>lua_yieldk</code> should be called with no continuation
(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
and the hook should return immediately after the call.
Lua will yield and,
when the coroutine resumes again,
it will continue the normal execution
of the (Lua) function that triggered the hook.
<p>
This function can raise an error if it is called from a thread
with a pending C call with no continuation function
(what is called a <em>C-call boundary</em>),
or it is called from a thread that is not running inside a resume
(typically the main thread).
<h2>4.9 – <a name="4.9">The Debug Interface</a></h2>
<p>
Lua has no built-in debugging facilities.
Instead, it offers a special interface
by means of functions and <em>hooks</em>.
This interface allows the construction of different
kinds of debuggers, profilers, and other tools
that need "inside information" from the interpreter.
<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
<pre>typedef struct lua_Debug {
int event;
const char *name; /* (n) */
const char *namewhat; /* (n) */
const char *what; /* (S) */
const char *source; /* (S) */
size_t srclen; /* (S) */
int currentline; /* (l) */
int linedefined; /* (S) */
int lastlinedefined; /* (S) */
unsigned char nups; /* (u) number of upvalues */
unsigned char nparams; /* (u) number of parameters */
char isvararg; /* (u) */
char istailcall; /* (t) */
unsigned short ftransfer; /* (r) index of first value transferred */
unsigned short ntransfer; /* (r) number of transferred values */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */
<em>other fields</em>
} lua_Debug;</pre>
<p>
A structure used to carry different pieces of
information about a function or an activation record.
<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
of this structure, for later use.
To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
<p>
The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
<ul>
<li><b><code>source</code>: </b>
the source of the chunk that created the function.
If <code>source</code> starts with a '<code>@</code>',
it means that the function was defined in a file where
the file name follows the '<code>@</code>'.
If <code>source</code> starts with a '<code>=</code>',
the remainder of its contents describe the source in a user-dependent manner.
Otherwise,
the function was defined in a string where
<code>source</code> is that string.
</li>
<li><b><code>srclen</code>: </b>
The length of the string <code>source</code>.
</li>
<li><b><code>short_src</code>: </b>
a "printable" version of <code>source</code>, to be used in error messages.
</li>
<li><b><code>linedefined</code>: </b>
the line number where the definition of the function starts.
</li>
<li><b><code>lastlinedefined</code>: </b>
the line number where the definition of the function ends.
</li>
<li><b><code>what</code>: </b>
the string <code>"Lua"</code> if the function is a Lua function,
<code>"C"</code> if it is a C function,
<code>"main"</code> if it is the main part of a chunk.
</li>
<li><b><code>currentline</code>: </b>
the current line where the given function is executing.
When no line information is available,
<code>currentline</code> is set to -1.
</li>
<li><b><code>name</code>: </b>
a reasonable name for the given function.
Because functions in Lua are first-class values,
they do not have a fixed name:
some functions can be the value of multiple global variables,
while others can be stored only in a table field.
The <code>lua_getinfo</code> function checks how the function was
called to find a suitable name.
If it cannot find a name,
then <code>name</code> is set to <code>NULL</code>.
</li>
<li><b><code>namewhat</code>: </b>
explains the <code>name</code> field.
The value of <code>namewhat</code> can be
<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
according to how the function was called.
(Lua uses the empty string when no other option seems to apply.)
</li>
<li><b><code>istailcall</code>: </b>
true if this function invocation was called by a tail call.
In this case, the caller of this level is not in the stack.
</li>
<li><b><code>nups</code>: </b>
the number of upvalues of the function.
</li>
<li><b><code>nparams</code>: </b>
the number of parameters of the function
(always 0 for C functions).
</li>
<li><b><code>isvararg</code>: </b>
true if the function is a vararg function
(always true for C functions).
</li>
<li><b><code>ftransfer</code>: </b>
the index on the stack of the first value being "transferred",
that is, parameters in a call or return values in a return.
(The other values are in consecutive indices.)
Using this index, you can access and modify these values
through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
This field is only meaningful during a
call hook, denoting the first parameter,
or a return hook, denoting the first value being returned.
(For call hooks, this value is always 1.)
</li>
<li><b><code>ntransfer</code>: </b>
The number of values being transferred (see previous item).
(For calls of Lua functions,
this value is always equal to <code>nparams</code>.)
</li>
</ul>
<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_Hook lua_gethook (lua_State *L);</pre>
<p>
Returns the current hook function.
<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_gethookcount (lua_State *L);</pre>
<p>
Returns the current hook count.
<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_gethookmask (lua_State *L);</pre>
<p>
Returns the current hook mask.
<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
<span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
<p>
Gets information about a specific function or function invocation.
<p>
To get information about a function invocation,
the parameter <code>ar</code> must be a valid activation record that was
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
<p>
To get information about a function, you push it onto the stack
and start the <code>what</code> string with the character '<code>></code>'.
(In that case,
<code>lua_getinfo</code> pops the function from the top of the stack.)
For instance, to know in which line a function <code>f</code> was defined,
you can write the following code:
<pre>
lua_Debug ar;
lua_getglobal(L, "f"); /* get global 'f' */
lua_getinfo(L, ">S", &ar);
printf("%d\n", ar.linedefined);
</pre>
<p>
Each character in the string <code>what</code>
selects some fields of the structure <code>ar</code> to be filled or
a value to be pushed on the stack:
<ul>
<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
</li>
<li><b>'<code>S</code>': </b>
fills in the fields <code>source</code>, <code>short_src</code>,
<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
</li>
<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
</li>
<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
</li>
<li><b>'<code>u</code>': </b> fills in the fields
<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
</li>
<li><b>'<code>f</code>': </b>
pushes onto the stack the function that is
running at the given level;
</li>
<li><b>'<code>L</code>': </b>
pushes onto the stack a table whose indices are the
numbers of the lines that are valid on the function.
(A <em>valid line</em> is a line with some associated code,
that is, a line where you can put a break point.
Non-valid lines include empty lines and comments.)
<p>
If this option is given together with option '<code>f</code>',
its table is pushed after the function.
<p>
This is the only option that can raise a memory error.
</li>
</ul>
<p>
This function returns 0 to signal an invalid option in <code>what</code>;
even then the valid options are handled correctly.
<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
<span class="apii">[-0, +(0|1), –]</span>
<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
<p>
Gets information about a local variable or a temporary value
of a given activation record or a given function.
<p>
In the first case,
the parameter <code>ar</code> must be a valid activation record that was
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
The index <code>n</code> selects which local variable to inspect;
see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
and names.
<p>
<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
and returns its name.
<p>
In the second case, <code>ar</code> must be <code>NULL</code> and the function
to be inspected must be on the top of the stack.
In this case, only parameters of Lua functions are visible
(as there is no information about what variables are active)
and no values are pushed onto the stack.
<p>
Returns <code>NULL</code> (and pushes nothing)
when the index is greater than
the number of active local variables.
<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
<p>
Gets information about the interpreter runtime stack.
<p>
This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
an identification of the <em>activation record</em>
of the function executing at a given level.
Level 0 is the current running function,
whereas level <em>n+1</em> is the function that has called level <em>n</em>
(except for tail calls, which do not count on the stack).
When called with a level greater than the stack depth,
<a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
otherwise it returns 1.
<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
<span class="apii">[-0, +(0|1), –]</span>
<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
<p>
Gets information about the <code>n</code>-th upvalue
of the closure at index <code>funcindex</code>.
It pushes the upvalue's value onto the stack
and returns its name.
Returns <code>NULL</code> (and pushes nothing)
when the index <code>n</code> is greater than the number of upvalues.
<p>
See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
<p>
Type for debugging hook functions.
<p>
Whenever a hook is called, its <code>ar</code> argument has its field
<code>event</code> set to the specific event that triggered the hook.
Lua identifies these events with the following constants:
<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
Moreover, for line events, the field <code>currentline</code> is also set.
To get the value of any other field in <code>ar</code>,
the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
<p>
For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
in this case, there will be no corresponding return event.
<p>
While Lua is running a hook, it disables other calls to hooks.
Therefore, if a hook calls back Lua to execute a function or a chunk,
this execution occurs without any calls to hooks.
<p>
Hook functions cannot have continuations,
that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
<a href="#lua_pcallk"><code>lua_pcallk</code></a>, or <a href="#lua_callk"><code>lua_callk</code></a> with a non-null <code>k</code>.
<p>
Hook functions can yield under the following conditions:
Only count and line events can yield;
to yield, a hook function must finish its execution
calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
(that is, with no values).
<hr><h3><a name="lua_setcstacklimit"><code>lua_setcstacklimit</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>int (lua_setcstacklimit) (lua_State *L, unsigned int limit);</pre>
<p>
Sets a new limit for the C stack.
This limit controls how deeply nested calls can go in Lua,
with the intent of avoiding a stack overflow.
Returns the old limit in case of success,
or zero in case of error.
For more details about this function,
see <a href="#pdf-debug.setcstacklimit"><code>debug.setcstacklimit</code></a>,
its equivalent in the standard library.
<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
<p>
Sets the debugging hook function.
<p>
Argument <code>f</code> is the hook function.
<code>mask</code> specifies on which events the hook will be called:
it is formed by a bitwise OR of the constants
<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
The <code>count</code> argument is only meaningful when the mask
includes <code>LUA_MASKCOUNT</code>.
For each event, the hook is called as explained below:
<ul>
<li><b>The call hook: </b> is called when the interpreter calls a function.
The hook is called just after Lua enters the new function,
before the function gets its arguments.
</li>
<li><b>The return hook: </b> is called when the interpreter returns from a function.
The hook is called just before Lua leaves the function.
</li>
<li><b>The line hook: </b> is called when the interpreter is about to
start the execution of a new line of code,
or when it jumps back in the code (even to the same line).
This event only happens while Lua is executing a Lua function.
</li>
<li><b>The count hook: </b> is called after the interpreter executes every
<code>count</code> instructions.
This event only happens while Lua is executing a Lua function.
</li>
</ul>
<p>
Hooks are disabled by setting <code>mask</code> to zero.
<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
<span class="apii">[-(0|1), +0, –]</span>
<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
<p>
Sets the value of a local variable of a given activation record.
It assigns the value on the top of the stack
to the variable and returns its name.
It also pops the value from the stack.
<p>
Returns <code>NULL</code> (and pops nothing)
when the index is greater than
the number of active local variables.
<p>
Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
<span class="apii">[-(0|1), +0, –]</span>
<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
<p>
Sets the value of a closure's upvalue.
It assigns the value on the top of the stack
to the upvalue and returns its name.
It also pops the value from the stack.
<p>
Returns <code>NULL</code> (and pops nothing)
when the index <code>n</code> is greater than the number of upvalues.
<p>
Parameters <code>funcindex</code> and <code>n</code> are as in
the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
<p>
Returns a unique identifier for the upvalue numbered <code>n</code>
from the closure at index <code>funcindex</code>.
<p>
These unique identifiers allow a program to check whether different
closures share upvalues.
Lua closures that share an upvalue
(that is, that access a same external local variable)
will return identical ids for those upvalue indices.
<p>
Parameters <code>funcindex</code> and <code>n</code> are as in
the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
but <code>n</code> cannot be greater than the number of upvalues.
<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
int funcindex2, int n2);</pre>
<p>
Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
<h1>5 – <a name="5">The Auxiliary Library</a></h1>
<p>
The <em>auxiliary library</em> provides several convenient functions
to interface C with Lua.
While the basic API provides the primitive functions for all
interactions between C and Lua,
the auxiliary library provides higher-level functions for some
common tasks.
<p>
All functions and types from the auxiliary library
are defined in header file <code>lauxlib.h</code> and
have a prefix <code>luaL_</code>.
<p>
All functions in the auxiliary library are built on
top of the basic API,
and so they provide nothing that cannot be done with that API.
Nevertheless, the use of the auxiliary library ensures
more consistency to your code.
<p>
Several functions in the auxiliary library use internally some
extra stack slots.
When a function in the auxiliary library uses less than five slots,
it does not check the stack size;
it simply assumes that there are enough slots.
<p>
Several functions in the auxiliary library are used to
check C function arguments.
Because the error message is formatted for arguments
(e.g., "<code>bad argument #1</code>"),
you should not use these functions for other stack values.
<p>
Functions called <code>luaL_check*</code>
always raise an error if the check is not satisfied.
<h2>5.1 – <a name="5.1">Functions and Types</a></h2>
<p>
Here we list all functions and types from the auxiliary library
in alphabetical order.
<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
<p>
Adds the byte <code>c</code> to the buffer <code>B</code>
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
<span class="apii">[-0, +0, <em>m</em>]</span>
<pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
const char *p, const char *r);</pre>
<p>
Adds a copy of the string <code>s</code> to the buffer <code>B</code>,
replacing any occurrence of the string <code>p</code>
with the string <code>r</code>.
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
<p>
Adds the string pointed to by <code>s</code> with length <code>l</code> to
the buffer <code>B</code>
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
The string can contain embedded zeros.
<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
<span class="apii">[-?, +?, –]</span>
<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
<p>
Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
a string of length <code>n</code> previously copied to the
buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
<p>
Adds the zero-terminated string pointed to by <code>s</code>
to the buffer <code>B</code>
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
<span class="apii">[-1, +?, <em>m</em>]</span>
<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
<p>
Adds the value on the top of the stack
to the buffer <code>B</code>
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
Pops the value.
<p>
This is the only function on string buffers that can (and must)
be called with an extra element on the stack,
which is the value to be added to the buffer.
<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_argcheck (lua_State *L,
int cond,
int arg,
const char *extramsg);</pre>
<p>
Checks whether <code>cond</code> is true.
If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
<p>
Raises an error reporting a problem with argument <code>arg</code>
of the C function that called it,
using a standard message
that includes <code>extramsg</code> as a comment:
<pre>
bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
</pre><p>
This function never returns.
<hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_argexpected (lua_State *L,
int cond,
int arg,
const char *tname);</pre>
<p>
Checks whether <code>cond</code> is true.
If it is not, raises an error about the type of the argument <code>arg</code>
with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
<p>
Type for a <em>string buffer</em>.
<p>
A string buffer allows C code to build Lua strings piecemeal.
Its pattern of use is as follows:
<ul>
<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
<li>Then initialize it with a call <code>luaL_buffinit(L, &b)</code>.</li>
<li>
Then add string pieces to the buffer calling any of
the <code>luaL_add*</code> functions.
</li>
<li>
Finish by calling <code>luaL_pushresult(&b)</code>.
This call leaves the final string on the top of the stack.
</li>
</ul>
<p>
If you know beforehand the maximum size of the resulting string,
you can use the buffer like this:
<ul>
<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
<li>Then initialize it and preallocate a space of
size <code>sz</code> with a call <code>luaL_buffinitsize(L, &b, sz)</code>.</li>
<li>Then produce the string into that space.</li>
<li>
Finish by calling <code>luaL_pushresultsize(&b, sz)</code>,
where <code>sz</code> is the total size of the resulting string
copied into that space (which may be less than or
equal to the preallocated size).
</li>
</ul>
<p>
During its normal operation,
a string buffer uses a variable number of stack slots.
So, while using a buffer, you cannot assume that you know where
the top of the stack is.
You can use the stack between successive calls to buffer operations
as long as that use is balanced;
that is,
when you call a buffer operation,
the stack is at the same level
it was immediately after the previous buffer operation.
(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
the stack is back to its level when the buffer was initialized,
plus the final string on its top.
<hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
<p>
Returns the address of the current contents of buffer <code>B</code>.
Note that any addition to the buffer may invalidate this address.
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
<p>
Initializes a buffer <code>B</code>.
This function does not allocate any space;
the buffer must be declared as a variable
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
<p>
Returns the length of the current contents of buffer <code>B</code>.
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
<p>
Equivalent to the sequence
<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
<span class="apii">[-0, +(0|1), <em>e</em>]</span>
<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
<p>
Calls a metamethod.
<p>
If the object at index <code>obj</code> has a metatable and this
metatable has a field <code>e</code>,
this function calls this field passing the object as its only argument.
In this case this function returns true and pushes onto the
stack the value returned by the call.
If there is no metatable or no metamethod,
this function returns false without pushing any value on the stack.
<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_checkany (lua_State *L, int arg);</pre>
<p>
Checks whether the function has an argument
of any type (including <b>nil</b>) at position <code>arg</code>.
<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
<p>
Checks whether the function argument <code>arg</code> is an integer
(or can be converted to an integer)
and returns this integer.
<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
<p>
Checks whether the function argument <code>arg</code> is a string
and returns this string;
if <code>l</code> is not <code>NULL</code> fills its referent
with the string's length.
<p>
This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
so all conversions and caveats of that function apply here.
<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
<p>
Checks whether the function argument <code>arg</code> is a number
and returns this number converted to a <code>lua_Number</code>.
<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>int luaL_checkoption (lua_State *L,
int arg,
const char *def,
const char *const lst[]);</pre>
<p>
Checks whether the function argument <code>arg</code> is a string and
searches for this string in the array <code>lst</code>
(which must be NULL-terminated).
Returns the index in the array where the string was found.
Raises an error if the argument is not a string or
if the string cannot be found.
<p>
If <code>def</code> is not <code>NULL</code>,
the function uses <code>def</code> as a default value when
there is no argument <code>arg</code> or when this argument is <b>nil</b>.
<p>
This is a useful function for mapping strings to C enums.
(The usual convention in Lua libraries is
to use strings instead of numbers to select options.)
<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
<p>
Grows the stack size to <code>top + sz</code> elements,
raising an error if the stack cannot grow to that size.
<code>msg</code> is an additional text to go into the error message
(or <code>NULL</code> for no additional text).
<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
<p>
Checks whether the function argument <code>arg</code> is a string
and returns this string.
<p>
This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
so all conversions and caveats of that function apply here.
<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
<p>
Checks whether the function argument <code>arg</code> has type <code>t</code>.
See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
<p>
Checks whether the function argument <code>arg</code> is a userdata
of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>void luaL_checkversion (lua_State *L);</pre>
<p>
Checks whether the code making the call and the Lua library being called
are using the same version of Lua and the same numeric types.
<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
<span class="apii">[-0, +?, <em>m</em>]</span>
<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
<p>
Loads and runs the given file.
It is defined as the following macro:
<pre>
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
</pre><p>
It returns false if there are no errors
or true in case of errors.
<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
<span class="apii">[-0, +?, –]</span>
<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
<p>
Loads and runs the given string.
It is defined as the following macro:
<pre>
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
</pre><p>
It returns false if there are no errors
or true in case of errors.
<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
<p>
Raises an error.
The error message format is given by <code>fmt</code>
plus any extra arguments,
following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
It also adds at the beginning of the message the file name and
the line number where the error occurred,
if this information is available.
<p>
This function never returns,
but it is an idiom to use it in C functions
as <code>return luaL_error(<em>args</em>)</code>.
<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
<span class="apii">[-0, +3, <em>m</em>]</span>
<pre>int luaL_execresult (lua_State *L, int stat);</pre>
<p>
This function produces the return values for
process-related functions in the standard library
(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
<span class="apii">[-0, +(1|3), <em>m</em>]</span>
<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
<p>
This function produces the return values for
file-related functions in the standard library
(<a href="#pdf-io.open"><code>io.open</code></a>, <a href="#pdf-os.rename"><code>os.rename</code></a>, <a href="#pdf-file:seek"><code>file:seek</code></a>, etc.).
<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
<span class="apii">[-0, +(0|1), <em>m</em>]</span>
<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
<p>
Pushes onto the stack the field <code>e</code> from the metatable
of the object at index <code>obj</code> and returns the type of the pushed value.
If the object does not have a metatable,
or if the metatable does not have this field,
pushes nothing and returns <code>LUA_TNIL</code>.
<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
<p>
Pushes onto the stack the metatable associated with the name <code>tname</code>
in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
or <b>nil</b> if there is no metatable associated with that name.
Returns the type of the pushed value.
<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
<p>
Ensures that the value <code>t[fname]</code>,
where <code>t</code> is the value at index <code>idx</code>,
is a table,
and pushes that table onto the stack.
Returns true if it finds a previous table there
and false if it creates a new table.
<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>const char *luaL_gsub (lua_State *L,
const char *s,
const char *p,
const char *r);</pre>
<p>
Creates a copy of string <code>s</code>,
replacing any occurrence of the string <code>p</code>
with the string <code>r</code>.
Pushes the resulting string on the stack and returns it.
<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
<span class="apii">[-0, +0, <em>e</em>]</span>
<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
<p>
Returns the "length" of the value at the given index
as a number;
it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>).
Raises an error if the result of the operation is not an integer.
(This case can only happen through metamethods.)
<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int luaL_loadbuffer (lua_State *L,
const char *buff,
size_t sz,
const char *name);</pre>
<p>
Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int luaL_loadbufferx (lua_State *L,
const char *buff,
size_t sz,
const char *name,
const char *mode);</pre>
<p>
Loads a buffer as a Lua chunk.
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
buffer pointed to by <code>buff</code> with size <code>sz</code>.
<p>
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
<code>name</code> is the chunk name,
used for debug information and error messages.
The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
<p>
Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>int luaL_loadfilex (lua_State *L, const char *filename,
const char *mode);</pre>
<p>
Loads a file as a Lua chunk.
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
named <code>filename</code>.
If <code>filename</code> is <code>NULL</code>,
then it loads from the standard input.
The first line in the file is ignored if it starts with a <code>#</code>.
<p>
The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
<p>
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
for file-related errors
(e.g., it cannot open or read the file).
<p>
As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
it does not run it.
<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
<span class="apii">[-0, +1, –]</span>
<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
<p>
Loads a string as a Lua chunk.
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
the zero-terminated string <code>s</code>.
<p>
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
<p>
Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
it does not run it.
<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
<p>
Creates a new table and registers there
the functions in the list <code>l</code>.
<p>
It is implemented as the following macro:
<pre>
(luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
</pre><p>
The array <code>l</code> must be the actual array,
not a pointer to it.
<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
<p>
Creates a new table with a size optimized
to store all entries in the array <code>l</code>
(but does not actually store them).
It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
<p>
It is implemented as a macro.
The array <code>l</code> must be the actual array,
not a pointer to it.
<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
<p>
If the registry already has the key <code>tname</code>,
returns 0.
Otherwise,
creates a new table to be used as a metatable for userdata,
adds to this new table the pair <code>__name = tname</code>,
adds to the registry the pair <code>[tname] = new table</code>,
and returns 1.
<p>
In both cases,
the function pushes onto the stack the final value associated
with <code>tname</code> in the registry.
<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>lua_State *luaL_newstate (void);</pre>
<p>
Creates a new Lua state.
It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
allocator based on the standard C allocation functions
and then sets a warning function and a panic function (see <a href="#4.6">§4.6</a>)
that print messages to the standard error output.
<p>
Returns the new state,
or <code>NULL</code> if there is a memory allocation error.
<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
<span class="apii">[-0, +0, <em>e</em>]</span>
<pre>void luaL_openlibs (lua_State *L);</pre>
<p>
Opens all standard Lua libraries into the given state.
<hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>T luaL_opt (L, func, arg, dflt);</pre>
<p>
This macro is defined as follows:
<pre>
(lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
</pre><p>
In words, if the argument <code>arg</code> is nil or absent,
the macro results in the default <code>dflt</code>.
Otherwise, it results in the result of calling <code>func</code>
with the state <code>L</code> and the argument index <code>arg</code> as
arguments.
Note that it evaluates the expression <code>dflt</code> only if needed.
<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>lua_Integer luaL_optinteger (lua_State *L,
int arg,
lua_Integer d);</pre>
<p>
If the function argument <code>arg</code> is an integer
(or it is convertible to an integer),
returns this integer.
If this argument is absent or is <b>nil</b>,
returns <code>d</code>.
Otherwise, raises an error.
<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>const char *luaL_optlstring (lua_State *L,
int arg,
const char *d,
size_t *l);</pre>
<p>
If the function argument <code>arg</code> is a string,
returns this string.
If this argument is absent or is <b>nil</b>,
returns <code>d</code>.
Otherwise, raises an error.
<p>
If <code>l</code> is not <code>NULL</code>,
fills its referent with the result's length.
If the result is <code>NULL</code>
(only possible when returning <code>d</code> and <code>d == NULL</code>),
its length is considered zero.
<p>
This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
so all conversions and caveats of that function apply here.
<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
<p>
If the function argument <code>arg</code> is a number,
returns this number as a <code>lua_Number</code>.
If this argument is absent or is <b>nil</b>,
returns <code>d</code>.
Otherwise, raises an error.
<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>const char *luaL_optstring (lua_State *L,
int arg,
const char *d);</pre>
<p>
If the function argument <code>arg</code> is a string,
returns this string.
If this argument is absent or is <b>nil</b>,
returns <code>d</code>.
Otherwise, raises an error.
<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
<p>
Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
<span class="apii">[-?, +?, <em>m</em>]</span>
<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
<p>
Returns an address to a space of size <code>sz</code>
where you can copy a string to be added to buffer <code>B</code>
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
After copying the string into this space you must call
<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
it to the buffer.
<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
<span class="apii">[-?, +1, <em>m</em>]</span>
<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
<p>
Finishes the use of buffer <code>B</code> leaving the final string on
the top of the stack.
<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
<span class="apii">[-?, +1, <em>m</em>]</span>
<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
<p>
Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
<span class="apii">[-1, +0, <em>m</em>]</span>
<pre>int luaL_ref (lua_State *L, int t);</pre>
<p>
Creates and returns a <em>reference</em>,
in the table at index <code>t</code>,
for the object on the top of the stack (and pops the object).
<p>
A reference is a unique integer key.
As long as you do not manually add integer keys into the table <code>t</code>,
<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
You can retrieve an object referred by the reference <code>r</code>
by calling <code>lua_rawgeti(L, t, r)</code>.
The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
<p>
If the object on the top of the stack is <b>nil</b>,
<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
<pre>typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;</pre>
<p>
Type for arrays of functions to be registered by
<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
<code>name</code> is the function name and <code>func</code> is a pointer to
the function.
Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>void luaL_requiref (lua_State *L, const char *modname,
lua_CFunction openf, int glb);</pre>
<p>
If <code>package.loaded[modname]</code> is not true,
calls the function <code>openf</code> with the string <code>modname</code> as an argument
and sets the call result to <code>package.loaded[modname]</code>,
as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
<p>
If <code>glb</code> is true,
also stores the module into the global <code>modname</code>.
<p>
Leaves a copy of the module on the stack.
<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
<span class="apii">[-nup, +0, <em>m</em>]</span>
<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
<p>
Registers all functions in the array <code>l</code>
(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
(below optional upvalues, see next).
<p>
When <code>nup</code> is not zero,
all functions are created with <code>nup</code> upvalues,
initialized with copies of the <code>nup</code> values
previously pushed on the stack
on top of the library table.
These values are popped from the stack after the registration.
<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
<p>
Sets the metatable of the object on the top of the stack
as the metatable associated with name <code>tname</code>
in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
<pre>typedef struct luaL_Stream {
FILE *f;
lua_CFunction closef;
} luaL_Stream;</pre>
<p>
The standard representation for file handles
used by the standard I/O library.
<p>
A file handle is implemented as a full userdata,
with a metatable called <code>LUA_FILEHANDLE</code>
(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
The metatable is created by the I/O library
(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
<p>
This userdata must start with the structure <code>luaL_Stream</code>;
it can contain other data after this initial structure.
The field <code>f</code> points to the corresponding C stream
(or it can be <code>NULL</code> to indicate an incompletely created handle).
The field <code>closef</code> points to a Lua function
that will be called to close the stream
when the handle is closed or collected;
this function receives the file handle as its sole argument and
must return either <b>true</b>, in case of success,
or a false value plus an error message, in case of error.
Once Lua calls this field,
it changes the field value to <code>NULL</code>
to signal that the handle is closed.
<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
<span class="apii">[-0, +0, <em>m</em>]</span>
<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
<p>
This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
except that, when the test fails,
it returns <code>NULL</code> instead of raising an error.
<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
<span class="apii">[-0, +1, <em>e</em>]</span>
<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
<p>
Converts any Lua value at the given index to a C string
in a reasonable format.
The resulting string is pushed onto the stack and also
returned by the function.
If <code>len</code> is not <code>NULL</code>,
the function also sets <code>*len</code> with the string length.
<p>
If the value has a metatable with a <code>__tostring</code> field,
then <code>luaL_tolstring</code> calls the corresponding metamethod
with the value as argument,
and uses the result of the call as its result.
<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
int level);</pre>
<p>
Creates and pushes a traceback of the stack <code>L1</code>.
If <code>msg</code> is not <code>NULL</code>, it is appended
at the beginning of the traceback.
The <code>level</code> parameter tells at which level
to start the traceback.
<hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
<span class="apii">[-0, +0, <em>v</em>]</span>
<pre>const char *luaL_typeerror (lua_State *L,
int arg,
const char *tname);</pre>
<p>
Raises a type error for the argument <code>arg</code>
of the C function that called it,
using a standard message;
<code>tname</code> is a "name" for the expected type.
This function never returns.
<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>const char *luaL_typename (lua_State *L, int index);</pre>
<p>
Returns the name of the type of the value at the given index.
<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
<span class="apii">[-0, +0, –]</span>
<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
<p>
Releases the reference <code>ref</code> from the table at index <code>t</code>
(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
The entry is removed from the table,
so that the referred object can be collected.
The reference <code>ref</code> is also freed to be used again.
<p>
If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>,
<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
<span class="apii">[-0, +1, <em>m</em>]</span>
<pre>void luaL_where (lua_State *L, int lvl);</pre>
<p>
Pushes onto the stack a string identifying the current position
of the control at level <code>lvl</code> in the call stack.
Typically this string has the following format:
<pre>
<em>chunkname</em>:<em>currentline</em>:
</pre><p>
Level 0 is the running function,
level 1 is the function that called the running function,
etc.
<p>
This function is used to build a prefix for error messages.
<h1>6 – <a name="6">The Standard Libraries</a></h1>
<p>
The standard Lua libraries provide useful functions
that are implemented in C through the C API.
Some of these functions provide essential services to the language
(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
others provide access to outside services (e.g., I/O);
and others could be implemented in Lua itself,
but that for different reasons
deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
<p>
All libraries are implemented through the official C API
and are provided as separate C modules.
Unless otherwise noted,
these library functions do not adjust its number of arguments
to its expected parameters.
For instance, a function documented as <code>foo(arg)</code>
should not be called without an argument.
<p>
The notation <b>fail</b> means a return value representing
some kind of failure or the absence of a better value to return.
Currently, <b>fail</b> is equal to <b>nil</b>,
but that may change in future versions.
The recommendation is to always test the success of these functions
with <code>(not status)</code>, instead of <code>(status == nil)</code>.
<p>
Currently, Lua has the following standard libraries:
<ul>
<li>basic library (<a href="#6.1">§6.1</a>);</li>
<li>coroutine library (<a href="#6.2">§6.2</a>);</li>
<li>package library (<a href="#6.3">§6.3</a>);</li>
<li>string manipulation (<a href="#6.4">§6.4</a>);</li>
<li>basic UTF-8 support (<a href="#6.5">§6.5</a>);</li>
<li>table manipulation (<a href="#6.6">§6.6</a>);</li>
<li>mathematical functions (<a href="#6.7">§6.7</a>) (sin, log, etc.);</li>
<li>input and output (<a href="#6.8">§6.8</a>);</li>
<li>operating system facilities (<a href="#6.9">§6.9</a>);</li>
<li>debug facilities (<a href="#6.10">§6.10</a>).</li>
</ul><p>
Except for the basic and the package libraries,
each library provides all its functions as fields of a global table
or as methods of its objects.
<p>
To have access to these libraries,
the C host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
which opens all standard libraries.
Alternatively,
the host program can open them individually by using
<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
<h2>6.1 – <a name="6.1">Basic Functions</a></h2>
<p>
The basic library provides core functions to Lua.
If you do not include this library in your application,
you should check carefully whether you need to provide
implementations for some of its facilities.
<p>
<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
<p>
Calls <a href="#pdf-error"><code>error</code></a> if
the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
otherwise, returns all its arguments.
In case of error,
<code>message</code> is the error object;
when absent, it defaults to "<code>assertion failed!</code>"
<p>
<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
<p>
This function is a generic interface to the garbage collector.
It performs different functions according to its first argument, <code>opt</code>:
<ul>
<li><b>"<code>collect</code>": </b>
Performs a full garbage-collection cycle.
This is the default option.
</li>
<li><b>"<code>stop</code>": </b>
Stops automatic execution of the garbage collector.
The collector will run only when explicitly invoked,
until a call to restart it.
</li>
<li><b>"<code>restart</code>": </b>
Restarts automatic execution of the garbage collector.
</li>
<li><b>"<code>count</code>": </b>
Returns the total memory in use by Lua in Kbytes.
The value has a fractional part,
so that it multiplied by 1024
gives the exact number of bytes in use by Lua.
</li>
<li><b>"<code>step</code>": </b>
Performs a garbage-collection step.
The step "size" is controlled by <code>arg</code>.
With a zero value,
the collector will perform one basic (indivisible) step.
For non-zero values,
the collector will perform as if that amount of memory
(in Kbytes) had been allocated by Lua.
Returns <b>true</b> if the step finished a collection cycle.
</li>
<li><b>"<code>isrunning</code>": </b>
Returns a boolean that tells whether the collector is running
(i.e., not stopped).
</li>
<li><b>"<code>incremental</code>": </b>
Change the collector mode to incremental.
This option can be followed by three numbers:
the garbage-collector pause,
the step multiplier,
and the step size (see <a href="#2.5.1">§2.5.1</a>).
A zero means to not change that value.
</li>
<li><b>"<code>generational</code>": </b>
Change the collector mode to generational.
This option can be followed by two numbers:
the garbage-collector minor multiplier
and the major multiplier (see <a href="#2.5.2">§2.5.2</a>).
A zero means to not change that value.
</li>
</ul><p>
See <a href="#2.5">§2.5</a> for more details about garbage collection
and some of these options.
<p>
<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
Opens the named file and executes its contents as a Lua chunk.
When called without arguments,
<code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
Returns all values returned by the chunk.
In case of errors, <code>dofile</code> propagates the error
to its caller.
(That is, <code>dofile</code> does not run in protected mode.)
<p>
<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
Terminates the last protected function called
and returns <code>message</code> as the error object.
This function never returns.
<p>
Usually, <code>error</code> adds some information about the error position
at the beginning of the message, if the message is a string.
The <code>level</code> argument specifies how to get the error position.
With level 1 (the default), the error position is where the
<code>error</code> function was called.
Level 2 points the error to where the function
that called <code>error</code> was called; and so on.
Passing a level 0 avoids the addition of error position information
to the message.
<p>
<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
A global variable (not a function) that
holds the global environment (see <a href="#2.2">§2.2</a>).
Lua itself does not use this variable;
changing its value does not affect any environment,
nor vice versa.
<p>
<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
<p>
If <code>object</code> does not have a metatable, returns <b>nil</b>.
Otherwise,
if the object's metatable has a <code>__metatable</code> field,
returns the associated value.
Otherwise, returns the metatable of the given object.
<p>
<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
<p>
Returns three values (an iterator function, the table <code>t</code>, and 0)
so that the construction
<pre>
for i,v in ipairs(t) do <em>body</em> end
</pre><p>
will iterate over the key–value pairs
(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
up to the first absent index.
<p>
<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
<p>
Loads a chunk.
<p>
If <code>chunk</code> is a string, the chunk is this string.
If <code>chunk</code> is a function,
<code>load</code> calls it repeatedly to get the chunk pieces.
Each call to <code>chunk</code> must return a string that concatenates
with previous results.
A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
<p>
If there are no syntactic errors,
<code>load</code> returns the compiled chunk as a function;
otherwise, it returns <b>fail</b> plus the error message.
<p>
When you load a main chunk,
the resulting function will always have exactly one upvalue,
the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>).
However,
when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
the resulting function can have an arbitrary number of upvalues,
and there is no guarantee that its first upvalue will be
the <code>_ENV</code> variable.
(A non-main function may not even have an <code>_ENV</code> upvalue.)
<p>
Regardless, if the resulting function has any upvalues,
its first upvalue is set to the value of <code>env</code>,
if that parameter is given,
or to the value of the global environment.
Other upvalues are initialized with <b>nil</b>.
All upvalues are fresh, that is,
they are not shared with any other function.
<p>
<code>chunkname</code> is used as the name of the chunk for error messages
and debug information (see <a href="#4.9">§4.9</a>).
When absent,
it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
or to "<code>=(load)</code>" otherwise.
<p>
The string <code>mode</code> controls whether the chunk can be text or binary
(that is, a precompiled chunk).
It may be the string "<code>b</code>" (only binary chunks),
"<code>t</code>" (only text chunks),
or "<code>bt</code>" (both binary and text).
The default is "<code>bt</code>".
<p>
Lua does not check the consistency of binary chunks.
Maliciously crafted binary chunks can crash
the interpreter.
<p>
<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
<p>
Similar to <a href="#pdf-load"><code>load</code></a>,
but gets the chunk from file <code>filename</code>
or from the standard input,
if no file name is given.
<p>
<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
<p>
Allows a program to traverse all fields of a table.
Its first argument is a table and its second argument
is an index in this table.
A call to <code>next</code> returns the next index of the table
and its associated value.
When called with <b>nil</b> as its second argument,
<code>next</code> returns an initial index
and its associated value.
When called with the last index,
or with <b>nil</b> in an empty table,
<code>next</code> returns <b>nil</b>.
If the second argument is absent, then it is interpreted as <b>nil</b>.
In particular,
you can use <code>next(t)</code> to check whether a table is empty.
<p>
The order in which the indices are enumerated is not specified,
<em>even for numeric indices</em>.
(To traverse a table in numerical order,
use a numerical <b>for</b>.)
<p>
The behavior of <code>next</code> is undefined if,
during the traversal,
you assign any value to a non-existent field in the table.
You may however modify existing fields.
In particular, you may set existing fields to nil.
<p>
<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
<p>
If <code>t</code> has a metamethod <code>__pairs</code>,
calls it with <code>t</code> as argument and returns the first three
results from the call.
<p>
Otherwise,
returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
so that the construction
<pre>
for k,v in pairs(t) do <em>body</em> end
</pre><p>
will iterate over all key–value pairs of table <code>t</code>.
<p>
See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
the table during its traversal.
<p>
<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, ···])</code></a></h3>
<p>
Calls the function <code>f</code> with
the given arguments in <em>protected mode</em>.
This means that any error inside <code>f</code> is not propagated;
instead, <code>pcall</code> catches the error
and returns a status code.
Its first result is the status code (a boolean),
which is true if the call succeeds without errors.
In such case, <code>pcall</code> also returns all results from the call,
after this first result.
In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
<p>
<hr><h3><a name="pdf-print"><code>print (···)</code></a></h3>
Receives any number of arguments
and prints their values to <code>stdout</code>,
converting each argument to a string
following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
<p>
The function <code>print</code> is not intended for formatted output,
but only as a quick way to show a value,
for instance for debugging.
For complete control over the output,
use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
<p>
<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
Checks whether <code>v1</code> is equal to <code>v2</code>,
without invoking the <code>__eq</code> metamethod.
Returns a boolean.
<p>
<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
Gets the real value of <code>table[index]</code>,
without invoking the <code>__index</code> metamethod.
<code>table</code> must be a table;
<code>index</code> may be any value.
<p>
<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
Returns the length of the object <code>v</code>,
which must be a table or a string,
without invoking the <code>__len</code> metamethod.
Returns an integer.
<p>
<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
Sets the real value of <code>table[index]</code> to <code>value</code>,
without invoking the <code>__newindex</code> metamethod.
<code>table</code> must be a table,
<code>index</code> any value different from <b>nil</b> and NaN,
and <code>value</code> any Lua value.
<p>
This function returns <code>table</code>.
<p>
<hr><h3><a name="pdf-select"><code>select (index, ···)</code></a></h3>
<p>
If <code>index</code> is a number,
returns all arguments after argument number <code>index</code>;
a negative number indexes from the end (-1 is the last argument).
Otherwise, <code>index</code> must be the string <code>"#"</code>,
and <code>select</code> returns the total number of extra arguments it received.
<p>
<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
<p>
Sets the metatable for the given table.
If <code>metatable</code> is <b>nil</b>,
removes the metatable of the given table.
If the original metatable has a <code>__metatable</code> field,
raises an error.
<p>
This function returns <code>table</code>.
<p>
To change the metatable of other types from Lua code,
you must use the debug library (<a href="#6.10">§6.10</a>).
<p>
<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
<p>
When called with no <code>base</code>,
<code>tonumber</code> tries to convert its argument to a number.
If the argument is already a number or
a string convertible to a number,
then <code>tonumber</code> returns this number;
otherwise, it returns <b>fail</b>.
<p>
The conversion of strings can result in integers or floats,
according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>).
The string may have leading and trailing spaces and a sign.
<p>
When called with <code>base</code>,
then <code>e</code> must be a string to be interpreted as
an integer numeral in that base.
The base may be any integer between 2 and 36, inclusive.
In bases above 10, the letter '<code>A</code>' (in either upper or lower case)
represents 10, '<code>B</code>' represents 11, and so forth,
with '<code>Z</code>' representing 35.
If the string <code>e</code> is not a valid numeral in the given base,
the function returns <b>fail</b>.
<p>
<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
Receives a value of any type and
converts it to a string in a human-readable format.
(For complete control of how numbers are converted,
use <a href="#pdf-string.format"><code>string.format</code></a>.)
<p>
If the metatable of <code>v</code> has a <code>__tostring</code> field,
then <code>tostring</code> calls the corresponding value
with <code>v</code> as argument,
and uses the result of the call as its result.
<p>
<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
Returns the type of its only argument, coded as a string.
The possible results of this function are
"<code>nil</code>" (a string, not the value <b>nil</b>),
"<code>number</code>",
"<code>string</code>",
"<code>boolean</code>",
"<code>table</code>",
"<code>function</code>",
"<code>thread</code>",
and "<code>userdata</code>".
<p>
<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
<p>
A global variable (not a function) that
holds a string containing the running Lua version.
The current value of this variable is "<code>Lua 5.4</code>".
<p>
<hr><h3><a name="pdf-warn"><code>warn (msg1, ···)</code></a></h3>
<p>
Emits a warning with a message composed by the concatenation
of all its arguments (which should be strings).
<p>
By convention,
a one-piece message starting with '<code>@</code>'
is intended to be a <em>control message</em>,
which is a message to the warning system itself.
In particular, the standard warning function in Lua
recognizes the control messages "<code>@off</code>",
to stop the emission of warnings,
and "<code>@on</code>", to (re)start the emission;
it ignores unknown control messages.
<p>
<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, ···])</code></a></h3>
<p>
This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
except that it sets a new message handler <code>msgh</code>.
<h2>6.2 – <a name="6.2">Coroutine Manipulation</a></h2>
<p>
This library comprises the operations to manipulate coroutines,
which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
See <a href="#2.6">§2.6</a> for a general description of coroutines.
<p>
<hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
<p>
Closes coroutine <code>co</code>,
that is,
closes all its pending to-be-closed variables
and puts the coroutine in a dead state.
The given coroutine must be dead or suspended.
In case of error closing some variable,
returns <b>false</b> plus the error object;
otherwise returns <b>true</b>.
<p>
<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
<p>
Creates a new coroutine, with body <code>f</code>.
<code>f</code> must be a function.
Returns this new coroutine,
an object with type <code>"thread"</code>.
<p>
<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
<p>
Returns true when the coroutine <code>co</code> can yield.
The default for <code>co</code> is the running coroutine.
<p>
A coroutine is yieldable if it is not the main thread and
it is not inside a non-yieldable C function.
<p>
<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, ···])</code></a></h3>
<p>
Starts or continues the execution of coroutine <code>co</code>.
The first time you resume a coroutine,
it starts running its body.
The values <code>val1</code>, ... are passed
as the arguments to the body function.
If the coroutine has yielded,
<code>resume</code> restarts it;
the values <code>val1</code>, ... are passed
as the results from the yield.
<p>
If the coroutine runs without any errors,
<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
(when the coroutine yields) or any values returned by the body function
(when the coroutine terminates).
If there is any error,
<code>resume</code> returns <b>false</b> plus the error message.
<p>
<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
<p>
Returns the running coroutine plus a boolean,
true when the running coroutine is the main one.
<p>
<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
<p>
Returns the status of the coroutine <code>co</code>, as a string:
<code>"running"</code>,
if the coroutine is running
(that is, it is the one that called <code>status</code>);
<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
or if it has not started running yet;
<code>"normal"</code> if the coroutine is active but not running
(that is, it has resumed another coroutine);
and <code>"dead"</code> if the coroutine has finished its body function,
or if it has stopped with an error.
<p>
<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
<p>
Creates a new coroutine, with body <code>f</code>;
<code>f</code> must be a function.
Returns a function that resumes the coroutine each time it is called.
Any arguments passed to this function behave as the
extra arguments to <code>resume</code>.
The function returns the same values returned by <code>resume</code>,
except the first boolean.
In case of error,
the function closes the coroutine and propagates the error.
<p>
<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (···)</code></a></h3>
<p>
Suspends the execution of the calling coroutine.
Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
<h2>6.3 – <a name="6.3">Modules</a></h2>
<p>
The package library provides basic
facilities for loading modules in Lua.
It exports one function directly in the global environment:
<a href="#pdf-require"><code>require</code></a>.
Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
<p>
<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
<p>
Loads the given module.
The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
to determine whether <code>modname</code> is already loaded.
If it is, then <code>require</code> returns the value stored
at <code>package.loaded[modname]</code>.
(The absence of a second result in this case
signals that this call did not have to load the module.)
Otherwise, it tries to find a <em>loader</em> for the module.
<p>
To find a loader,
<code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
Each item in this table is a search function,
that searches for the module in a particular way.
By changing this table,
we can change how <code>require</code> looks for a module.
The following explanation is based on the default configuration
for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
<p>
First <code>require</code> queries <code>package.preload[modname]</code>.
If it has a value,
this value (which must be a function) is the loader.
Otherwise <code>require</code> searches for a Lua loader using the
path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
If that also fails, it searches for a C loader using the
path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
If that also fails,
it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
<p>
Once a loader is found,
<code>require</code> calls the loader with two arguments:
<code>modname</code> and an extra value,
a <em>loader data</em>,
also returned by the searcher.
The loader data can be any value useful to the module;
for the default searchers,
it indicates where the loader was found.
(For instance, if the loader came from a file,
this extra value is the file path.)
If the loader returns any non-nil value,
<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
If the loader does not return a non-nil value and
has not assigned any value to <code>package.loaded[modname]</code>,
then <code>require</code> assigns <b>true</b> to this entry.
In any case, <code>require</code> returns the
final value of <code>package.loaded[modname]</code>.
Besides that value, <code>require</code> also returns as a second result
the loader data returned by the searcher,
which indicates how <code>require</code> found the module.
<p>
If there is any error loading or running the module,
or if it cannot find any loader for the module,
then <code>require</code> raises an error.
<p>
<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
<p>
A string describing some compile-time configurations for packages.
This string is a sequence of lines:
<ul>
<li>The first line is the directory separator string.
Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
<li>The second line is the character that separates templates in a path.
Default is '<code>;</code>'.</li>
<li>The third line is the string that marks the
substitution points in a template.
Default is '<code>?</code>'.</li>
<li>The fourth line is a string that, in a path in Windows,
is replaced by the executable's directory.
Default is '<code>!</code>'.</li>
<li>The fifth line is a mark to ignore all text after it
when building the <code>luaopen_</code> function name.
Default is '<code>-</code>'.</li>
</ul>
<p>
<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
<p>
The path used by <a href="#pdf-require"><code>require</code></a> to search for a C loader.
<p>
Lua initializes the C path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
or a default path defined in <code>luaconf.h</code>.
<p>
<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
<p>
A table used by <a href="#pdf-require"><code>require</code></a> to control which
modules are already loaded.
When you require a module <code>modname</code> and
<code>package.loaded[modname]</code> is not false,
<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
<p>
This variable is only a reference to the real table;
assignments to this variable do not change the
table used by <a href="#pdf-require"><code>require</code></a>.
<p>
<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
<p>
Dynamically links the host program with the C library <code>libname</code>.
<p>
If <code>funcname</code> is "<code>*</code>",
then it only links with the library,
making the symbols exported by the library
available to other dynamically linked libraries.
Otherwise,
it looks for a function <code>funcname</code> inside the library
and returns this function as a C function.
So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
<p>
This is a low-level function.
It completely bypasses the package and module system.
Unlike <a href="#pdf-require"><code>require</code></a>,
it does not perform any path searching and
does not automatically adds extensions.
<code>libname</code> must be the complete file name of the C library,
including if necessary a path and an extension.
<code>funcname</code> must be the exact name exported by the C library
(which may depend on the C compiler and linker used).
<p>
This function is not supported by Standard C.
As such, it is only available on some platforms
(Windows, Linux, Mac OS X, Solaris, BSD,
plus other Unix systems that support the <code>dlfcn</code> standard).
<p>
<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
<p>
The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
<p>
At start-up, Lua initializes this variable with
the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
with a default path defined in <code>luaconf.h</code>,
if those environment variables are not defined.
A "<code>;;</code>" in the value of the environment variable
is replaced by the default path.
<p>
<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
<p>
A table to store loaders for specific modules
(see <a href="#pdf-require"><code>require</code></a>).
<p>
This variable is only a reference to the real table;
assignments to this variable do not change the
table used by <a href="#pdf-require"><code>require</code></a>.
<p>
<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
<p>
A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
<p>
Each entry in this table is a <em>searcher function</em>.
When looking for a module,
<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
sole argument.
If the searcher finds the module,
it returns another function, the module <em>loader</em>,
plus an extra value, a <em>loader data</em>,
that will be passed to that loader and
returned as a second result by <a href="#pdf-require"><code>require</code></a>.
If it cannot find the module,
it returns a string explaining why
(or <b>nil</b> if it has nothing to say).
<p>
Lua initializes this table with four searcher functions.
<p>
The first searcher simply looks for a loader in the
<a href="#pdf-package.preload"><code>package.preload</code></a> table.
<p>
The second searcher looks for a loader as a Lua library,
using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
<p>
The third searcher looks for a loader as a C library,
using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
Again,
the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
For instance,
if the C path is the string
<pre>
"./?.so;./?.dll;/usr/local/?/init.so"
</pre><p>
the searcher for module <code>foo</code>
will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
and <code>/usr/local/foo/init.so</code>, in that order.
Once it finds a C library,
this searcher first uses a dynamic link facility to link the
application with the library.
Then it tries to find a C function inside the library to
be used as the loader.
The name of this C function is the string "<code>luaopen_</code>"
concatenated with a copy of the module name where each dot
is replaced by an underscore.
Moreover, if the module name has a hyphen,
its suffix after (and including) the first hyphen is removed.
For instance, if the module name is <code>a.b.c-v2.1</code>,
the function name will be <code>luaopen_a_b_c</code>.
<p>
The fourth searcher tries an <em>all-in-one loader</em>.
It searches the C path for a library for
the root name of the given module.
For instance, when requiring <code>a.b.c</code>,
it will search for a C library for <code>a</code>.
If found, it looks into it for an open function for
the submodule;
in our example, that would be <code>luaopen_a_b_c</code>.
With this facility, a package can pack several C submodules
into one single library,
with each submodule keeping its original open function.
<p>
All searchers except the first one (preload) return as the extra value
the file path where the module was found,
as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
The first searcher always returns the string "<code>:preload:</code>".
<p>
Searchers should raise no errors and have no side effects in Lua.
(They may have side effects in C,
for instance by linking the application with a library.)
<p>
<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
<p>
Searches for the given <code>name</code> in the given <code>path</code>.
<p>
A path is a string containing a sequence of
<em>templates</em> separated by semicolons.
For each template,
the function replaces each interrogation mark (if any)
in the template with a copy of <code>name</code>
wherein all occurrences of <code>sep</code>
(a dot, by default)
were replaced by <code>rep</code>
(the system's directory separator, by default),
and then tries to open the resulting file name.
<p>
For instance, if the path is the string
<pre>
"./?.lua;./?.lc;/usr/local/?/init.lua"
</pre><p>
the search for the name <code>foo.a</code>
will try to open the files
<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
<code>/usr/local/foo/a/init.lua</code>, in that order.
<p>
Returns the resulting name of the first file that it can
open in read mode (after closing the file),
or <b>fail</b> plus an error message if none succeeds.
(This error message lists all file names it tried to open.)
<h2>6.4 – <a name="6.4">String Manipulation</a></h2>
<p>
This library provides generic functions for string manipulation,
such as finding and extracting substrings, and pattern matching.
When indexing a string in Lua, the first character is at position 1
(not at 0, as in C).
Indices are allowed to be negative and are interpreted as indexing backwards,
from the end of the string.
Thus, the last character is at position -1, and so on.
<p>
The string library provides all its functions inside the table
<a name="pdf-string"><code>string</code></a>.
It also sets a metatable for strings
where the <code>__index</code> field points to the <code>string</code> table.
Therefore, you can use the string functions in object-oriented style.
For instance, <code>string.byte(s,i)</code>
can be written as <code>s:byte(i)</code>.
<p>
The string library assumes one-byte character encodings.
<p>
<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
Returns the internal numeric codes of the characters <code>s[i]</code>,
<code>s[i+1]</code>, ..., <code>s[j]</code>.
The default value for <code>i</code> is 1;
the default value for <code>j</code> is <code>i</code>.
These indices are corrected
following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
<p>
Numeric codes are not necessarily portable across platforms.
<p>
<hr><h3><a name="pdf-string.char"><code>string.char (···)</code></a></h3>
Receives zero or more integers.
Returns a string with length equal to the number of arguments,
in which each character has the internal numeric code equal
to its corresponding argument.
<p>
Numeric codes are not necessarily portable across platforms.
<p>
<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
<p>
Returns a string containing a binary representation
(a <em>binary chunk</em>)
of the given function,
so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
a copy of the function (but with new upvalues).
If <code>strip</code> is a true value,
the binary representation may not include all debug information
about the function,
to save space.
<p>
Functions with upvalues have only their number of upvalues saved.
When (re)loaded,
those upvalues receive fresh instances.
(See the <a href="#pdf-load"><code>load</code></a> function for details about
how these upvalues are initialized.
You can use the debug library to serialize
and reload the upvalues of a function
in a way adequate to your needs.)
<p>
<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
<p>
Looks for the first match of
<code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>.
If it finds a match, then <code>find</code> returns the indices of <code>s</code>
where this occurrence starts and ends;
otherwise, it returns <b>fail</b>.
A third, optional numeric argument <code>init</code> specifies
where to start the search;
its default value is 1 and can be negative.
A value of <b>true</b> as a fourth, optional argument <code>plain</code>
turns off the pattern matching facilities,
so the function does a plain "find substring" operation,
with no characters in <code>pattern</code> being considered magic.
<p>
If the pattern has captures,
then in a successful match
the captured values are also returned,
after the two indices.
<p>
<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, ···)</code></a></h3>
<p>
Returns a formatted version of its variable number of arguments
following the description given in its first argument,
which must be a string.
The format string follows the same rules as the ISO C function <code>sprintf</code>.
The only differences are that the conversion specifiers and modifiers
<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, and <code>n</code> are not supported
and that there is an extra specifier, <code>q</code>.
<p>
The specifier <code>q</code> formats booleans, nil, numbers, and strings
in a way that the result is a valid constant in Lua source code.
Booleans and nil are written in the obvious way
(<code>true</code>, <code>false</code>, <code>nil</code>).
Floats are written in hexadecimal,
to preserve full precision.
A string is written between double quotes,
using escape sequences when necessary to ensure that
it can safely be read back by the Lua interpreter.
For instance, the call
<pre>
string.format('%q', 'a string with "quotes" and \n new line')
</pre><p>
may produce the string:
<pre>
"a string with \"quotes\" and \
new line"
</pre><p>
This specifier does not support modifiers (flags, width, length).
<p>
The conversion specifiers
<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
<code>G</code>, and <code>g</code> all expect a number as argument.
The specifiers <code>c</code>, <code>d</code>,
<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
expect an integer.
When Lua is compiled with a C89 compiler,
the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
do not support modifiers.
<p>
The specifier <code>s</code> expects a string;
if its argument is not a string,
it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
If the specifier has any modifier,
the corresponding string argument should not contain embedded zeros.
<p>
The specifier <code>p</code> formats the pointer
returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
That gives a unique string identifier for tables, userdata,
threads, strings, and functions.
For other values (numbers, nil, booleans),
this specifier results in a string representing
the pointer <code>NULL</code>.
<p>
<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
Returns an iterator function that,
each time it is called,
returns the next captures from <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>)
over the string <code>s</code>.
If <code>pattern</code> specifies no captures,
then the whole match is produced in each call.
A third, optional numeric argument <code>init</code> specifies
where to start the search;
its default value is 1 and can be negative.
<p>
As an example, the following loop
will iterate over all the words from string <code>s</code>,
printing one per line:
<pre>
s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
</pre><p>
The next example collects all pairs <code>key=value</code> from the
given string into a table:
<pre>
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
</pre>
<p>
For this function, a caret '<code>^</code>' at the start of a pattern does not
work as an anchor, as this would prevent the iteration.
<p>
<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
Returns a copy of <code>s</code>
in which all (or the first <code>n</code>, if given)
occurrences of the <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) have been
replaced by a replacement string specified by <code>repl</code>,
which can be a string, a table, or a function.
<code>gsub</code> also returns, as its second value,
the total number of matches that occurred.
The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
<p>
If <code>repl</code> is a string, then its value is used for replacement.
The character <code>%</code> works as an escape character:
any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
with <em>d</em> between 1 and 9,
stands for the value of the <em>d</em>-th captured substring;
the sequence <code>%0</code> stands for the whole match;
the sequence <code>%%</code> stands for a single <code>%</code>.
<p>
If <code>repl</code> is a table, then the table is queried for every match,
using the first capture as the key.
<p>
If <code>repl</code> is a function, then this function is called every time a
match occurs, with all captured substrings passed as arguments,
in order.
<p>
In any case,
if the pattern specifies no captures,
then it behaves as if the whole pattern was inside a capture.
<p>
If the value returned by the table query or by the function call
is a string or a number,
then it is used as the replacement string;
otherwise, if it is <b>false</b> or <b>nil</b>,
then there is no replacement
(that is, the original match is kept in the string).
<p>
Here are some examples:
<pre>
x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"
x = string.gsub("hello world", "%w+", "%0 %0", 1)
--> x="hello hello world"
x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
return load(s)()
end)
--> x="4+5 = 9"
local t = {name="lua", version="5.4"}
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.4.tar.gz"
</pre>
<p>
<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
<p>
Receives a string and returns its length.
The empty string <code>""</code> has length 0.
Embedded zeros are counted,
so <code>"a\000bc\000"</code> has length 5.
<p>
<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
<p>
Receives a string and returns a copy of this string with all
uppercase letters changed to lowercase.
All other characters are left unchanged.
The definition of what an uppercase letter is depends on the current locale.
<p>
<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
<p>
Looks for the first <em>match</em> of
the <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>.
If it finds one, then <code>match</code> returns
the captures from the pattern;
otherwise it returns <b>fail</b>.
If <code>pattern</code> specifies no captures,
then the whole match is returned.
A third, optional numeric argument <code>init</code> specifies
where to start the search;
its default value is 1 and can be negative.
<p>
<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, ···)</code></a></h3>
<p>
Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
serialized in binary form (packed)
according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>).
<p>
<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
<p>
Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
with the given format.
The format string cannot have the variable-length options
'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">§6.4.2</a>).
<p>
<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
<p>
Returns a string that is the concatenation of <code>n</code> copies of
the string <code>s</code> separated by the string <code>sep</code>.
The default value for <code>sep</code> is the empty string
(that is, no separator).
Returns the empty string if <code>n</code> is not positive.
<p>
(Note that it is very easy to exhaust the memory of your machine
with a single call to this function.)
<p>
<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
<p>
Returns a string that is the string <code>s</code> reversed.
<p>
<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
<p>
Returns the substring of <code>s</code> that
starts at <code>i</code> and continues until <code>j</code>;
<code>i</code> and <code>j</code> can be negative.
If <code>j</code> is absent, then it is assumed to be equal to -1
(which is the same as the string length).
In particular,
the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
with length <code>j</code>,
and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
returns a suffix of <code>s</code>
with length <code>i</code>.
<p>
If, after the translation of negative indices,
<code>i</code> is less than 1,
it is corrected to 1.
If <code>j</code> is greater than the string length,
it is corrected to that length.
If, after these corrections,
<code>i</code> is greater than <code>j</code>,
the function returns the empty string.
<p>
<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
<p>
Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>).
An optional <code>pos</code> marks where
to start reading in <code>s</code> (default is 1).
After the read values,
this function also returns the index of the first unread byte in <code>s</code>.
<p>
<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
<p>
Receives a string and returns a copy of this string with all
lowercase letters changed to uppercase.
All other characters are left unchanged.
The definition of what a lowercase letter is depends on the current locale.
<h3>6.4.1 – <a name="6.4.1">Patterns</a></h3>
<p>
Patterns in Lua are described by regular strings,
which are interpreted as patterns by the pattern-matching functions
<a href="#pdf-string.find"><code>string.find</code></a>,
<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
and <a href="#pdf-string.match"><code>string.match</code></a>.
This section describes the syntax and the meaning
(that is, what they match) of these strings.
<h4>Character Class:</h4><p>
A <em>character class</em> is used to represent a set of characters.
The following combinations are allowed in describing a character class:
<ul>
<li><b><em>x</em>: </b>
(where <em>x</em> is not one of the <em>magic characters</em>
<code>^$()%.[]*+-?</code>)
represents the character <em>x</em> itself.
</li>
<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
<li><b><code>%a</code>: </b> represents all letters.</li>
<li><b><code>%c</code>: </b> represents all control characters.</li>
<li><b><code>%d</code>: </b> represents all digits.</li>
<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
<li><b><code>%s</code>: </b> represents all space characters.</li>
<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
represents the character <em>x</em>.
This is the standard way to escape the magic characters.
Any non-alphanumeric character
(including all punctuation characters, even the non-magical)
can be preceded by a '<code>%</code>' to represent itself in a pattern.
</li>
<li><b><code>[<em>set</em>]</code>: </b>
represents the class which is the union of all
characters in <em>set</em>.
A range of characters can be specified by
separating the end characters of the range,
in ascending order, with a '<code>-</code>'.
All classes <code>%</code><em>x</em> described above can also be used as
components in <em>set</em>.
All other characters in <em>set</em> represent themselves.
For example, <code>[%w_]</code> (or <code>[_%w]</code>)
represents all alphanumeric characters plus the underscore,
<code>[0-7]</code> represents the octal digits,
and <code>[0-7%l%-]</code> represents the octal digits plus
the lowercase letters plus the '<code>-</code>' character.
<p>
You can put a closing square bracket in a set
by positioning it as the first character in the set.
You can put a hyphen in a set
by positioning it as the first or the last character in the set.
(You can also use an escape for both cases.)
<p>
The interaction between ranges and classes is not defined.
Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
have no meaning.
</li>
<li><b><code>[^<em>set</em>]</code>: </b>
represents the complement of <em>set</em>,
where <em>set</em> is interpreted as above.
</li>
</ul><p>
For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
the corresponding uppercase letter represents the complement of the class.
For instance, <code>%S</code> represents all non-space characters.
<p>
The definitions of letter, space, and other character groups
depend on the current locale.
In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
<h4>Pattern Item:</h4><p>
A <em>pattern item</em> can be
<ul>
<li>
a single character class,
which matches any single character in the class;
</li>
<li>
a single character class followed by '<code>*</code>',
which matches sequences of zero or more characters in the class.
These repetition items will always match the longest possible sequence;
</li>
<li>
a single character class followed by '<code>+</code>',
which matches sequences of one or more characters in the class.
These repetition items will always match the longest possible sequence;
</li>
<li>
a single character class followed by '<code>-</code>',
which also matches sequences of zero or more characters in the class.
Unlike '<code>*</code>',
these repetition items will always match the shortest possible sequence;
</li>
<li>
a single character class followed by '<code>?</code>',
which matches zero or one occurrence of a character in the class.
It always matches one occurrence if possible;
</li>
<li>
<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
such item matches a substring equal to the <em>n</em>-th captured string
(see below);
</li>
<li>
<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
such item matches strings that start with <em>x</em>, end with <em>y</em>,
and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
This means that, if one reads the string from left to right,
counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
For instance, the item <code>%b()</code> matches expressions with
balanced parentheses.
</li>
<li>
<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
such item matches an empty string at any position such that
the next character belongs to <em>set</em>
and the previous character does not belong to <em>set</em>.
The set <em>set</em> is interpreted as previously described.
The beginning and the end of the subject are handled as if
they were the character '<code>\0</code>'.
</li>
</ul>
<h4>Pattern:</h4><p>
A <em>pattern</em> is a sequence of pattern items.
A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
beginning of the subject string.
A '<code>$</code>' at the end of a pattern anchors the match at the
end of the subject string.
At other positions,
'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
<h4>Captures:</h4><p>
A pattern can contain sub-patterns enclosed in parentheses;
they describe <em>captures</em>.
When a match succeeds, the substrings of the subject string
that match captures are stored (<em>captured</em>) for future use.
Captures are numbered according to their left parentheses.
For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
the part of the string matching <code>"a*(.)%w(%s*)"</code> is
stored as the first capture, and therefore has number 1;
the character matching "<code>.</code>" is captured with number 2,
and the part matching "<code>%s*</code>" has number 3.
<p>
As a special case, the capture <code>()</code> captures
the current string position (a number).
For instance, if we apply the pattern <code>"()aa()"</code> on the
string <code>"flaaap"</code>, there will be two captures: 3 and 5.
<h4>Multiple matches:</h4><p>
The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
match multiple occurrences of the given pattern in the subject.
For these functions,
a new match is considered valid only
if it ends at least one byte after the end of the previous match.
In other words, the pattern machine never accepts the
empty string as a match immediately after another match.
As an example,
consider the results of the following code:
<pre>
> string.gsub("abc", "()a*()", print);
--> 1 2
--> 3 3
--> 4 4
</pre><p>
The second and third results come from Lua matching an empty
string after '<code>b</code>' and another one after '<code>c</code>'.
Lua does not match an empty string after '<code>a</code>',
because it would end at the same position of the previous match.
<h3>6.4.2 – <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
<p>
The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
is a format string,
which describes the layout of the structure being created or read.
<p>
A format string is a sequence of conversion options.
The conversion options are as follows:
<ul>
<li><b><code><</code>: </b>sets little endian</li>
<li><b><code>></code>: </b>sets big endian</li>
<li><b><code>=</code>: </b>sets native endian</li>
<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
(default is native alignment)</li>
<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
(default is native size)</li>
<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
(default is native size)</li>
<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
<li><b><code>z</code>: </b>a zero-terminated string</li>
<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
coded as an unsigned integer with <code>n</code> bytes
(default is a <code>size_t</code>)</li>
<li><b><code>x</code>: </b>one byte of padding</li>
<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
according to option <code>op</code>
(which is otherwise ignored)</li>
<li><b>'<code> </code>': </b>(empty space) ignored</li>
</ul><p>
(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
Except for padding, spaces, and configurations
(options "<code>xX <=>!</code>"),
each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
<p>
For options "<code>!<em>n</em></code>", "<code>s<em>n</em></code>", "<code>i<em>n</em></code>", and "<code>I<em>n</em></code>",
<code>n</code> can be any integer between 1 and 16.
All integral options check overflows;
<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
For the unsigned options,
Lua integers are treated as unsigned values too.
<p>
Any format string starts as if prefixed by "<code>!1=</code>",
that is,
with maximum alignment of 1 (no alignment)
and native endianness.
<p>
Native endianness assumes that the whole system is
either big or little endian.
The packing functions will not emulate correctly the behavior
of mixed-endian formats.
<p>
Alignment works as follows:
For each option,
the format gets extra padding until the data starts
at an offset that is a multiple of the minimum between the
option size and the maximum alignment;
this minimum must be a power of 2.
Options "<code>c</code>" and "<code>z</code>" are not aligned;
option "<code>s</code>" follows the alignment of its starting integer.
<p>
All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
<h2>6.5 – <a name="6.5">UTF-8 Support</a></h2>
<p>
This library provides basic support for UTF-8 encoding.
It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
This library does not provide any support for Unicode other
than the handling of the encoding.
Any operation that needs the meaning of a character,
such as character classification, is outside its scope.
<p>
Unless stated otherwise,
all functions that expect a byte position as a parameter
assume that the given position is either the start of a byte sequence
or one plus the length of the subject string.
As in the string library,
negative indices count from the end of the string.
<p>
Functions that create byte sequences
accept all values up to <code>0x7FFFFFFF</code>,
as defined in the original UTF-8 specification;
that implies byte sequences of up to six bytes.
<p>
Functions that interpret byte sequences only accept
valid sequences (well formed and not overlong).
By default, they only accept byte sequences
that result in valid Unicode code points,
rejecting values greater than <code>10FFFF</code> and surrogates.
A boolean argument <code>lax</code>, when available,
lifts these checks,
so that all values up to <code>0x7FFFFFFF</code> are accepted.
(Not well formed and overlong sequences are still rejected.)
<p>
<hr><h3><a name="pdf-utf8.char"><code>utf8.char (···)</code></a></h3>
<p>
Receives zero or more integers,
converts each one to its corresponding UTF-8 byte sequence
and returns a string with the concatenation of all these sequences.
<p>
<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
<p>
The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
(see <a href="#6.4.1">§6.4.1</a>),
which matches exactly one UTF-8 byte sequence,
assuming that the subject is a valid UTF-8 string.
<p>
<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
<p>
Returns values so that the construction
<pre>
for p, c in utf8.codes(s) do <em>body</em> end
</pre><p>
will iterate over all UTF-8 characters in string <code>s</code>,
with <code>p</code> being the position (in bytes) and <code>c</code> the code point
of each character.
It raises an error if it meets any invalid byte sequence.
<p>
<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
<p>
Returns the code points (as integers) from all characters in <code>s</code>
that start between byte position <code>i</code> and <code>j</code> (both included).
The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
It raises an error if it meets any invalid byte sequence.
<p>
<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
<p>
Returns the number of UTF-8 characters in string <code>s</code>
that start between positions <code>i</code> and <code>j</code> (both inclusive).
The default for <code>i</code> is 1 and for <code>j</code> is -1.
If it finds any invalid byte sequence,
returns <b>fail</b> plus the position of the first invalid byte.
<p>
<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
<p>
Returns the position (in bytes) where the encoding of the
<code>n</code>-th character of <code>s</code>
(counting from position <code>i</code>) starts.
A negative <code>n</code> gets characters before position <code>i</code>.
The default for <code>i</code> is 1 when <code>n</code> is non-negative
and <code>#s + 1</code> otherwise,
so that <code>utf8.offset(s, -n)</code> gets the offset of the
<code>n</code>-th character from the end of the string.
If the specified character is neither in the subject
nor right after its end,
the function returns <b>fail</b>.
<p>
As a special case,
when <code>n</code> is 0 the function returns the start of the encoding
of the character that contains the <code>i</code>-th byte of <code>s</code>.
<p>
This function assumes that <code>s</code> is a valid UTF-8 string.
<h2>6.6 – <a name="6.6">Table Manipulation</a></h2>
<p>
This library provides generic functions for table manipulation.
It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
<p>
Remember that, whenever an operation needs the length of a table,
all caveats about the length operator apply (see <a href="#3.4.7">§3.4.7</a>).
All functions ignore non-numeric keys
in the tables given as arguments.
<p>
<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
<p>
Given a list where all elements are strings or numbers,
returns the string <code>list[i]..sep..list[i+1] ··· sep..list[j]</code>.
The default value for <code>sep</code> is the empty string,
the default for <code>i</code> is 1,
and the default for <code>j</code> is <code>#list</code>.
If <code>i</code> is greater than <code>j</code>, returns the empty string.
<p>
<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
<p>
Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
shifting up the elements
<code>list[pos], list[pos+1], ···, list[#list]</code>.
The default value for <code>pos</code> is <code>#list+1</code>,
so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
of the list <code>t</code>.
<p>
<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
<p>
Moves elements from the table <code>a1</code> to the table <code>a2</code>,
performing the equivalent to the following
multiple assignment:
<code>a2[t],··· = a1[f],···,a1[e]</code>.
The default for <code>a2</code> is <code>a1</code>.
The destination range can overlap with the source range.
The number of elements to be moved must fit in a Lua integer.
<p>
Returns the destination table <code>a2</code>.
<p>
<hr><h3><a name="pdf-table.pack"><code>table.pack (···)</code></a></h3>
<p>
Returns a new table with all arguments stored into keys 1, 2, etc.
and with a field "<code>n</code>" with the total number of arguments.
Note that the resulting table may not be a sequence,
if some arguments are <b>nil</b>.
<p>
<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
<p>
Removes from <code>list</code> the element at position <code>pos</code>,
returning the value of the removed element.
When <code>pos</code> is an integer between 1 and <code>#list</code>,
it shifts down the elements
<code>list[pos+1], list[pos+2], ···, list[#list]</code>
and erases element <code>list[#list]</code>;
The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
or <code>#list + 1</code>.
<p>
The default value for <code>pos</code> is <code>#list</code>,
so that a call <code>table.remove(l)</code> removes the last element
of the list <code>l</code>.
<p>
<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
<p>
Sorts the list elements in a given order, <em>in-place</em>,
from <code>list[1]</code> to <code>list[#list]</code>.
If <code>comp</code> is given,
then it must be a function that receives two list elements
and returns true when the first element must come
before the second in the final order
(so that, after the sort,
<code>i < j</code> implies <code>not comp(list[j],list[i])</code>).
If <code>comp</code> is not given,
then the standard Lua operator <code><</code> is used instead.
<p>
Note that the <code>comp</code> function must define
a strict partial order over the elements in the list;
that is, it must be asymmetric and transitive.
Otherwise, no valid sort may be possible.
<p>
The sort algorithm is not stable:
elements considered equal by the given order
may have their relative positions changed by the sort.
<p>
<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
<p>
Returns the elements from the given list.
This function is equivalent to
<pre>
return list[i], list[i+1], ···, list[j]
</pre><p>
By default, <code>i</code> is 1 and <code>j</code> is <code>#list</code>.
<h2>6.7 – <a name="6.7">Mathematical Functions</a></h2>
<p>
This library provides basic mathematical functions.
It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
Functions with the annotation "<code>integer/float</code>" give
integer results for integer arguments
and float results for float (or mixed) arguments.
the rounding functions
<a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>
return an integer when the result fits in the range of an integer,
or a float otherwise.
<p>
<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
<p>
Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
<p>
<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
<p>
Returns the arc cosine of <code>x</code> (in radians).
<p>
<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
<p>
Returns the arc sine of <code>x</code> (in radians).
<p>
<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
<p>
Returns the arc tangent of <code>y/x</code> (in radians),
but uses the signs of both arguments to find the
quadrant of the result.
It also handles correctly the case of <code>x</code> being zero.
<p>
The default value for <code>x</code> is 1,
so that the call <code>math.atan(y)</code>
returns the arc tangent of <code>y</code>.
<p>
<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
<p>
Returns the smallest integral value greater than or equal to <code>x</code>.
<p>
<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
<p>
Returns the cosine of <code>x</code> (assumed to be in radians).
<p>
<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
<p>
Converts the angle <code>x</code> from radians to degrees.
<p>
<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
<p>
Returns the value <em>e<sup>x</sup></em>
(where <code>e</code> is the base of natural logarithms).
<p>
<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
<p>
Returns the largest integral value less than or equal to <code>x</code>.
<p>
<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
<p>
Returns the remainder of the division of <code>x</code> by <code>y</code>
that rounds the quotient towards zero. (integer/float)
<p>
<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
<p>
The float value <code>HUGE_VAL</code>,
a value greater than any other numeric value.
<p>
<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
<p>
Returns the logarithm of <code>x</code> in the given base.
The default for <code>base</code> is <em>e</em>
(so that the function returns the natural logarithm of <code>x</code>).
<p>
<hr><h3><a name="pdf-math.max"><code>math.max (x, ···)</code></a></h3>
<p>
Returns the argument with the maximum value,
according to the Lua operator <code><</code>.
<p>
<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
An integer with the maximum value for an integer.
<p>
<hr><h3><a name="pdf-math.min"><code>math.min (x, ···)</code></a></h3>
<p>
Returns the argument with the minimum value,
according to the Lua operator <code><</code>.
<p>
<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
An integer with the minimum value for an integer.
<p>
<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
<p>
Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
Its second result is always a float.
<p>
<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
<p>
The value of <em>π</em>.
<p>
<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
<p>
Converts the angle <code>x</code> from degrees to radians.
<p>
<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
<p>
When called without arguments,
returns a pseudo-random float with uniform distribution
in the range <em>[0,1)</em>.
When called with two integers <code>m</code> and <code>n</code>,
<code>math.random</code> returns a pseudo-random integer
with uniform distribution in the range <em>[m, n]</em>.
The call <code>math.random(n)</code>, for a positive <code>n</code>,
is equivalent to <code>math.random(1,n)</code>.
The call <code>math.random(0)</code> produces an integer with
all bits (pseudo)random.
<p>
Lua initializes its pseudo-random generator with the equivalent of
a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
so that <code>math.random</code> should generate
different sequences of results each time the program runs.
<p>
The results from this function have good statistical qualities,
but they are not cryptographically secure.
(For instance, there are no guarantees that it is hard
to predict future results based on the observation of
some number of previous results.)
<p>
<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
<p>
When called with at least one argument,
the integer parameters <code>x</code> and <code>y</code> are
joined into a 128-bit <em>seed</em> that
is used to reinitialize the pseudo-random generator;
equal seeds produce equal sequences of numbers.
The default for <code>y</code> is zero.
<p>
When called with no arguments,
Lua generates a seed with
a weak attempt for randomness.
<p>
This function returns the two seed components
that were effectively used,
so that setting them again repeats the sequence.
<p>
To ensure a required level of randomness to the initial state
(or contrarily, to have a deterministic sequence,
for instance when debugging a program),
you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
<p>
<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
<p>
Returns the sine of <code>x</code> (assumed to be in radians).
<p>
<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
<p>
Returns the square root of <code>x</code>.
(You can also use the expression <code>x^0.5</code> to compute this value.)
<p>
<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
<p>
Returns the tangent of <code>x</code> (assumed to be in radians).
<p>
<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
<p>
If the value <code>x</code> is convertible to an integer,
returns that integer.
Otherwise, returns <b>fail</b>.
<p>
<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
<p>
Returns "<code>integer</code>" if <code>x</code> is an integer,
"<code>float</code>" if it is a float,
or <b>fail</b> if <code>x</code> is not a number.
<p>
<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
<p>
Returns a boolean,
true if and only if integer <code>m</code> is below integer <code>n</code> when
they are compared as unsigned integers.
<h2>6.8 – <a name="6.8">Input and Output Facilities</a></h2>
<p>
The I/O library provides two different styles for file manipulation.
The first one uses implicit file handles;
that is, there are operations to set a default input file and a
default output file,
and all input/output operations are done over these default files.
The second style uses explicit file handles.
<p>
When using implicit file handles,
all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
When using explicit file handles,
the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
and then all operations are supplied as methods of the file handle.
<p>
The metatable for file handles provides metamethods
for <code>__gc</code> and <code>__close</code> that try
to close the file when called.
<p>
The table <code>io</code> also provides
three predefined file handles with their usual meanings from C:
<a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>.
The I/O library never closes these files.
<p>
Unless otherwise stated,
all I/O functions return <b>fail</b> on failure,
plus an error message as a second result and
a system-dependent error code as a third result,
and some non-false value on success.
On non-POSIX systems,
the computation of the error message and error code
in case of errors
may be not thread safe,
because they rely on the global C variable <code>errno</code>.
<p>
<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
<p>
Equivalent to <code>file:close()</code>.
Without a <code>file</code>, closes the default output file.
<p>
<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
<p>
Equivalent to <code>io.output():flush()</code>.
<p>
<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
<p>
When called with a file name, it opens the named file (in text mode),
and sets its handle as the default input file.
When called with a file handle,
it simply sets this file handle as the default input file.
When called without arguments,
it returns the current default input file.
<p>
In case of errors this function raises the error,
instead of returning an error code.
<p>
<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, ···])</code></a></h3>
<p>
Opens the given file name in read mode
and returns an iterator function that
works like <code>file:lines(···)</code> over the opened file.
When the iterator function fails to read any value,
it automatically closes the file.
Besides the iterator function,
<code>io.lines</code> returns three other values:
two <b>nil</b> values as placeholders,
plus the created file handle.
Therefore, when used in a generic <b>for</b> loop,
the file is closed also if the loop is interrupted by an
error or a <b>break</b>.
<p>
The call <code>io.lines()</code> (with no file name) is equivalent
to <code>io.input():lines("l")</code>;
that is, it iterates over the lines of the default input file.
In this case, the iterator does not close the file when the loop ends.
<p>
In case of errors opening the file,
this function raises the error,
instead of returning an error code.
<p>
<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
<p>
This function opens a file,
in the mode specified in the string <code>mode</code>.
In case of success,
it returns a new file handle.
<p>
The <code>mode</code> string can be any of the following:
<ul>
<li><b>"<code>r</code>": </b> read mode (the default);</li>
<li><b>"<code>w</code>": </b> write mode;</li>
<li><b>"<code>a</code>": </b> append mode;</li>
<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
writing is only allowed at the end of file.</li>
</ul><p>
The <code>mode</code> string can also have a '<code>b</code>' at the end,
which is needed in some systems to open the file in binary mode.
<p>
<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
<p>
Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
<p>
<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
<p>
This function is system dependent and is not available
on all platforms.
<p>
Starts the program <code>prog</code> in a separated process and returns
a file handle that you can use to read data from this program
(if <code>mode</code> is <code>"r"</code>, the default)
or to write data to this program
(if <code>mode</code> is <code>"w"</code>).
<p>
<hr><h3><a name="pdf-io.read"><code>io.read (···)</code></a></h3>
<p>
Equivalent to <code>io.input():read(···)</code>.
<p>
<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
<p>
In case of success,
returns a handle for a temporary file.
This file is opened in update mode
and it is automatically removed when the program ends.
<p>
<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
<p>
Checks whether <code>obj</code> is a valid file handle.
Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
<code>"closed file"</code> if <code>obj</code> is a closed file handle,
or <b>fail</b> if <code>obj</code> is not a file handle.
<p>
<hr><h3><a name="pdf-io.write"><code>io.write (···)</code></a></h3>
<p>
Equivalent to <code>io.output():write(···)</code>.
<p>
<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
<p>
Closes <code>file</code>.
Note that files are automatically closed when
their handles are garbage collected,
but that takes an unpredictable amount of time to happen.
<p>
When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
<p>
<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
<p>
Saves any written data to <code>file</code>.
<p>
<hr><h3><a name="pdf-file:lines"><code>file:lines (···)</code></a></h3>
<p>
Returns an iterator function that,
each time it is called,
reads the file according to the given formats.
When no format is given,
uses "<code>l</code>" as a default.
As an example, the construction
<pre>
for c in file:lines(1) do <em>body</em> end
</pre><p>
will iterate over all characters of the file,
starting at the current position.
Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
when the loop ends.
<p>
<hr><h3><a name="pdf-file:read"><code>file:read (···)</code></a></h3>
<p>
Reads the file <code>file</code>,
according to the given formats, which specify what to read.
For each format,
the function returns a string or a number with the characters read,
or <b>fail</b> if it cannot read data with the specified format.
(In this latter case,
the function does not read subsequent formats.)
When called without arguments,
it uses a default format that reads the next line
(see below).
<p>
The available formats are
<ul>
<li><b>"<code>n</code>": </b>
reads a numeral and returns it as a float or an integer,
following the lexical conventions of Lua.
(The numeral may have leading spaces and a sign.)
This format always reads the longest input sequence that
is a valid prefix for a numeral;
if that prefix does not form a valid numeral
(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
or it is too long (more than 200 characters),
it is discarded and the format returns <b>fail</b>.
</li>
<li><b>"<code>a</code>": </b>
reads the whole file, starting at the current position.
On end of file, it returns the empty string;
this format never fails.
</li>
<li><b>"<code>l</code>": </b>
reads the next line skipping the end of line,
returning <b>fail</b> on end of file.
This is the default format.
</li>
<li><b>"<code>L</code>": </b>
reads the next line keeping the end-of-line character (if present),
returning <b>fail</b> on end of file.
</li>
<li><b><em>number</em>: </b>
reads a string with up to this number of bytes,
returning <b>fail</b> on end of file.
If <code>number</code> is zero,
it reads nothing and returns an empty string,
or <b>fail</b> on end of file.
</li>
</ul><p>
The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
<p>
<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
<p>
Sets and gets the file position,
measured from the beginning of the file,
to the position given by <code>offset</code> plus a base
specified by the string <code>whence</code>, as follows:
<ul>
<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
<li><b>"<code>cur</code>": </b> base is current position;</li>
<li><b>"<code>end</code>": </b> base is end of file;</li>
</ul><p>
In case of success, <code>seek</code> returns the final file position,
measured in bytes from the beginning of the file.
If <code>seek</code> fails, it returns <b>fail</b>,
plus a string describing the error.
<p>
The default value for <code>whence</code> is <code>"cur"</code>,
and for <code>offset</code> is 0.
Therefore, the call <code>file:seek()</code> returns the current
file position, without changing it;
the call <code>file:seek("set")</code> sets the position to the
beginning of the file (and returns 0);
and the call <code>file:seek("end")</code> sets the position to the
end of the file, and returns its size.
<p>
<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
<p>
Sets the buffering mode for a file.
There are three available modes:
<ul>
<li><b>"<code>no</code>": </b> no buffering.</li>
<li><b>"<code>full</code>": </b> full buffering.</li>
<li><b>"<code>line</code>": </b> line buffering.</li>
</ul>
<p>
For the last two cases,
<code>size</code> is a hint for the size of the buffer, in bytes.
The default is an appropriate size.
<p>
The specific behavior of each mode is non portable;
check the underlying ISO C function <code>setvbuf</code> in your platform for
more details.
<p>
<hr><h3><a name="pdf-file:write"><code>file:write (···)</code></a></h3>
<p>
Writes the value of each of its arguments to <code>file</code>.
The arguments must be strings or numbers.
<p>
In case of success, this function returns <code>file</code>.
<h2>6.9 – <a name="6.9">Operating System Facilities</a></h2>
<p>
This library is implemented through table <a name="pdf-os"><code>os</code></a>.
<p>
<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
<p>
Returns an approximation of the amount in seconds of CPU time
used by the program.
<p>
<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
<p>
Returns a string or a table containing date and time,
formatted according to the given string <code>format</code>.
<p>
If the <code>time</code> argument is present,
this is the time to be formatted
(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
Otherwise, <code>date</code> formats the current time.
<p>
If <code>format</code> starts with '<code>!</code>',
then the date is formatted in Coordinated Universal Time.
After this optional character,
if <code>format</code> is the string "<code>*t</code>",
then <code>date</code> returns a table with the following fields:
<code>year</code>, <code>month</code> (1–12), <code>day</code> (1–31),
<code>hour</code> (0–23), <code>min</code> (0–59),
<code>sec</code> (0–61, due to leap seconds),
<code>wday</code> (weekday, 1–7, Sunday is 1),
<code>yday</code> (day of the year, 1–366),
and <code>isdst</code> (daylight saving flag, a boolean).
This last field may be absent
if the information is not available.
<p>
If <code>format</code> is not "<code>*t</code>",
then <code>date</code> returns the date as a string,
formatted according to the same rules as the ISO C function <code>strftime</code>.
<p>
If <code>format</code> is absent, it defaults to "<code>%c</code>",
which gives a human-readable date and time representation
using the current locale.
<p>
On non-POSIX systems,
this function may be not thread safe
because of its reliance on C function <code>gmtime</code> and C function <code>localtime</code>.
<p>
<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
<p>
Returns the difference, in seconds,
from time <code>t1</code> to time <code>t2</code>
(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
In POSIX, Windows, and some other systems,
this value is exactly <code>t2</code><em>-</em><code>t1</code>.
<p>
<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
<p>
This function is equivalent to the ISO C function <code>system</code>.
It passes <code>command</code> to be executed by an operating system shell.
Its first result is <b>true</b>
if the command terminated successfully,
or <b>fail</b> otherwise.
After this first result
the function returns a string plus a number,
as follows:
<ul>
<li><b>"<code>exit</code>": </b>
the command terminated normally;
the following number is the exit status of the command.
</li>
<li><b>"<code>signal</code>": </b>
the command was terminated by a signal;
the following number is the signal that terminated the command.
</li>
</ul>
<p>
When called without a <code>command</code>,
<code>os.execute</code> returns a boolean that is true if a shell is available.
<p>
<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
<p>
Calls the ISO C function <code>exit</code> to terminate the host program.
If <code>code</code> is <b>true</b>,
the returned status is <code>EXIT_SUCCESS</code>;
if <code>code</code> is <b>false</b>,
the returned status is <code>EXIT_FAILURE</code>;
if <code>code</code> is a number,
the returned status is this number.
The default value for <code>code</code> is <b>true</b>.
<p>
If the optional second argument <code>close</code> is true,
closes the Lua state before exiting.
<p>
<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
<p>
Returns the value of the process environment variable <code>varname</code>,
or <b>fail</b> if the variable is not defined.
<p>
<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
<p>
Deletes the file (or empty directory, on POSIX systems)
with the given name.
If this function fails, it returns <b>fail</b>
plus a string describing the error and the error code.
Otherwise, it returns true.
<p>
<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
<p>
Renames the file or directory named <code>oldname</code> to <code>newname</code>.
If this function fails, it returns <b>fail</b>,
plus a string describing the error and the error code.
Otherwise, it returns true.
<p>
<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
<p>
Sets the current locale of the program.
<code>locale</code> is a system-dependent string specifying a locale;
<code>category</code> is an optional string describing which category to change:
<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
the default category is <code>"all"</code>.
The function returns the name of the new locale,
or <b>fail</b> if the request cannot be honored.
<p>
If <code>locale</code> is the empty string,
the current locale is set to an implementation-defined native locale.
If <code>locale</code> is the string "<code>C</code>",
the current locale is set to the standard C locale.
<p>
When called with <b>nil</b> as the first argument,
this function only returns the name of the current locale
for the given category.
<p>
This function may be not thread safe
because of its reliance on C function <code>setlocale</code>.
<p>
<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
<p>
Returns the current time when called without arguments,
or a time representing the local date and time specified by the given table.
This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
and may have fields
<code>hour</code> (default is 12),
<code>min</code> (default is 0),
<code>sec</code> (default is 0),
and <code>isdst</code> (default is <b>nil</b>).
Other fields are ignored.
For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
<p>
When the function is called,
the values in these fields do not need to be inside their valid ranges.
For instance, if <code>sec</code> is -10,
it means 10 seconds before the time specified by the other fields;
if <code>hour</code> is 1000,
it means 1000 hours after the time specified by the other fields.
<p>
The returned value is a number, whose meaning depends on your system.
In POSIX, Windows, and some other systems,
this number counts the number
of seconds since some given start time (the "epoch").
In other systems, the meaning is not specified,
and the number returned by <code>time</code> can be used only as an argument to
<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
<p>
When called with a table,
<code>os.time</code> also normalizes all the fields
documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
so that they represent the same time as before the call
but with values inside their valid ranges.
<p>
<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
<p>
Returns a string with a file name that can
be used for a temporary file.
The file must be explicitly opened before its use
and explicitly removed when no longer needed.
<p>
In POSIX systems,
this function also creates a file with that name,
to avoid security risks.
(Someone else might create the file with wrong permissions
in the time between getting the name and creating the file.)
You still have to open the file to use it
and to remove it (even if you do not use it).
<p>
When possible,
you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
which automatically removes the file when the program ends.
<h2>6.10 – <a name="6.10">The Debug Library</a></h2>
<p>
This library provides
the functionality of the debug interface (<a href="#4.9">§4.9</a>) to Lua programs.
You should exert care when using this library.
Several of its functions
violate basic assumptions about Lua code
(e.g., that variables local to a function
cannot be accessed from outside;
that userdata metatables cannot be changed by Lua code;
that Lua programs do not crash)
and therefore can compromise otherwise secure code.
Moreover, some functions in this library may be slow.
<p>
All functions in this library are provided
inside the <a name="pdf-debug"><code>debug</code></a> table.
All functions that operate over a thread
have an optional first argument which is the
thread to operate over.
The default is always the current thread.
<p>
<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
<p>
Enters an interactive mode with the user,
running each string that the user enters.
Using simple commands and other debug facilities,
the user can inspect global and local variables,
change their values, evaluate expressions, and so on.
A line containing only the word <code>cont</code> finishes this function,
so that the caller continues its execution.
<p>
Note that commands for <code>debug.debug</code> are not lexically nested
within any function and so have no direct access to local variables.
<p>
<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
<p>
Returns the current hook settings of the thread, as three values:
the current hook function, the current hook mask,
and the current hook count,
as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
<p>
Returns <b>fail</b> if there is no active hook.
<p>
<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
<p>
Returns a table with information about a function.
You can give the function directly
or you can give a number as the value of <code>f</code>,
which means the function running at level <code>f</code> of the call stack
of the given thread:
level 0 is the current function (<code>getinfo</code> itself);
level 1 is the function that called <code>getinfo</code>
(except for tail calls, which do not count on the stack);
and so on.
If <code>f</code> is a number greater than the number of active functions,
then <code>getinfo</code> returns <b>fail</b>.
<p>
The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
with the string <code>what</code> describing which fields to fill in.
The default for <code>what</code> is to get all information available,
except the table of valid lines.
If present,
the option '<code>f</code>'
adds a field named <code>func</code> with the function itself.
If present,
the option '<code>L</code>'
adds a field named <code>activelines</code> with the table of
valid lines.
<p>
For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
a name for the current function,
if a reasonable name can be found,
and the expression <code>debug.getinfo(print)</code>
returns a table with all available information
about the <a href="#pdf-print"><code>print</code></a> function.
<p>
<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
<p>
This function returns the name and the value of the local variable
with index <code>local</code> of the function at level <code>f</code> of the stack.
This function accesses not only explicit local variables,
but also parameters and temporary values.
<p>
The first parameter or local variable has index 1, and so on,
following the order that they are declared in the code,
counting only the variables that are active
in the current scope of the function.
Compile-time constants may not appear in this listing,
if they were optimized away by the compiler.
Negative indices refer to vararg arguments;
-1 is the first vararg argument.
The function returns <b>fail</b>
if there is no variable with the given index,
and raises an error when called with a level out of range.
(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
<p>
Variable names starting with '<code>(</code>' (open parenthesis)
represent variables with no known names
(internal variables such as loop control variables,
and variables from chunks saved without debug information).
<p>
The parameter <code>f</code> may also be a function.
In that case, <code>getlocal</code> returns only the name of function parameters.
<p>
<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
<p>
Returns the metatable of the given <code>value</code>
or <b>nil</b> if it does not have a metatable.
<p>
<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
<p>
Returns the registry table (see <a href="#4.5">§4.5</a>).
<p>
<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
<p>
This function returns the name and the value of the upvalue
with index <code>up</code> of the function <code>f</code>.
The function returns <b>fail</b>
if there is no upvalue with the given index.
<p>
(For Lua functions,
upvalues are the external local variables that the function uses,
and that are consequently included in its closure.)
<p>
For C functions, this function uses the empty string <code>""</code>
as a name for all upvalues.
<p>
Variable name '<code>?</code>' (interrogation mark)
represents variables with no known names
(variables from chunks saved without debug information).
<p>
<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
<p>
Returns the <code>n</code>-th user value associated
to the userdata <code>u</code> plus a boolean,
<b>false</b> if the userdata does not have that value.
<p>
<hr><h3><a name="pdf-debug.setcstacklimit"><code>debug.setcstacklimit (limit)</code></a></h3>
<p>
Sets a new limit for the C stack.
This limit controls how deeply nested calls can go in Lua,
with the intent of avoiding a stack overflow.
A limit too small restricts recursive calls pointlessly;
a limit too large exposes the interpreter to stack-overflow crashes.
Unfortunately, there is no way to know a priori
the maximum safe limit for a platform.
<p>
Each call made from Lua code counts one unit.
Other operations (e.g., calls made from C to Lua or resuming a coroutine)
may have a higher cost.
<p>
This function has the following restrictions:
<ul>
<li>It can only be called from the main coroutine (thread);</li>
<li>It cannot be called while handling a stack-overflow error;</li>
<li><code>limit</code> must be less than 40000;</li>
<li><code>limit</code> cannot be less than the amount of C stack in use.</li>
</ul><p>
If a call does not respect some restriction,
it returns a falsy value.
Otherwise,
the call returns the old limit.
<p>
<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
<p>
Sets the given function as the debug hook.
The string <code>mask</code> and the number <code>count</code> describe
when the hook will be called.
The string mask may have any combination of the following characters,
with the given meaning:
<ul>
<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
</ul><p>
Moreover,
with a <code>count</code> different from zero,
the hook is called also after every <code>count</code> instructions.
<p>
When called without arguments,
<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
<p>
When the hook is called, its first parameter is a string
describing the event that has triggered its call:
<code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
<code>"line"</code>, and <code>"count"</code>.
For line events,
the hook also gets the new line number as its second parameter.
Inside a hook,
you can call <code>getinfo</code> with level 2 to get more information about
the running function.
(Level 0 is the <code>getinfo</code> function,
and level 1 is the hook function.)
<p>
<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
<p>
This function assigns the value <code>value</code> to the local variable
with index <code>local</code> of the function at level <code>level</code> of the stack.
The function returns <b>fail</b> if there is no local
variable with the given index,
and raises an error when called with a <code>level</code> out of range.
(You can call <code>getinfo</code> to check whether the level is valid.)
Otherwise, it returns the name of the local variable.
<p>
See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
variable indices and names.
<p>
<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
<p>
Sets the metatable for the given <code>value</code> to the given <code>table</code>
(which can be <b>nil</b>).
Returns <code>value</code>.
<p>
<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
<p>
This function assigns the value <code>value</code> to the upvalue
with index <code>up</code> of the function <code>f</code>.
The function returns <b>fail</b> if there is no upvalue
with the given index.
Otherwise, it returns the name of the upvalue.
<p>
See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
<p>
<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
<p>
Sets the given <code>value</code> as
the <code>n</code>-th user value associated to the given <code>udata</code>.
<code>udata</code> must be a full userdata.
<p>
Returns <code>udata</code>,
or <b>fail</b> if the userdata does not have that value.
<p>
<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
<p>
If <code>message</code> is present but is neither a string nor <b>nil</b>,
this function returns <code>message</code> without further processing.
Otherwise,
it returns a string with a traceback of the call stack.
The optional <code>message</code> string is appended
at the beginning of the traceback.
An optional <code>level</code> number tells at which level
to start the traceback
(default is 1, the function calling <code>traceback</code>).
<p>
<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
<p>
Returns a unique identifier (as a light userdata)
for the upvalue numbered <code>n</code>
from the given function.
<p>
These unique identifiers allow a program to check whether different
closures share upvalues.
Lua closures that share an upvalue
(that is, that access a same external local variable)
will return identical ids for those upvalue indices.
<p>
<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
<p>
Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
<h1>7 – <a name="7">Lua Standalone</a></h1>
<p>
Although Lua has been designed as an extension language,
to be embedded in a host C program,
it is also frequently used as a standalone language.
An interpreter for Lua as a standalone language,
called simply <code>lua</code>,
is provided with the standard distribution.
The standalone interpreter includes
all standard libraries.
Its usage is:
<pre>
lua [options] [script [args]]
</pre><p>
The options are:
<ul>
<li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li>
<li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em> and assigns the
result to global <em>mod</em>;</li>
<li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li>
<li><b><code>-v</code>: </b> prints version information;</li>
<li><b><code>-E</code>: </b> ignores environment variables;</li>
<li><b><code>-W</code>: </b> turn warnings on;</li>
<li><b><code>--</code>: </b> stops handling options;</li>
<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
</ul><p>
After handling its options, <code>lua</code> runs the given <em>script</em>.
When called without arguments,
<code>lua</code> behaves as <code>lua -v -i</code>
when the standard input (<code>stdin</code>) is a terminal,
and as <code>lua -</code> otherwise.
<p>
When called without the option <code>-E</code>,
the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
before running any argument.
If the variable content has the format <code>@<em>filename</em></code>,
then <code>lua</code> executes the file.
Otherwise, <code>lua</code> executes the string itself.
<p>
When called with the option <code>-E</code>,
besides ignoring <code>LUA_INIT</code>,
Lua also ignores
the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
setting the values of
<a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
with the default paths defined in <code>luaconf.h</code>.
<p>
The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
the order they appear.
For instance, an invocation like
<pre>
$ lua -e 'a=1' -llib1 script.lua
</pre><p>
will first set <code>a</code> to 1, then require the library <code>lib1</code>,
and finally run the file <code>script.lua</code> with no arguments.
(Here <code>$</code> is the shell prompt. Your prompt may be different.)
<p>
Before running any code,
<code>lua</code> collects all command-line arguments
in a global table called <code>arg</code>.
The script name goes to index 0,
the first argument after the script name goes to index 1,
and so on.
Any arguments before the script name
(that is, the interpreter name plus its options)
go to negative indices.
For instance, in the call
<pre>
$ lua -la b.lua t1 t2
</pre><p>
the table is like this:
<pre>
arg = { [-2] = "lua", [-1] = "-la",
[0] = "b.lua",
[1] = "t1", [2] = "t2" }
</pre><p>
If there is no script in the call,
the interpreter name goes to index 0,
followed by the other arguments.
For instance, the call
<pre>
$ lua -e "print(arg[1])"
</pre><p>
will print "<code>-e</code>".
If there is a script,
the script is called with arguments
<code>arg[1]</code>, ···, <code>arg[#arg]</code>.
Like all chunks in Lua,
the script is compiled as a vararg function.
<p>
In interactive mode,
Lua repeatedly prompts and waits for a line.
After reading a line,
Lua first try to interpret the line as an expression.
If it succeeds, it prints its value.
Otherwise, it interprets the line as a statement.
If you write an incomplete statement,
the interpreter waits for its completion
by issuing a different prompt.
<p>
If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
then its value is used as the prompt.
Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
its value is used as the secondary prompt
(issued during incomplete statements).
<p>
In case of unprotected errors in the script,
the interpreter reports the error to the standard error stream.
If the error object is not a string but
has a metamethod <code>__tostring</code>,
the interpreter calls this metamethod to produce the final message.
Otherwise, the interpreter converts the error object to a string
and adds a stack traceback to it.
When warnings are on,
they are simply printed in the standard error output.
<p>
When finishing normally,
the interpreter closes its main Lua state
(see <a href="#lua_close"><code>lua_close</code></a>).
The script can avoid this step by
calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
<p>
To allow the use of Lua as a
script interpreter in Unix systems,
Lua skips the first line of a file chunk if it starts with <code>#</code>.
Therefore, Lua scripts can be made into executable programs
by using <code>chmod +x</code> and the <code>#!</code> form,
as in
<pre>
#!/usr/local/bin/lua
</pre><p>
Of course,
the location of the Lua interpreter may be different in your machine.
If <code>lua</code> is in your <code>PATH</code>,
then
<pre>
#!/usr/bin/env lua
</pre><p>
is a more portable solution.
<h1>8 – <a name="8">Incompatibilities with the Previous Version</a></h1>
<p>
Here we list the incompatibilities that you may find when moving a program
from Lua 5.3 to Lua 5.4.
<p>
You can avoid some incompatibilities by compiling Lua with
appropriate options (see file <code>luaconf.h</code>).
However,
all these compatibility options will be removed in the future.
More often than not,
compatibility issues arise when these compatibility options
are removed.
So, whenever you have the chance,
you should try to test your code with a version of Lua compiled
with all compatibility options turned off.
That will ease transitions to newer versions of Lua.
<p>
Lua versions can always change the C API in ways that
do not imply source-code changes in a program,
such as the numeric values for constants
or the implementation of functions as macros.
Therefore,
you should never assume that binaries are compatible between
different Lua versions.
Always recompile clients of the Lua API when
using a new version.
<p>
Similarly, Lua versions can always change the internal representation
of precompiled chunks;
precompiled chunks are not compatible between different Lua versions.
<p>
The standard paths in the official distribution may
change between versions.
<h2>8.1 – <a name="8.1">Incompatibilities in the Language</a></h2>
<ul>
<li>
The coercion of strings to numbers in
arithmetic and bitwise operations
has been removed from the core language.
The string library does a similar job
for arithmetic (but not for bitwise) operations
using the string metamethods.
However, unlike in previous versions,
the new implementation preserves the implicit type of the numeral
in the string.
For instance, the result of <code>"1" + "2"</code> now is an integer,
not a float.
</li>
<li>
The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
has been removed.
When needed, this metamethod must be explicitly defined.
</li>
<li>
The semantics of the numerical <b>for</b> loop
over integers changed in some details.
In particular, the control variable never wraps around.
</li>
<li>
A label for a <b>goto</b> cannot be declared where a label with the same
name is visible, even if this other label is declared in an enclosing
block.
</li>
<li>
When finalizing an object,
Lua does not ignore <code>__gc</code> metamethods that are not functions.
Any value will be called, if present.
(Non-callable values will generate a warning,
like any other error when calling a finalizer.)
</li>
</ul>
<h2>8.2 – <a name="8.2">Incompatibilities in the Libraries</a></h2>
<ul>
<li>
The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
to format its arguments;
instead, it has this functionality hardwired.
You should use <code>__tostring</code> to modify how values are printed.
</li>
<li>
The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
now starts with a somewhat random seed.
Moreover, it uses a different algorithm.
</li>
<li>
By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
do not accept surrogates as valid code points.
An extra parameter in these functions makes them more permissive.
</li>
<li>
The options "<code>setpause</code>" and "<code>setstepmul</code>"
of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
You should use the new option "<code>incremental</code>" to set them.
</li>
</ul>
<h2>8.3 – <a name="8.3">Incompatibilities in the API</a></h2>
<ul>
<li>
Full userdata now has an arbitrary number of associated user values.
Therefore, the functions <code>lua_newuserdata</code>,
<code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
which have an extra argument.
<p>
For compatibility, the old names still work as macros assuming
one single user value.
Note, however, that userdata with zero user values
are more efficient memory-wise.
</li>
<li>
The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
This out parameter returns the number of values on
the top of the stack that were yielded or returned by the coroutine.
(In previous versions,
those values were the entire stack.)
</li>
<li>
The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
instead of an address of the version number.
The Lua core should work correctly with libraries using their
own static copies of the same core,
so there is no need to check whether they are using the same
address space.
</li>
<li>
The constant <code>LUA_ERRGCMM</code> was removed.
Errors in finalizers are never propagated;
instead, they generate a warning.
</li>
<li>
The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
You should use the new option <code>LUA_GCINC</code> to set them.
</li>
</ul>
<h1>9 – <a name="9">The Complete Syntax of Lua</a></h1>
<p>
Here is the complete syntax of Lua in extended BNF.
As usual in extended BNF,
{A} means 0 or more As,
and [A] means an optional A.
(For operator precedences, see <a href="#3.4.8">§3.4.8</a>;
for a description of the terminals
Name, Numeral,
and LiteralString, see <a href="#3.1">§3.1</a>.)
<pre>
chunk ::= block
block ::= {stat} [retstat]
stat ::= ‘<b>;</b>’ |
varlist ‘<b>=</b>’ explist |
functioncall |
label |
<b>break</b> |
<b>goto</b> Name |
<b>do</b> block <b>end</b> |
<b>while</b> exp <b>do</b> block <b>end</b> |
<b>repeat</b> block <b>until</b> exp |
<b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
<b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b> |
<b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
<b>function</b> funcname funcbody |
<b>local</b> <b>function</b> Name funcbody |
<b>local</b> attnamelist [‘<b>=</b>’ explist]
attnamelist ::= Name attrib {‘<b>,</b>’ Name attrib}
attrib ::= [‘<b><</b>’ Name ‘<b>></b>’]
retstat ::= <b>return</b> [explist] [‘<b>;</b>’]
label ::= ‘<b>::</b>’ Name ‘<b>::</b>’
funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name]
varlist ::= var {‘<b>,</b>’ var}
var ::= Name | prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ | prefixexp ‘<b>.</b>’ Name
namelist ::= Name {‘<b>,</b>’ Name}
explist ::= exp {‘<b>,</b>’ exp}
exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | ‘<b>...</b>’ | functiondef |
prefixexp | tableconstructor | exp binop exp | unop exp
prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’
functioncall ::= prefixexp args | prefixexp ‘<b>:</b>’ Name args
args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ | tableconstructor | LiteralString
functiondef ::= <b>function</b> funcbody
funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b>
parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’
tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp
fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’
binop ::= ‘<b>+</b>’ | ‘<b>-</b>’ | ‘<b>*</b>’ | ‘<b>/</b>’ | ‘<b>//</b>’ | ‘<b>^</b>’ | ‘<b>%</b>’ |
‘<b>&</b>’ | ‘<b>~</b>’ | ‘<b>|</b>’ | ‘<b>>></b>’ | ‘<b><<</b>’ | ‘<b>..</b>’ |
‘<b><</b>’ | ‘<b><=</b>’ | ‘<b>></b>’ | ‘<b>>=</b>’ | ‘<b>==</b>’ | ‘<b>~=</b>’ |
<b>and</b> | <b>or</b>
unop ::= ‘<b>-</b>’ | <b>not</b> | ‘<b>#</b>’ | ‘<b>~</b>’
</pre>
<p>
<P CLASS="footer">
Last update:
Tue Oct 8 15:13:21 UTC 2019
</P>
<!--
Last change: revised for Lua 5.4.0 (beta)
-->
</body></html>
| 29.8683 | 188 | 0.702009 |
ba1e83772a92f215cd91b6eca4f1b79adda2a839 | 3,823 | kt | Kotlin | presentation/src/main/java/com/grekov/translate/presentation/main/presenter/HomePresenter.kt | sgrekov/Translater | 24a1a1955ca901d4bf5ff08ff2f8e3eb2719c825 | [
"Apache-2.0"
] | 26 | 2017-12-01T08:14:44.000Z | 2021-11-17T22:48:35.000Z | presentation/src/main/java/com/grekov/translate/presentation/main/presenter/HomePresenter.kt | sgrekov/Translater | 24a1a1955ca901d4bf5ff08ff2f8e3eb2719c825 | [
"Apache-2.0"
] | 2 | 2019-04-16T19:08:37.000Z | 2019-04-21T10:16:15.000Z | presentation/src/main/java/com/grekov/translate/presentation/main/presenter/HomePresenter.kt | sgrekov/Translater | 24a1a1955ca901d4bf5ff08ff2f8e3eb2719c825 | [
"Apache-2.0"
] | 4 | 2018-04-19T03:55:09.000Z | 2019-06-10T09:58:54.000Z | package com.grekov.translate.presentation.main.presenter
import android.annotation.SuppressLint
import android.os.Parcelable
import com.grekov.translate.domain.elm.Cmd
import com.grekov.translate.domain.elm.Idle
import com.grekov.translate.domain.elm.Init
import com.grekov.translate.domain.elm.Msg
import com.grekov.translate.domain.elm.None
import com.grekov.translate.domain.elm.OneShotCmd
import com.grekov.translate.domain.model.Phrase
import com.grekov.translate.presentation.core.elm.Program
import com.grekov.translate.presentation.core.elm.Screen
import com.grekov.translate.presentation.core.elm.State
import com.grekov.translate.presentation.core.elm.TimeTravel
import com.grekov.translate.presentation.core.presenter.BasePresenter
import com.grekov.translate.presentation.history.presenter.Favorites
import com.grekov.translate.presentation.history.presenter.History
import com.grekov.translate.presentation.main.view.IHomeView
import com.grekov.translate.presentation.translate.presenter.Translate
import io.reactivex.Single
import kotlinx.android.parcel.Parcelize
import timber.log.Timber
@SuppressLint("ParcelCreator")
@Parcelize
data class Home(val stub: Unit = Unit) : Screen(), Parcelable
class HomePresenter(view: IHomeView, program: Program<HomeState>) :
BasePresenter<IHomeView, HomePresenter.HomeState>(view, program), TimeTravel {
@Parcelize
data class HomeState(
val tabNum: Int,
override val screen: Home = Home(),
val activeScreen: Screen,
val selectedPhrase: Phrase? = null
) : State(screen), Parcelable
data class TabSelectMsg(val tab: Screen) : Msg()
data class PhraseSelectMsg(val phrase: Phrase) : Msg()
object ResetPhraseMsg : Msg()
override fun initialState(): HomeState {
return HomeState(0, activeScreen = Translate())
}
override fun onInit() {
Timber.d("onInit")
addDisposable(program.init(initialState(), this))
program.accept(Init)
}
override fun update(msg: Msg, state: HomeState): Pair<HomeState, Cmd> {
return when (msg) {
is TabSelectMsg -> when (msg.tab) {
is Translate -> state.copy(tabNum = 0, activeScreen = Translate()) to None
is History -> state.copy(tabNum = 1, activeScreen = History()) to None
is Favorites -> state.copy(tabNum = 2, activeScreen = Favorites()) to None
else -> state to None
}
is PhraseSelectMsg ->
state.copy(tabNum = 0, activeScreen = Translate(), selectedPhrase = msg.phrase) to OneShotCmd(
ResetPhraseMsg
)
is ResetPhraseMsg -> state.copy(selectedPhrase = null) to None
else -> state to None
}
}
override fun render(state: HomeState) {
view()?.let { view ->
state.apply {
view.setTab(tabNum)
when (activeScreen) {
is Translate -> view.showTranslate(selectedPhrase)
is History -> view.showHistory()
is Favorites -> view.showFavorites()
}
}
}
}
override fun call(cmd: Cmd): Single<Msg> {
return Single.just(Idle)
}
override fun sub(state: HomeState) {}
override fun travel(screen: Screen, state: State) {
if (screen is Home && state is HomeState) {
render(state)
}
}
fun translateSelect() {
program.accept(TabSelectMsg(Translate()))
}
fun historySelect() {
program.accept(TabSelectMsg(History()))
}
fun favoritesSelect() {
program.accept(TabSelectMsg(Favorites()))
}
fun onPhraseClick(model: Phrase) {
program.accept(PhraseSelectMsg(model))
}
}
| 31.858333 | 110 | 0.658907 |
fb5bffc8e92440624b379fb2c8722b98fcc8f55d | 1,686 | java | Java | magiccube-web/src/main/java/com/missfresh/magiccube/web/controller/ReportManageController.java | Eillot/MagicCube | 4f387a8d643cfb69f15bf2c985102c66cb636c88 | [
"Apache-2.0"
] | null | null | null | magiccube-web/src/main/java/com/missfresh/magiccube/web/controller/ReportManageController.java | Eillot/MagicCube | 4f387a8d643cfb69f15bf2c985102c66cb636c88 | [
"Apache-2.0"
] | null | null | null | magiccube-web/src/main/java/com/missfresh/magiccube/web/controller/ReportManageController.java | Eillot/MagicCube | 4f387a8d643cfb69f15bf2c985102c66cb636c88 | [
"Apache-2.0"
] | null | null | null | package com.simon.magiccube.web.controller;
import com.simon.magiccube.dao.domain.ParameterizationData;
import com.simon.magiccube.dao.domain.ReportManage;
import com.simon.magiccube.engine.impl.ReportManageEngineImp;
import com.simon.magiccube.facade.support.CommonResult;
import com.simon.magiccube.web.constants.HttpResultConstants;
import com.simon.magiccube.web.constants.MessageConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @version: java version 1.8+
* @Author : simon
* @Explain :
* @contact:
* @Time : 2020/4/2 7:31 PM
* @File : ReportManageController
* @Software: IntelliJ IDEA 2018.1.8
*/
@RestController
@RequestMapping("/v1/ReportManage")
public class ReportManageController {
@Autowired
private ReportManageEngineImp reportManageEngineImp;
@RequestMapping(value = "/updateBycaseId", method = RequestMethod.POST)
public CommonResult findParameterizationDataById(@RequestBody() ReportManage reportManage) {
//@TODO 请求失败的check待统一封装完毕后在check
int result = reportManageEngineImp.ReportManageUpdateAssertByCaseId(reportManage);
CommonResult commonResult = new CommonResult();
commonResult.setStatus(MessageConstants.STATUS_SUCCESS);
commonResult.setCode(HttpResultConstants.SUCCESS_CODE);
commonResult.setMsg(MessageConstants.SELECT_SUCCESS);
commonResult.setData(result);
return commonResult;
}
}
| 36.652174 | 96 | 0.786477 |
cb7e989e99b577f2d2aabba55767862363292056 | 685 | asm | Assembly | data/pokemon/base_stats/jolteon.asm | opiter09/ASM-Machina | 75d8e457b3e82cc7a99b8e70ada643ab02863ada | [
"CC0-1.0"
] | 1 | 2022-02-15T00:19:44.000Z | 2022-02-15T00:19:44.000Z | data/pokemon/base_stats/jolteon.asm | opiter09/ASM-Machina | 75d8e457b3e82cc7a99b8e70ada643ab02863ada | [
"CC0-1.0"
] | null | null | null | data/pokemon/base_stats/jolteon.asm | opiter09/ASM-Machina | 75d8e457b3e82cc7a99b8e70ada643ab02863ada | [
"CC0-1.0"
] | null | null | null | db DEX_JOLTEON ; pokedex id
db 65, 65, 60, 130, 110
; hp atk def spd spc
db ELECTRIC, ELECTRIC ; type
db 45 ; catch rate
db 197 ; base exp
INCBIN "gfx/pokemon/front/jolteon.pic", 0, 1 ; sprite dimensions
dw JolteonPicFront, JolteonPicBack
db TACKLE, SAND_ATTACK, QUICK_ATTACK, THUNDERSHOCK ; level 1 learnset
db GROWTH_MEDIUM_FAST ; growth rate
; tm/hm learnset
tmhm TOXIC, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, HYPER_BEAM, \
RAGE, THUNDERBOLT, THUNDER, MIMIC, DOUBLE_TEAM, \
REFLECT, BIDE, SWIFT, SKULL_BASH, REST, \
THUNDER_WAVE, SUBSTITUTE, FLASH
; end
db 0 ; padding
| 28.541667 | 77 | 0.630657 |
0e444072bc512f631ecb6e7b545b9472f7448b90 | 1,497 | html | HTML | src/ImagesOverview/search.html | MichellePauwels/FRONTEND-week9 | 7eab23d5025aa9357e4096197d3d1d4f65a1d825 | [
"MIT"
] | null | null | null | src/ImagesOverview/search.html | MichellePauwels/FRONTEND-week9 | 7eab23d5025aa9357e4096197d3d1d4f65a1d825 | [
"MIT"
] | null | null | null | src/ImagesOverview/search.html | MichellePauwels/FRONTEND-week9 | 7eab23d5025aa9357e4096197d3d1d4f65a1d825 | [
"MIT"
] | null | null | null | <section ng-controller="FlickrController">
<img ng-hide="images" src="images/5.gif" alt="wachten trut" />
<fieldset ng-show="images">
<legend>Search Images</legend>
<div class="form-container">
<label for="searchText">Search for</label>
<input type="text" placeholder="query..." id="searchText" class="form-control" ng-model="searchQuery" />
</div>
<div class="form-container">
<label for="sortOn">Sort on</label>
<select id="sortOn" class="form-control" ng-model="sortProperty">
<option value="title">Title ASC</option>
<option value="-title">Title DESC</option> <!-- - is voor aflopend, + voor oplopend -->
</select>
</div>
<div class="form-container">
<label for="searchinImagesText">Search in found images</label>
<input type="text" ng-model="filterQuery" class="form-control" name="searchinImagesText" placeholder="cats..." />
</div>
<div class="form-container">
<button type="button" class="btn btn-primary" ng-click="searchImages()">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</fieldset>
<div ng-show="images" id="wrapper">
<ul id="imageList">
<li class="flickrimage" ng-class="checkandStyleTitle(i)" ng-repeat="i in images | orderBy:sortProperty | filter:filterImages"> <!-- 'title' op de title, zonder de '' sorteren op iets met propertyname title -->
<flickrimage></flickrimage>
</li>
</ul>
</div>
</section>
| 35.642857 | 215 | 0.634603 |
197e0a908d47dcddb164d3765370a15026cc02a4 | 321 | dart | Dart | app/lib/util/localization.dart | hpi-studyu/studyu | 92fa1903ddb782d60f4d4e93f13be79e3095e8eb | [
"MIT"
] | 10 | 2021-01-05T14:57:09.000Z | 2021-11-09T14:35:47.000Z | app/lib/util/localization.dart | hpi-studyu/studyu | 92fa1903ddb782d60f4d4e93f13be79e3095e8eb | [
"MIT"
] | 5 | 2021-03-13T18:26:27.000Z | 2021-07-13T18:23:12.000Z | app/lib/util/localization.dart | hpi-studyu/studyu | 92fa1903ddb782d60f4d4e93f13be79e3095e8eb | [
"MIT"
] | 2 | 2021-03-10T13:54:39.000Z | 2021-06-20T14:18:25.000Z | import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
String localeName(BuildContext context, String countryCode) {
final localeStrings = {
'en': AppLocalizations.of(context).en,
'de': AppLocalizations.of(context).de,
};
return localeStrings[countryCode];
}
| 29.181818 | 61 | 0.757009 |
96f452cc4a8925491beb34a1d5ac9e4957f115df | 165 | cc | C++ | src/sharedLibraries/source/OptimizedMethodJoin.cc | venkate5hgunda/CSE598-Spring22-Group22-NetsDB | 6c2dabd1a3b3f5901a97c788423fdd93cc0015d4 | [
"Apache-2.0"
] | 13 | 2022-01-17T16:14:26.000Z | 2022-03-30T02:06:04.000Z | src/sharedLibraries/source/OptimizedMethodJoin.cc | venkate5hgunda/CSE598-Spring22-Group22-NetsDB | 6c2dabd1a3b3f5901a97c788423fdd93cc0015d4 | [
"Apache-2.0"
] | 1 | 2022-01-28T23:17:14.000Z | 2022-01-28T23:17:14.000Z | src/sharedLibraries/source/OptimizedMethodJoin.cc | venkate5hgunda/CSE598-Spring22-Group22-NetsDB | 6c2dabd1a3b3f5901a97c788423fdd93cc0015d4 | [
"Apache-2.0"
] | 3 | 2022-01-18T02:13:53.000Z | 2022-03-06T19:28:19.000Z | #ifndef OPTIMIZED_METHOD_JOIN_CC
#define OPTIMIZED_METHOD_JOIN_CC
#include "OptimizedMethodJoin.h"
#include "GetVTable.h"
GET_V_TABLE(OptimizedMethodJoin)
#endif
| 16.5 | 32 | 0.842424 |
e51b96e5c62990faf6772750723f8780ff96cff2 | 4,711 | html | HTML | demo/index.html | ioncache/collapsible-selector | 6e34b3def2f4782f4e5301d62a7d70801ddcca3f | [
"MIT"
] | null | null | null | demo/index.html | ioncache/collapsible-selector | 6e34b3def2f4782f4e5301d62a7d70801ddcca3f | [
"MIT"
] | 12 | 2019-09-30T12:06:30.000Z | 2022-03-15T10:05:01.000Z | demo/index.html | ioncache/collapsible-selector | 6e34b3def2f4782f4e5301d62a7d70801ddcca3f | [
"MIT"
] | null | null | null | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>collapsible-selector demo</title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script src="../../webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../split-me/dist/split-me.js"></script>
<link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html">
<link rel="import" href="../../iron-demo-helpers/demo-snippet.html">
<link rel="import" href="../collapsible-selector.html">
<style is="custom-style" include="demo-pages-shared-styles"></style>
<style>
.centered {
max-width: 100% !important;
}
h3 {
margin-left: auto;
margin-right: auto;
width: 800px;
}
</style>
</head>
<body>
<div class="vertical-section-container centered">
<h3>Basic collapsible-selector demo</h3>
<collapsible-selector-demo></collapsible-selector-demo>
<dom-module id="collapsible-selector-demo">
<template>
<style>
.currently-selected {
margin-bottom: 15px;
}
.demo-container {
border: 1px solid black;
box-sizing: border-box;
margin: 0 auto;
padding: 10px;
max-width: 800px;
min-width: 285px;
}
split-me > * {
padding: 20px;
}
</style>
<div class="demo-container">
<split-me n="2" min-sizes="0.2, 0.2">
<div slot="0">
<div class="currently-selected">Currently selected: [[selectedItem]]</div>
<template is="dom-repeat" items="[[tabs]]">
<div>
<input type="checkbox" id="[[item.name]]" name="framework[]" value="[[item.name]]" checked$="[[item.selected]]" on-change="_changeSelected">
<label for="[[item.name]]">[[item.name]]</label>
</div>
</template>
</div>
<collapsible-selector
dropdown-button-text="More"
items="[[selectedTabs]]"
selected-item="{{selectedItem}}"
slot="1"
resize-event-name="selectorResized"
></collapsible-selector>
</split-me>
</div>
</template>
</dome-module>
</div>
</body>
<script>
'use strict';
Polymer({
is: 'collapsible-selector-demo',
properties: {
selectedItem: {
type: String,
value: 'Elm'
},
selectedTabs: {
type: Array,
value: []
},
tabs: {
type: Array,
value: [
{
name: 'Angular',
selected: true
},
{
name: 'AngularJS',
selected: false
},
{
name: 'Aurelia',
selected: true
},
{
name: 'Backbone',
selected: false
},
{
name: 'Elm',
selected: true
},
{
name: 'Ember',
selected: false
},
{
name: 'Meteor',
selected: true
},
{
name: 'Mithril',
selected: true
},
{
name: 'Polymer',
selected: true
},
{
name: 'React',
selected: true
},
{
name: 'Vue',
selected: true
}
]
}
},
observers: [
'_tabsChanged(tabs.*)'
],
attached: function() {
this.listen(this.querySelector('split-me'), 'slotResized', '_handleResize');
},
_changeSelected: function(e) {
const changedIndex = this.tabs.findIndex(i => i.name === e.target.id);
this.tabs[changedIndex].selected = !this.tabs[changedIndex].selected;
this.notifyPath(`tabs.#${changedIndex}.selected`);
},
_handleResize: function(e) {
this.fire('selectorResized');
},
_tabsChanged: function(change) {
this.set('selectedTabs', this.tabs.filter(i => i.selected).map(i => {
return {
display: i.name,
value: i.name
};
}));
}
});
</script>
</html>
| 25.743169 | 160 | 0.454893 |
05f82306d41181b6e36feca70b86d6e7ca5a617e | 3,408 | lua | Lua | .config/awesome/ui/tags.lua | HishamAHai/Dotfiles | cf51e1257768989b4b6cab740c4dbb0111b848e5 | [
"MIT"
] | null | null | null | .config/awesome/ui/tags.lua | HishamAHai/Dotfiles | cf51e1257768989b4b6cab740c4dbb0111b848e5 | [
"MIT"
] | null | null | null | .config/awesome/ui/tags.lua | HishamAHai/Dotfiles | cf51e1257768989b4b6cab740c4dbb0111b848e5 | [
"MIT"
] | null | null | null | local gears = require('gears')
local awful = require('awful')
local wibox = require('wibox')
require('widgets.decoration')
local beautiful = require('beautiful')
local bling = require('modules.bling')
local tags = {}
awful.screen.connect_for_each_screen(function(s)
awful.tag.add('',{
name = '⠚⠁⠧⠗⠊⠎', -- JARVIS
id = '1',
layout = awful.layout.suit.tile,
--layout = bling.layout.centered,
gap_single_client = true,
gap = 6,
selected = true
}
)
awful.tag.add('',{
name = '⠞⠁⠗⠎', -- TARS
id = '2',
layout = awful.layout.suit.tile,
master_width_factor = 0.6,
gap_single_client = true,
gap = 6,
}
)
awful.tag.add('',{
name = '⠍⠕⠞⠓⠑⠗', -- MOTHER
id = '3',
layout = awful.layout.suit.tile,
gap_single_client = true,
gap = 6,
}
)
awful.tag.add('',{
name = '⠓⠁⠇', -- HAL
id = '4',
layout = awful.layout.suit.tile,
gap_single_client = true,
gap = 6,
}
)
awful.tag.add('',{
name = '⠎⠅⠽⠝⠑⠞', -- SKYNET
id = '5',
layout = awful.layout.suit.tile,
gap_single_client = true,
gap = 6,
}
)
awful.tag.add('',{
name = '⠋⠗⠊⠙⠁⠽', -- FRIDAY
id = '6',
layout = awful.layout.suit.tile,
master_width_factor = 0.75,
gap_single_client = true,
gap = 6,
}
)
awful.tag.add('',{
name = '⠧⠕⠽⠁⠛⠑⠗', --VOYAGER
id = '7',
layout = awful.layout.suit.tile,
gap_single_client = true,
gap = 3,
}
)
mytasklist = awful.widget.tasklist {
screen = s,
filter = awful.widget.tasklist.filter.focused,
style = {
shape = Wdt_shape,
bg_focus = Wdt_bg,
align = 'center'
},
layout = {
spacing = 5,
max_widget_size = awful.screen.focused().geometry.width * 0.13,
layout = wibox.layout.flex.horizontal
},
widget_template = {
{
{
{
id = 'text_role',
widget = wibox.widget.textbox,
},
layout = wibox.layout.fixed.horizontal,
},
left = 10,
right = 10,
widget = wibox.container.margin
},
id = 'background_role',
widget = wibox.container.background,
},
}
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(gears.table.join(
awful.button({ }, 1, function () awful.layout.inc( 1) end)))
-- Create a taglist widget
s.mytaglist = awful.widget.taglist {
screen = s,
style = {
shape = Wdt_shape,
},
layout = {
layout = wibox.layout.fixed.horizontal,
spacing = 5,
},
filter = awful.widget.taglist.filter.all,
buttons = awful.button({ }, 1, function(t) t:view_only() end)
}
end)
return tags
| 28.4 | 87 | 0.436033 |
5b1a187e36d3bc2a3aae1a14818694da8323ffb1 | 2,725 | cc | C++ | src/pythonapi/threadBaseClass.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | src/pythonapi/threadBaseClass.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | src/pythonapi/threadBaseClass.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | /***
DEVSIM
Copyright 2013 Devsim 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
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.
***/
#include "threadBaseClass.hh"
#include "mymutex.hh"
#include "mycondition.hh"
#include <cstdio>
#if _WIN32
#include <Windows.h>
struct ThreadStuff{
HANDLE hhandle;
DWORD id;
};
#else
#include <errno.h>
#include <pthread.h>
#endif
/**
* the typename is the type of the input data
*/
#if _WIN32
//unsigned (__stdcall threadFactory)(ClientData x)
DWORD WINAPI threadFactory(LPVOID x)
#else
void *(threadFactory)(void *x)
#endif
{
threadBaseClass *y = (reinterpret_cast<threadBaseClass *>(x));
y->run();
#if _WIN32
return 0;
#else
pthread_exit(0);
#endif
}
#if 0
#ifdef _WIN32
unsigned (__stdcall testfoo)(ClientData x)
#else
void (testfoo)(ClientData x)
#endif
{
#ifdef _WIN32
return 0;
#endif
}
#endif
threadBaseClass::~threadBaseClass()
{
}
size_t threadBaseClass::getThreadId()
{
#if _WIN32
ThreadStuff *p = reinterpret_cast<ThreadStuff *>(id);
return p->id;
#else
return size_t(id);
#endif
}
void threadBaseClass::start()
{
//#warning "fix all these up so they check errors
#if _WIN32
ThreadStuff *p = new ThreadStuff;
id = p;
p->hhandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
threadFactory, // thread function name
this, // argument to thread function
0, // use default creation flags
&(p->id)); // returns the thread identifier
#else
int ret=pthread_create(reinterpret_cast<pthread_t *>(&id), NULL, threadFactory, this);
if (ret != 0)
{
perror("threadBaseClass::start()");
}
#endif
}
void threadBaseClass::join()
{
#if _WIN32
ThreadStuff *p = reinterpret_cast<ThreadStuff *>(id);
WaitForSingleObject(p->hhandle, INFINITE);
#else
int ret = pthread_join(reinterpret_cast<pthread_t >(id), NULL);
if (ret != 0)
{
perror("threadBaseClass::join()");
}
#endif
}
void threadBaseClass::wait()
{
cond.wait(mutex);
}
void threadBaseClass::lock()
{
mutex.lock();
}
#if 0
void threadBaseClass::signal()
{
cond.signal();
}
#endif
void threadBaseClass::unlock()
{
mutex.unlock();
}
| 19.604317 | 88 | 0.67156 |
83dc158339bd0e2b99b7a557f3db323e9d1e4cbe | 1,426 | java | Java | src/main/java/com/vztekoverflow/lospiratos/viewmodel/actions/transactions/RepairShipViaRepayment.java | jagotu/LosPiratos | 2632c5043895503038b9eb364a2cfc6cee7066dd | [
"MIT"
] | 1 | 2020-08-09T10:06:17.000Z | 2020-08-09T10:06:17.000Z | src/main/java/com/vztekoverflow/lospiratos/viewmodel/actions/transactions/RepairShipViaRepayment.java | jagotu/LosPiratos | 2632c5043895503038b9eb364a2cfc6cee7066dd | [
"MIT"
] | 10 | 2020-07-04T11:42:33.000Z | 2020-08-01T13:35:32.000Z | src/main/java/com/vztekoverflow/lospiratos/viewmodel/actions/transactions/RepairShipViaRepayment.java | jagotu/LosPiratos | 2632c5043895503038b9eb364a2cfc6cee7066dd | [
"MIT"
] | null | null | null | package com.vztekoverflow.lospiratos.viewmodel.actions.transactions;
import com.vztekoverflow.lospiratos.viewmodel.ResourceReadOnly;
import com.vztekoverflow.lospiratos.viewmodel.actions.Action;
import com.vztekoverflow.lospiratos.viewmodel.actions.ActionIcon;
public class RepairShipViaRepayment extends RepairShip {
@Override
protected Action createCopyAndResetThis() {
return new RepairShipViaRepayment();
}
@Override
public void performOnShipInternal() {
getRelatedShip().repairShip();
}
@Override
public String getČeskéJméno() {
return "oprava lodě pomocí zaplacení";
}
@Override
protected void recomputeCost() {
if(getRelatedShip().isDestroyed()){
cost.setAll(getRelatedShip().getShipType().getBasicRepairCost());
return;
}
double coeff = 1f-(getRelatedShip().getCurrentHP() / (double) getRelatedShip().getMaxHP());
ResourceReadOnly c = getRelatedShip().getShipType().getBuyingCost().times(1/50f).times(1 + 4 * coeff);
cost.setAll(c);
}
@Override
protected boolean recomputePlannable() {
return super.recomputePlannable() && getRelatedShip().getTeam().getOwnedResource().isGreaterThanOrEqual(getCost());
}
@Override
public ActionIcon getIcon() {
return ActionIcon.repairViaPayment;
}
}
| 31 | 124 | 0.669705 |
860ca1cf71306f10f638d8bd3fc4697834df9a3c | 2,496 | java | Java | src/main/java/com/homeadvisor/kafdrop/config/ZookeeperProperties.java | csalmhof/Kafdrop | c26ed8628b36d41ce7b25827a36e59b1608cc222 | [
"Apache-2.0"
] | 399 | 2016-04-28T15:32:40.000Z | 2022-03-28T08:47:55.000Z | src/main/java/com/homeadvisor/kafdrop/config/ZookeeperProperties.java | csalmhof/Kafdrop | c26ed8628b36d41ce7b25827a36e59b1608cc222 | [
"Apache-2.0"
] | 53 | 2016-03-23T18:46:28.000Z | 2021-07-02T09:35:57.000Z | src/main/java/com/homeadvisor/kafdrop/config/ZookeeperProperties.java | AlexRogalskiy/Kafdrop | ea27d99c2822367de4239ad8f82851058c0bb163 | [
"Apache-2.0"
] | 185 | 2016-04-28T15:32:43.000Z | 2022-03-24T17:17:05.000Z | /*
* Copyright 2019 HomeAdvisor, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.homeadvisor.kafdrop.config;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ZookeeperProperties
{
public static final Pattern CONNECT_SEPARATOR = Pattern.compile("\\s*,\\s*");
@NotBlank
private String connect;
private int sessionTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(5);
private int connectTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(15);
private int retryMillis = (int) TimeUnit.SECONDS.toMillis(5);
private int maxRetries = Integer.MAX_VALUE;
public String getConnect()
{
return connect;
}
public void setConnect(String connect)
{
this.connect = connect;
}
public List<String> getConnectList()
{
return CONNECT_SEPARATOR.splitAsStream(this.connect)
.map(String::trim)
.filter(s -> s.length() > 0)
.collect(Collectors.toList());
}
public int getRetryMillis()
{
return retryMillis;
}
public void setRetryMillis(int retryMillis)
{
this.retryMillis = retryMillis;
}
public int getMaxRetries()
{
return maxRetries;
}
public void setMaxRetries(int maxRetries)
{
this.maxRetries = maxRetries;
}
public int getSessionTimeoutMillis()
{
return sessionTimeoutMillis;
}
public void setSessionTimeoutMillis(int sessionTimeoutMillis)
{
this.sessionTimeoutMillis = sessionTimeoutMillis;
}
public int getConnectTimeoutMillis()
{
return connectTimeoutMillis;
}
public void setConnectTimeoutMillis(int connectTimeoutMillis)
{
this.connectTimeoutMillis = connectTimeoutMillis;
}
}
| 24.712871 | 80 | 0.715545 |
ea1416add4f0435cb8ff5972523f279064be4fa9 | 2,746 | ps1 | PowerShell | Scripts/UpdateVariableGroup.ps1 | marvin-garcia/IoTGateway | 383a9253ae38fdfff7b2e240ec957a0546450329 | [
"MIT"
] | 1 | 2021-03-30T16:05:57.000Z | 2021-03-30T16:05:57.000Z | Scripts/UpdateVariableGroup.ps1 | marvin-garcia/IoTGateway | 383a9253ae38fdfff7b2e240ec957a0546450329 | [
"MIT"
] | 4 | 2020-12-20T02:17:07.000Z | 2020-12-20T02:17:07.000Z | Scripts/UpdateVariableGroup.ps1 | marvin-garcia/IoTGateway | 383a9253ae38fdfff7b2e240ec957a0546450329 | [
"MIT"
] | null | null | null | <#
IMPORTANT!
If a Personal Access Token (PAT) is passed among the script parameters (not recommended),
it will be used to authenticate with the DevOps site. The token must have
at least read&create permissions for variable groups.
If a PAT is not provided (recommended), the script will authenticate using the OAuth access token,
in order to be successful, two things need to be configured:
1- The agent phase must have the option 'Allow scripts to access the OAuth token' enabled.
2- The variable group must grant the Administrator role to the user
'Project Collection Build Service (xxxx)', where xxxx is the project name. You can change
the role by going to Security under the variable group you want to edit.
More info at https://stackoverflow.com/questions/52986076/having-no-permission-for-updating-variable-group-via-azure-devops-rest-api-from
#>
Param(
[string]$PAToken = $null,
[string]$VariableGroupName,
[string]$VariableName,
[bool]$VariableIsSecret = $false,
[string]$VariableValue)
#region Request authentication header
if (!!$PAToken)
{
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $PAToken)))
$headers = @{ Authorization=("Basic {0}" -f $base64AuthInfo) }
}
else
{
$headers = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
}
#endregion
#region Get variable group
$getVarGroupsUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/distributedtask/variablegroups?api-version=5.1-preview.1"
Write-Host "URL: $getVarGroupsUrl"
$response = Invoke-RestMethod -Uri $getVarGroupsUrl -Method Get -Headers $headers
$variableGroups = $response.value
Write-Host "Available variable groups: $($variableGroups.name -Join ', ')"
$variableGroup = $variableGroups | ? { $_.name -eq $VariableGroupName }
if (!$variableGroup)
{
throw "Unable to get variable group $VariableGroupName"
}
Write-Host "variable group: $($variableGroup.name | Out-String)"
#endregion
# Edit variable
$variableGroup.variables.$VariableName.value = $VariableValue
if ($VariableIsSecret) { $variableGroup.variables.$VariableName.isSecret = $true }
$json = ConvertTo-Json -InputObject $variableGroup -Depth 10
$editVariableUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/distributedtask/variablegroups/$($variableGroup.id)?api-version=5.1-preview.1"
Write-Host "URL: $editVariableUrl"
$response = Invoke-RestMethod -Uri $editVariableUrl -Method Put -Body $json -ContentType "application/json" -Headers $headers
#$response
#Write-Host "New Variable Value: $($pipeline.variables.$VariableName.value)"
| 42.246154 | 172 | 0.74909 |
9fb06beb6c92c367d357c056a95bacd6b0c06080 | 994 | asm | Assembly | Kernel/asm/libasm.asm | juangod1/SO-TP2 | 1e2487acac3e64b4e135e3a733102fe9142f8805 | [
"BSD-3-Clause"
] | 1 | 2020-04-22T02:39:31.000Z | 2020-04-22T02:39:31.000Z | Kernel/asm/libasm.asm | juangod1/SO-TP2 | 1e2487acac3e64b4e135e3a733102fe9142f8805 | [
"BSD-3-Clause"
] | null | null | null | Kernel/asm/libasm.asm | juangod1/SO-TP2 | 1e2487acac3e64b4e135e3a733102fe9142f8805 | [
"BSD-3-Clause"
] | null | null | null | GLOBAL cpuVendor
GLOBAL initialize_stack_frame
GLOBAL get_eip
GLOBAL clear_interrupts
GLOBAL set_interrupts
section .text
%macro PUSHAQ 0
push gs
push fs
push r15
push r14
push r13
push r12
push r11
push r10
push r9
push r8
push rsi
push rdi
push rbp
push rdx
push rcx
push rbx
push rax
%endmacro
%macro pushaqlite 0
push rbx
push rcx
push rdx
push rbp
push rdi
push rsi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
%endmacro
cpuVendor:
push rbp
mov rbp, rsp
push rbx
mov rax, 0
cpuid
mov [rdi], ebx
mov [rdi + 4], edx
mov [rdi + 8], ecx
mov byte [rdi+13], 0
mov rax, rdi
pop rbx
mov rsp, rbp
pop rbp
ret
initialize_stack_frame:
pop rbx
mov rcx, rsp
mov rsp, rsi
push 0x0
push rsi
push 0x202
push 0x08
push rdi
push 0x0
pushaqlite
mov rax, rsp
mov rsp, rcx
push rbx
ret
get_eip:
pop rax
ret
clear_interrupts:
cli
ret
set_interrupts:
sti
ret | 10.463158 | 29 | 0.674044 |