text
stringlengths 2
99.9k
| meta
dict |
---|---|
//
// PJUserViewController.m
// Peek
//
// Created by pjpjpj on 2018/7/26.
// Copyright © 2018年 #incloud. All rights reserved.
//
#import "PJUserViewController.h"
#import "PJUserFavoriteView.h"
@interface PJUserViewController ()
@property (nonatomic, readwrite, strong) UIImageView *userBackImageView;
@property (nonatomic, readwrite, strong) UILabel *userNameLabel;
@property (nonatomic, readwrite, assign) NSInteger attentionNum;
@property (nonatomic, readwrite, assign) NSInteger listNum;
@property (nonatomic, readwrite, strong) PJUserFavoriteView *favoriteView;
@property (nonatomic, readwrite, strong) UIScrollView *backScrollView;
@end
@implementation PJUserViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)initView {
self.view.backgroundColor = [UIColor whiteColor];
self.attentionNum = 0;
UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 30, 50, 20)];
[self.view addSubview:cancleBtn];
[cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
[cancleBtn setImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateNormal];
[cancleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, self.view.height - 64)];
[self.view addSubview:self.backScrollView];
self.backScrollView.showsVerticalScrollIndicator = NO;
self.userBackImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, self.view.width * 0.7, 140)];
[self.backScrollView addSubview:self.userBackImageView];
self.userBackImageView.image = [PJTool imageWithRoundCorner:[UIImage imageNamed:@"userBackView"] cornerRadius:8.0 size:self.userBackImageView.size];
self.userBackImageView.layer.shadowColor = [UIColor blackColor].CGColor;
self.userBackImageView.layer.shadowRadius = 5;
self.userBackImageView.layer.shadowOffset = CGSizeMake(0, 0);
self.userBackImageView.layer.shadowOpacity = 0.2;
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.userBackImageView.width, self.userBackImageView.height)];
[self.userBackImageView addSubview:backView];
backView.backgroundColor = [UIColor blackColor];
backView.alpha = 0.3;
backView.layer.cornerRadius = 8;
backView.layer.masksToBounds = YES;
self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 0, 20)];
[self.userBackImageView addSubview:self.userNameLabel];
if ([AVUser.currentUser valueForKey:@"nickName"]) {
self.userNameLabel.text = [AVUser.currentUser valueForKey:@"nickName"];
} else {
self.userNameLabel.text = @"快来设置昵称吧~";
}
self.userNameLabel.textColor = [UIColor whiteColor];
self.userNameLabel.font = [UIFont boldSystemFontOfSize:22];
[self.userNameLabel sizeToFit];
self.userNameLabel.bottom = self.userBackImageView.height - 20 - 15;
UILabel *tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.userNameLabel.left, self.userNameLabel.bottom + 5, 0, 10)];
[self.userBackImageView addSubview:tipsLabel];
tipsLabel.text = @"查看主页";
[tipsLabel sizeToFit];
tipsLabel.textColor = [UIColor whiteColor];
tipsLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightThin];
UIImageView *editImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
[self.userBackImageView addSubview:editImageView];
editImageView.right = self.userBackImageView.width - 10;
editImageView.image = [UIImage imageNamed:@"user_edit"];
CGFloat messageBtnW = self.view.width - self.userBackImageView.right - 20;
UIButton *messageButton = [[UIButton alloc] initWithFrame:CGRectMake(self.userBackImageView.right + 10, self.userBackImageView.top, messageBtnW, self.userBackImageView.height * 0.55)];
[self.backScrollView addSubview:messageButton];
[messageButton setImage:[UIImage imageNamed:@"user_message"] forState:UIControlStateNormal];
messageButton.backgroundColor = [UIColor whiteColor];
[PJTool addShadowToView:messageButton withOpacity:0.2 shadowRadius:5 andCornerRadius:8];
UIButton *settingBtn = [[UIButton alloc] initWithFrame:CGRectMake(messageButton.left, messageButton.bottom + 10, messageButton.width, self.userBackImageView.height - messageButton.height - 10)];
[self.backScrollView addSubview:settingBtn];
[settingBtn setImage:[UIImage imageNamed:@"user_setting"] forState:UIControlStateNormal];
settingBtn.backgroundColor = [UIColor whiteColor];
[PJTool addShadowToView:settingBtn withOpacity:0.2 shadowRadius:5 andCornerRadius:8];
UIView *attentionListView = ({
UIView *listView = [[UIView alloc] initWithFrame:CGRectMake(0, self.userBackImageView.bottom + 30, self.view.width, 40)];
[self.backScrollView addSubview:listView];
UIImageView *tagImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 20, 20)];
tagImageView.image = [UIImage imageNamed:@"user_tag"];
[listView addSubview:tagImageView];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(tagImageView.right + 10, 0, 50, listView.height)];
[listView addSubview:label];
label.text = @"关注";
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor blackColor];
label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightLight];
UIImageView *detailsImageView = [[UIImageView alloc] initWithFrame:CGRectMake(listView.width - 30, (listView.height - listView.height * 0.7 * 0.7)/2, 15 * 0.7, listView.height * 0.7 * 0.7)];
detailsImageView.image = [UIImage imageNamed:@"user_details"];
[listView addSubview:detailsImageView];
UILabel *attentionNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, listView.width - label.right - detailsImageView.width - 10, listView.height)];
attentionNumLabel.right = detailsImageView.left - 10;
[listView addSubview:attentionNumLabel];
attentionNumLabel.text = [NSString stringWithFormat:@"你现在有 %ld 个关注", (long)self.attentionNum];
attentionNumLabel.textAlignment = NSTextAlignmentRight;
attentionNumLabel.textColor = RGB(150, 150, 150);
attentionNumLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightLight];
listView;
});
UIView *cardListView = ({
UIView *listView = [[UIView alloc] initWithFrame:CGRectMake(0, self.userBackImageView.bottom + 30 + 40 + 20, self.view.width, 40)];
[self.backScrollView addSubview:listView];
UIImageView *tagImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 20, 20)];
tagImageView.image = [UIImage imageNamed:@"user_list"];
[listView addSubview:tagImageView];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(tagImageView.right + 10, 0, 50, listView.height)];
[listView addSubview:label];
label.text = @"清单";
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor blackColor];
label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightLight];
UIImageView *detailsImageView = [[UIImageView alloc] initWithFrame:CGRectMake(listView.width - 30, (listView.height - listView.height * 0.7 * 0.7)/2, 15 * 0.7, listView.height * 0.7 * 0.7)];
detailsImageView.image = [UIImage imageNamed:@"user_details"];
[listView addSubview:detailsImageView];
UILabel *listNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, listView.width - label.right - detailsImageView.width - 10, listView.height)];
listNumLabel.right = detailsImageView.left - 10;
[listView addSubview:listNumLabel];
listNumLabel.text = [NSString stringWithFormat:@"%ld 个清单正在进行", (long)self.attentionNum];
listNumLabel.textAlignment = NSTextAlignmentRight;
listNumLabel.textColor = RGB(150, 150, 150);
listNumLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightLight];
listView;
});
self.favoriteView = ({
PJUserFavoriteView *favoriteView = [[PJUserFavoriteView alloc] initWithFrame:CGRectMake(10, cardListView.bottom + 30, self.view.width - 20, 250)];
[self.backScrollView addSubview:favoriteView];
favoriteView;
});
if (self.favoriteView.bottom + 10 < self.view.height) {
self.backScrollView.contentSize = CGSizeMake(0, self.view.height + 1);
} else {
self.backScrollView.contentSize = CGSizeMake(0, self.favoriteView.bottom + 20);
}
}
- (void)cancleBtnClick {
[self.navigationController popViewControllerAnimated:YES];
}
@end
| {
"pile_set_name": "Github"
} |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef SLIDERSGROUP_H
#define SLIDERSGROUP_H
#include <QGroupBox>
QT_BEGIN_NAMESPACE
class QDial;
class QScrollBar;
class QSlider;
QT_END_NAMESPACE
//! [0]
class SlidersGroup : public QGroupBox
{
Q_OBJECT
public:
SlidersGroup(Qt::Orientation orientation, const QString &title,
QWidget *parent = nullptr);
signals:
void valueChanged(int value);
public slots:
void setValue(int value);
void setMinimum(int value);
void setMaximum(int value);
void invertAppearance(bool invert);
void invertKeyBindings(bool invert);
private:
QSlider *slider;
QScrollBar *scrollBar;
QDial *dial;
};
//! [0]
#endif
| {
"pile_set_name": "Github"
} |
/* contrib/spi/moddatetime--1.0.sql */
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION moddatetime" to load this file. \quit
CREATE FUNCTION moddatetime()
RETURNS trigger
AS 'MODULE_PATHNAME'
LANGUAGE C;
| {
"pile_set_name": "Github"
} |
cheats = 4
cheat0_desc = "Infinite Lives"
cheat0_code = "Z 8 49988 0 0"
cheat0_enable = false
cheat1_desc = "Infinite Grenades"
cheat1_code = "Z 8 64252 0 0"
cheat1_enable = false
cheat2_desc = "Infinite Shield"
cheat2_code = "Z 8 49447 0 0"
cheat2_enable = false
cheat3_desc = "Immunity"
cheat3_code = "Z 8 49753 195 0"
cheat3_enable = false | {
"pile_set_name": "Github"
} |
/* fsys_jfs.c - an implementation for the IBM JFS file system */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2001,2002 Free Software Foundation, Inc.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef FSYS_JFS
#include "shared.h"
#include "filesys.h"
#include "jfs.h"
#define MAX_LINK_COUNT 8
#define DTTYPE_INLINE 0
#define DTTYPE_PAGE 1
struct jfs_info
{
unsigned long bsize;
unsigned long l2bsize;
unsigned long bdlog;
unsigned long xindex;
unsigned long xlastindex;
unsigned long sindex;
unsigned long slastindex;
unsigned long de_index;
unsigned long dttype;
struct xad *xad;
ldtentry_t *de;
};
static struct jfs_info jfs;
#define xtPage ((xtpage_t *)FSYS_BUF)
#define dtPage ((dtpage_t *)((char *)FSYS_BUF + 4096))
#define fileSet ((dinode_t *)((char *)FSYS_BUF + 8192))
#define iNode ((dinode_t *)((char *)FSYS_BUF + 8192 + sizeof(dinode_t)))
#define dtRoot ((dtroot_t *)(&iNode->di_xtroot))
#ifndef GRUB_UTIL
static char *linkbuf = (char *)(FSYS_BUF - JFS_PATH_MAX); /* buffer for following symbolic links */
static char *namebuf = (char *)(FSYS_BUF - JFS_PATH_MAX - JFS_NAME_MAX - 1);
#else
static char namebuf[JFS_NAME_MAX + 1], linkbuf[JFS_PATH_MAX];
#endif
static ldtentry_t de_always[2] = {
{1, -1, 2, {'.', '.'}},
{1, -1, 1, {'.'}}
};
static int
isinxt (s64 key, s64 offset, s64 len)
{
return (key >= offset) ? (key < offset + len ? 1 : 0) : 0;
}
static struct xad *
first_extent (dinode_t *di)
{
xtpage_t *xtp;
jfs.xindex = 2;
xtp = (xtpage_t *)&di->di_xtroot;
jfs.xad = &xtp->xad[2];
if (xtp->header.flag & BT_LEAF) {
jfs.xlastindex = xtp->header.nextindex;
} else {
do {
devread (addressXAD (jfs.xad) << jfs.bdlog, 0,
sizeof(xtpage_t), (char *)xtPage);
jfs.xad = &xtPage->xad[2];
} while (!(xtPage->header.flag & BT_LEAF));
jfs.xlastindex = xtPage->header.nextindex;
}
return jfs.xad;
}
static struct xad *
next_extent (void)
{
if (++jfs.xindex < jfs.xlastindex) {
} else if (xtPage->header.next) {
devread (xtPage->header.next << jfs.bdlog, 0,
sizeof(xtpage_t), (char *)xtPage);
jfs.xlastindex = xtPage->header.nextindex;
jfs.xindex = XTENTRYSTART;
jfs.xad = &xtPage->xad[XTENTRYSTART];
} else {
return NULL;
}
return ++jfs.xad;
}
static void
di_read (u32 inum, dinode_t *di)
{
s64 key;
u32 xd, ioffset;
s64 offset;
struct xad *xad;
pxd_t pxd; /* struct size = 8 */
key = (((inum >> L2INOSPERIAG) << L2INOSPERIAG) + 4096) >> jfs.l2bsize;
xd = (inum & (INOSPERIAG - 1)) >> L2INOSPEREXT;
ioffset = ((inum & (INOSPERIAG - 1)) & (INOSPEREXT - 1)) << L2DISIZE;
xad = first_extent (fileSet);
do {
offset = offsetXAD (xad);
if (isinxt (key, offset, lengthXAD (xad))) {
devread ((addressXAD (xad) + key - offset) << jfs.bdlog,
3072 + xd*sizeof(pxd_t), sizeof(pxd_t), (char *)&pxd);
devread (addressPXD (&pxd) << jfs.bdlog,
ioffset, DISIZE, (char *)di);
break;
}
} while ((xad = next_extent ()));
}
static ldtentry_t *
next_dentry (void)
{
ldtentry_t *de;
s8 *stbl;
if (jfs.dttype == DTTYPE_INLINE) {
if (jfs.sindex < jfs.slastindex) {
return (ldtentry_t *)&dtRoot->slot[(int)dtRoot->header.stbl[jfs.sindex++]];
}
} else {
de = (ldtentry_t *)dtPage->slot;
stbl = (s8 *)&de[(int)dtPage->header.stblindex];
if (jfs.sindex < jfs.slastindex) {
return &de[(int)stbl[jfs.sindex++]];
} else if (dtPage->header.next) {
devread (dtPage->header.next << jfs.bdlog, 0,
sizeof(dtpage_t), (char *)dtPage);
jfs.slastindex = dtPage->header.nextindex;
jfs.sindex = 1;
return &de[(int)((s8 *)&de[(int)dtPage->header.stblindex])[0]];
}
}
return (jfs.de_index < 2) ? &de_always[jfs.de_index++] : NULL;
}
static ldtentry_t *
first_dentry (void)
{
dtroot_t *dtr;
pxd_t *xd;
idtentry_t *de;
dtr = (dtroot_t *)&iNode->di_xtroot;
jfs.sindex = 0;
jfs.de_index = 0;
de_always[0].inumber = iNode->di_parent;
de_always[1].inumber = iNode->di_number;
if (dtr->header.flag & BT_LEAF) {
jfs.dttype = DTTYPE_INLINE;
jfs.slastindex = dtr->header.nextindex;
} else {
de = (idtentry_t *)dtPage->slot;
jfs.dttype = DTTYPE_PAGE;
xd = &((idtentry_t *)dtr->slot)[(int)dtr->header.stbl[0]].xd;
for (;;) {
devread (addressPXD (xd) << jfs.bdlog, 0,
sizeof(dtpage_t), (char *)dtPage);
if (dtPage->header.flag & BT_LEAF)
break;
xd = &de[(int)((s8 *)&de[(int)dtPage->header.stblindex])[0]].xd;
}
jfs.slastindex = dtPage->header.nextindex;
}
return next_dentry ();
}
static dtslot_t *
next_dslot (int next)
{
return (jfs.dttype == DTTYPE_INLINE)
? (dtslot_t *)&dtRoot->slot[next]
: &((dtslot_t *)dtPage->slot)[next];
}
#if 0
static void
uni2ansi (UniChar *uni, char *ansi, int len)
{
for (; len; len--, uni++)
*ansi++ = (*uni & 0xff80) ? '?' : *(char *)uni;
}
#else
#define uni2ansi unicode_to_utf8
#endif
int
jfs_mount (void)
{
struct jfs_superblock super; /* struct size = 160 */
if (part_length < MINJFS >> SECTOR_BITS
|| !devread (SUPER1_OFF >> SECTOR_BITS, 0,
sizeof(struct jfs_superblock), (char *)&super)
|| (super.s_magic != JFS_MAGIC)
|| !devread ((AITBL_OFF >> SECTOR_BITS) + FILESYSTEM_I,
0, DISIZE, (char*)fileSet)) {
return 0;
}
jfs.bsize = super.s_bsize;
jfs.l2bsize = super.s_l2bsize;
jfs.bdlog = jfs.l2bsize - SECTOR_BITS;
return 1;
}
unsigned long
jfs_read (char *buf, unsigned long len)
{
struct xad *xad;
s64 endofprev, endofcur;
s64 offset, xadlen;
unsigned long toread, startpos, endpos;
startpos = filepos;
endpos = filepos + len;
endofprev = (1ULL << 62) - 1;
xad = first_extent (iNode);
do {
offset = offsetXAD (xad);
xadlen = lengthXAD (xad);
if (isinxt (filepos >> jfs.l2bsize, offset, xadlen)) {
endofcur = (offset + xadlen) << jfs.l2bsize;
toread = (endofcur >= endpos)
? len : (endofcur - filepos);
disk_read_func = disk_read_hook;
devread (addressXAD (xad) << jfs.bdlog,
filepos - (offset << jfs.l2bsize), toread, buf);
disk_read_func = NULL;
buf += toread;
len -= toread; /* len always >= 0 */
filepos += toread;
} else if (offset > endofprev) {
toread = ((offset << jfs.l2bsize) >= endpos)
? len : ((offset - endofprev) << jfs.l2bsize);
len -= toread;
filepos += toread;
for (; toread; toread--) {
*buf++ = 0;
}
if (len + toread < toread)
break;
continue;
}
endofprev = offset + xadlen;
xad = next_extent ();
} while (len > 0 && xad);
return filepos - startpos;
}
int
jfs_dir (char *dirname)
{
char *ptr, *rest, ch;
ldtentry_t *de;
dtslot_t *ds;
u32 inum, parent_inum;
s64 di_size;
u32 di_mode;
int cmp;
unsigned long namlen, n, link_count;
// char namebuf[JFS_NAME_MAX + 1], linkbuf[JFS_PATH_MAX];
parent_inum = inum = ROOT_I;
link_count = 0;
for (;;) {
di_read (inum, iNode);
di_size = iNode->di_size;
di_mode = iNode->di_mode;
if ((di_mode & IFMT) == IFLNK) {
if (++link_count > MAX_LINK_COUNT) {
errnum = ERR_SYMLINK_LOOP;
return 0;
}
if (di_size < (di_mode & INLINEEA ? 256 : 128)) {
grub_memmove (linkbuf, iNode->di_fastsymlink, di_size);
n = di_size;
} else if (di_size < JFS_PATH_MAX - 1) {
filepos = 0;
filemax = di_size;
n = jfs_read (linkbuf, filemax);
} else {
errnum = ERR_FILELENGTH;
return 0;
}
inum = (linkbuf[0] == '/') ? ROOT_I : parent_inum;
while (n < (JFS_PATH_MAX - 1) && (linkbuf[n++] = *dirname++));
linkbuf[n] = 0;
dirname = linkbuf;
continue;
}
if (!*dirname || isspace (*dirname)) {
if ((di_mode & IFMT) != IFREG) {
errnum = ERR_BAD_FILETYPE;
return 0;
}
filepos = 0;
filemax = di_size;
return 1;
}
if ((di_mode & IFMT) != IFDIR) {
errnum = ERR_BAD_FILETYPE;
return 0;
}
for (; *dirname == '/'; dirname++);
//for (rest = dirname; (ch = *rest) && !isspace (ch) && ch != '/'; rest++);
for (rest = dirname; (ch = *rest) && !isspace (ch) && ch != '/'; rest++)
{
if (ch == '\\')
{
rest++;
if (! (ch = *rest))
break;
}
}
*rest = 0;
de = first_dentry ();
for (;;) {
namlen = de->namlen;
if (de->next == -1) {
uni2ansi (de->name, (unsigned char *)namebuf, namlen);
namebuf[namlen] = 0;
} else {
uni2ansi (de->name, (unsigned char *)namebuf, DTLHDRDATALEN);
ptr = namebuf;
ptr += DTLHDRDATALEN;
namlen -= DTLHDRDATALEN;
ds = next_dslot (de->next);
while (ds->next != -1) {
uni2ansi (ds->name, (unsigned char *)ptr, DTSLOTDATALEN);
ptr += DTSLOTDATALEN;
namlen -= DTSLOTDATALEN;
ds = next_dslot (ds->next);
}
uni2ansi (ds->name, (unsigned char *)ptr, namlen);
ptr += namlen;
*ptr = 0;
}
cmp = (!*dirname) ? -1 : substring (dirname, namebuf, 0);
#ifndef STAGE1_5
if (print_possibilities && ch != '/'
&& cmp <= 0) {
if (print_possibilities > 0)
print_possibilities = -print_possibilities;
print_a_completion (namebuf);
} else
#endif
if (cmp == 0) {
parent_inum = inum;
inum = de->inumber;
*(dirname = rest) = ch;
break;
}
de = next_dentry ();
if (de == NULL) {
if (print_possibilities < 0)
return 1;
errnum = ERR_FILE_NOT_FOUND;
*rest = ch;
return 0;
}
}
}
}
unsigned long
jfs_embed (unsigned long *start_sector, unsigned long needed_sectors)
{
struct jfs_superblock super; /* struct size = 160 */
if (needed_sectors > 63
|| !devread (SUPER1_OFF >> SECTOR_BITS, 0,
sizeof (struct jfs_superblock),
(char *)&super)
|| (super.s_magic != JFS_MAGIC)) {
return 0;
}
*start_sector = 1;
return 1;
}
#endif /* FSYS_JFS */
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
@interface EPNameFormulaCleaner : EDProcessor
- (void)applyProcessorToObject:(id)arg1 sheet:(id)arg2;
- (bool)isObjectSupported:(id)arg1;
@end
| {
"pile_set_name": "Github"
} |
/*
* Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4266172
* @summary Verify that fix for 4266172 does not affect named inner classes.
* @author maddox
*
* @run compile/fail AnonInnerException_3.java
*/
class AnonInnerException_3 {
void foo() throws Exception {
class Inner extends AnonInnerExceptionAux {};
AnonInnerExceptionAux x = new Inner();
}
}
class AnonInnerExceptionAux {
AnonInnerExceptionAux() throws Exception {}
}
| {
"pile_set_name": "Github"
} |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
quartz-scheduler-2.x=org.apache.skywalking.apm.plugin.quartz.define.JobRunShellInterceptorInstrumentation | {
"pile_set_name": "Github"
} |
.row.admin-posts-field
.small-12.columns
h3.blog-title #{t('admin.comments')}
h4.blog-title
= link_to @post.title, blog_path(@post), target: '_blank'
table width="100%"
thead
tr
th #{t('admin.comments_head.name')}
th #{t('admin.comments_head.email')}
th #{t('admin.comments_head.content')}
th #{t('admin.comments_head.created_at')}
th #{t('admin.comments_head.operation')}
tbody
- @comments.each do |comment|
tr
td #{comment.name}
td
= mail_to comment.email
td
= simple_format(comment.content)
td
= format_time(comment.created_at)
td
= link_to t('admin.comments_head.reply'), blog_path(@post), target: '_blank', class: 'edit-post-link'
= link_to t('admin.comments_head.destroy'), admin_post_comment_path(@post, comment), method: 'DELETE', 'data-confirm'=> '确认删除?'
| {
"pile_set_name": "Github"
} |
#[macro_use]
extern crate criterion;
extern crate blockstack_lib;
extern crate rand;
use blockstack_lib::chainstate::burn::BlockHeaderHash;
use blockstack_lib::chainstate::stacks::index::{marf::MARF, storage::TrieFileStorage, MARFValue};
use criterion::Criterion;
use rand::prelude::*;
use std::fs;
fn benchmark_marf_usage(filename: &str, blocks: u32, writes_per_block: u32, reads_per_block: u32, batch: bool) {
if fs::metadata(filename).is_ok() {
fs::remove_file(filename).unwrap();
};
let f = TrieFileStorage::new(filename).unwrap();
let mut block_header = BlockHeaderHash::from_bytes(&[0u8; 32]).unwrap();
let mut marf = MARF::from_storage(f);
marf.begin(&TrieFileStorage::block_sentinel(), &block_header).unwrap();
let mut rng = rand::thread_rng();
let mut values = vec![];
for i in 0..blocks {
if batch {
let mut batch_keys = Vec::new();
let mut batch_vals = Vec::new();
for k in 0..writes_per_block {
let key = format!("{}::{}", i, k);
let mut value = [0u8; 40];
rng.fill_bytes(&mut value);
batch_keys.push(key.clone());
batch_vals.push(MARFValue(value.clone()));
values.push((key, MARFValue(value)));
}
marf.insert_batch(&batch_keys, batch_vals).unwrap();
} else {
for k in 0..writes_per_block {
let key = format!("{}::{}", i, k);
let mut value = [0u8; 40];
rng.fill_bytes(&mut value);
marf.insert(&key, MARFValue(value.clone())).unwrap();
values.push((key, MARFValue(value)));
}
}
for _k in 0..reads_per_block {
let (key, value) = values.as_slice().choose(&mut rng).unwrap();
assert_eq!(marf.get(&block_header, key).unwrap().unwrap(), *value);
}
let mut next_block_header = (i+1).to_le_bytes().to_vec();
next_block_header.resize(32, 0);
let next_block_header = BlockHeaderHash::from_bytes(next_block_header.as_slice()).unwrap();
marf.commit().unwrap();
marf.begin(&block_header, &next_block_header).unwrap();
block_header = next_block_header;
}
marf.commit().unwrap();
}
fn benchmark_marf_read(filename: &str, reads: u32, block: u32, writes_per_block: u32) {
let f = TrieFileStorage::new(filename).unwrap();
let mut block_header = block.to_le_bytes().to_vec();
block_header.resize(32, 0);
let block_header = BlockHeaderHash::from_bytes(block_header.as_slice()).unwrap();
let mut marf = MARF::from_storage(f);
let mut rng = rand::thread_rng();
for _i in 0..reads {
let i: u32 = rng.gen_range(0, block);
let k: u32 = rng.gen_range(0, writes_per_block);
let key = format!("{}::{}", i, k);
marf.get(&block_header, &key).unwrap().unwrap();
}
}
pub fn basic_usage_benchmark(c: &mut Criterion) {
c.bench_function("marf_setup_1000b_5kW", |b| b.iter(|| benchmark_marf_usage("/tmp/db.1k.sqlite", 1000, 5000, 0, false)));
c.bench_function("marf_setup_400b_5kW", |b| b.iter(|| benchmark_marf_usage("/tmp/db.400.sqlite", 1000, 5000, 0, false)));
c.bench_function("marf_read_1000b_1kW", |b| b.iter(|| benchmark_marf_read("/tmp/db.1k.sqlite", 1000, 1000, 5000)));
c.bench_function("marf_read_400b_1kW", |b| b.iter(|| benchmark_marf_read("/tmp/db.400.sqlite", 1000, 400, 5000)));
c.bench_function("marf_usage_1b_10kW_0kR", |b| b.iter(|| benchmark_marf_usage("/tmp/foo.bar.z.sqlite", 1, 10000, 0, false)));
c.bench_function("marf_usage_10b_1kW_2kR", |b| b.iter(|| benchmark_marf_usage("/tmp/foo.bar.z.sqlite", 10, 1000, 2000, false)));
c.bench_function("marf_usage_100b_5kW_20kR", |b| b.iter(|| benchmark_marf_usage("/tmp/foo.bar.z.sqlite", 20, 5000, 20000, false)));
c.bench_function("marf_usage_batches_10b_1kW_2kR", |b| b.iter(|| benchmark_marf_usage("/tmp/foo.bar.z.sqlite", 10, 1000, 2000, true)));
}
pub fn scaling_read_ratio(_c: &mut Criterion) {
}
criterion_group!(benches, basic_usage_benchmark);
criterion_main!(benches);
| {
"pile_set_name": "Github"
} |
##===- lib/Target/Sparc/TargetDesc/Makefile ----------------*- Makefile -*-===##
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
LEVEL = ../../../..
LIBRARYNAME = LLVMSparcDesc
# Hack: we need to include 'main' target directory to grab private headers
CPP.Flags += -I$(PROJ_OBJ_DIR)/.. -I$(PROJ_SRC_DIR)/..
include $(LEVEL)/Makefile.common
| {
"pile_set_name": "Github"
} |
------------------------------------------------------------------------------
-- GNAT Studio --
-- --
-- Copyright (C) 2010-2020, AdaCore --
-- --
-- This is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. This software is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY 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 distributed with this software; see file --
-- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy --
-- of the license. --
------------------------------------------------------------------------------
-- This package handles the on-the-fly creation of an environment to
-- compile a file from the currently loaded project tree without actually
-- modifying it, by creating an Extending project.
with GNATCOLL.VFS; use GNATCOLL.VFS;
with GPS.Core_Kernels; use GPS.Core_Kernels;
with GNATCOLL.Projects; use GNATCOLL.Projects;
package Extending_Environments is
type Extending_Environment is private;
function Get_File (Env : Extending_Environment) return Virtual_File;
-- Return the source file in Env
function Get_Project (Env : Extending_Environment) return Virtual_File;
-- Return the project file in Env
function Create_Extending_Environment
(Kernel : access Core_Kernel_Record'Class;
Source : Virtual_File;
Project : Project_Type) return Extending_Environment;
-- Create an extending environment needed to build Source.
-- The current Source is copied as-is from the current buffer into the
-- extending environment.
-- This environment should be Destroyed when no longer needed.
-- Project is used with aggregate projects to remove ambiguities.
procedure Destroy (Env : Extending_Environment);
-- Remove files created for Env
private
type Extending_Environment is record
Project : Project_Type := No_Project;
File : Virtual_File := No_File;
Project_File : Virtual_File := No_File;
Temporary_Dir : Virtual_File := No_File;
end record;
end Extending_Environments;
| {
"pile_set_name": "Github"
} |
//
// BWTokenField.h
// BWToolkit
//
// Created by Brandon Walkin (www.brandonwalkin.com)
// All code is provided under the New BSD license.
//
#import <Cocoa/Cocoa.h>
@interface BWTokenField : NSTokenField
{
}
@end
| {
"pile_set_name": "Github"
} |
// 20.1.2.4 Number.isNaN(number)
var $export = require('./_export');
$export($export.S, 'Number', {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.runtime.core.internal.streaming.object;
import org.mule.runtime.api.streaming.object.CursorIterator;
import org.mule.runtime.api.streaming.object.CursorIteratorProvider;
import org.mule.runtime.core.internal.streaming.AbstractCursorIterator;
import java.io.IOException;
import java.util.NoSuchElementException;
/**
* A {@link CursorIterator} which pulls its data from an {@link ObjectStreamBuffer}.
*
* @see ObjectStreamBuffer
* @since 4.0
*/
public class BufferedCursorIterator<T> extends AbstractCursorIterator<T> {
private final ObjectStreamBuffer<T> buffer;
private Bucket<T> bucket = null;
public BufferedCursorIterator(ObjectStreamBuffer<T> buffer, CursorIteratorProvider provider) {
super(provider);
this.buffer = buffer;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
return buffer.hasNext(getPosition());
}
/**
* {@inheritDoc}
*/
@Override
protected T doNext(long p) {
Position position = buffer.toPosition(p);
if (bucket == null || !bucket.contains(position)) {
Bucket<T> nextBucket = buffer.getBucketFor(position);
if (nextBucket != null) {
bucket = nextBucket;
}
}
if (bucket != null) {
return bucket.get(position.getItemIndex()).orElseThrow(NoSuchElementException::new);
} else {
throw new NoSuchElementException();
}
}
/**
* {@inheritDoc}
*/
@Override
public void release() {
bucket = null;
}
/**
* {@inheritDoc}
*/
@Override
protected void doClose() throws IOException {
}
/**
* {@inheritDoc}
*/
@Override
public int getSize() {
return buffer.getSize();
}
}
| {
"pile_set_name": "Github"
} |
### Generated automatically from Makefile.org by Configure.
##
## Makefile for OpenSSL
##
VERSION=1.0.2h
MAJOR=1
MINOR=0.2
SHLIB_VERSION_NUMBER=1.0.0
SHLIB_VERSION_HISTORY=
SHLIB_MAJOR=1
SHLIB_MINOR=0.0
SHLIB_EXT=
PLATFORM=dist
OPTIONS= no-ec_nistp_64_gcc_128 no-gmp no-jpake no-krb5 no-libunbound no-md2 no-rc5 no-rfc3779 no-sctp no-shared no-ssl-trace no-ssl2 no-store no-unit-test no-weak-ssl-ciphers no-zlib no-zlib-dynamic static-engine
CONFIGURE_ARGS=dist
SHLIB_TARGET=
# HERE indicates where this Makefile lives. This can be used to indicate
# where sub-Makefiles are expected to be. Currently has very limited usage,
# and should probably not be bothered with at all.
HERE=.
# INSTALL_PREFIX is for package builders so that they can configure
# for, say, /usr/ and yet have everything installed to /tmp/somedir/usr/.
# Normally it is left empty.
INSTALL_PREFIX=
INSTALLTOP=/usr/local/ssl
# Do not edit this manually. Use Configure --openssldir=DIR do change this!
OPENSSLDIR=/usr/local/ssl
# NO_IDEA - Define to build without the IDEA algorithm
# NO_RC4 - Define to build without the RC4 algorithm
# NO_RC2 - Define to build without the RC2 algorithm
# THREADS - Define when building with threads, you will probably also need any
# system defines as well, i.e. _REENTERANT for Solaris 2.[34]
# TERMIO - Define the termio terminal subsystem, needed if sgtty is missing.
# TERMIOS - Define the termios terminal subsystem, Silicon Graphics.
# LONGCRYPT - Define to use HPUX 10.x's long password modification to crypt(3).
# DEVRANDOM - Give this the value of the 'random device' if your OS supports
# one. 32 bytes will be read from this when the random
# number generator is initalised.
# SSL_FORBID_ENULL - define if you want the server to be not able to use the
# NULL encryption ciphers.
#
# LOCK_DEBUG - turns on lots of lock debug output :-)
# REF_CHECK - turn on some xyz_free() assertions.
# REF_PRINT - prints some stuff on structure free.
# CRYPTO_MDEBUG - turns on my 'memory leak' detecting stuff
# MFUNC - Make all Malloc/Free/Realloc calls call
# CRYPTO_malloc/CRYPTO_free/CRYPTO_realloc which can be setup to
# call application defined callbacks via CRYPTO_set_mem_functions()
# MD5_ASM needs to be defined to use the x86 assembler for MD5
# SHA1_ASM needs to be defined to use the x86 assembler for SHA1
# RMD160_ASM needs to be defined to use the x86 assembler for RIPEMD160
# Do not define B_ENDIAN or L_ENDIAN if 'unsigned long' == 8. It must
# equal 4.
# PKCS1_CHECK - pkcs1 tests.
CC= cc
CFLAG= -O
DEPFLAG= -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS
PEX_LIBS=
EX_LIBS=
EXE_EXT=
ARFLAGS=
AR= ar $(ARFLAGS) r
RANLIB= /usr/bin/ranlib
NM= nm
PERL= /usr/bin/perl
TAR= tar
TARFLAGS= --no-recursion
MAKEDEPPROG=makedepend
LIBDIR=lib
# We let the C compiler driver to take care of .s files. This is done in
# order to be excused from maintaining a separate set of architecture
# dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC
# gcc, then the driver will automatically translate it to -xarch=v8plus
# and pass it down to assembler.
AS=$(CC) -c
ASFLAG=$(CFLAG)
# For x86 assembler: Set PROCESSOR to 386 if you want to support
# the 80386.
PROCESSOR=
# CPUID module collects small commonly used assembler snippets
CPUID_OBJ= mem_clr.o
BN_ASM= bn_asm.o
EC_ASM=
DES_ENC= des_enc.o fcrypt_b.o
AES_ENC= aes_core.o aes_cbc.o
BF_ENC= bf_enc.o
CAST_ENC= c_enc.o
RC4_ENC= rc4_enc.o rc4_skey.o
RC5_ENC= rc5_enc.o
MD5_ASM_OBJ=
SHA1_ASM_OBJ=
RMD160_ASM_OBJ=
WP_ASM_OBJ= wp_block.o
CMLL_ENC= camellia.o cmll_misc.o cmll_cbc.o
MODES_ASM_OBJ=
ENGINES_ASM_OBJ=
PERLASM_SCHEME=
# KRB5 stuff
KRB5_INCLUDES=
LIBKRB5=
# Zlib stuff
ZLIB_INCLUDE=
LIBZLIB=
# TOP level FIPS install directory.
FIPSDIR=/usr/local/ssl/fips-2.0
# This is the location of fipscanister.o and friends.
# The FIPS module build will place it $(INSTALLTOP)/lib
# but since $(INSTALLTOP) can only take the default value
# when the module is built it will be in /usr/local/ssl/lib
# $(INSTALLTOP) for this build may be different so hard
# code the path.
FIPSLIBDIR=
# The location of the library which contains fipscanister.o
# normally it will be libcrypto unless fipsdso is set in which
# case it will be libfips. If not compiling in FIPS mode at all
# this is empty making it a useful test for a FIPS compile.
FIPSCANLIB=
# Shared library base address. Currently only used on Windows.
#
BASEADDR=0xFB00000
DIRS= crypto ssl engines apps test tools
ENGDIRS= ccgost
SHLIBDIRS= crypto ssl
# dirs in crypto to build
SDIRS= \
objects \
md4 md5 sha mdc2 hmac ripemd whrlpool \
des aes rc2 rc4 idea bf cast camellia seed modes \
bn ec rsa dsa ecdsa dh ecdh dso engine \
buffer bio stack lhash rand err \
evp asn1 pem x509 x509v3 conf txt_db pkcs7 pkcs12 comp ocsp ui krb5 \
cms pqueue ts srp cmac
# keep in mind that the above list is adjusted by ./Configure
# according to no-xxx arguments...
# tests to perform. "alltests" is a special word indicating that all tests
# should be performed.
TESTS = alltests
MAKEFILE= Makefile
MANDIR=$(OPENSSLDIR)/man
MAN1=1
MAN3=3
MANSUFFIX=
HTMLSUFFIX=html
HTMLDIR=$(OPENSSLDIR)/html
SHELL=/bin/sh
TOP= .
ONEDIRS=out tmp
EDIRS= times doc bugs util include certs ms shlib mt demos perl sf dep VMS
WDIRS= windows
LIBS= libcrypto.a libssl.a
SHARED_CRYPTO=libcrypto$(SHLIB_EXT)
SHARED_SSL=libssl$(SHLIB_EXT)
SHARED_LIBS=
SHARED_LIBS_LINK_EXTS=
SHARED_LDFLAGS=
GENERAL= Makefile
BASENAME= openssl
NAME= $(BASENAME)-$(VERSION)
TARFILE= ../$(NAME).tar
EXHEADER= e_os2.h
HEADER= e_os.h
all: Makefile build_all
# as we stick to -e, CLEARENV ensures that local variables in lower
# Makefiles remain local and variable. $${VAR+VAR} is tribute to Korn
# shell, which [annoyingly enough] terminates unset with error if VAR
# is not present:-( TOP= && unset TOP is tribute to HP-UX /bin/sh,
# which terminates unset with error if no variable was present:-(
CLEARENV= TOP= && unset TOP $${LIB+LIB} $${LIBS+LIBS} \
$${INCLUDE+INCLUDE} $${INCLUDES+INCLUDES} \
$${DIR+DIR} $${DIRS+DIRS} $${SRC+SRC} \
$${LIBSRC+LIBSRC} $${LIBOBJ+LIBOBJ} $${ALL+ALL} \
$${EXHEADER+EXHEADER} $${HEADER+HEADER} \
$${GENERAL+GENERAL} $${CFLAGS+CFLAGS} \
$${ASFLAGS+ASFLAGS} $${AFLAGS+AFLAGS} \
$${LDCMD+LDCMD} $${LDFLAGS+LDFLAGS} $${SCRIPTS+SCRIPTS} \
$${SHAREDCMD+SHAREDCMD} $${SHAREDFLAGS+SHAREDFLAGS} \
$${SHARED_LIB+SHARED_LIB} $${LIBEXTRAS+LIBEXTRAS}
# LC_ALL=C ensures that error [and other] messages are delivered in
# same language for uniform treatment.
BUILDENV= LC_ALL=C PLATFORM='$(PLATFORM)' PROCESSOR='$(PROCESSOR)'\
CC='$(CC)' CFLAG='$(CFLAG)' \
AS='$(CC)' ASFLAG='$(CFLAG) -c' \
AR='$(AR)' NM='$(NM)' RANLIB='$(RANLIB)' \
CROSS_COMPILE='$(CROSS_COMPILE)' \
PERL='$(PERL)' ENGDIRS='$(ENGDIRS)' \
SDIRS='$(SDIRS)' LIBRPATH='$(INSTALLTOP)/$(LIBDIR)' \
INSTALL_PREFIX='$(INSTALL_PREFIX)' \
INSTALLTOP='$(INSTALLTOP)' OPENSSLDIR='$(OPENSSLDIR)' \
LIBDIR='$(LIBDIR)' \
MAKEDEPEND='$$$${TOP}/util/domd $$$${TOP} -MD $(MAKEDEPPROG)' \
DEPFLAG='-DOPENSSL_NO_DEPRECATED $(DEPFLAG)' \
MAKEDEPPROG='$(MAKEDEPPROG)' \
SHARED_LDFLAGS='$(SHARED_LDFLAGS)' \
KRB5_INCLUDES='$(KRB5_INCLUDES)' LIBKRB5='$(LIBKRB5)' \
ZLIB_INCLUDE='$(ZLIB_INCLUDE)' LIBZLIB='$(LIBZLIB)' \
EXE_EXT='$(EXE_EXT)' SHARED_LIBS='$(SHARED_LIBS)' \
SHLIB_EXT='$(SHLIB_EXT)' SHLIB_TARGET='$(SHLIB_TARGET)' \
PEX_LIBS='$(PEX_LIBS)' EX_LIBS='$(EX_LIBS)' \
CPUID_OBJ='$(CPUID_OBJ)' BN_ASM='$(BN_ASM)' \
EC_ASM='$(EC_ASM)' DES_ENC='$(DES_ENC)' \
AES_ENC='$(AES_ENC)' CMLL_ENC='$(CMLL_ENC)' \
BF_ENC='$(BF_ENC)' CAST_ENC='$(CAST_ENC)' \
RC4_ENC='$(RC4_ENC)' RC5_ENC='$(RC5_ENC)' \
SHA1_ASM_OBJ='$(SHA1_ASM_OBJ)' \
MD5_ASM_OBJ='$(MD5_ASM_OBJ)' \
RMD160_ASM_OBJ='$(RMD160_ASM_OBJ)' \
WP_ASM_OBJ='$(WP_ASM_OBJ)' \
MODES_ASM_OBJ='$(MODES_ASM_OBJ)' \
ENGINES_ASM_OBJ='$(ENGINES_ASM_OBJ)' \
PERLASM_SCHEME='$(PERLASM_SCHEME)' \
FIPSLIBDIR='${FIPSLIBDIR}' \
FIPSDIR='${FIPSDIR}' \
FIPSCANLIB="$${FIPSCANLIB:-$(FIPSCANLIB)}" \
THIS=$${THIS:-$@} MAKEFILE=Makefile MAKEOVERRIDES=
# MAKEOVERRIDES= effectively "equalizes" GNU-ish and SysV-ish make flavors,
# which in turn eliminates ambiguities in variable treatment with -e.
# BUILD_CMD is a generic macro to build a given target in a given
# subdirectory. The target must be given through the shell variable
# `target' and the subdirectory to build in must be given through `dir'.
# This macro shouldn't be used directly, use RECURSIVE_BUILD_CMD or
# BUILD_ONE_CMD instead.
#
# BUILD_ONE_CMD is a macro to build a given target in a given
# subdirectory if that subdirectory is part of $(DIRS). It requires
# exactly the same shell variables as BUILD_CMD.
#
# RECURSIVE_BUILD_CMD is a macro to build a given target in all
# subdirectories defined in $(DIRS). It requires that the target
# is given through the shell variable `target'.
BUILD_CMD= if [ -d "$$dir" ]; then \
( cd $$dir && echo "making $$target in $$dir..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. DIR=$$dir $$target \
) || exit 1; \
fi
RECURSIVE_BUILD_CMD=for dir in $(DIRS); do $(BUILD_CMD); done
BUILD_ONE_CMD=\
if expr " $(DIRS) " : ".* $$dir " >/dev/null 2>&1; then \
$(BUILD_CMD); \
fi
reflect:
@[ -n "$(THIS)" ] && $(CLEARENV) && $(MAKE) $(THIS) -e $(BUILDENV)
sub_all: build_all
build_all: build_libs build_apps build_tests build_tools
build_libs: build_libcrypto build_libssl openssl.pc
build_libcrypto: build_crypto build_engines libcrypto.pc
build_libssl: build_ssl libssl.pc
build_crypto:
@dir=crypto; target=all; $(BUILD_ONE_CMD)
build_ssl: build_crypto
@dir=ssl; target=all; $(BUILD_ONE_CMD)
build_engines: build_crypto
@dir=engines; target=all; $(BUILD_ONE_CMD)
build_apps: build_libs
@dir=apps; target=all; $(BUILD_ONE_CMD)
build_tests: build_libs
@dir=test; target=all; $(BUILD_ONE_CMD)
build_tools: build_libs
@dir=tools; target=all; $(BUILD_ONE_CMD)
all_testapps: build_libs build_testapps
build_testapps:
@dir=crypto; target=testapps; $(BUILD_ONE_CMD)
fips_premain_dso$(EXE_EXT): libcrypto.a
[ -z "$(FIPSCANLIB)" ] || $(CC) $(CFLAG) -Iinclude \
-DFINGERPRINT_PREMAIN_DSO_LOAD -o $@ \
$(FIPSLIBDIR)fips_premain.c $(FIPSLIBDIR)fipscanister.o \
libcrypto.a $(EX_LIBS)
libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT)
@if [ "$(SHLIB_TARGET)" != "" ]; then \
if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \
FIPSLD_LIBCRYPTO=libcrypto.a ; \
FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \
export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \
fi; \
$(MAKE) -e SHLIBDIRS=crypto CC="$${CC:-$(CC)}" build-shared && \
(touch -c fips_premain_dso$(EXE_EXT) || :); \
else \
echo "There's no support for shared libraries on this platform" >&2; \
exit 1; \
fi
libssl$(SHLIB_EXT): libcrypto$(SHLIB_EXT) libssl.a
@if [ "$(SHLIB_TARGET)" != "" ]; then \
$(MAKE) SHLIBDIRS=ssl SHLIBDEPS='-lcrypto' build-shared; \
else \
echo "There's no support for shared libraries on this platform" >&2; \
exit 1; \
fi
clean-shared:
@set -e; for i in $(SHLIBDIRS); do \
if [ -n "$(SHARED_LIBS_LINK_EXTS)" ]; then \
tmp="$(SHARED_LIBS_LINK_EXTS)"; \
for j in $${tmp:-x}; do \
( set -x; rm -f lib$$i$$j ); \
done; \
fi; \
( set -x; rm -f lib$$i$(SHLIB_EXT) ); \
if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \
( set -x; rm -f cyg$$i$(SHLIB_EXT) lib$$i$(SHLIB_EXT).a ); \
fi; \
done
link-shared:
@ set -e; for i in $(SHLIBDIRS); do \
$(MAKE) -f $(HERE)/Makefile.shared -e $(BUILDENV) \
LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \
LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \
symlink.$(SHLIB_TARGET); \
libs="$$libs -l$$i"; \
done
build-shared: do_$(SHLIB_TARGET) link-shared
do_$(SHLIB_TARGET):
@ set -e; libs='-L. $(SHLIBDEPS)'; for i in $(SHLIBDIRS); do \
if [ "$$i" = "ssl" -a -n "$(LIBKRB5)" ]; then \
libs="$(LIBKRB5) $$libs"; \
fi; \
$(CLEARENV) && $(MAKE) -f Makefile.shared -e $(BUILDENV) \
LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \
LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \
LIBDEPS="$$libs $(EX_LIBS)" \
link_a.$(SHLIB_TARGET); \
libs="-l$$i $$libs"; \
done
libcrypto.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL-libcrypto'; \
echo 'Description: OpenSSL cryptography library'; \
echo 'Version: '$(VERSION); \
echo 'Requires: '; \
echo 'Libs: -L$${libdir} -lcrypto'; \
echo 'Libs.private: $(EX_LIBS)'; \
echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libcrypto.pc
libssl.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL-libssl'; \
echo 'Description: Secure Sockets Layer and cryptography libraries'; \
echo 'Version: '$(VERSION); \
echo 'Requires.private: libcrypto'; \
echo 'Libs: -L$${libdir} -lssl'; \
echo 'Libs.private: $(EX_LIBS)'; \
echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libssl.pc
openssl.pc: Makefile
@ ( echo 'prefix=$(INSTALLTOP)'; \
echo 'exec_prefix=$${prefix}'; \
echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \
echo 'includedir=$${prefix}/include'; \
echo ''; \
echo 'Name: OpenSSL'; \
echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \
echo 'Version: '$(VERSION); \
echo 'Requires: libssl libcrypto' ) > openssl.pc
Makefile: Makefile.org Configure config
@echo "Makefile is older than Makefile.org, Configure or config."
@echo "Reconfigure the source tree (via './config' or 'perl Configure'), please."
@false
libclean:
rm -f *.map *.so *.so.* *.dylib *.dll engines/*.so engines/*.dll engines/*.dylib *.a engines/*.a */lib */*/lib
clean: libclean
rm -f shlib/*.o *.o core a.out fluff rehash.time testlog make.log cctest cctest.c
@set -e; target=clean; $(RECURSIVE_BUILD_CMD)
rm -f $(LIBS)
rm -f openssl.pc libssl.pc libcrypto.pc
rm -f speed.* .pure
rm -f $(TARFILE)
@set -e; for i in $(ONEDIRS) ;\
do \
rm -fr $$i/*; \
done
makefile.one: files
$(PERL) util/mk1mf.pl >makefile.one; \
sh util/do_ms.sh
files:
$(PERL) $(TOP)/util/files.pl Makefile > $(TOP)/MINFO
@set -e; target=files; $(RECURSIVE_BUILD_CMD)
links:
@$(PERL) $(TOP)/util/mkdir-p.pl include/openssl
@$(PERL) $(TOP)/util/mklink.pl include/openssl $(EXHEADER)
@set -e; target=links; $(RECURSIVE_BUILD_CMD)
gentests:
@(cd test && echo "generating dummy tests (if needed)..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on generate );
dclean:
rm -rf *.bak include/openssl certs/.0
@set -e; target=dclean; $(RECURSIVE_BUILD_CMD)
rehash: rehash.time
rehash.time: certs apps
@if [ -z "$(CROSS_COMPILE)" ]; then \
(OPENSSL="`pwd`/util/opensslwrap.sh"; \
[ -x "apps/openssl.exe" ] && OPENSSL="apps/openssl.exe" || :; \
OPENSSL_DEBUG_MEMORY=on; \
export OPENSSL OPENSSL_DEBUG_MEMORY; \
$(PERL) tools/c_rehash certs/demo) && \
touch rehash.time; \
else :; fi
test: tests
tests: rehash
@(cd test && echo "testing..." && \
$(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on OPENSSL_CONF=../apps/openssl.cnf tests );
OPENSSL_CONF=apps/openssl.cnf util/opensslwrap.sh version -a
report:
@$(PERL) util/selftest.pl
update: errors stacks util/libeay.num util/ssleay.num TABLE
@set -e; target=update; $(RECURSIVE_BUILD_CMD)
depend:
@set -e; target=depend; $(RECURSIVE_BUILD_CMD)
lint:
@set -e; target=lint; $(RECURSIVE_BUILD_CMD)
tags:
rm -f TAGS
find . -name '[^.]*.[ch]' | xargs etags -a
errors:
$(PERL) util/ck_errf.pl -strict */*.c */*/*.c
$(PERL) util/mkerr.pl -recurse -write
(cd engines; $(MAKE) PERL=$(PERL) errors)
stacks:
$(PERL) util/mkstack.pl -write
util/libeay.num::
$(PERL) util/mkdef.pl crypto update
util/ssleay.num::
$(PERL) util/mkdef.pl ssl update
TABLE: Configure
(echo 'Output of `Configure TABLE'"':"; \
$(PERL) Configure TABLE) > TABLE
# Build distribution tar-file. As the list of files returned by "find" is
# pretty long, on several platforms a "too many arguments" error or similar
# would occur. Therefore the list of files is temporarily stored into a file
# and read directly, requiring GNU-Tar. Call "make TAR=gtar dist" if the normal
# tar does not support the --files-from option.
TAR_COMMAND=$(TAR) $(TARFLAGS) --files-from $(TARFILE).list \
--owner 0 --group 0 \
--transform 's|^|$(NAME)/|' \
-cvf -
$(TARFILE).list:
find * \! -name STATUS \! -name TABLE \! -name '*.o' \! -name '*.a' \
\! -name '*.so' \! -name '*.so.*' \! -name 'openssl' \
\( \! -name '*test' -o -name bctest -o -name pod2mantest \) \
\! -name '.#*' \! -name '*~' \! -type l \
| sort > $(TARFILE).list
tar: $(TARFILE).list
find . -type d -print | xargs chmod 755
find . -type f -print | xargs chmod a+r
find . -type f -perm -0100 -print | xargs chmod a+x
$(TAR_COMMAND) | gzip --best > $(TARFILE).gz
rm -f $(TARFILE).list
ls -l $(TARFILE).gz
tar-snap: $(TARFILE).list
$(TAR_COMMAND) > $(TARFILE)
rm -f $(TARFILE).list
ls -l $(TARFILE)
dist:
$(PERL) Configure dist
@$(MAKE) SDIRS='$(SDIRS)' clean
@$(MAKE) TAR='$(TAR)' TARFLAGS='$(TARFLAGS)' $(DISTTARVARS) tar
install: all install_docs install_sw
install_sw:
@$(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/bin \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR) \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines \
$(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig \
$(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl \
$(INSTALL_PREFIX)$(OPENSSLDIR)/misc \
$(INSTALL_PREFIX)$(OPENSSLDIR)/certs \
$(INSTALL_PREFIX)$(OPENSSLDIR)/private
@set -e; headerlist="$(EXHEADER)"; for i in $$headerlist;\
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
@set -e; target=install; $(RECURSIVE_BUILD_CMD)
@set -e; liblist="$(LIBS)"; for i in $$liblist ;\
do \
if [ -f "$$i" ]; then \
( echo installing $$i; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
$(RANLIB) $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i ); \
fi; \
done;
@set -e; if [ -n "$(SHARED_LIBS)" ]; then \
tmp="$(SHARED_LIBS)"; \
for i in $${tmp:-x}; \
do \
if [ -f "$$i" -o -f "$$i.a" ]; then \
( echo installing $$i; \
if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \
c=`echo $$i | sed 's/^lib\(.*\)\.dll\.a/cyg\1-$(SHLIB_VERSION_NUMBER).dll/'`; \
cp $$c $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \
chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \
else \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \
fi ); \
if expr $(PLATFORM) : 'mingw' > /dev/null; then \
( case $$i in \
*crypto*) i=libeay32.dll;; \
*ssl*) i=ssleay32.dll;; \
esac; \
echo installing $$i; \
cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \
chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \
mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \
fi; \
fi; \
done; \
( here="`pwd`"; \
cd $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR); \
$(MAKE) -f $$here/Makefile HERE="$$here" link-shared ); \
if [ "$(INSTALLTOP)" != "/usr" ]; then \
echo 'OpenSSL shared libraries have been installed in:'; \
echo ' $(INSTALLTOP)'; \
echo ''; \
sed -e '1,/^$$/d' doc/openssl-shared.txt; \
fi; \
fi
cp libcrypto.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc
cp libssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc
cp openssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc
install_html_docs:
here="`pwd`"; \
filecase=; \
case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \
filecase=-i; \
esac; \
for subdir in apps crypto ssl; do \
mkdir -p $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \
for i in doc/$$subdir/*.pod; do \
fn=`basename $$i .pod`; \
echo "installing html/$$fn.$(HTMLSUFFIX)"; \
cat $$i \
| sed -r 's/L<([^)]*)(\([0-9]\))?\|([^)]*)(\([0-9]\))?>/L<\1|\3>/g' \
| pod2html --podroot=doc --htmlroot=.. --podpath=apps:crypto:ssl \
| sed -r 's/<!DOCTYPE.*//g' \
> $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir/$$fn.$(HTMLSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
grep -v $$filecase "^$$fn\$$" | \
(cd $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$(HTMLSUFFIX) "$$n".$(HTMLSUFFIX); \
done); \
done; \
done
install_docs:
@$(PERL) $(TOP)/util/mkdir-p.pl \
$(INSTALL_PREFIX)$(MANDIR)/man1 \
$(INSTALL_PREFIX)$(MANDIR)/man3 \
$(INSTALL_PREFIX)$(MANDIR)/man5 \
$(INSTALL_PREFIX)$(MANDIR)/man7
@pod2man="`cd ./util; ./pod2mantest $(PERL)`"; \
here="`pwd`"; \
filecase=; \
case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \
filecase=-i; \
esac; \
set -e; for i in doc/apps/*.pod; do \
fn=`basename $$i .pod`; \
sec=`$(PERL) util/extract-section.pl 1 < $$i`; \
echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \
(cd `$(PERL) util/dirname.pl $$i`; \
sh -c "$$pod2man \
--section=$$sec --center=OpenSSL \
--release=$(VERSION) `basename $$i`") \
> $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
(grep -v $$filecase "^$$fn\$$"; true) | \
(grep -v "[ ]"; true) | \
(cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \
done); \
done; \
set -e; for i in doc/crypto/*.pod doc/ssl/*.pod; do \
fn=`basename $$i .pod`; \
sec=`$(PERL) util/extract-section.pl 3 < $$i`; \
echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \
(cd `$(PERL) util/dirname.pl $$i`; \
sh -c "$$pod2man \
--section=$$sec --center=OpenSSL \
--release=$(VERSION) `basename $$i`") \
> $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \
$(PERL) util/extract-names.pl < $$i | \
(grep -v $$filecase "^$$fn\$$"; true) | \
(grep -v "[ ]"; true) | \
(cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \
while read n; do \
PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \
done); \
done
# DO NOT DELETE THIS LINE -- make depend depends on it.
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
import sys, os, datetime, x_stress_util
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import utils
r = utils.import_python_driver()
class Workload:
def __init__(self, options):
self.db = options["db"]
self.table = options["table"]
self.cid_dist = x_stress_util.Pareto(1000)
self.typ_dist = x_stress_util.Pareto(10)
self.time_dist = x_stress_util.TimeDistribution(os.getenv("X_END_DATE"), os.getenv("X_DATE_INTERVAL"))
def run(self, conn):
(start_date, end_date) = self.time_dist.get()
def run(self, conn):
cid = "customer%03d" % self.cid_dist.get()
typ = "type%d" % self.typ_dist.get()
(start_date, end_date) = self.time_dist.get()
time_1 = r.time(start_date.year, start_date.month, start_date.day, 'Z')
time_2 = r.time(end_date.year, end_date.month, end_date.day, 'Z')
res = r.db(self.db).table(self.table).between([cid, time_1], [cid, time_2], index="compound") \
.filter(lambda row: row["type"].eq(typ)) \
.map(lambda row: row["arr"].reduce(lambda acc,val: acc + val).default(0)) \
.reduce(lambda acc,val: acc + val).default(0) \
.run(conn)
return {}
| {
"pile_set_name": "Github"
} |
/* Threads compatibility routines for libgcc2 and libobjc. */
/* Compile this one with gcc. */
/* Copyright (C) 1997-2013 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#ifndef _GLIBCXX_GCC_GTHR_POSIX_H
#define _GLIBCXX_GCC_GTHR_POSIX_H
/* POSIX threads specific definitions.
Easy, since the interface is just one-to-one mapping. */
#define __GTHREADS 1
#define __GTHREADS_CXX0X 1
#include <pthread.h>
#if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \
|| !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK))
# include <unistd.h>
# if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 0
# define _GTHREAD_USE_MUTEX_TIMEDLOCK 1
# else
# define _GTHREAD_USE_MUTEX_TIMEDLOCK 0
# endif
#endif
typedef pthread_t __gthread_t;
typedef pthread_key_t __gthread_key_t;
typedef pthread_once_t __gthread_once_t;
typedef pthread_mutex_t __gthread_mutex_t;
typedef pthread_mutex_t __gthread_recursive_mutex_t;
typedef pthread_cond_t __gthread_cond_t;
typedef struct timespec __gthread_time_t;
/* POSIX like conditional variables are supported. Please look at comments
in gthr.h for details. */
#define __GTHREAD_HAS_COND 1
#define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER
#define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function
#define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT
#if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
#define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER
#elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
#define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
#else
#define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function
#endif
#define __GTHREAD_COND_INIT PTHREAD_COND_INITIALIZER
#define __GTHREAD_TIME_INIT {0,0}
#ifdef _GTHREAD_USE_MUTEX_INIT_FUNC
# undef __GTHREAD_MUTEX_INIT
#endif
#ifdef _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC
# undef __GTHREAD_RECURSIVE_MUTEX_INIT
# undef __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION
# define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function
#endif
#ifdef _GTHREAD_USE_COND_INIT_FUNC
# undef __GTHREAD_COND_INIT
# define __GTHREAD_COND_INIT_FUNCTION __gthread_cond_init_function
#endif
#if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK
# ifndef __gthrw_pragma
# define __gthrw_pragma(pragma)
# endif
# define __gthrw2(name,name2,type) \
static __typeof(type) name __attribute__ ((__weakref__(#name2))); \
__gthrw_pragma(weak type)
# define __gthrw_(name) __gthrw_ ## name
#else
# define __gthrw2(name,name2,type)
# define __gthrw_(name) name
#endif
/* Typically, __gthrw_foo is a weak reference to symbol foo. */
#define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name)
__gthrw(pthread_once)
__gthrw(pthread_getspecific)
__gthrw(pthread_setspecific)
__gthrw(pthread_create)
__gthrw(pthread_join)
__gthrw(pthread_equal)
__gthrw(pthread_self)
__gthrw(pthread_detach)
#ifndef __BIONIC__
__gthrw(pthread_cancel)
#endif
__gthrw(sched_yield)
__gthrw(pthread_mutex_lock)
__gthrw(pthread_mutex_trylock)
#if _GTHREAD_USE_MUTEX_TIMEDLOCK
__gthrw(pthread_mutex_timedlock)
#endif
__gthrw(pthread_mutex_unlock)
__gthrw(pthread_mutex_init)
__gthrw(pthread_mutex_destroy)
__gthrw(pthread_cond_init)
__gthrw(pthread_cond_broadcast)
__gthrw(pthread_cond_signal)
__gthrw(pthread_cond_wait)
__gthrw(pthread_cond_timedwait)
__gthrw(pthread_cond_destroy)
__gthrw(pthread_key_create)
__gthrw(pthread_key_delete)
__gthrw(pthread_mutexattr_init)
__gthrw(pthread_mutexattr_settype)
__gthrw(pthread_mutexattr_destroy)
#if defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)
/* Objective-C. */
__gthrw(pthread_exit)
#ifdef _POSIX_PRIORITY_SCHEDULING
#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
__gthrw(sched_get_priority_max)
__gthrw(sched_get_priority_min)
#endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */
#endif /* _POSIX_PRIORITY_SCHEDULING */
__gthrw(pthread_attr_destroy)
__gthrw(pthread_attr_init)
__gthrw(pthread_attr_setdetachstate)
#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
__gthrw(pthread_getschedparam)
__gthrw(pthread_setschedparam)
#endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */
#endif /* _LIBOBJC || _LIBOBJC_WEAK */
#if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK
/* On Solaris 2.6 up to 9, the libc exposes a POSIX threads interface even if
-pthreads is not specified. The functions are dummies and most return an
error value. However pthread_once returns 0 without invoking the routine
it is passed so we cannot pretend that the interface is active if -pthreads
is not specified. On Solaris 2.5.1, the interface is not exposed at all so
we need to play the usual game with weak symbols. On Solaris 10 and up, a
working interface is always exposed. On FreeBSD 6 and later, libc also
exposes a dummy POSIX threads interface, similar to what Solaris 2.6 up
to 9 does. FreeBSD >= 700014 even provides a pthread_cancel stub in libc,
which means the alternate __gthread_active_p below cannot be used there. */
#if defined(__FreeBSD__) || (defined(__sun) && defined(__svr4__))
static volatile int __gthread_active = -1;
static void
__gthread_trigger (void)
{
__gthread_active = 1;
}
static inline int
__gthread_active_p (void)
{
static pthread_mutex_t __gthread_active_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_once_t __gthread_active_once = PTHREAD_ONCE_INIT;
/* Avoid reading __gthread_active twice on the main code path. */
int __gthread_active_latest_value = __gthread_active;
/* This test is not protected to avoid taking a lock on the main code
path so every update of __gthread_active in a threaded program must
be atomic with regard to the result of the test. */
if (__builtin_expect (__gthread_active_latest_value < 0, 0))
{
if (__gthrw_(pthread_once))
{
/* If this really is a threaded program, then we must ensure that
__gthread_active has been set to 1 before exiting this block. */
__gthrw_(pthread_mutex_lock) (&__gthread_active_mutex);
__gthrw_(pthread_once) (&__gthread_active_once, __gthread_trigger);
__gthrw_(pthread_mutex_unlock) (&__gthread_active_mutex);
}
/* Make sure we'll never enter this block again. */
if (__gthread_active < 0)
__gthread_active = 0;
__gthread_active_latest_value = __gthread_active;
}
return __gthread_active_latest_value != 0;
}
#else /* neither FreeBSD nor Solaris */
/* For a program to be multi-threaded the only thing that it certainly must
be using is pthread_create. However, there may be other libraries that
intercept pthread_create with their own definitions to wrap pthreads
functionality for some purpose. In those cases, pthread_create being
defined might not necessarily mean that libpthread is actually linked
in.
For the GNU C library, we can use a known internal name. This is always
available in the ABI, but no other library would define it. That is
ideal, since any public pthread function might be intercepted just as
pthread_create might be. __pthread_key_create is an "internal"
implementation symbol, but it is part of the public exported ABI. Also,
it's among the symbols that the static libpthread.a always links in
whenever pthread_create is used, so there is no danger of a false
negative result in any statically-linked, multi-threaded program.
For others, we choose pthread_cancel as a function that seems unlikely
to be redefined by an interceptor library. The bionic (Android) C
library does not provide pthread_cancel, so we do use pthread_create
there (and interceptor libraries lose). */
#ifdef __GLIBC__
__gthrw2(__gthrw_(__pthread_key_create),
__pthread_key_create,
pthread_key_create)
# define GTHR_ACTIVE_PROXY __gthrw_(__pthread_key_create)
#elif defined (__BIONIC__)
# define GTHR_ACTIVE_PROXY __gthrw_(pthread_create)
#else
# define GTHR_ACTIVE_PROXY __gthrw_(pthread_cancel)
#endif
static inline int
__gthread_active_p (void)
{
static void *const __gthread_active_ptr
= __extension__ (void *) >HR_ACTIVE_PROXY;
return __gthread_active_ptr != 0;
}
#endif /* FreeBSD or Solaris */
#else /* not __GXX_WEAK__ */
/* Similar to Solaris, HP-UX 11 for PA-RISC provides stubs for pthread
calls in shared flavors of the HP-UX C library. Most of the stubs
have no functionality. The details are described in the "libc cumulative
patch" for each subversion of HP-UX 11. There are two special interfaces
provided for checking whether an application is linked to a shared pthread
library or not. However, these interfaces aren't available in early
libpthread libraries. We also need a test that works for archive
libraries. We can't use pthread_once as some libc versions call the
init function. We also can't use pthread_create or pthread_attr_init
as these create a thread and thereby prevent changing the default stack
size. The function pthread_default_stacksize_np is available in both
the archive and shared versions of libpthread. It can be used to
determine the default pthread stack size. There is a stub in some
shared libc versions which returns a zero size if pthreads are not
active. We provide an equivalent stub to handle cases where libc
doesn't provide one. */
#if defined(__hppa__) && defined(__hpux__)
static volatile int __gthread_active = -1;
static inline int
__gthread_active_p (void)
{
/* Avoid reading __gthread_active twice on the main code path. */
int __gthread_active_latest_value = __gthread_active;
size_t __s;
if (__builtin_expect (__gthread_active_latest_value < 0, 0))
{
pthread_default_stacksize_np (0, &__s);
__gthread_active = __s ? 1 : 0;
__gthread_active_latest_value = __gthread_active;
}
return __gthread_active_latest_value != 0;
}
#else /* not hppa-hpux */
static inline int
__gthread_active_p (void)
{
return 1;
}
#endif /* hppa-hpux */
#endif /* __GXX_WEAK__ */
#ifdef _LIBOBJC
/* This is the config.h file in libobjc/ */
#include <config.h>
#ifdef HAVE_SCHED_H
# include <sched.h>
#endif
/* Key structure for maintaining thread specific storage */
static pthread_key_t _objc_thread_storage;
static pthread_attr_t _objc_thread_attribs;
/* Thread local storage for a single thread */
static void *thread_local_storage = NULL;
/* Backend initialization functions */
/* Initialize the threads subsystem. */
static inline int
__gthread_objc_init_thread_system (void)
{
if (__gthread_active_p ())
{
/* Initialize the thread storage key. */
if (__gthrw_(pthread_key_create) (&_objc_thread_storage, NULL) == 0)
{
/* The normal default detach state for threads is
* PTHREAD_CREATE_JOINABLE which causes threads to not die
* when you think they should. */
if (__gthrw_(pthread_attr_init) (&_objc_thread_attribs) == 0
&& __gthrw_(pthread_attr_setdetachstate) (&_objc_thread_attribs,
PTHREAD_CREATE_DETACHED) == 0)
return 0;
}
}
return -1;
}
/* Close the threads subsystem. */
static inline int
__gthread_objc_close_thread_system (void)
{
if (__gthread_active_p ()
&& __gthrw_(pthread_key_delete) (_objc_thread_storage) == 0
&& __gthrw_(pthread_attr_destroy) (&_objc_thread_attribs) == 0)
return 0;
return -1;
}
/* Backend thread functions */
/* Create a new thread of execution. */
static inline objc_thread_t
__gthread_objc_thread_detach (void (*func)(void *), void *arg)
{
objc_thread_t thread_id;
pthread_t new_thread_handle;
if (!__gthread_active_p ())
return NULL;
if (!(__gthrw_(pthread_create) (&new_thread_handle, &_objc_thread_attribs,
(void *) func, arg)))
thread_id = (objc_thread_t) new_thread_handle;
else
thread_id = NULL;
return thread_id;
}
/* Set the current thread's priority. */
static inline int
__gthread_objc_thread_set_priority (int priority)
{
if (!__gthread_active_p ())
return -1;
else
{
#ifdef _POSIX_PRIORITY_SCHEDULING
#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
pthread_t thread_id = __gthrw_(pthread_self) ();
int policy;
struct sched_param params;
int priority_min, priority_max;
if (__gthrw_(pthread_getschedparam) (thread_id, &policy, ¶ms) == 0)
{
if ((priority_max = __gthrw_(sched_get_priority_max) (policy)) == -1)
return -1;
if ((priority_min = __gthrw_(sched_get_priority_min) (policy)) == -1)
return -1;
if (priority > priority_max)
priority = priority_max;
else if (priority < priority_min)
priority = priority_min;
params.sched_priority = priority;
/*
* The solaris 7 and several other man pages incorrectly state that
* this should be a pointer to policy but pthread.h is universally
* at odds with this.
*/
if (__gthrw_(pthread_setschedparam) (thread_id, policy, ¶ms) == 0)
return 0;
}
#endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */
#endif /* _POSIX_PRIORITY_SCHEDULING */
return -1;
}
}
/* Return the current thread's priority. */
static inline int
__gthread_objc_thread_get_priority (void)
{
#ifdef _POSIX_PRIORITY_SCHEDULING
#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
if (__gthread_active_p ())
{
int policy;
struct sched_param params;
if (__gthrw_(pthread_getschedparam) (__gthrw_(pthread_self) (), &policy, ¶ms) == 0)
return params.sched_priority;
else
return -1;
}
else
#endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */
#endif /* _POSIX_PRIORITY_SCHEDULING */
return OBJC_THREAD_INTERACTIVE_PRIORITY;
}
/* Yield our process time to another thread. */
static inline void
__gthread_objc_thread_yield (void)
{
if (__gthread_active_p ())
__gthrw_(sched_yield) ();
}
/* Terminate the current thread. */
static inline int
__gthread_objc_thread_exit (void)
{
if (__gthread_active_p ())
/* exit the thread */
__gthrw_(pthread_exit) (&__objc_thread_exit_status);
/* Failed if we reached here */
return -1;
}
/* Returns an integer value which uniquely describes a thread. */
static inline objc_thread_t
__gthread_objc_thread_id (void)
{
if (__gthread_active_p ())
return (objc_thread_t) __gthrw_(pthread_self) ();
else
return (objc_thread_t) 1;
}
/* Sets the thread's local storage pointer. */
static inline int
__gthread_objc_thread_set_data (void *value)
{
if (__gthread_active_p ())
return __gthrw_(pthread_setspecific) (_objc_thread_storage, value);
else
{
thread_local_storage = value;
return 0;
}
}
/* Returns the thread's local storage pointer. */
static inline void *
__gthread_objc_thread_get_data (void)
{
if (__gthread_active_p ())
return __gthrw_(pthread_getspecific) (_objc_thread_storage);
else
return thread_local_storage;
}
/* Backend mutex functions */
/* Allocate a mutex. */
static inline int
__gthread_objc_mutex_allocate (objc_mutex_t mutex)
{
if (__gthread_active_p ())
{
mutex->backend = objc_malloc (sizeof (pthread_mutex_t));
if (__gthrw_(pthread_mutex_init) ((pthread_mutex_t *) mutex->backend, NULL))
{
objc_free (mutex->backend);
mutex->backend = NULL;
return -1;
}
}
return 0;
}
/* Deallocate a mutex. */
static inline int
__gthread_objc_mutex_deallocate (objc_mutex_t mutex)
{
if (__gthread_active_p ())
{
int count;
/*
* Posix Threads specifically require that the thread be unlocked
* for __gthrw_(pthread_mutex_destroy) to work.
*/
do
{
count = __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend);
if (count < 0)
return -1;
}
while (count);
if (__gthrw_(pthread_mutex_destroy) ((pthread_mutex_t *) mutex->backend))
return -1;
objc_free (mutex->backend);
mutex->backend = NULL;
}
return 0;
}
/* Grab a lock on a mutex. */
static inline int
__gthread_objc_mutex_lock (objc_mutex_t mutex)
{
if (__gthread_active_p ()
&& __gthrw_(pthread_mutex_lock) ((pthread_mutex_t *) mutex->backend) != 0)
{
return -1;
}
return 0;
}
/* Try to grab a lock on a mutex. */
static inline int
__gthread_objc_mutex_trylock (objc_mutex_t mutex)
{
if (__gthread_active_p ()
&& __gthrw_(pthread_mutex_trylock) ((pthread_mutex_t *) mutex->backend) != 0)
{
return -1;
}
return 0;
}
/* Unlock the mutex */
static inline int
__gthread_objc_mutex_unlock (objc_mutex_t mutex)
{
if (__gthread_active_p ()
&& __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend) != 0)
{
return -1;
}
return 0;
}
/* Backend condition mutex functions */
/* Allocate a condition. */
static inline int
__gthread_objc_condition_allocate (objc_condition_t condition)
{
if (__gthread_active_p ())
{
condition->backend = objc_malloc (sizeof (pthread_cond_t));
if (__gthrw_(pthread_cond_init) ((pthread_cond_t *) condition->backend, NULL))
{
objc_free (condition->backend);
condition->backend = NULL;
return -1;
}
}
return 0;
}
/* Deallocate a condition. */
static inline int
__gthread_objc_condition_deallocate (objc_condition_t condition)
{
if (__gthread_active_p ())
{
if (__gthrw_(pthread_cond_destroy) ((pthread_cond_t *) condition->backend))
return -1;
objc_free (condition->backend);
condition->backend = NULL;
}
return 0;
}
/* Wait on the condition */
static inline int
__gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex)
{
if (__gthread_active_p ())
return __gthrw_(pthread_cond_wait) ((pthread_cond_t *) condition->backend,
(pthread_mutex_t *) mutex->backend);
else
return 0;
}
/* Wake up all threads waiting on this condition. */
static inline int
__gthread_objc_condition_broadcast (objc_condition_t condition)
{
if (__gthread_active_p ())
return __gthrw_(pthread_cond_broadcast) ((pthread_cond_t *) condition->backend);
else
return 0;
}
/* Wake up one thread waiting on this condition. */
static inline int
__gthread_objc_condition_signal (objc_condition_t condition)
{
if (__gthread_active_p ())
return __gthrw_(pthread_cond_signal) ((pthread_cond_t *) condition->backend);
else
return 0;
}
#else /* _LIBOBJC */
static inline int
__gthread_create (__gthread_t *__threadid, void *(*__func) (void*),
void *__args)
{
return __gthrw_(pthread_create) (__threadid, NULL, __func, __args);
}
static inline int
__gthread_join (__gthread_t __threadid, void **__value_ptr)
{
return __gthrw_(pthread_join) (__threadid, __value_ptr);
}
static inline int
__gthread_detach (__gthread_t __threadid)
{
return __gthrw_(pthread_detach) (__threadid);
}
static inline int
__gthread_equal (__gthread_t __t1, __gthread_t __t2)
{
return __gthrw_(pthread_equal) (__t1, __t2);
}
static inline __gthread_t
__gthread_self (void)
{
return __gthrw_(pthread_self) ();
}
static inline int
__gthread_yield (void)
{
return __gthrw_(sched_yield) ();
}
static inline int
__gthread_once (__gthread_once_t *__once, void (*__func) (void))
{
if (__gthread_active_p ())
return __gthrw_(pthread_once) (__once, __func);
else
return -1;
}
static inline int
__gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *))
{
return __gthrw_(pthread_key_create) (__key, __dtor);
}
static inline int
__gthread_key_delete (__gthread_key_t __key)
{
return __gthrw_(pthread_key_delete) (__key);
}
static inline void *
__gthread_getspecific (__gthread_key_t __key)
{
return __gthrw_(pthread_getspecific) (__key);
}
static inline int
__gthread_setspecific (__gthread_key_t __key, const void *__ptr)
{
return __gthrw_(pthread_setspecific) (__key, __ptr);
}
static inline void
__gthread_mutex_init_function (__gthread_mutex_t *__mutex)
{
if (__gthread_active_p ())
__gthrw_(pthread_mutex_init) (__mutex, NULL);
}
static inline int
__gthread_mutex_destroy (__gthread_mutex_t *__mutex)
{
if (__gthread_active_p ())
return __gthrw_(pthread_mutex_destroy) (__mutex);
else
return 0;
}
static inline int
__gthread_mutex_lock (__gthread_mutex_t *__mutex)
{
if (__gthread_active_p ())
return __gthrw_(pthread_mutex_lock) (__mutex);
else
return 0;
}
static inline int
__gthread_mutex_trylock (__gthread_mutex_t *__mutex)
{
if (__gthread_active_p ())
return __gthrw_(pthread_mutex_trylock) (__mutex);
else
return 0;
}
#if _GTHREAD_USE_MUTEX_TIMEDLOCK
static inline int
__gthread_mutex_timedlock (__gthread_mutex_t *__mutex,
const __gthread_time_t *__abs_timeout)
{
if (__gthread_active_p ())
return __gthrw_(pthread_mutex_timedlock) (__mutex, __abs_timeout);
else
return 0;
}
#endif
static inline int
__gthread_mutex_unlock (__gthread_mutex_t *__mutex)
{
if (__gthread_active_p ())
return __gthrw_(pthread_mutex_unlock) (__mutex);
else
return 0;
}
#if !defined( PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) \
|| defined(_GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC)
static inline int
__gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex)
{
if (__gthread_active_p ())
{
pthread_mutexattr_t __attr;
int __r;
__r = __gthrw_(pthread_mutexattr_init) (&__attr);
if (!__r)
__r = __gthrw_(pthread_mutexattr_settype) (&__attr,
PTHREAD_MUTEX_RECURSIVE);
if (!__r)
__r = __gthrw_(pthread_mutex_init) (__mutex, &__attr);
if (!__r)
__r = __gthrw_(pthread_mutexattr_destroy) (&__attr);
return __r;
}
return 0;
}
#endif
static inline int
__gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex)
{
return __gthread_mutex_lock (__mutex);
}
static inline int
__gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex)
{
return __gthread_mutex_trylock (__mutex);
}
#if _GTHREAD_USE_MUTEX_TIMEDLOCK
static inline int
__gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *__mutex,
const __gthread_time_t *__abs_timeout)
{
return __gthread_mutex_timedlock (__mutex, __abs_timeout);
}
#endif
static inline int
__gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex)
{
return __gthread_mutex_unlock (__mutex);
}
static inline int
__gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex)
{
return __gthread_mutex_destroy (__mutex);
}
#ifdef _GTHREAD_USE_COND_INIT_FUNC
static inline void
__gthread_cond_init_function (__gthread_cond_t *__cond)
{
if (__gthread_active_p ())
__gthrw_(pthread_cond_init) (__cond, NULL);
}
#endif
static inline int
__gthread_cond_broadcast (__gthread_cond_t *__cond)
{
return __gthrw_(pthread_cond_broadcast) (__cond);
}
static inline int
__gthread_cond_signal (__gthread_cond_t *__cond)
{
return __gthrw_(pthread_cond_signal) (__cond);
}
static inline int
__gthread_cond_wait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex)
{
return __gthrw_(pthread_cond_wait) (__cond, __mutex);
}
static inline int
__gthread_cond_timedwait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex,
const __gthread_time_t *__abs_timeout)
{
return __gthrw_(pthread_cond_timedwait) (__cond, __mutex, __abs_timeout);
}
static inline int
__gthread_cond_wait_recursive (__gthread_cond_t *__cond,
__gthread_recursive_mutex_t *__mutex)
{
return __gthread_cond_wait (__cond, __mutex);
}
static inline int
__gthread_cond_destroy (__gthread_cond_t* __cond)
{
return __gthrw_(pthread_cond_destroy) (__cond);
}
#endif /* _LIBOBJC */
#endif /* ! _GLIBCXX_GCC_GTHR_POSIX_H */
| {
"pile_set_name": "Github"
} |
import math
from .. import veros_method, runtime_settings as rs
from ..variables import allocate
from . import numerics, utilities
@veros_method
def explicit_vert_friction(vs):
"""
explicit vertical friction
dissipation is calculated and added to K_diss_v
"""
diss = allocate(vs, ('xt', 'yt', 'zw'))
"""
vertical friction of zonal momentum
"""
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[2:-1, 1:-2, :-1])
vs.flux_top[1:-2, 1:-2, :-1] = fxa * (vs.u[1:-2, 1:-2, 1:, vs.tau] - vs.u[1:-2, 1:-2, :-1, vs.tau]) \
/ vs.dzw[np.newaxis, np.newaxis, :-1] * vs.maskU[1:-2, 1:-2, 1:] * vs.maskU[1:-2, 1:-2, :-1]
vs.flux_top[:, :, -1] = 0.0
vs.du_mix[:, :, 0] = vs.flux_top[:, :, 0] / vs.dzt[0] * vs.maskU[:, :, 0]
vs.du_mix[:, :, 1:] = (vs.flux_top[:, :, 1:] - vs.flux_top[:, :, :-1]) / vs.dzt[1:] * vs.maskU[:, :, 1:]
"""
diagnose dissipation by vertical friction of zonal momentum
"""
diss[1:-2, 1:-2, :-1] = (vs.u[1:-2, 1:-2, 1:, vs.tau] - vs.u[1:-2, 1:-2, :-1, vs.tau]) \
* vs.flux_top[1:-2, 1:-2, :-1] / vs.dzw[np.newaxis, np.newaxis, :-1]
diss[:, :, vs.nz - 1] = 0.0
diss[...] = numerics.ugrid_to_tgrid(vs, diss)
vs.K_diss_v += diss
"""
vertical friction of meridional momentum
"""
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[1:-2, 2:-1, :-1])
vs.flux_top[1:-2, 1:-2, :-1] = fxa * (vs.v[1:-2, 1:-2, 1:, vs.tau] - vs.v[1:-2, 1:-2, :-1, vs.tau]) \
/ vs.dzw[np.newaxis, np.newaxis, :-1] * vs.maskV[1:-2, 1:-2, 1:] \
* vs.maskV[1:-2, 1:-2, :-1]
vs.flux_top[:, :, -1] = 0.0
vs.dv_mix[:, :, 1:] = (vs.flux_top[:, :, 1:] - vs.flux_top[:, :, :-1]) \
/ vs.dzt[np.newaxis, np.newaxis, 1:] * vs.maskV[:, :, 1:]
vs.dv_mix[:, :, 0] = vs.flux_top[:, :, 0] / vs.dzt[0] * vs.maskV[:, :, 0]
"""
diagnose dissipation by vertical friction of meridional momentum
"""
diss[1:-2, 1:-2, :-1] = (vs.v[1:-2, 1:-2, 1:, vs.tau] - vs.v[1:-2, 1:-2, :-1, vs.tau]) \
* vs.flux_top[1:-2, 1:-2, :-1] / vs.dzw[np.newaxis, np.newaxis, :-1]
diss[:, :, -1] = 0.0
diss[...] = numerics.vgrid_to_tgrid(vs, diss)
vs.K_diss_v += diss
@veros_method
def implicit_vert_friction(vs):
"""
vertical friction
dissipation is calculated and added to K_diss_v
"""
a_tri = allocate(vs, ('xt', 'yt', 'zw'))[1:-2, 1:-2]
b_tri = allocate(vs, ('xt', 'yt', 'zw'))[1:-2, 1:-2]
c_tri = allocate(vs, ('xt', 'yt', 'zw'))[1:-2, 1:-2]
d_tri = allocate(vs, ('xt', 'yt', 'zw'))[1:-2, 1:-2]
delta = allocate(vs, ('xt', 'yt', 'zw'))[1:-2, 1:-2]
diss = allocate(vs, ('xt', 'yt', 'zw'))
"""
implicit vertical friction of zonal momentum
"""
kss = np.maximum(vs.kbot[1:-2, 1:-2], vs.kbot[2:-1, 1:-2]) - 1
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[2:-1, 1:-2, :-1])
delta[:, :, :-1] = vs.dt_mom / vs.dzw[:-1] * fxa * \
vs.maskU[1:-2, 1:-2, 1:] * vs.maskU[1:-2, 1:-2, :-1]
a_tri[:, :, 1:] = -delta[:, :, :-1] / vs.dzt[np.newaxis, np.newaxis, 1:]
b_tri[:, :, 1:] = 1 + delta[:, :, :-1] / vs.dzt[np.newaxis, np.newaxis, 1:]
b_tri[:, :, 1:-1] += delta[:, :, 1:-1] / vs.dzt[np.newaxis, np.newaxis, 1:-1]
b_tri_edge = 1 + delta / vs.dzt[np.newaxis, np.newaxis, :]
c_tri[...] = -delta / vs.dzt[np.newaxis, np.newaxis, :]
d_tri[...] = vs.u[1:-2, 1:-2, :, vs.tau]
res, mask = utilities.solve_implicit(vs, kss, a_tri, b_tri, c_tri, d_tri, b_edge=b_tri_edge)
vs.u[1:-2, 1:-2, :, vs.taup1] = utilities.where(vs, mask, res, vs.u[1:-2, 1:-2, :, vs.taup1])
vs.du_mix[1:-2, 1:-2] = (vs.u[1:-2, 1:-2, :, vs.taup1] -
vs.u[1:-2, 1:-2, :, vs.tau]) / vs.dt_mom
"""
diagnose dissipation by vertical friction of zonal momentum
"""
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[2:-1, 1:-2, :-1])
vs.flux_top[1:-2, 1:-2, :-1] = fxa * (vs.u[1:-2, 1:-2, 1:, vs.taup1] - vs.u[1:-2, 1:-2, :-1, vs.taup1]) \
/ vs.dzw[:-1] * vs.maskU[1:-2, 1:-2, 1:] * vs.maskU[1:-2, 1:-2, :-1]
diss[1:-2, 1:-2, :-1] = (vs.u[1:-2, 1:-2, 1:, vs.tau] - vs.u[1:-2, 1:-2, :-1, vs.tau]) \
* vs.flux_top[1:-2, 1:-2, :-1] / vs.dzw[:-1]
diss[:, :, -1] = 0.0
diss[...] = numerics.ugrid_to_tgrid(vs, diss)
vs.K_diss_v += diss
"""
implicit vertical friction of meridional momentum
"""
kss = np.maximum(vs.kbot[1:-2, 1:-2], vs.kbot[1:-2, 2:-1]) - 1
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[1:-2, 2:-1, :-1])
delta[:, :, :-1] = vs.dt_mom / vs.dzw[np.newaxis, np.newaxis, :-1] * \
fxa * vs.maskV[1:-2, 1:-2, 1:] * vs.maskV[1:-2, 1:-2, :-1]
a_tri[:, :, 1:] = -delta[:, :, :-1] / vs.dzt[np.newaxis, np.newaxis, 1:]
b_tri[:, :, 1:] = 1 + delta[:, :, :-1] / vs.dzt[np.newaxis, np.newaxis, 1:]
b_tri[:, :, 1:-1] += delta[:, :, 1:-1] / vs.dzt[np.newaxis, np.newaxis, 1:-1]
b_tri_edge = 1 + delta / vs.dzt[np.newaxis, np.newaxis, :]
c_tri[:, :, :-1] = -delta[:, :, :-1] / vs.dzt[np.newaxis, np.newaxis, :-1]
c_tri[:, :, -1] = 0.
d_tri[...] = vs.v[1:-2, 1:-2, :, vs.tau]
res, mask = utilities.solve_implicit(vs, kss, a_tri, b_tri, c_tri, d_tri, b_edge=b_tri_edge)
vs.v[1:-2, 1:-2, :, vs.taup1] = utilities.where(vs, mask, res, vs.v[1:-2, 1:-2, :, vs.taup1])
vs.dv_mix[1:-2, 1:-2] = (vs.v[1:-2, 1:-2, :, vs.taup1] - vs.v[1:-2, 1:-2, :, vs.tau]) / vs.dt_mom
"""
diagnose dissipation by vertical friction of meridional momentum
"""
fxa = 0.5 * (vs.kappaM[1:-2, 1:-2, :-1] + vs.kappaM[1:-2, 2:-1, :-1])
vs.flux_top[1:-2, 1:-2, :-1] = fxa * (vs.v[1:-2, 1:-2, 1:, vs.taup1] - vs.v[1:-2, 1:-2, :-1, vs.taup1]) \
/ vs.dzw[:-1] * vs.maskV[1:-2, 1:-2, 1:] * vs.maskV[1:-2, 1:-2, :-1]
diss[1:-2, 1:-2, :-1] = (vs.v[1:-2, 1:-2, 1:, vs.tau] - vs.v[1:-2, 1:-2, :-1, vs.tau]) \
* vs.flux_top[1:-2, 1:-2, :-1] / vs.dzw[:-1]
diss[:, :, -1] = 0.0
diss = numerics.vgrid_to_tgrid(vs, diss)
vs.K_diss_v += diss
@veros_method
def rayleigh_friction(vs):
"""
interior Rayleigh friction
dissipation is calculated and added to K_diss_bot
"""
vs.du_mix[...] += -vs.maskU * vs.r_ray * vs.u[..., vs.tau]
if vs.enable_conserve_energy:
diss = vs.maskU * vs.r_ray * vs.u[..., vs.tau]**2
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'U')
vs.dv_mix[...] += -vs.maskV * vs.r_ray * vs.v[..., vs.tau]
if vs.enable_conserve_energy:
diss = vs.maskV * vs.r_ray * vs.v[..., vs.tau]**2
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'V')
@veros_method
def linear_bottom_friction(vs):
"""
linear bottom friction
dissipation is calculated and added to K_diss_bot
"""
if vs.enable_bottom_friction_var:
"""
with spatially varying coefficient
"""
k = np.maximum(vs.kbot[1:-2, 2:-2], vs.kbot[2:-1, 2:-2]) - 1
mask = np.arange(vs.nz) == k[:, :, np.newaxis]
vs.du_mix[1:-2, 2:-2] += -(vs.maskU[1:-2, 2:-2] * vs.r_bot_var_u[1:-2, 2:-2, np.newaxis]) \
* vs.u[1:-2, 2:-2, :, vs.tau] * mask
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yt', 'zt'))
diss[1:-2, 2:-2] = vs.maskU[1:-2, 2:-2] * vs.r_bot_var_u[1:-2, 2:-2, np.newaxis] \
* vs.u[1:-2, 2:-2, :, vs.tau]**2 * mask
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'U')
k = np.maximum(vs.kbot[2:-2, 2:-1], vs.kbot[2:-2, 1:-2]) - 1
mask = np.arange(vs.nz) == k[:, :, np.newaxis]
vs.dv_mix[2:-2, 1:-2] += -(vs.maskV[2:-2, 1:-2] * vs.r_bot_var_v[2:-2, 1:-2, np.newaxis]) \
* vs.v[2:-2, 1:-2, :, vs.tau] * mask
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yu', 'zt'))
diss[2:-2, 1:-2] = vs.maskV[2:-2, 1:-2] * vs.r_bot_var_v[2:-2, 1:-2, np.newaxis] \
* vs.v[2:-2, 1:-2, :, vs.tau]**2 * mask
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'V')
else:
"""
with constant coefficient
"""
k = np.maximum(vs.kbot[1:-2, 2:-2], vs.kbot[2:-1, 2:-2]) - 1
mask = np.arange(vs.nz) == k[:, :, np.newaxis]
vs.du_mix[1:-2, 2:-2] += -vs.maskU[1:-2, 2:-2] * vs.r_bot * vs.u[1:-2, 2:-2, :, vs.tau] * mask
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yt', 'zt'))
diss[1:-2, 2:-2] = vs.maskU[1:-2, 2:-2] * vs.r_bot * vs.u[1:-2, 2:-2, :, vs.tau]**2 * mask
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'U')
k = np.maximum(vs.kbot[2:-2, 2:-1], vs.kbot[2:-2, 1:-2]) - 1
mask = np.arange(vs.nz) == k[:, :, np.newaxis]
vs.dv_mix[2:-2, 1:-2] += -vs.maskV[2:-2, 1:-2] * vs.r_bot * vs.v[2:-2, 1:-2, :, vs.tau] * mask
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yu', 'zt'))
diss[2:-2, 1:-2] = vs.maskV[2:-2, 1:-2] * vs.r_bot * vs.v[2:-2, 1:-2, :, vs.tau]**2 * mask
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'V')
@veros_method
def quadratic_bottom_friction(vs):
"""
quadratic bottom friction
dissipation is calculated and added to K_diss_bot
"""
# we might want to account for EKE in the drag, also a tidal residual
k = np.maximum(vs.kbot[1:-2, 2:-2], vs.kbot[2:-1, 2:-2]) - 1
mask = k[..., np.newaxis] == np.arange(vs.nz)[np.newaxis, np.newaxis, :]
fxa = vs.maskV[1:-2, 2:-2, :] * vs.v[1:-2, 2:-2, :, vs.tau]**2 \
+ vs.maskV[1:-2, 1:-3, :] * vs.v[1:-2, 1:-3, :, vs.tau]**2 \
+ vs.maskV[2:-1, 2:-2, :] * vs.v[2:-1, 2:-2, :, vs.tau]**2 \
+ vs.maskV[2:-1, 1:-3, :] * vs.v[2:-1, 1:-3, :, vs.tau]**2
fxa = np.sqrt(vs.u[1:-2, 2:-2, :, vs.tau]**2 + 0.25 * fxa)
aloc = vs.maskU[1:-2, 2:-2, :] * vs.r_quad_bot * vs.u[1:-2, 2:-2, :, vs.tau] \
* fxa / vs.dzt[np.newaxis, np.newaxis, :] * mask
vs.du_mix[1:-2, 2:-2, :] += -aloc
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yt', 'zt'))
diss[1:-2, 2:-2, :] = aloc * vs.u[1:-2, 2:-2, :, vs.tau]
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'U')
k = np.maximum(vs.kbot[2:-2, 1:-2], vs.kbot[2:-2, 2:-1]) - 1
mask = k[..., np.newaxis] == np.arange(vs.nz)[np.newaxis, np.newaxis, :]
fxa = vs.maskU[2:-2, 1:-2, :] * vs.u[2:-2, 1:-2, :, vs.tau]**2 \
+ vs.maskU[1:-3, 1:-2, :] * vs.u[1:-3, 1:-2, :, vs.tau]**2 \
+ vs.maskU[2:-2, 2:-1, :] * vs.u[2:-2, 2:-1, :, vs.tau]**2 \
+ vs.maskU[1:-3, 2:-1, :] * vs.u[1:-3, 2:-1, :, vs.tau]**2
fxa = np.sqrt(vs.v[2:-2, 1:-2, :, vs.tau]**2 + 0.25 * fxa)
aloc = vs.maskV[2:-2, 1:-2, :] * vs.r_quad_bot * vs.v[2:-2, 1:-2, :, vs.tau] \
* fxa / vs.dzt[np.newaxis, np.newaxis, :] * mask
vs.dv_mix[2:-2, 1:-2, :] += -aloc
if vs.enable_conserve_energy:
diss = allocate(vs, ('xt', 'yu', 'zt'))
diss[2:-2, 1:-2, :] = aloc * vs.v[2:-2, 1:-2, :, vs.tau]
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'V')
@veros_method
def harmonic_friction(vs):
"""
horizontal harmonic friction
dissipation is calculated and added to K_diss_h
"""
diss = allocate(vs, ('xt', 'yt', 'zt'))
"""
Zonal velocity
"""
if vs.enable_hor_friction_cos_scaling:
fxa = vs.cost**vs.hor_friction_cosPower
vs.flux_east[:-1] = vs.A_h * fxa[np.newaxis, :, np.newaxis] * (vs.u[1:, :, :, vs.tau] - vs.u[:-1, :, :, vs.tau]) \
/ (vs.cost * vs.dxt[1:, np.newaxis])[:, :, np.newaxis] * vs.maskU[1:] * vs.maskU[:-1]
fxa = vs.cosu**vs.hor_friction_cosPower
vs.flux_north[:, :-1] = vs.A_h * fxa[np.newaxis, :-1, np.newaxis] * (vs.u[:, 1:, :, vs.tau] - vs.u[:, :-1, :, vs.tau]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * vs.maskU[:, 1:] * vs.maskU[:, :-1] * vs.cosu[np.newaxis, :-1, np.newaxis]
if vs.enable_noslip_lateral:
vs.flux_north[:, :-1] += 2 * vs.A_h * fxa[np.newaxis, :-1, np.newaxis] * (vs.u[:, 1:, :, vs.tau]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * vs.maskU[:, 1:] * (1 - vs.maskU[:, :-1]) * vs.cosu[np.newaxis, :-1, np.newaxis]\
- 2 * vs.A_h * fxa[np.newaxis, :-1, np.newaxis] * (vs.u[:, :-1, :, vs.tau]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * (1 - vs.maskU[:, 1:]) * vs.maskU[:, :-1] * vs.cosu[np.newaxis, :-1, np.newaxis]
else:
vs.flux_east[:-1, :, :] = vs.A_h * (vs.u[1:, :, :, vs.tau] - vs.u[:-1, :, :, vs.tau]) \
/ (vs.cost * vs.dxt[1:, np.newaxis])[:, :, np.newaxis] * vs.maskU[1:] * vs.maskU[:-1]
vs.flux_north[:, :-1, :] = vs.A_h * (vs.u[:, 1:, :, vs.tau] - vs.u[:, :-1, :, vs.tau]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * vs.maskU[:, 1:] * vs.maskU[:, :-1] * vs.cosu[np.newaxis, :-1, np.newaxis]
if vs.enable_noslip_lateral:
vs.flux_north[:, :-1] += 2 * vs.A_h * vs.u[:, 1:, :, vs.tau] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* vs.maskU[:, 1:] * (1 - vs.maskU[:, :-1]) * vs.cosu[np.newaxis, :-1, np.newaxis]\
- 2 * vs.A_h * vs.u[:, :-1, :, vs.tau] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* (1 - vs.maskU[:, 1:]) * vs.maskU[:, :-1] * vs.cosu[np.newaxis, :-1, np.newaxis]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
"""
update tendency
"""
vs.du_mix[2:-2, 2:-2, :] += vs.maskU[2:-2, 2:-2] * ((vs.flux_east[2:-2, 2:-2] - vs.flux_east[1:-3, 2:-2])
/ (vs.cost[2:-2] * vs.dxu[2:-2, np.newaxis])[:, :, np.newaxis]
+ (vs.flux_north[2:-2, 2:-2] - vs.flux_north[2:-2, 1:-3])
/ (vs.cost[2:-2] * vs.dyt[2:-2])[np.newaxis, :, np.newaxis])
if vs.enable_conserve_energy:
"""
diagnose dissipation by lateral friction
"""
diss[1:-2, 2:-2] = 0.5 * ((vs.u[2:-1, 2:-2, :, vs.tau] - vs.u[1:-2, 2:-2, :, vs.tau]) * vs.flux_east[1:-2, 2:-2]
+ (vs.u[1:-2, 2:-2, :, vs.tau] - vs.u[:-3, 2:-2, :, vs.tau]) * vs.flux_east[:-3, 2:-2]) \
/ (vs.cost[2:-2] * vs.dxu[1:-2, np.newaxis])[:, :, np.newaxis]\
+ 0.5 * ((vs.u[1:-2, 3:-1, :, vs.tau] - vs.u[1:-2, 2:-2, :, vs.tau]) * vs.flux_north[1:-2, 2:-2]
+ (vs.u[1:-2, 2:-2, :, vs.tau] - vs.u[1:-2, 1:-3, :, vs.tau]) * vs.flux_north[1:-2, 1:-3]) \
/ (vs.cost[2:-2] * vs.dyt[2:-2])[np.newaxis, :, np.newaxis]
vs.K_diss_h[...] = 0.
vs.K_diss_h[...] += numerics.calc_diss(vs, diss, 'U')
"""
Meridional velocity
"""
if vs.enable_hor_friction_cos_scaling:
vs.flux_east[:-1] = vs.A_h * vs.cosu[np.newaxis, :, np.newaxis] ** vs.hor_friction_cosPower \
* (vs.v[1:, :, :, vs.tau] - vs.v[:-1, :, :, vs.tau]) \
/ (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] * vs.maskV[1:] * vs.maskV[:-1]
if vs.enable_noslip_lateral:
vs.flux_east[:-1] += 2 * vs.A_h * fxa[np.newaxis, :, np.newaxis] * vs.v[1:, :, :, vs.tau] \
/ (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] * vs.maskV[1:] * (1 - vs.maskV[:-1]) \
- 2 * vs.A_h * fxa[np.newaxis, :, np.newaxis] * vs.v[:-1, :, :, vs.tau] \
/ (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] * (1 - vs.maskV[1:]) * vs.maskV[:-1]
vs.flux_north[:, :-1] = vs.A_h * vs.cost[np.newaxis, 1:, np.newaxis] ** vs.hor_friction_cosPower \
* (vs.v[:, 1:, :, vs.tau] - vs.v[:, :-1, :, vs.tau]) \
/ vs.dyt[np.newaxis, 1:, np.newaxis] * vs.cost[np.newaxis, 1:, np.newaxis] * vs.maskV[:, :-1] * vs.maskV[:, 1:]
else:
vs.flux_east[:-1] = vs.A_h * (vs.v[1:, :, :, vs.tau] - vs.v[:-1, :, :, vs.tau]) \
/ (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] * vs.maskV[1:] * vs.maskV[:-1]
if vs.enable_noslip_lateral:
vs.flux_east[:-1] += 2 * vs.A_h * vs.v[1:, :, :, vs.tau] / (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] \
* vs.maskV[1:] * (1 - vs.maskV[:-1]) \
- 2 * vs.A_h * vs.v[:-1, :, :, vs.tau] / (vs.cosu * vs.dxu[:-1, np.newaxis])[:, :, np.newaxis] \
* (1 - vs.maskV[1:]) * vs.maskV[:-1]
vs.flux_north[:, :-1] = vs.A_h * (vs.v[:, 1:, :, vs.tau] - vs.v[:, :-1, :, vs.tau]) \
/ vs.dyt[np.newaxis, 1:, np.newaxis] * vs.cost[np.newaxis, 1:, np.newaxis] * vs.maskV[:, :-1] * vs.maskV[:, 1:]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
"""
update tendency
"""
vs.dv_mix[2:-2, 2:-2] += vs.maskV[2:-2, 2:-2] * ((vs.flux_east[2:-2, 2:-2] - vs.flux_east[1:-3, 2:-2])
/ (vs.cosu[2:-2] * vs.dxt[2:-2, np.newaxis])[:, :, np.newaxis]
+ (vs.flux_north[2:-2, 2:-2] - vs.flux_north[2:-2, 1:-3])
/ (vs.dyu[2:-2] * vs.cosu[2:-2])[np.newaxis, :, np.newaxis])
if vs.enable_conserve_energy:
"""
diagnose dissipation by lateral friction
"""
diss[2:-2, 1:-2] = 0.5 * ((vs.v[3:-1, 1:-2, :, vs.tau] - vs.v[2:-2, 1:-2, :, vs.tau]) * vs.flux_east[2:-2, 1:-2]
+ (vs.v[2:-2, 1:-2, :, vs.tau] - vs.v[1:-3, 1:-2, :, vs.tau]) * vs.flux_east[1:-3, 1:-2]) \
/ (vs.cosu[1:-2] * vs.dxt[2:-2, np.newaxis])[:, :, np.newaxis] \
+ 0.5 * ((vs.v[2:-2, 2:-1, :, vs.tau] - vs.v[2:-2, 1:-2, :, vs.tau]) * vs.flux_north[2:-2, 1:-2]
+ (vs.v[2:-2, 1:-2, :, vs.tau] - vs.v[2:-2, :-3, :, vs.tau]) * vs.flux_north[2:-2, :-3]) \
/ (vs.cosu[1:-2] * vs.dyu[1:-2])[np.newaxis, :, np.newaxis]
vs.K_diss_h[...] += numerics.calc_diss(vs, diss, 'V')
@veros_method
def biharmonic_friction(vs):
"""
horizontal biharmonic friction
dissipation is calculated and added to K_diss_h
"""
fxa = math.sqrt(abs(vs.A_hbi))
"""
Zonal velocity
"""
vs.flux_east[:-1, :, :] = fxa * (vs.u[1:, :, :, vs.tau] - vs.u[:-1, :, :, vs.tau]) \
/ (vs.cost[np.newaxis, :, np.newaxis] * vs.dxt[1:, np.newaxis, np.newaxis]) \
* vs.maskU[1:, :, :] * vs.maskU[:-1, :, :]
vs.flux_north[:, :-1, :] = fxa * (vs.u[:, 1:, :, vs.tau] - vs.u[:, :-1, :, vs.tau]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * vs.maskU[:, 1:, :] \
* vs.maskU[:, :-1, :] * vs.cosu[np.newaxis, :-1, np.newaxis]
if vs.enable_noslip_lateral:
vs.flux_north[:, :-1] += 2 * fxa * vs.u[:, 1:, :, vs.tau] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* vs.maskU[:, 1:] * (1 - vs.maskU[:, :-1]) * vs.cosu[np.newaxis, :-1, np.newaxis]\
- 2 * fxa * vs.u[:, :-1, :, vs.tau] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* (1 - vs.maskU[:, 1:]) * vs.maskU[:, :-1] * vs.cosu[np.newaxis, :-1, np.newaxis]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
del2 = allocate(vs, ('xt', 'yt', 'zt'))
del2[1:, 1:, :] = (vs.flux_east[1:, 1:, :] - vs.flux_east[:-1, 1:, :]) \
/ (vs.cost[np.newaxis, 1:, np.newaxis] * vs.dxu[1:, np.newaxis, np.newaxis]) \
+ (vs.flux_north[1:, 1:, :] - vs.flux_north[1:, :-1, :]) \
/ (vs.cost[np.newaxis, 1:, np.newaxis] * vs.dyt[np.newaxis, 1:, np.newaxis])
vs.flux_east[:-1, :, :] = fxa * (del2[1:, :, :] - del2[:-1, :, :]) \
/ (vs.cost[np.newaxis, :, np.newaxis] * vs.dxt[1:, np.newaxis, np.newaxis]) \
* vs.maskU[1:, :, :] * vs.maskU[:-1, :, :]
vs.flux_north[:, :-1, :] = fxa * (del2[:, 1:, :] - del2[:, :-1, :]) \
/ vs.dyu[np.newaxis, :-1, np.newaxis] * vs.maskU[:, 1:, :] \
* vs.maskU[:, :-1, :] * vs.cosu[np.newaxis, :-1, np.newaxis]
if vs.enable_noslip_lateral:
vs.flux_north[:,:-1,:] += 2 * fxa * del2[:, 1:, :] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* vs.maskU[:, 1:, :] * (1 - vs.maskU[:, :-1, :]) * vs.cosu[np.newaxis, :-1, np.newaxis] \
- 2 * fxa * del2[:, :-1, :] / vs.dyu[np.newaxis, :-1, np.newaxis] \
* (1 - vs.maskU[:, 1:, :]) * vs.maskU[:, :-1, :] * vs.cosu[np.newaxis, :-1, np.newaxis]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
"""
update tendency
"""
vs.du_mix[2:-2, 2:-2, :] += -vs.maskU[2:-2, 2:-2, :] * ((vs.flux_east[2:-2, 2:-2, :] - vs.flux_east[1:-3, 2:-2, :])
/ (vs.cost[np.newaxis, 2:-2, np.newaxis] * vs.dxu[2:-2, np.newaxis, np.newaxis])
+ (vs.flux_north[2:-2, 2:-2, :] - vs.flux_north[2:-2, 1:-3, :])
/ (vs.cost[np.newaxis, 2:-2, np.newaxis] * vs.dyt[np.newaxis, 2:-2, np.newaxis]))
if vs.enable_conserve_energy:
"""
diagnose dissipation by lateral friction
"""
utilities.enforce_boundaries(vs, vs.flux_east)
utilities.enforce_boundaries(vs, vs.flux_north)
diss = allocate(vs, ('xt', 'yt', 'zt'))
diss[1:-2, 2:-2, :] = -0.5 * ((vs.u[2:-1, 2:-2, :, vs.tau] - vs.u[1:-2, 2:-2, :, vs.tau]) * vs.flux_east[1:-2, 2:-2, :]
+ (vs.u[1:-2, 2:-2, :, vs.tau] - vs.u[:-3, 2:-2, :, vs.tau]) * vs.flux_east[:-3, 2:-2, :]) \
/ (vs.cost[np.newaxis, 2:-2, np.newaxis] * vs.dxu[1:-2, np.newaxis, np.newaxis]) \
- 0.5 * ((vs.u[1:-2, 3:-1, :, vs.tau] - vs.u[1:-2, 2:-2, :, vs.tau]) * vs.flux_north[1:-2, 2:-2, :]
+ (vs.u[1:-2, 2:-2, :, vs.tau] - vs.u[1:-2, 1:-3, :, vs.tau]) * vs.flux_north[1:-2, 1:-3, :]) \
/ (vs.cost[np.newaxis, 2:-2, np.newaxis] * vs.dyt[np.newaxis, 2:-2, np.newaxis])
vs.K_diss_h[...] = 0.
vs.K_diss_h[...] += numerics.calc_diss(vs, diss, 'U')
"""
Meridional velocity
"""
vs.flux_east[:-1, :, :] = fxa * (vs.v[1:, :, :, vs.tau] - vs.v[:-1, :, :, vs.tau]) \
/ (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* vs.maskV[1:, :, :] * vs.maskV[:-1, :, :]
if vs.enable_noslip_lateral:
vs.flux_east[:-1, :, :] += 2 * fxa * vs.v[1:, :, :, vs.tau] / (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* vs.maskV[1:, :, :] * (1 - vs.maskV[:-1, :, :]) \
- 2 * fxa * vs.v[:-1, :, :, vs.tau] / (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* (1 - vs.maskV[1:, :, :]) * vs.maskV[:-1, :, :]
vs.flux_north[:, :-1, :] = fxa * (vs.v[:, 1:, :, vs.tau] - vs.v[:, :-1, :, vs.tau]) \
/ vs.dyt[np.newaxis, 1:, np.newaxis] * vs.cost[np.newaxis, 1:, np.newaxis] \
* vs.maskV[:, :-1, :] * vs.maskV[:, 1:, :]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
del2[1:, 1:, :] = (vs.flux_east[1:, 1:, :] - vs.flux_east[:-1, 1:, :]) \
/ (vs.cosu[np.newaxis, 1:, np.newaxis] * vs.dxt[1:, np.newaxis, np.newaxis]) \
+ (vs.flux_north[1:, 1:, :] - vs.flux_north[1:, :-1, :]) \
/ (vs.dyu[np.newaxis, 1:, np.newaxis] * vs.cosu[np.newaxis, 1:, np.newaxis])
vs.flux_east[:-1, :, :] = fxa * (del2[1:, :, :] - del2[:-1, :, :]) \
/ (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* vs.maskV[1:, :, :] * vs.maskV[:-1, :, :]
if vs.enable_noslip_lateral:
vs.flux_east[:-1, :, :] += 2 * fxa * del2[1:, :, :] / (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* vs.maskV[1:, :, :] * (1 - vs.maskV[:-1, :, :]) \
- 2 * fxa * del2[:-1, :, :] / (vs.cosu[np.newaxis, :, np.newaxis] * vs.dxu[:-1, np.newaxis, np.newaxis]) \
* (1 - vs.maskV[1:, :, :]) * vs.maskV[:-1, :, :]
vs.flux_north[:, :-1, :] = fxa * (del2[:, 1:, :] - del2[:, :-1, :]) \
/ vs.dyt[np.newaxis, 1:, np.newaxis] * vs.cost[np.newaxis, 1:, np.newaxis] \
* vs.maskV[:, :-1, :] * vs.maskV[:, 1:, :]
vs.flux_east[-1, :, :] = 0.
vs.flux_north[:, -1, :] = 0.
"""
update tendency
"""
vs.dv_mix[2:-2, 2:-2, :] += -vs.maskV[2:-2, 2:-2, :] * ((vs.flux_east[2:-2, 2:-2, :] - vs.flux_east[1:-3, 2:-2, :])
/ (vs.cosu[np.newaxis, 2:-2, np.newaxis] * vs.dxt[2:-2, np.newaxis, np.newaxis])
+ (vs.flux_north[2:-2, 2:-2, :] - vs.flux_north[2:-2, 1:-3, :])
/ (vs.dyu[np.newaxis, 2:-2, np.newaxis] * vs.cosu[np.newaxis, 2:-2, np.newaxis]))
if vs.enable_conserve_energy:
"""
diagnose dissipation by lateral friction
"""
utilities.enforce_boundaries(vs, vs.flux_east)
utilities.enforce_boundaries(vs, vs.flux_north)
diss[2:-2, 1:-2, :] = -0.5 * ((vs.v[3:-1, 1:-2, :, vs.tau] - vs.v[2:-2, 1:-2, :, vs.tau]) * vs.flux_east[2:-2, 1:-2, :]
+ (vs.v[2:-2, 1:-2, :, vs.tau] - vs.v[1:-3, 1:-2, :, vs.tau]) * vs.flux_east[1:-3, 1:-2, :]) \
/ (vs.cosu[np.newaxis, 1:-2, np.newaxis] * vs.dxt[2:-2, np.newaxis, np.newaxis]) \
- 0.5 * ((vs.v[2:-2, 2:-1, :, vs.tau] - vs.v[2:-2, 1:-2, :, vs.tau]) * vs.flux_north[2:-2, 1:-2, :]
+ (vs.v[2:-2, 1:-2, :, vs.tau] - vs.v[2:-2, :-3, :, vs.tau]) * vs.flux_north[2:-2, :-3, :]) \
/ (vs.cosu[np.newaxis, 1:-2, np.newaxis] * vs.dyu[np.newaxis, 1:-2, np.newaxis])
vs.K_diss_h[...] += numerics.calc_diss(vs, diss, 'V')
@veros_method
def momentum_sources(vs):
"""
other momentum sources
dissipation is calculated and added to K_diss_bot
"""
vs.du_mix[...] += vs.maskU * vs.u_source
if vs.enable_conserve_energy:
diss = -vs.maskU * vs.u[..., vs.tau] * vs.u_source
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'U')
vs.dv_mix[...] += vs.maskV * vs.v_source
if vs.enable_conserve_energy:
diss = -vs.maskV * vs.v[..., vs.tau] * vs.v_source
vs.K_diss_bot[...] += numerics.calc_diss(vs, diss, 'V')
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* An I2C and SPI driver for the NXP PCF2127/29 RTC
* Copyright 2013 Til-Technologies
*
* Author: Renaud Cerrato <[email protected]>
*
* Watchdog and tamper functions
* Author: Bruno Thomsen <[email protected]>
*
* based on the other drivers in this same directory.
*
* Datasheet: http://cache.nxp.com/documents/data_sheet/PCF2127.pdf
*/
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/bcd.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/regmap.h>
#include <linux/watchdog.h>
/* Control register 1 */
#define PCF2127_REG_CTRL1 0x00
#define PCF2127_BIT_CTRL1_TSF1 BIT(4)
/* Control register 2 */
#define PCF2127_REG_CTRL2 0x01
#define PCF2127_BIT_CTRL2_AIE BIT(1)
#define PCF2127_BIT_CTRL2_TSIE BIT(2)
#define PCF2127_BIT_CTRL2_AF BIT(4)
#define PCF2127_BIT_CTRL2_TSF2 BIT(5)
#define PCF2127_BIT_CTRL2_WDTF BIT(6)
/* Control register 3 */
#define PCF2127_REG_CTRL3 0x02
#define PCF2127_BIT_CTRL3_BLIE BIT(0)
#define PCF2127_BIT_CTRL3_BIE BIT(1)
#define PCF2127_BIT_CTRL3_BLF BIT(2)
#define PCF2127_BIT_CTRL3_BF BIT(3)
#define PCF2127_BIT_CTRL3_BTSE BIT(4)
/* Time and date registers */
#define PCF2127_REG_SC 0x03
#define PCF2127_BIT_SC_OSF BIT(7)
#define PCF2127_REG_MN 0x04
#define PCF2127_REG_HR 0x05
#define PCF2127_REG_DM 0x06
#define PCF2127_REG_DW 0x07
#define PCF2127_REG_MO 0x08
#define PCF2127_REG_YR 0x09
/* Alarm registers */
#define PCF2127_REG_ALARM_SC 0x0A
#define PCF2127_REG_ALARM_MN 0x0B
#define PCF2127_REG_ALARM_HR 0x0C
#define PCF2127_REG_ALARM_DM 0x0D
#define PCF2127_REG_ALARM_DW 0x0E
#define PCF2127_BIT_ALARM_AE BIT(7)
/* Watchdog registers */
#define PCF2127_REG_WD_CTL 0x10
#define PCF2127_BIT_WD_CTL_TF0 BIT(0)
#define PCF2127_BIT_WD_CTL_TF1 BIT(1)
#define PCF2127_BIT_WD_CTL_CD0 BIT(6)
#define PCF2127_BIT_WD_CTL_CD1 BIT(7)
#define PCF2127_REG_WD_VAL 0x11
/* Tamper timestamp registers */
#define PCF2127_REG_TS_CTRL 0x12
#define PCF2127_BIT_TS_CTRL_TSOFF BIT(6)
#define PCF2127_BIT_TS_CTRL_TSM BIT(7)
#define PCF2127_REG_TS_SC 0x13
#define PCF2127_REG_TS_MN 0x14
#define PCF2127_REG_TS_HR 0x15
#define PCF2127_REG_TS_DM 0x16
#define PCF2127_REG_TS_MO 0x17
#define PCF2127_REG_TS_YR 0x18
/*
* RAM registers
* PCF2127 has 512 bytes general-purpose static RAM (SRAM) that is
* battery backed and can survive a power outage.
* PCF2129 doesn't have this feature.
*/
#define PCF2127_REG_RAM_ADDR_MSB 0x1A
#define PCF2127_REG_RAM_WRT_CMD 0x1C
#define PCF2127_REG_RAM_RD_CMD 0x1D
/* Watchdog timer value constants */
#define PCF2127_WD_VAL_STOP 0
#define PCF2127_WD_VAL_MIN 2
#define PCF2127_WD_VAL_MAX 255
#define PCF2127_WD_VAL_DEFAULT 60
struct pcf2127 {
struct rtc_device *rtc;
struct watchdog_device wdd;
struct regmap *regmap;
};
/*
* In the routines that deal directly with the pcf2127 hardware, we use
* rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch.
*/
static int pcf2127_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
unsigned char buf[10];
int ret;
/*
* Avoid reading CTRL2 register as it causes WD_VAL register
* value to reset to 0 which means watchdog is stopped.
*/
ret = regmap_bulk_read(pcf2127->regmap, PCF2127_REG_CTRL3,
(buf + PCF2127_REG_CTRL3),
ARRAY_SIZE(buf) - PCF2127_REG_CTRL3);
if (ret) {
dev_err(dev, "%s: read error\n", __func__);
return ret;
}
if (buf[PCF2127_REG_CTRL3] & PCF2127_BIT_CTRL3_BLF)
dev_info(dev,
"low voltage detected, check/replace RTC battery.\n");
/* Clock integrity is not guaranteed when OSF flag is set. */
if (buf[PCF2127_REG_SC] & PCF2127_BIT_SC_OSF) {
/*
* no need clear the flag here,
* it will be cleared once the new date is saved
*/
dev_warn(dev,
"oscillator stop detected, date/time is not reliable\n");
return -EINVAL;
}
dev_dbg(dev,
"%s: raw data is cr3=%02x, sec=%02x, min=%02x, hr=%02x, "
"mday=%02x, wday=%02x, mon=%02x, year=%02x\n",
__func__, buf[PCF2127_REG_CTRL3], buf[PCF2127_REG_SC],
buf[PCF2127_REG_MN], buf[PCF2127_REG_HR],
buf[PCF2127_REG_DM], buf[PCF2127_REG_DW],
buf[PCF2127_REG_MO], buf[PCF2127_REG_YR]);
tm->tm_sec = bcd2bin(buf[PCF2127_REG_SC] & 0x7F);
tm->tm_min = bcd2bin(buf[PCF2127_REG_MN] & 0x7F);
tm->tm_hour = bcd2bin(buf[PCF2127_REG_HR] & 0x3F); /* rtc hr 0-23 */
tm->tm_mday = bcd2bin(buf[PCF2127_REG_DM] & 0x3F);
tm->tm_wday = buf[PCF2127_REG_DW] & 0x07;
tm->tm_mon = bcd2bin(buf[PCF2127_REG_MO] & 0x1F) - 1; /* rtc mn 1-12 */
tm->tm_year = bcd2bin(buf[PCF2127_REG_YR]);
tm->tm_year += 100;
dev_dbg(dev, "%s: tm is secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
return 0;
}
static int pcf2127_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
unsigned char buf[7];
int i = 0, err;
dev_dbg(dev, "%s: secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
/* hours, minutes and seconds */
buf[i++] = bin2bcd(tm->tm_sec); /* this will also clear OSF flag */
buf[i++] = bin2bcd(tm->tm_min);
buf[i++] = bin2bcd(tm->tm_hour);
buf[i++] = bin2bcd(tm->tm_mday);
buf[i++] = tm->tm_wday & 0x07;
/* month, 1 - 12 */
buf[i++] = bin2bcd(tm->tm_mon + 1);
/* year */
buf[i++] = bin2bcd(tm->tm_year - 100);
/* write register's data */
err = regmap_bulk_write(pcf2127->regmap, PCF2127_REG_SC, buf, i);
if (err) {
dev_err(dev,
"%s: err=%d", __func__, err);
return err;
}
return 0;
}
static int pcf2127_rtc_ioctl(struct device *dev,
unsigned int cmd, unsigned long arg)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
int val, touser = 0;
int ret;
switch (cmd) {
case RTC_VL_READ:
ret = regmap_read(pcf2127->regmap, PCF2127_REG_CTRL3, &val);
if (ret)
return ret;
if (val & PCF2127_BIT_CTRL3_BLF)
touser |= RTC_VL_BACKUP_LOW;
if (val & PCF2127_BIT_CTRL3_BF)
touser |= RTC_VL_BACKUP_SWITCH;
return put_user(touser, (unsigned int __user *)arg);
case RTC_VL_CLR:
return regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL3,
PCF2127_BIT_CTRL3_BF, 0);
default:
return -ENOIOCTLCMD;
}
}
static const struct rtc_class_ops pcf2127_rtc_ops = {
.ioctl = pcf2127_rtc_ioctl,
.read_time = pcf2127_rtc_read_time,
.set_time = pcf2127_rtc_set_time,
};
static int pcf2127_nvmem_read(void *priv, unsigned int offset,
void *val, size_t bytes)
{
struct pcf2127 *pcf2127 = priv;
int ret;
unsigned char offsetbuf[] = { offset >> 8, offset };
ret = regmap_bulk_write(pcf2127->regmap, PCF2127_REG_RAM_ADDR_MSB,
offsetbuf, 2);
if (ret)
return ret;
ret = regmap_bulk_read(pcf2127->regmap, PCF2127_REG_RAM_RD_CMD,
val, bytes);
return ret ?: bytes;
}
static int pcf2127_nvmem_write(void *priv, unsigned int offset,
void *val, size_t bytes)
{
struct pcf2127 *pcf2127 = priv;
int ret;
unsigned char offsetbuf[] = { offset >> 8, offset };
ret = regmap_bulk_write(pcf2127->regmap, PCF2127_REG_RAM_ADDR_MSB,
offsetbuf, 2);
if (ret)
return ret;
ret = regmap_bulk_write(pcf2127->regmap, PCF2127_REG_RAM_WRT_CMD,
val, bytes);
return ret ?: bytes;
}
/* watchdog driver */
static int pcf2127_wdt_ping(struct watchdog_device *wdd)
{
struct pcf2127 *pcf2127 = watchdog_get_drvdata(wdd);
return regmap_write(pcf2127->regmap, PCF2127_REG_WD_VAL, wdd->timeout);
}
/*
* Restart watchdog timer if feature is active.
*
* Note: Reading CTRL2 register causes watchdog to stop which is unfortunate,
* since register also contain control/status flags for other features.
* Always call this function after reading CTRL2 register.
*/
static int pcf2127_wdt_active_ping(struct watchdog_device *wdd)
{
int ret = 0;
if (watchdog_active(wdd)) {
ret = pcf2127_wdt_ping(wdd);
if (ret)
dev_err(wdd->parent,
"%s: watchdog restart failed, ret=%d\n",
__func__, ret);
}
return ret;
}
static int pcf2127_wdt_start(struct watchdog_device *wdd)
{
return pcf2127_wdt_ping(wdd);
}
static int pcf2127_wdt_stop(struct watchdog_device *wdd)
{
struct pcf2127 *pcf2127 = watchdog_get_drvdata(wdd);
return regmap_write(pcf2127->regmap, PCF2127_REG_WD_VAL,
PCF2127_WD_VAL_STOP);
}
static int pcf2127_wdt_set_timeout(struct watchdog_device *wdd,
unsigned int new_timeout)
{
dev_dbg(wdd->parent, "new watchdog timeout: %is (old: %is)\n",
new_timeout, wdd->timeout);
wdd->timeout = new_timeout;
return pcf2127_wdt_active_ping(wdd);
}
static const struct watchdog_info pcf2127_wdt_info = {
.identity = "NXP PCF2127/PCF2129 Watchdog",
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT,
};
static const struct watchdog_ops pcf2127_watchdog_ops = {
.owner = THIS_MODULE,
.start = pcf2127_wdt_start,
.stop = pcf2127_wdt_stop,
.ping = pcf2127_wdt_ping,
.set_timeout = pcf2127_wdt_set_timeout,
};
/* Alarm */
static int pcf2127_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
unsigned int buf[5], ctrl2;
int ret;
ret = regmap_read(pcf2127->regmap, PCF2127_REG_CTRL2, &ctrl2);
if (ret)
return ret;
ret = pcf2127_wdt_active_ping(&pcf2127->wdd);
if (ret)
return ret;
ret = regmap_bulk_read(pcf2127->regmap, PCF2127_REG_ALARM_SC, buf,
sizeof(buf));
if (ret)
return ret;
alrm->enabled = ctrl2 & PCF2127_BIT_CTRL2_AIE;
alrm->pending = ctrl2 & PCF2127_BIT_CTRL2_AF;
alrm->time.tm_sec = bcd2bin(buf[0] & 0x7F);
alrm->time.tm_min = bcd2bin(buf[1] & 0x7F);
alrm->time.tm_hour = bcd2bin(buf[2] & 0x3F);
alrm->time.tm_mday = bcd2bin(buf[3] & 0x3F);
return 0;
}
static int pcf2127_rtc_alarm_irq_enable(struct device *dev, u32 enable)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
int ret;
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL2,
PCF2127_BIT_CTRL2_AIE,
enable ? PCF2127_BIT_CTRL2_AIE : 0);
if (ret)
return ret;
return pcf2127_wdt_active_ping(&pcf2127->wdd);
}
static int pcf2127_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
uint8_t buf[5];
int ret;
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL2,
PCF2127_BIT_CTRL2_AF, 0);
if (ret)
return ret;
ret = pcf2127_wdt_active_ping(&pcf2127->wdd);
if (ret)
return ret;
buf[0] = bin2bcd(alrm->time.tm_sec);
buf[1] = bin2bcd(alrm->time.tm_min);
buf[2] = bin2bcd(alrm->time.tm_hour);
buf[3] = bin2bcd(alrm->time.tm_mday);
buf[4] = PCF2127_BIT_ALARM_AE; /* Do not match on week day */
ret = regmap_bulk_write(pcf2127->regmap, PCF2127_REG_ALARM_SC, buf,
sizeof(buf));
if (ret)
return ret;
return pcf2127_rtc_alarm_irq_enable(dev, alrm->enabled);
}
static irqreturn_t pcf2127_rtc_irq(int irq, void *dev)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev);
unsigned int ctrl2 = 0;
int ret = 0;
ret = regmap_read(pcf2127->regmap, PCF2127_REG_CTRL2, &ctrl2);
if (ret)
return IRQ_NONE;
if (!(ctrl2 & PCF2127_BIT_CTRL2_AF))
return IRQ_NONE;
regmap_write(pcf2127->regmap, PCF2127_REG_CTRL2,
ctrl2 & ~(PCF2127_BIT_CTRL2_AF | PCF2127_BIT_CTRL2_WDTF));
rtc_update_irq(pcf2127->rtc, 1, RTC_IRQF | RTC_AF);
pcf2127_wdt_active_ping(&pcf2127->wdd);
return IRQ_HANDLED;
}
static const struct rtc_class_ops pcf2127_rtc_alrm_ops = {
.ioctl = pcf2127_rtc_ioctl,
.read_time = pcf2127_rtc_read_time,
.set_time = pcf2127_rtc_set_time,
.read_alarm = pcf2127_rtc_read_alarm,
.set_alarm = pcf2127_rtc_set_alarm,
.alarm_irq_enable = pcf2127_rtc_alarm_irq_enable,
};
/* sysfs interface */
static ssize_t timestamp0_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev->parent);
int ret;
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL1,
PCF2127_BIT_CTRL1_TSF1, 0);
if (ret) {
dev_err(dev, "%s: update ctrl1 ret=%d\n", __func__, ret);
return ret;
}
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL2,
PCF2127_BIT_CTRL2_TSF2, 0);
if (ret) {
dev_err(dev, "%s: update ctrl2 ret=%d\n", __func__, ret);
return ret;
}
ret = pcf2127_wdt_active_ping(&pcf2127->wdd);
if (ret)
return ret;
return count;
};
static ssize_t timestamp0_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pcf2127 *pcf2127 = dev_get_drvdata(dev->parent);
struct rtc_time tm;
int ret;
unsigned char data[25];
ret = regmap_bulk_read(pcf2127->regmap, PCF2127_REG_CTRL1, data,
sizeof(data));
if (ret) {
dev_err(dev, "%s: read error ret=%d\n", __func__, ret);
return ret;
}
dev_dbg(dev,
"%s: raw data is cr1=%02x, cr2=%02x, cr3=%02x, ts_sc=%02x, "
"ts_mn=%02x, ts_hr=%02x, ts_dm=%02x, ts_mo=%02x, ts_yr=%02x\n",
__func__, data[PCF2127_REG_CTRL1], data[PCF2127_REG_CTRL2],
data[PCF2127_REG_CTRL3], data[PCF2127_REG_TS_SC],
data[PCF2127_REG_TS_MN], data[PCF2127_REG_TS_HR],
data[PCF2127_REG_TS_DM], data[PCF2127_REG_TS_MO],
data[PCF2127_REG_TS_YR]);
ret = pcf2127_wdt_active_ping(&pcf2127->wdd);
if (ret)
return ret;
if (!(data[PCF2127_REG_CTRL1] & PCF2127_BIT_CTRL1_TSF1) &&
!(data[PCF2127_REG_CTRL2] & PCF2127_BIT_CTRL2_TSF2))
return 0;
tm.tm_sec = bcd2bin(data[PCF2127_REG_TS_SC] & 0x7F);
tm.tm_min = bcd2bin(data[PCF2127_REG_TS_MN] & 0x7F);
tm.tm_hour = bcd2bin(data[PCF2127_REG_TS_HR] & 0x3F);
tm.tm_mday = bcd2bin(data[PCF2127_REG_TS_DM] & 0x3F);
/* TS_MO register (month) value range: 1-12 */
tm.tm_mon = bcd2bin(data[PCF2127_REG_TS_MO] & 0x1F) - 1;
tm.tm_year = bcd2bin(data[PCF2127_REG_TS_YR]);
if (tm.tm_year < 70)
tm.tm_year += 100; /* assume we are in 1970...2069 */
ret = rtc_valid_tm(&tm);
if (ret)
return ret;
return sprintf(buf, "%llu\n",
(unsigned long long)rtc_tm_to_time64(&tm));
};
static DEVICE_ATTR_RW(timestamp0);
static struct attribute *pcf2127_attrs[] = {
&dev_attr_timestamp0.attr,
NULL
};
static const struct attribute_group pcf2127_attr_group = {
.attrs = pcf2127_attrs,
};
static int pcf2127_probe(struct device *dev, struct regmap *regmap,
int alarm_irq, const char *name, bool has_nvmem)
{
struct pcf2127 *pcf2127;
u32 wdd_timeout;
int ret = 0;
dev_dbg(dev, "%s\n", __func__);
pcf2127 = devm_kzalloc(dev, sizeof(*pcf2127), GFP_KERNEL);
if (!pcf2127)
return -ENOMEM;
pcf2127->regmap = regmap;
dev_set_drvdata(dev, pcf2127);
pcf2127->rtc = devm_rtc_allocate_device(dev);
if (IS_ERR(pcf2127->rtc))
return PTR_ERR(pcf2127->rtc);
pcf2127->rtc->ops = &pcf2127_rtc_ops;
pcf2127->rtc->range_min = RTC_TIMESTAMP_BEGIN_2000;
pcf2127->rtc->range_max = RTC_TIMESTAMP_END_2099;
pcf2127->rtc->set_start_time = true; /* Sets actual start to 1970 */
pcf2127->rtc->uie_unsupported = 1;
if (alarm_irq >= 0) {
ret = devm_request_threaded_irq(dev, alarm_irq, NULL,
pcf2127_rtc_irq,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
dev_name(dev), dev);
if (ret) {
dev_err(dev, "failed to request alarm irq\n");
return ret;
}
}
if (alarm_irq >= 0 || device_property_read_bool(dev, "wakeup-source")) {
device_init_wakeup(dev, true);
pcf2127->rtc->ops = &pcf2127_rtc_alrm_ops;
}
pcf2127->wdd.parent = dev;
pcf2127->wdd.info = &pcf2127_wdt_info;
pcf2127->wdd.ops = &pcf2127_watchdog_ops;
pcf2127->wdd.min_timeout = PCF2127_WD_VAL_MIN;
pcf2127->wdd.max_timeout = PCF2127_WD_VAL_MAX;
pcf2127->wdd.timeout = PCF2127_WD_VAL_DEFAULT;
pcf2127->wdd.min_hw_heartbeat_ms = 500;
pcf2127->wdd.status = WATCHDOG_NOWAYOUT_INIT_STATUS;
watchdog_set_drvdata(&pcf2127->wdd, pcf2127);
if (has_nvmem) {
struct nvmem_config nvmem_cfg = {
.priv = pcf2127,
.reg_read = pcf2127_nvmem_read,
.reg_write = pcf2127_nvmem_write,
.size = 512,
};
ret = rtc_nvmem_register(pcf2127->rtc, &nvmem_cfg);
}
/*
* Watchdog timer enabled and reset pin /RST activated when timed out.
* Select 1Hz clock source for watchdog timer.
* Note: Countdown timer disabled and not available.
*/
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_WD_CTL,
PCF2127_BIT_WD_CTL_CD1 |
PCF2127_BIT_WD_CTL_CD0 |
PCF2127_BIT_WD_CTL_TF1 |
PCF2127_BIT_WD_CTL_TF0,
PCF2127_BIT_WD_CTL_CD1 |
PCF2127_BIT_WD_CTL_CD0 |
PCF2127_BIT_WD_CTL_TF1);
if (ret) {
dev_err(dev, "%s: watchdog config (wd_ctl) failed\n", __func__);
return ret;
}
/* Test if watchdog timer is started by bootloader */
ret = regmap_read(pcf2127->regmap, PCF2127_REG_WD_VAL, &wdd_timeout);
if (ret)
return ret;
if (wdd_timeout)
set_bit(WDOG_HW_RUNNING, &pcf2127->wdd.status);
#ifdef CONFIG_WATCHDOG
ret = devm_watchdog_register_device(dev, &pcf2127->wdd);
if (ret)
return ret;
#endif /* CONFIG_WATCHDOG */
/*
* Disable battery low/switch-over timestamp and interrupts.
* Clear battery interrupt flags which can block new trigger events.
* Note: This is the default chip behaviour but added to ensure
* correct tamper timestamp and interrupt function.
*/
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL3,
PCF2127_BIT_CTRL3_BTSE |
PCF2127_BIT_CTRL3_BIE |
PCF2127_BIT_CTRL3_BLIE, 0);
if (ret) {
dev_err(dev, "%s: interrupt config (ctrl3) failed\n",
__func__);
return ret;
}
/*
* Enable timestamp function and store timestamp of first trigger
* event until TSF1 and TFS2 interrupt flags are cleared.
*/
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_TS_CTRL,
PCF2127_BIT_TS_CTRL_TSOFF |
PCF2127_BIT_TS_CTRL_TSM,
PCF2127_BIT_TS_CTRL_TSM);
if (ret) {
dev_err(dev, "%s: tamper detection config (ts_ctrl) failed\n",
__func__);
return ret;
}
/*
* Enable interrupt generation when TSF1 or TSF2 timestamp flags
* are set. Interrupt signal is an open-drain output and can be
* left floating if unused.
*/
ret = regmap_update_bits(pcf2127->regmap, PCF2127_REG_CTRL2,
PCF2127_BIT_CTRL2_TSIE,
PCF2127_BIT_CTRL2_TSIE);
if (ret) {
dev_err(dev, "%s: tamper detection config (ctrl2) failed\n",
__func__);
return ret;
}
ret = rtc_add_group(pcf2127->rtc, &pcf2127_attr_group);
if (ret) {
dev_err(dev, "%s: tamper sysfs registering failed\n",
__func__);
return ret;
}
return rtc_register_device(pcf2127->rtc);
}
#ifdef CONFIG_OF
static const struct of_device_id pcf2127_of_match[] = {
{ .compatible = "nxp,pcf2127" },
{ .compatible = "nxp,pcf2129" },
{ .compatible = "nxp,pca2129" },
{}
};
MODULE_DEVICE_TABLE(of, pcf2127_of_match);
#endif
#if IS_ENABLED(CONFIG_I2C)
static int pcf2127_i2c_write(void *context, const void *data, size_t count)
{
struct device *dev = context;
struct i2c_client *client = to_i2c_client(dev);
int ret;
ret = i2c_master_send(client, data, count);
if (ret != count)
return ret < 0 ? ret : -EIO;
return 0;
}
static int pcf2127_i2c_gather_write(void *context,
const void *reg, size_t reg_size,
const void *val, size_t val_size)
{
struct device *dev = context;
struct i2c_client *client = to_i2c_client(dev);
int ret;
void *buf;
if (WARN_ON(reg_size != 1))
return -EINVAL;
buf = kmalloc(val_size + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
memcpy(buf, reg, 1);
memcpy(buf + 1, val, val_size);
ret = i2c_master_send(client, buf, val_size + 1);
kfree(buf);
if (ret != val_size + 1)
return ret < 0 ? ret : -EIO;
return 0;
}
static int pcf2127_i2c_read(void *context, const void *reg, size_t reg_size,
void *val, size_t val_size)
{
struct device *dev = context;
struct i2c_client *client = to_i2c_client(dev);
int ret;
if (WARN_ON(reg_size != 1))
return -EINVAL;
ret = i2c_master_send(client, reg, 1);
if (ret != 1)
return ret < 0 ? ret : -EIO;
ret = i2c_master_recv(client, val, val_size);
if (ret != val_size)
return ret < 0 ? ret : -EIO;
return 0;
}
/*
* The reason we need this custom regmap_bus instead of using regmap_init_i2c()
* is that the STOP condition is required between set register address and
* read register data when reading from registers.
*/
static const struct regmap_bus pcf2127_i2c_regmap = {
.write = pcf2127_i2c_write,
.gather_write = pcf2127_i2c_gather_write,
.read = pcf2127_i2c_read,
};
static struct i2c_driver pcf2127_i2c_driver;
static int pcf2127_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct regmap *regmap;
static const struct regmap_config config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = 0x1d,
};
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
regmap = devm_regmap_init(&client->dev, &pcf2127_i2c_regmap,
&client->dev, &config);
if (IS_ERR(regmap)) {
dev_err(&client->dev, "%s: regmap allocation failed: %ld\n",
__func__, PTR_ERR(regmap));
return PTR_ERR(regmap);
}
return pcf2127_probe(&client->dev, regmap, client->irq,
pcf2127_i2c_driver.driver.name, id->driver_data);
}
static const struct i2c_device_id pcf2127_i2c_id[] = {
{ "pcf2127", 1 },
{ "pcf2129", 0 },
{ "pca2129", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pcf2127_i2c_id);
static struct i2c_driver pcf2127_i2c_driver = {
.driver = {
.name = "rtc-pcf2127-i2c",
.of_match_table = of_match_ptr(pcf2127_of_match),
},
.probe = pcf2127_i2c_probe,
.id_table = pcf2127_i2c_id,
};
static int pcf2127_i2c_register_driver(void)
{
return i2c_add_driver(&pcf2127_i2c_driver);
}
static void pcf2127_i2c_unregister_driver(void)
{
i2c_del_driver(&pcf2127_i2c_driver);
}
#else
static int pcf2127_i2c_register_driver(void)
{
return 0;
}
static void pcf2127_i2c_unregister_driver(void)
{
}
#endif
#if IS_ENABLED(CONFIG_SPI_MASTER)
static struct spi_driver pcf2127_spi_driver;
static int pcf2127_spi_probe(struct spi_device *spi)
{
static const struct regmap_config config = {
.reg_bits = 8,
.val_bits = 8,
.read_flag_mask = 0xa0,
.write_flag_mask = 0x20,
.max_register = 0x1d,
};
struct regmap *regmap;
regmap = devm_regmap_init_spi(spi, &config);
if (IS_ERR(regmap)) {
dev_err(&spi->dev, "%s: regmap allocation failed: %ld\n",
__func__, PTR_ERR(regmap));
return PTR_ERR(regmap);
}
return pcf2127_probe(&spi->dev, regmap, spi->irq,
pcf2127_spi_driver.driver.name,
spi_get_device_id(spi)->driver_data);
}
static const struct spi_device_id pcf2127_spi_id[] = {
{ "pcf2127", 1 },
{ "pcf2129", 0 },
{ "pca2129", 0 },
{ }
};
MODULE_DEVICE_TABLE(spi, pcf2127_spi_id);
static struct spi_driver pcf2127_spi_driver = {
.driver = {
.name = "rtc-pcf2127-spi",
.of_match_table = of_match_ptr(pcf2127_of_match),
},
.probe = pcf2127_spi_probe,
.id_table = pcf2127_spi_id,
};
static int pcf2127_spi_register_driver(void)
{
return spi_register_driver(&pcf2127_spi_driver);
}
static void pcf2127_spi_unregister_driver(void)
{
spi_unregister_driver(&pcf2127_spi_driver);
}
#else
static int pcf2127_spi_register_driver(void)
{
return 0;
}
static void pcf2127_spi_unregister_driver(void)
{
}
#endif
static int __init pcf2127_init(void)
{
int ret;
ret = pcf2127_i2c_register_driver();
if (ret) {
pr_err("Failed to register pcf2127 i2c driver: %d\n", ret);
return ret;
}
ret = pcf2127_spi_register_driver();
if (ret) {
pr_err("Failed to register pcf2127 spi driver: %d\n", ret);
pcf2127_i2c_unregister_driver();
}
return ret;
}
module_init(pcf2127_init)
static void __exit pcf2127_exit(void)
{
pcf2127_spi_unregister_driver();
pcf2127_i2c_unregister_driver();
}
module_exit(pcf2127_exit)
MODULE_AUTHOR("Renaud Cerrato <[email protected]>");
MODULE_DESCRIPTION("NXP PCF2127/29 RTC driver");
MODULE_LICENSE("GPL v2");
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<QtTesting>
<settings>
<name widget="qApp" command="applicationName" arguments=""/>
<version widget="qApp" command="applicationVersion" arguments=""/>
<font widget="MainWindow" command="font" arguments="Loma,10,-1,5,50,0,0,0,0,0"/>
<geometry widget="MainWindow" command="mainWindowGeometry" arguments="01d9d0cb00010000000000000000003100000329000001b3000000060000004a00000323000001ad000000000000"/>
<state widget="MainWindow" command="mainWindowState" arguments="000000ff00000000fd000000000000031e0000015000000004000000040000000800000008fc00000000"/>
</settings>
<events>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseWheel" arguments="(1.17333,1.35333,0,0,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseWheel" arguments="(1.17333,1.35333,1,0,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseWheel" arguments="(1.17333,1.35333,1,0,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseWheel" arguments="(1.17333,1.35333,1,0,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mousePress" arguments="(-0.373333,-0.426667,1,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.373333,-0.433333,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.366667,-0.433333,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.366667,-0.44,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.36,-0.446667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.306667,-0.48,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.226667,-0.52,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.18,-0.54,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(-0.08,-0.553333,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.0266667,-0.586667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.0733333,-0.593333,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.126667,-0.6,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.133333,-0.6,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.14,-0.6,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.146667,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.153333,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.16,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.166667,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.173333,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.18,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.186667,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.193333,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.2,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseMove" arguments="(0.2,-0.606667,0,1,0)"/>
<event widget="ctkEventTranslatorPlayerWidget/centralwidget/stackedWidget/1QWidget0/1qMRMLThreeDView0/1ctkVTKOpenGLNativeWidget0" command="mouseRelease" arguments="(0.2,-0.606667,1,0,0)"/>
</events>
</QtTesting>
| {
"pile_set_name": "Github"
} |
FILE=chord.h
DESTFILE=chordscripting.h
HEADER=../../_script_template/header.tmpl
HEADERADDONS=../../_script_template/baseitemHeader.tmpl;../../_script_template/itemHeader.tmpl
BODYFILES=../../_script_template/common.tmpl;../../_script_template/baseitemBody.tmpl;../../_script_template/itemBody.tmpl
FOOTER=../../_script_template/footer.tmpl
ENUMSECTION=../../_script_template/enumsection.tmpl
ENUMREPEATADDONS=../../_script_template/baseitemRepeat.tmpl;../../_script_template/itemRepeat.tmpl
CLASSNAME=ChordItem
OBJECTNAME=chord | {
"pile_set_name": "Github"
} |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Modals = factory());
}(this, (function () { 'use strict';
// https://stackoverflow.com/a/34624648
function copy(o) {
var _out, v, _key;
_out = Array.isArray(o) ? [] : {};
for (_key in o) {
v = o[_key];
_out[_key] = (typeof v === "object" && v !== null) ? copy(v) : v;
}
return _out;
}
// https://github.com/jaredreich/tread
function merge(oldObject, newObject, strict) {
var obj = oldObject
for (var key in newObject) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
merge(obj[key], newObject[key])
} else {
if (strict) {
if (obj.hasOwnProperty(key)) {
obj[key] = newObject[key]
}
} else {
obj[key] = newObject[key]
}
}
}
return obj
}
function copyMerge(targ, src) {
return merge(copy(targ), copy(src));
}
var el = domvm.defineElement;
function Modals(opts) {
this.opts = opts || {};
var stack = this.stack = [];
var vm = this.vm = domvm.createView(ModalsView, this);
this.push = function(cfg) {
stack.push(copy(cfg));
vm.redraw();
};
this.pop = function(howMany) {
howMany = howMany || 1;
while (howMany--)
stack.pop();
vm.redraw();
};
this.mount = function(ctnr) {
vm.mount(ctnr);
};
}
function ModalsView(vm, mods) {
function initAttrs(cfg) {
return (cfg.attrs = {_hooks: genHooks(cfg)});
}
function updAttrs(cfg, attrs) {
return (cfg.attrs = copyMerge(cfg.attrs || {}, attrs || {}));
}
function genHooks(cfg) {
var push = cfg.onpush;
var pop = cfg.onpop;
var hooks = {};
if (push) {
if (push.initial) {
hooks.willInsert = function(node) {
node.patch(updAttrs(cfg, push.initial(node)));
};
}
if (push.delayed) {
hooks.didInsert = function(node) {
node.patch(updAttrs(cfg, push.delayed(node)));
// must determine if there's a transition to set up hook, assumed yes for now
// http://codepen.io/csuwldcat/pen/EempF
if (push.settled) {
var setPatch = function() {
node.patch(updAttrs(cfg, push.settled(node)));
};
node.patch(updAttrs(cfg, {ontransitionend: [setPatch]}));
}
};
}
}
if (pop) {
if (pop.initial || pop.delayed) {
hooks.willRemove = function(node) {
if (pop.initial)
node.patch(updAttrs(cfg, pop.initial(node)));
if (pop.delayed) {
return new Promise(function(resolve, reject) {
node.patch(updAttrs(cfg, merge(pop.delayed(node), {ontransitionend: [resolve]})));
});
}
};
}
}
return Object.keys(hooks).length > 0 ? hooks : null;
}
function modalTpl(i, stack) {
var cfg = stack[i];
var isLast = i === stack.length - 1;
var ovrAttrs = copy(cfg.overlay.attrs || initAttrs(cfg.overlay));
var cntAttrs = copy(cfg.content.attrs || initAttrs(cfg.content));
return el(".dv-modals-overlay", ovrAttrs, [
el(".dv-modals-content", cntAttrs, [
cfg.content.body(),
isLast ? null : modalTpl(i + 1, stack),
])
]);
}
return function() {
return el(".dv-modals", [
mods.stack.length > 0 && modalTpl(0, mods.stack)
]);
};
}
return Modals;
})));
/* usage */
var modals = new Modals();
modals.mount(document.body);
function dismiss() {
modals.pop();
}
// pop modal on overlay click
function overlayClick(e) {
if (e.target == e.currentTarget)
modals.pop();
}
// pop modal on esc
document.addEventListener("keyup", function(e) {
if (e.keyCode == 27)
modals.pop();
});
var el = domvm.defineElement,
tx = domvm.defineText;
var modalA = {
overlay: {
onpush: {
initial: function(node) { return {style: {opacity: 0, background: "rgba(128,255,255,.5)", position: "absolute"}, onclick: overlayClick}; }, // opacity: 1
delayed: function(node) { return {style: {opacity: 1, transition: "250ms"}}; },
},
onpop: {
delayed: function(node) { return {style: {opacity: 0, transition: "250ms"}}; },
}
},
content: {
body: function() { return (
el(".test1", [
el("p", "Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb."),
el("button.dismiss", {onclick: dismiss}, "Dismiss"),
])
)},
onpush: {
initial: function(node) { return {style: {height: 300, width: 600}}; }, // immediate
// delayed: function(node) { return {style: {color: "red", height: 600, transform: "rotateZ(360deg)", transition: "250ms"}}; }, // nextTick
// settled: function(node) { return {style: {color: "red", height: 600}}; }, // transitionend (shorthand for simply unsetting transition?)
},
onpop: {
// delayed: function(node) { return {style: {transition: "2s", opacity: 0}}; },
// initial: function(node) { return null; },
// delayed: function(node) { return {style: {color: "red", height: 600, transition: "500ms"}}; }, // nextTick
}
},
};
var modalB = {
overlay: {
onpush: {
initial: function(node) { return {style: {opacity: 0, background: "rgba(128,128,255,.5)", position: "absolute"}, onclick: overlayClick}; },
delayed: function(node) { return {style: {opacity: 1, transition: "250ms"}}; },
},
onpop: {
delayed: function(node) { return {style: {opacity: 0, transition: "250ms"}}; },
}
},
content: {
body: function() { return (
el(".test2", [
tx("bar"),
el("button.dismiss", {onclick: dismiss}, "Dismiss"),
])
)},
onpush: {
initial: function(node) { return {style: {height: 200, width: 400, transform: "translateX(-180px)"}}; },
delayed: function(node) { return {style: {transform: "translateX(0)", transition: "250ms"}}; },
},
onpop: {
initial: function(node) { return {style: {transform: "translateY(100px)", transition: "250ms"}}; },
// delayed: function(node) { return {style: {color: "red", height: 600, transition: "500ms"}}; }, // nextTick
}
},
};
var modalC = {
overlay: {
onpush: {
initial: function(node) { return {style: {opacity: 0, background: "rgba(255,128,255,.5)", position: "absolute"}, onclick: overlayClick}; },
delayed: function(node) { return {style: {opacity: 1, transition: "250ms"}}; },
},
onpop: {
delayed: function(node) { return {style: {opacity: 0, transition: "250ms"}}; },
}
},
content: {
body: function() { return (
el(".test3", [
tx("baz"),
el("button.dismiss", {onclick: dismiss}, "Dismiss"),
])
)},
onpush: {
initial: function(node) { return {style: {height: 600, transform: "rotateZ(-180deg)"}}; },
delayed: function(node) { return {style: {color: "blue", height: 200, transform: "none", transition: "250ms"}}; },
// settled: function(node) { return {style: {border: "1px solid red", transition: "0s"}}; },
},
onpop: {
initial: function(node) { return {style: {height: 600, transform: "rotateZ(-180deg)", transition: "250ms"}}; },
// delayed: function(node) { return {style: {color: "red", height: 600, transition: "500ms"}}; }, // nextTick
}
},
};
setTimeout(function() {
modals.push(modalA);
}, 0);
setTimeout(function() {
modals.push(modalB);
}, 1000);
setTimeout(function() {
modals.push(modalC);
}, 2000);
/*
setTimeout(function() {
modals.pop();
}, 3000);
setTimeout(function() {
modals.pop();
}, 4000);
setTimeout(function() {
modals.pop();
}, 5000);
*/ | {
"pile_set_name": "Github"
} |
<html><head><title>Pictures</title></head>
<body><a href="/lurk/ftp/Pictures/">To the pictures directory</a>
</body></html>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
# Copyright 2019 Koha Development team
#
# This file is part of Koha
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha 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 Koha; if not, see <http://www.gnu.org/licenses>.
use Modern::Perl;
use Test::More tests => 3;
use Koha::Account::DebitType;
use Koha::Account::DebitTypes;
use Koha::Database;
use t::lib::TestBuilder;
use Try::Tiny;
my $schema = Koha::Database->new->schema;
$schema->storage->txn_begin;
my $builder = t::lib::TestBuilder->new;
my $number_of_debit_types = Koha::Account::DebitTypes->search->count;
my $new_debit_type_1 = Koha::Account::DebitType->new(
{
code => '3CODE',
description => 'my description 3',
can_be_invoiced => 1,
default_amount => 0.45,
}
)->store;
my $new_debit_type_2 = Koha::Account::DebitType->new(
{
code => '4CODE',
description => 'my description 4',
can_be_invoiced => 1,
}
)->store;
my $retrieved_debit_types_all = Koha::Account::DebitTypes->search();
try {
$retrieved_debit_types_all->delete;
}
catch {
ok(
$_->isa('Koha::Exceptions::CannotDeleteDefault'),
'A system debit type cannot be deleted via the set'
);
};
is(
Koha::Account::DebitTypes->search->count,
$number_of_debit_types + 2,
'System debit types cannot be deleted as a set'
);
my $retrieved_debit_types_limited = Koha::Account::DebitTypes->search(
{
code => { 'in' => [ $new_debit_type_1->code, $new_debit_type_2->code ] }
}
);
$retrieved_debit_types_limited->delete;
is( Koha::Account::DebitTypes->search->count,
$number_of_debit_types, 'Non-system debit types can be deleted as a set' );
$schema->storage->txn_rollback;
1;
| {
"pile_set_name": "Github"
} |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
// NOTE: Boilerplate only. Ignore this file.
// Package v2 contains API Schema definitions for the bkbcs v2 API group
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=bk-bcs/bcs-mesos/pkg/apis/bkbcs
// +k8s:defaulter-gen=TypeMeta
// +groupName=bkbcs.tencent.com
package v2
import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/runtime/scheme"
)
var (
// SchemeGroupVersion is group version used to register these objects
SchemeGroupVersion = schema.GroupVersion{Group: "bkbcs.tencent.com", Version: "v2"}
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion}
// AddToScheme is required by pkg/client/...
AddToScheme = SchemeBuilder.AddToScheme
)
// Resource is required by pkg/client/listers/...
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
| {
"pile_set_name": "Github"
} |
#' @title Plot colours
#' @description Display a chart of colours from a vector of colours or ggthemr object.
#' @param x Character vector of colours or ggthemr palette object.
#' @export
#' @author Ciaran Tobin
#' @examples
#' colour_plot(c('#14B294', 'coral'))
#' colour_plot(ggthemr('sea'))
#' @export
colour_plot <- function (x)
UseMethod('colour_plot', x)
#' @rdname colour_plot
#' @export
colour_plot.character <- function (x)
plot_colours(x)
#' @rdname colour_plot
#' @export
colour_plot.ggthemr <- function (x)
plot_colours(unclass(x$palette$swatch), x$palette$background)
#' @rdname colour_plot
#' @export
colour_plot.ggthemr_palette <- function (x)
plot_colours(unclass(x$swatch), x$background)
#' @rdname colour_plot
#' @export
colour_plot.ggthemr_swatch <- function (x)
plot_colours(unclass(x))
| {
"pile_set_name": "Github"
} |
(set-env!
:resource-paths #{"resources"}
:dependencies '[[cljsjs/boot-cljsjs "0.10.5" :scope "test"]])
(require '[cljsjs.boot-cljsjs.packaging :refer :all])
(def +lib-version+ "1.5.0")
(def +version+ (str +lib-version+ "-0"))
(task-options!
pom {:project 'cljsjs/webslides
:version +version+
:description "Create HTML presentations in seconds"
:url "http://webslides.tv"
:scm {:url "https://github.com/cljsjs/packages"}
:license {"MIT" "http://opensource.org/licenses/MIT"}})
(deftask package []
(comp
(download
:url (format "https://github.com/webslides/webslides/archive/%s.zip" +lib-version+)
:unzip true)
(sift :move {#"^WebSlides-.*/static/js/webslides.js$" "cljsjs/webslides/development/webslides.inc.js"
#"^WebSlides-.*/static/js/webslides.min.js$" "cljsjs/webslides/production/webslides.min.inc.js"
#"^WebSlides-.*/static/css/([^/]+\.css)$" "cljsjs/webslides/common/$1"})
(sift :include #{#"^cljsjs"})
(deps-cljs
:name "cljsjs.webslides")
(pom)
(jar)
(validate)))
| {
"pile_set_name": "Github"
} |
About two years ago I decided to add HTTPS support to this site, using automatic certification via Let's Encrypt. All the articles on the subject relied on a tool called [certbot](https://certbot.eff.org/). A couple of variations were mentioned, some requiring the tool to run while the site is down, others using nginx + certbot combination. It seemed that installing and running some additional external tool(s) in production was mandatory.
At that point The Erlangelist was a standalone Elixir-powered system which required no external program. It seemed that now I have to start worrying about setting up additional services and interact with them using their custom DSLs. This would complicate operations, and create a disconnect between production and development. Any changes to the certification configuration would need to be tested directly in production, or alternatively I'd have to setup a staging server. Either way, testing of certification would be done manually.
Unhappy with this state I started the work on [site_encrypt](https://hexdocs.pm/site_encrypt/readme.html), a library which takes a different approach to automatic certification:
1. site_encrypt is a library dependency, not an external tool. You're not required to install any OS-level package to use it.
2. The certification process and periodical renewal are running in the same OS process as the rest of the system. No other OS processes need to be started.
3. Everything is configured in the same project where the system is implemented.
4. Interaction with site_encrypt is done via Elixir functions and data. No yaml, ini, json, or other kind of DSL is required.
5. It's trivial to run the certification locally, which reduces the differences between prod and local dev.
6. The support for automatic testing of the certification is provided. There's no need to setup staging machines, or make changes directly on the production system.
This is an example of what I call "integrated operations". Instead of being spread across a bunch of yamls, inis, jsons, and bash scripts, somehow all glued together at the OS-level, most of the operations is done in development, i.e. the same place where the rest of the system is implemented, using the same language. Such approach significantly reduces the technical complexity of the system. The Erlangelist is mostly implemented in Elixir, with only a few administrative tasks, such as installation of OS packages, users creation, port forwarding rules, and similar provisioning tasks being done outside of Elixir.
This also simplifies local development. The [instructions to start the system locally](https://github.com/sasa1977/erlangelist/#running-the-site-locally) are very simple:
1. Install build tools (Elixir, Erlang, nodejs)
2. Fetch dependencies
3. Invoke a single command to start the system
The locally started system will be extremely close to the production version. There is almost nothing of significance running on production which is not running locally. The only two differences of note I can think of are:
1. Ports 80/443 are forwarded in prod
2. The prod version uses Lets Encrypt for certification, while the local version uses a local CA server (more on this later).
Now, this may not sound like much for a simple blog host, but behind the scene The Erlangelist is a bit more than a simple request responder:
1. The Erlangelist system runs two separate web servers. The public facing server is the one you use to read this article. Another internal server uses the [Phoenix Live Dashboard](https://hexdocs.pm/phoenix_live_dashboard/Phoenix.LiveDashboard.html) to expose some metrics.
2. A small hand-made database is running which collects, aggregates, and persists the reading stats, periodically removing older stats from the disk.
3. The system periodically renews the certificate.
4. Locally and on CI, another web server which acts as a local certificate authority (CA) is running.
In other words, The Erlangelist is more than just a blog, a site, a server, or an app. It's a system consisting of multiple activities which collectively work together to support the full end-user service, as well as the operational aspects of the system. All of these activities are running concurrently. They don't block each other, or crash each other. The system utilizes all CPU cores of its host machine. For more details on how this works take a look at my talk [The soul of Erlang and Elixir](https://www.youtube.com/watch?v=JvBT4XBdoUE).
Let's take a closer look at site_encrypt.
## Certification
Let's Encrypt supports automatic certification via the [ACME (Automatic Certificate Management Environment) protocol](https://tools.ietf.org/html/rfc8555). This protocol describes the conversation between the client, which is a system wanting to obtain the certificate for some domain, and the server, which is the certificate authority (CA) that can create such certificate. In ACME conversation, our system asks the CA to provide the certificate for some domain, and the CA asks us to prove that we're the owners of that domain. The CA gives us some random bytes, and then makes a request at our domain, expecting to get those same bytes in return. This is also called a challenge. If we successfully respond to the challenge, the CA will create the certificate for us. The real story is of course more involved, but this simplified version hopefully gives you the basic idea.
This conversation is an activity of the system. It's a job which needs to be occasionally done to allow the system to provide the full service. If we don't do the certification, we don't have a valid certificate, and most people won't use the site. Likewise, if I decide to shut the site down, the certification serves no purpose anymore.
In such situations my preferred approach is to run this activity together with the rest of the system. The less fragmented the system is, the easier it is to manage. Running some part of the system externally is fine if there are stronger reasons, but I don't see such reasons in this simple scenario.
[site_encrypt makes this task straightforward](https://hexdocs.pm/site_encrypt/readme.html#quick-start). Add a library dep, fill in some blanks, and you're good to go. The certification configuration is provided by defining the `certification` function:
```elixir
def certification do
SiteEncrypt.configure(
client: :native,
domains: ["mysite.com", "www.mysite.com"],
emails: ["[email protected]", "[email protected]"],
db_folder: "/folder/where/site_encrypt/stores/files",
directory_url: directory_url(),
)
end
```
This code looks pretty declarative, but it is executable code, not just a collection of facts. And that means that we have a lot of flexibility to shape the configuration data however we want. For example, if we want to make the certification parameters configurable by the system operator, say via a yaml file, nothing stops us from invoking `load_configuration_from_yaml()` instead of hardcoding the data. Say we want to make only some parameters configurable (e.g. domains and email), while leaving the rest hardcoded. We can simply do `Keyword.merge(load_some_params_from_yaml(), hardcoded_data)`. Supporting other kinds of config sources, like etcd or a database, is equally straightforward. You can always build declarative on top of imperative, while the opposite will require some imagination and trickery, such as running external configuration generators, and good luck managing that in production :-)
It's also worth mentioning that site_encrypt internally ships with two lower-level modules, a sort of plumbing to this porcelain. There is a [mid-level module](https://hexdocs.pm/site_encrypt/SiteEncrypt.Acme.Client.html#content) which provides workflow-related operations, such as "create an account", or "perform the certification", and a [lower-level module](https://hexdocs.pm/site_encrypt/SiteEncrypt.Acme.Client.API.html#content) which provides basic ACME client operations. These modules can be used when you want a finer grained control over the certification process.
## Reducing the dev-production mismatch
There's one interesting thing happening in the configuration presented earlier:
```elixir
def certification do
SiteEncrypt.configure(
# ...
directory_url: directory_url(),
)
end
```
The `directory_url` property defines the CA where site_encrypt will obtain the certificate. Instead of hardcoding this url, we're invoking a function to compute it. This happens because we need to use different urls for production vs staging vs local development. Let's take a look:
```elixir
defp directory_url do
case System.get_env("MODE", "local") do
"production" -> "https://acme-v02.api.letsencrypt.org/directory"
"staging" -> "https://acme-staging-v02.api.letsencrypt.org/directory"
"local" -> {:internal, port: 4002}
end
end
```
Here, we're distinguishing production from staging from development based on the `MODE` OS env (easily replaceable with other source, owing to programmable API). If the env is not provided, we'll assume that the system running locally.
On a production machine, we go to the real CA, while for staging we'll use Let's Encrypt staging site. But what about the `{:internal, port: 4002}` thing which we use in local development? If we pass this particular shape of data to site_encrypt, an internal ACME server will be started on the given port, a sort of a local mock of Let's Encrypt. This server is running inside the same same OS process as the rest of the system.
So locally, site_encrypt will start a mock of Let's Encrypt, and it will use that mock to obtain the certificate. In other words, locally the system will certify itself. Here's an example of this in action on a local version of The Erlangelist:
```text
$ iex -S mix phx.server
[info] Running ErlangelistWeb.Blog.Endpoint at 0.0.0.0:20080 (http)
[info] Running ErlangelistWeb.Blog.Endpoint at 0.0.0.0:20443 (https)
[info] Running local ACME server at port 20081
[info] Creating new ACME account for domain theerlangelist.com
[info] Ordering a new certificate for domain theerlangelist.com
[info] New certificate for domain theerlangelist.com obtained
[info] Certificate successfully obtained!
```
## Testability
Since local Erlangelist behaves exactly as the real one, we can test more of the system behaviour. For example, even on the local version HTTP requests are redirected to HTTPS. Here's a test verifying this:
```elixir
test "http requests are redirected to https" do
assert redirected_to(Client.get("http://localhost/"), 301) ==
"https://localhost/"
end
```
Likewise, redirection to www can also be tested:
```elixir
test "theerlangelist.com is redirected to www.theerlangelist.com" do
assert redirected_to(Client.get("https://theerlangelist.com/"), 301)
== "https://www.theerlangelist.com/"
end
```
In contrast, external proxy rules, such as those defined in Nginx configuration are typically not tested, which means that some change in configuration might break something else in a way which is not obvious to the operator.
In addition, site_encrypt ships with a small helper for testing the certification. Here's the relevant test:
```elixir
test "certification" do
clean_restart(ErlangelistWeb.Blog.Endpoint)
cert = get_cert(ErlangelistWeb.Blog.Endpoint)
assert cert.domains == ~w/theerlangelist.com www.theerlangelist.com/
end
```
During this test, the blog endpoint (i.e. the blog web server) will be restarted, with all previously existing certificates removed. During the restart, the endpoint will be certified via the local ACME server. This certification will go through the whole process, with no mocking (save for the fact that a local CA is used). HTTP requests will be made, some keys will be generated, the system will call CA, which will then concurrently make a request to the system, and ultimately the certificate will be obtained.
Once that's all finished, the invocation of `get_cert` will establish an ssl connection to the blog server and fetch the certificate of the peer. Then we can assert the expected properties of the certificate.
Having such tests significantly increases my confidence in the system. Of course, there's always a chance of something going wrong in production (e.g. if DNS isn't correctly configured, and Let's Encrypt can't reach my site), but the possibility of errors is reduced, not only because of the tests, but also because a compiled language is used. For example, if I make a syntax error while changing the configuration, the code won't even compile, let alone make it to production. If I make a typo, e.g. by specifying `theerlangelist.org` instead of `theerlangelist.com`, the certification test will fail. In contrast, external configurations are much harder to test, and so they typically end up being manually verified on staging, or in some cases only in production.
## More automation
Beyond just obtaining the certificate, site_encrypt will periodically renew it. A periodic job is executed three times a day. This job checks the expiry date of the certificate, and starts the renewal process if the certificate is about to expire in 30 days. In addition, every time a certificate is obtained, site_encrypt can optionally generate a backup of its data. When the system is starting, if the site_encrypt database folder isn't present and the backup file exists, site_encrypt will automatically restore the database from the backup.
As a user of site_encrypt you have to do zero work to make this happen, which significantly reduces the amount of operational work required, bringing the bulk of it to the regular development.
For more elaborate backup scenarios, site_encrypt provides a callback hook. In your endpoint module you can define the function which is invoked after the certificate is obtained. You can use this function to e.g. store the cert in an arbitrary secure storage of your choice. Notice how this becomes a part of the regular system codebase, which is the most convenient and logical place to express such task. The fact that this is running together with the rest of the system, also means it's testable. Testing that the new certificate is correctly stored to desired storage is straightforward.
## Tight integration
Since it runs in the same OS process, and is powered by the same language, site_encrypt can integrate much better with its client, which leads to some nice benefits. I mentioned earlier that certification is a conversation between our system and the CA server. Now, when we're using the certbot tool, this dialogue turns into a three-party conversation. Instead of our system asking for the certificate, we ask certbot to do this on our behalf. However, the CA verification request (aka challenge) needs to be served by our site. Now, since certbot is an external tool, it treats our site as an opaque box. As a result, certbot doesn't know when we responded to the CA challenge, and so it has to be a bit more conservative. Namely, certbot will sleep for about three seconds before it starts polling CA to see if the challenge has been answered.
The native Elixir ACME client runs in the same OS process, and so it can integrate much better. The ACME client is informed by the challenge handler that the challenge is fulfilled, and so it can use a much shorter delay to start polling the CA. In production this optimization isn't particularly relevant, but on local dev, and especially in tests the difference becomes significant. The certification test via certbot takes about 6 seconds on my machine. The same test via the native client is about 800ms.
This tight integration offers some other interesting possibilities. With a bit of changes to the API, site_encrypt could support arbitrary storage for its database. It could also support coordination between multiple nodes, making it possible to implement a distributed certification, where an arbitrary node in the cluster initiates the certification, while any other node can successfully respond to the challenge, including even the nodes which came online after the challenge has been started.
## Operations
With the bulk of the system behaviour described in Elixir code, the remaining operational tasks done outside of Elixir are exclusively related to preparing the machine to run the Erlangelist. These tasks involve creating necessary accounts, creating the folder structure, installing required OS packages (essentially just Docker is needed), and setting up a single systemd unit for starting the container.
The production is dockerized, but the production docker image is very lightweight:
```text
FROM alpine:3.11 as site
RUN apk --no-cache upgrade && apk add --no-cache ncurses
COPY --from=builder /opt/app/site/_build/prod/rel/erlangelist /erlangelist
VOLUME /erlangelist/lib/erlangelist-0.0.1/priv/db
VOLUME /erlangelist/lib/erlangelist-0.0.1/priv/backup
WORKDIR /erlangelist
ENTRYPOINT ["/erlangelist/bin/erlangelist"]
```
The key part is the `COPY` instruction which adds the built release of the system to the image. This release will contain all the compiled binaries, as well as a minimal Erlang runtime system, and is therefore pretty much self-contained, requiring only one small OS-level package to be installed.
## Final thoughts
Some might argue that using certbot with optionally Nginx or Caddy is simple enough, and I wouldn't completely disagree. It's perfectly valid to reach for external products to solve a technical challenge not related to the business domain. Such products can help us solve our problem quickly and focus on our core challenges. On the other hand, I feel that we should be more critical of the problems introduced by such products. As I've tried to show in this simple example, the integrated operations approach reduces the amount of moving parts and technologies used, bridges the gap between production and development, and improves the testability of the system. The implementation is simpler and at the same time more flexible, since the tool is driven by functions and data.
For this approach to work, you need a runtime that supports managing multiple system activities. BEAM, the runtime of Erlang and Elixir, makes this possible. For example, in many cases serving traffic directly with Phoenix, without having a reverse proxy in front of it, will work just fine. Features such as ETS tables or GenServer will reduce the need for tools like Redis. Running periodic jobs, regulating load, rate-limiting, pipeline processing, can all be done directly from Elixir, without requiring any external product.
Of course, there will always be cases where external tools will make more sense. But there will also be many cases where integrated approach will work just fine, especially in smaller systems not operating at the level of scale or complexity of Netflix, Twitter, Facebook, and similar. Having both options available would allow us to start with simple and move to an external tool only in more complicated scenarios.
This is the reason why I started the work on site_encrypt. The library is still incomplete and probably buggy, but these are issues that can be fixed with time and effort :-) I believe that the benefits of this approach are worth the effort, so I'll continue the work on the library. I'd like to see more of such libraries appearing, giving us simpler options for challenges such as load balancing, proxying, or persistence. As long as there are technical challenges where running an external product is the only option, there is opportunity for simplification, and it's up to us, the developers, to make that happen.
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Kubernetes Authors.
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 create
import (
"fmt"
"strings"
"github.com/spf13/cobra"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
cliflag "k8s.io/component-base/cli/flag"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
"k8s.io/kubernetes/pkg/kubectl/util/templates"
)
var (
clusterRoleLong = templates.LongDesc(i18n.T(`
Create a ClusterRole.`))
clusterRoleExample = templates.Examples(i18n.T(`
# Create a ClusterRole named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods
# Create a ClusterRole named "pod-reader" with ResourceName specified
kubectl create clusterrole pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod
# Create a ClusterRole named "foo" with API Group specified
kubectl create clusterrole foo --verb=get,list,watch --resource=rs.extensions
# Create a ClusterRole named "foo" with SubResource specified
kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status
# Create a ClusterRole name "foo" with NonResourceURL specified
kubectl create clusterrole "foo" --verb=get --non-resource-url=/logs/*
# Create a ClusterRole name "monitoring" with AggregationRule specified
kubectl create clusterrole monitoring --aggregation-rule="rbac.example.com/aggregate-to-monitoring=true"`))
// Valid nonResource verb list for validation.
validNonResourceVerbs = []string{"*", "get", "post", "put", "delete", "patch", "head", "options"}
)
// CreateClusterRoleOptions is returned by NewCmdCreateClusterRole
type CreateClusterRoleOptions struct {
*CreateRoleOptions
NonResourceURLs []string
AggregationRule map[string]string
}
// NewCmdCreateClusterRole initializes and returns new ClusterRoles command
func NewCmdCreateClusterRole(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
c := &CreateClusterRoleOptions{
CreateRoleOptions: NewCreateRoleOptions(ioStreams),
AggregationRule: map[string]string{},
}
cmd := &cobra.Command{
Use: "clusterrole NAME --verb=verb --resource=resource.group [--resource-name=resourcename] [--dry-run]",
DisableFlagsInUseLine: true,
Short: clusterRoleLong,
Long: clusterRoleLong,
Example: clusterRoleExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(c.Complete(f, cmd, args))
cmdutil.CheckErr(c.Validate())
cmdutil.CheckErr(c.RunCreateRole())
},
}
c.PrintFlags.AddFlags(cmd)
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddDryRunFlag(cmd)
cmd.Flags().StringSliceVar(&c.Verbs, "verb", c.Verbs, "Verb that applies to the resources contained in the rule")
cmd.Flags().StringSliceVar(&c.NonResourceURLs, "non-resource-url", c.NonResourceURLs, "A partial url that user should have access to.")
cmd.Flags().StringSlice("resource", []string{}, "Resource that the rule applies to")
cmd.Flags().StringArrayVar(&c.ResourceNames, "resource-name", c.ResourceNames, "Resource in the white list that the rule applies to, repeat this flag for multiple items")
cmd.Flags().Var(cliflag.NewMapStringString(&c.AggregationRule), "aggregation-rule", "An aggregation label selector for combining ClusterRoles.")
return cmd
}
// Complete completes all the required options
func (c *CreateClusterRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
// Remove duplicate nonResourceURLs
nonResourceURLs := []string{}
for _, n := range c.NonResourceURLs {
if !arrayContains(nonResourceURLs, n) {
nonResourceURLs = append(nonResourceURLs, n)
}
}
c.NonResourceURLs = nonResourceURLs
return c.CreateRoleOptions.Complete(f, cmd, args)
}
// Validate makes sure there is no discrepency in CreateClusterRoleOptions
func (c *CreateClusterRoleOptions) Validate() error {
if c.Name == "" {
return fmt.Errorf("name must be specified")
}
if len(c.AggregationRule) > 0 {
if len(c.NonResourceURLs) > 0 || len(c.Verbs) > 0 || len(c.Resources) > 0 || len(c.ResourceNames) > 0 {
return fmt.Errorf("aggregation rule must be specified without nonResourceURLs, verbs, resources or resourceNames")
}
return nil
}
// validate verbs.
if len(c.Verbs) == 0 {
return fmt.Errorf("at least one verb must be specified")
}
if len(c.Resources) == 0 && len(c.NonResourceURLs) == 0 {
return fmt.Errorf("one of resource or nonResourceURL must be specified")
}
// validate resources
if len(c.Resources) > 0 {
for _, v := range c.Verbs {
if !arrayContains(validResourceVerbs, v) {
return fmt.Errorf("invalid verb: '%s'", v)
}
}
if err := c.validateResource(); err != nil {
return err
}
}
//validate non-resource-url
if len(c.NonResourceURLs) > 0 {
for _, v := range c.Verbs {
if !arrayContains(validNonResourceVerbs, v) {
return fmt.Errorf("invalid verb: '%s' for nonResourceURL", v)
}
}
for _, nonResourceURL := range c.NonResourceURLs {
if nonResourceURL == "*" {
continue
}
if nonResourceURL == "" || !strings.HasPrefix(nonResourceURL, "/") {
return fmt.Errorf("nonResourceURL should start with /")
}
if strings.ContainsRune(nonResourceURL[:len(nonResourceURL)-1], '*') {
return fmt.Errorf("nonResourceURL only supports wildcard matches when '*' is at the end")
}
}
}
return nil
}
// RunCreateRole creates a new clusterRole
func (c *CreateClusterRoleOptions) RunCreateRole() error {
clusterRole := &rbacv1.ClusterRole{
// this is ok because we know exactly how we want to be serialized
TypeMeta: metav1.TypeMeta{APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: "ClusterRole"},
}
clusterRole.Name = c.Name
var err error
if len(c.AggregationRule) == 0 {
rules, err := generateResourcePolicyRules(c.Mapper, c.Verbs, c.Resources, c.ResourceNames, c.NonResourceURLs)
if err != nil {
return err
}
clusterRole.Rules = rules
} else {
clusterRole.AggregationRule = &rbacv1.AggregationRule{
ClusterRoleSelectors: []metav1.LabelSelector{
{
MatchLabels: c.AggregationRule,
},
},
}
}
// Create ClusterRole.
if !c.DryRun {
clusterRole, err = c.Client.ClusterRoles().Create(clusterRole)
if err != nil {
return err
}
}
return c.PrintObj(clusterRole)
}
| {
"pile_set_name": "Github"
} |
spring.application.name=spring-boot-configuration
# random value
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[10,100]}
# property value
my.config.app=${spring.application.name}
my.config.user=happyxiaofan
my.config.age=24
[email protected]
my.config.blog=http://blog.csdn.net/u011116672
my.config.github=https://github.com/happyxiaofan/spring-boot-learning-examples
| {
"pile_set_name": "Github"
} |
From 8941017bc0226b60ce306d5271df15820ce66a53 Mon Sep 17 00:00:00 2001
From: Alan Modra <[email protected]>
Date: Tue, 30 Aug 2016 20:57:32 +0930
Subject: [PATCH] ppc apuinfo for spe parsed incorrectly
apuinfo saying SPE resulted in mach = bfd_mach_ppc_vle due to a
missing break.
PR 20531
* elf32-ppc.c (_bfd_elf_ppc_set_arch): Add missing "break".
---
bfd/elf32-ppc.c | 1 +
1 file changed, 1 insertion(+)
--- a/bfd/elf32-ppc.c
+++ b/bfd/elf32-ppc.c
@@ -2246,6 +2246,7 @@
case PPC_APUINFO_BRLOCK:
if (mach != bfd_mach_ppc_vle)
mach = bfd_mach_ppc_e500;
+ break;
case PPC_APUINFO_VLE:
mach = bfd_mach_ppc_vle;
| {
"pile_set_name": "Github"
} |
#include "a_lightning.h"
#include "doomstat.h"
#include "p_lnspec.h"
#include "statnums.h"
#include "m_random.h"
#include "templates.h"
#include "s_sound.h"
#include "p_acs.h"
#include "r_sky.h"
#include "g_level.h"
#include "r_state.h"
#include "serializer.h"
static FRandom pr_lightning ("Lightning");
IMPLEMENT_CLASS(DLightningThinker, false, false)
DLightningThinker::DLightningThinker ()
: DThinker (STAT_LIGHTNING)
{
Stopped = false;
LightningFlashCount = 0;
NextLightningFlash = ((pr_lightning()&15)+5)*35; // don't flash at level start
LightningLightLevels.Resize(numsectors);
fillshort(&LightningLightLevels[0], numsectors, SHRT_MAX);
}
DLightningThinker::~DLightningThinker ()
{
}
void DLightningThinker::Serialize(FSerializer &arc)
{
Super::Serialize (arc);
arc("stopped", Stopped)
("next", NextLightningFlash)
("count", LightningFlashCount)
("levels", LightningLightLevels);
}
void DLightningThinker::Tick ()
{
if (!NextLightningFlash || LightningFlashCount)
{
LightningFlash();
}
else
{
--NextLightningFlash;
if (Stopped) Destroy();
}
}
void DLightningThinker::LightningFlash ()
{
int i, j;
sector_t *tempSec;
BYTE flashLight;
if (LightningFlashCount)
{
LightningFlashCount--;
if (LightningFlashCount)
{ // reduce the brightness of the flash
tempSec = sectors;
for (i = numsectors, j = 0; i > 0; ++j, --i, ++tempSec)
{
// [RH] Checking this sector's applicability to lightning now
// is not enough to know if we should lower its light level,
// because it might have changed since the lightning flashed.
// Instead, change the light if this sector was effected by
// the last flash.
if (LightningLightLevels[j] < tempSec->lightlevel-4)
{
tempSec->ChangeLightLevel(-4);
}
}
}
else
{ // remove the alternate lightning flash special
tempSec = sectors;
for (i = numsectors, j = 0; i > 0; ++j, --i, ++tempSec)
{
if (LightningLightLevels[j] != SHRT_MAX)
{
tempSec->SetLightLevel(LightningLightLevels[j]);
}
}
fillshort(&LightningLightLevels[0], numsectors, SHRT_MAX);
level.flags &= ~LEVEL_SWAPSKIES;
}
return;
}
LightningFlashCount = (pr_lightning()&7)+8;
flashLight = 200+(pr_lightning()&31);
tempSec = sectors;
for (i = numsectors, j = 0; i > 0; --i, ++j, ++tempSec)
{
// allow combination of the lightning sector specials with bit masks
int special = tempSec->special;
if (tempSec->GetTexture(sector_t::ceiling) == skyflatnum
|| special == Light_IndoorLightning1
|| special == Light_IndoorLightning2
|| special == Light_OutdoorLightning)
{
LightningLightLevels[j] = tempSec->lightlevel;
if (special == Light_IndoorLightning1)
{
tempSec->SetLightLevel(MIN<int> (tempSec->lightlevel+64, flashLight));
}
else if (special == Light_IndoorLightning2)
{
tempSec->SetLightLevel(MIN<int> (tempSec->lightlevel+32, flashLight));
}
else
{
tempSec->SetLightLevel(flashLight);
}
if (tempSec->lightlevel < LightningLightLevels[j])
{ // The lightning is darker than this sector already is, so no lightning here.
tempSec->SetLightLevel(LightningLightLevels[j]);
LightningLightLevels[j] = SHRT_MAX;
}
}
}
level.flags |= LEVEL_SWAPSKIES; // set alternate sky
S_Sound (CHAN_AUTO, "world/thunder", 1.0, ATTN_NONE);
FBehavior::StaticStartTypedScripts (SCRIPT_Lightning, NULL, false); // [RH] Run lightning scripts
// Calculate the next lighting flash
if (!NextLightningFlash)
{
if (pr_lightning() < 50)
{ // Immediate Quick flash
NextLightningFlash = (pr_lightning()&15)+16;
}
else
{
if (pr_lightning() < 128 && !(level.time&32))
{
NextLightningFlash = ((pr_lightning()&7)+2)*35;
}
else
{
NextLightningFlash = ((pr_lightning()&15)+5)*35;
}
}
}
}
void DLightningThinker::ForceLightning (int mode)
{
switch (mode)
{
default:
NextLightningFlash = 0;
break;
case 1:
NextLightningFlash = 0;
// Fall through
case 2:
Stopped = true;
break;
}
}
static DLightningThinker *LocateLightning ()
{
TThinkerIterator<DLightningThinker> iterator (STAT_LIGHTNING);
return iterator.Next ();
}
void P_StartLightning ()
{
DLightningThinker *lightning = LocateLightning ();
if (lightning == NULL)
{
new DLightningThinker ();
}
}
void P_ForceLightning (int mode)
{
DLightningThinker *lightning = LocateLightning ();
if (lightning == NULL)
{
lightning = new DLightningThinker ();
}
if (lightning != NULL)
{
lightning->ForceLightning (mode);
}
}
| {
"pile_set_name": "Github"
} |
- SVG 指可伸缩矢量图形 (Scalable Vector Graphics)
- SVG 用来定义用于网络的基于矢量的图形
- SVG 使用 XML 格式定义图形
- SVG 图像在放大或改变尺寸的情况下其图形质量不会有所损失
- SVG 是万维网联盟的标准
- SVG 与诸如 DOM 和 XSL 之类的 W3C 标准是一个整体
- line 直线
- polyline:折线
- rect:矩形
- circle:圆形
- ellipse:椭圆形
- polygon:多边形 | {
"pile_set_name": "Github"
} |
glabel func_80B45EF0
/* 01EA0 80B45EF0 27BDFFC8 */ addiu $sp, $sp, 0xFFC8 ## $sp = FFFFFFC8
/* 01EA4 80B45EF4 AFBF002C */ sw $ra, 0x002C($sp)
/* 01EA8 80B45EF8 AFB00028 */ sw $s0, 0x0028($sp)
/* 01EAC 80B45EFC AFA5003C */ sw $a1, 0x003C($sp)
/* 01EB0 80B45F00 8C8E03F0 */ lw $t6, 0x03F0($a0) ## 000003F0
/* 01EB4 80B45F04 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 01EB8 80B45F08 51C0000E */ beql $t6, $zero, .L80B45F44
/* 01EBC 80B45F0C 2604014C */ addiu $a0, $s0, 0x014C ## $a0 = 0000014C
/* 01EC0 80B45F10 C4800080 */ lwc1 $f0, 0x0080($a0) ## 000001CC
/* 01EC4 80B45F14 C4840028 */ lwc1 $f4, 0x0028($a0) ## 00000174
/* 01EC8 80B45F18 4600203E */ c.le.s $f4, $f0
/* 01ECC 80B45F1C 00000000 */ nop
/* 01ED0 80B45F20 45020008 */ bc1fl .L80B45F44
/* 01ED4 80B45F24 2604014C */ addiu $a0, $s0, 0x014C ## $a0 = 0000014C
/* 01ED8 80B45F28 44803000 */ mtc1 $zero, $f6 ## $f6 = 0.00
/* 01EDC 80B45F2C 44804000 */ mtc1 $zero, $f8 ## $f8 = 0.00
/* 01EE0 80B45F30 E4800028 */ swc1 $f0, 0x0028($a0) ## 00000174
/* 01EE4 80B45F34 AC8003E4 */ sw $zero, 0x03E4($a0) ## 00000530
/* 01EE8 80B45F38 E4860060 */ swc1 $f6, 0x0060($a0) ## 000001AC
/* 01EEC 80B45F3C E4880068 */ swc1 $f8, 0x0068($a0) ## 000001B4
/* 01EF0 80B45F40 2604014C */ addiu $a0, $s0, 0x014C ## $a0 = 0000014C
.L80B45F44:
/* 01EF4 80B45F44 0C02927F */ jal SkelAnime_FrameUpdateMatrix
/* 01EF8 80B45F48 AFA40034 */ sw $a0, 0x0034($sp)
/* 01EFC 80B45F4C 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00
/* 01F00 80B45F50 1040001C */ beq $v0, $zero, .L80B45FC4
/* 01F04 80B45F54 8FA40034 */ lw $a0, 0x0034($sp)
/* 01F08 80B45F58 8E0F03F0 */ lw $t7, 0x03F0($s0) ## 000003F0
/* 01F0C 80B45F5C 3C050601 */ lui $a1, 0x0601 ## $a1 = 06010000
/* 01F10 80B45F60 24A58C6C */ addiu $a1, $a1, 0x8C6C ## $a1 = 06008C6C
/* 01F14 80B45F64 15E00012 */ bne $t7, $zero, .L80B45FB0
/* 01F18 80B45F68 3C064040 */ lui $a2, 0x4040 ## $a2 = 40400000
/* 01F1C 80B45F6C 3C014188 */ lui $at, 0x4188 ## $at = 41880000
/* 01F20 80B45F70 44815000 */ mtc1 $at, $f10 ## $f10 = 17.00
/* 01F24 80B45F74 3C01C040 */ lui $at, 0xC040 ## $at = C0400000
/* 01F28 80B45F78 44818000 */ mtc1 $at, $f16 ## $f16 = -3.00
/* 01F2C 80B45F7C 44070000 */ mfc1 $a3, $f0
/* 01F30 80B45F80 24180002 */ addiu $t8, $zero, 0x0002 ## $t8 = 00000002
/* 01F34 80B45F84 AFB80014 */ sw $t8, 0x0014($sp)
/* 01F38 80B45F88 E7AA0010 */ swc1 $f10, 0x0010($sp)
/* 01F3C 80B45F8C 0C029468 */ jal SkelAnime_ChangeAnim
/* 01F40 80B45F90 E7B00018 */ swc1 $f16, 0x0018($sp)
/* 01F44 80B45F94 2419000A */ addiu $t9, $zero, 0x000A ## $t9 = 0000000A
/* 01F48 80B45F98 AE1903F0 */ sw $t9, 0x03F0($s0) ## 000003F0
/* 01F4C 80B45F9C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 01F50 80B45FA0 0C00BE0A */ jal Audio_PlayActorSound2
/* 01F54 80B45FA4 2405382F */ addiu $a1, $zero, 0x382F ## $a1 = 0000382F
/* 01F58 80B45FA8 10000007 */ beq $zero, $zero, .L80B45FC8
/* 01F5C 80B45FAC 8FA8003C */ lw $t0, 0x003C($sp)
.L80B45FB0:
/* 01F60 80B45FB0 E6000068 */ swc1 $f0, 0x0068($s0) ## 00000068
/* 01F64 80B45FB4 AE0003E4 */ sw $zero, 0x03E4($s0) ## 000003E4
/* 01F68 80B45FB8 8FA5003C */ lw $a1, 0x003C($sp)
/* 01F6C 80B45FBC 0C2D15AD */ jal func_80B456B4
/* 01F70 80B45FC0 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
.L80B45FC4:
/* 01F74 80B45FC4 8FA8003C */ lw $t0, 0x003C($sp)
.L80B45FC8:
/* 01F78 80B45FC8 3C090001 */ lui $t1, 0x0001 ## $t1 = 00010000
/* 01F7C 80B45FCC 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 01F80 80B45FD0 01284821 */ addu $t1, $t1, $t0
/* 01F84 80B45FD4 8D291DE4 */ lw $t1, 0x1DE4($t1) ## 00011DE4
/* 01F88 80B45FD8 312A005F */ andi $t2, $t1, 0x005F ## $t2 = 00000000
/* 01F8C 80B45FDC 55400004 */ bnel $t2, $zero, .L80B45FF0
/* 01F90 80B45FE0 860B001C */ lh $t3, 0x001C($s0) ## 0000001C
/* 01F94 80B45FE4 0C00BE0A */ jal Audio_PlayActorSound2
/* 01F98 80B45FE8 24053829 */ addiu $a1, $zero, 0x3829 ## $a1 = 00003829
/* 01F9C 80B45FEC 860B001C */ lh $t3, 0x001C($s0) ## 0000001C
.L80B45FF0:
/* 01FA0 80B45FF0 2401FFFE */ addiu $at, $zero, 0xFFFE ## $at = FFFFFFFE
/* 01FA4 80B45FF4 55610011 */ bnel $t3, $at, .L80B4603C
/* 01FA8 80B45FF8 8FBF002C */ lw $ra, 0x002C($sp)
/* 01FAC 80B45FFC 960C0088 */ lhu $t4, 0x0088($s0) ## 00000088
/* 01FB0 80B46000 8FA4003C */ lw $a0, 0x003C($sp)
/* 01FB4 80B46004 318D0003 */ andi $t5, $t4, 0x0003 ## $t5 = 00000000
/* 01FB8 80B46008 51A0000C */ beql $t5, $zero, .L80B4603C
/* 01FBC 80B4600C 8FBF002C */ lw $ra, 0x002C($sp)
/* 01FC0 80B46010 0C2D133C */ jal func_80B44CF0
/* 01FC4 80B46014 02002825 */ or $a1, $s0, $zero ## $a1 = 00000000
/* 01FC8 80B46018 10400005 */ beq $v0, $zero, .L80B46030
/* 01FCC 80B4601C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 01FD0 80B46020 0C2D1A89 */ jal func_80B46A24
/* 01FD4 80B46024 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 01FD8 80B46028 10000004 */ beq $zero, $zero, .L80B4603C
/* 01FDC 80B4602C 8FBF002C */ lw $ra, 0x002C($sp)
.L80B46030:
/* 01FE0 80B46030 0C2D20F9 */ jal func_80B483E4
/* 01FE4 80B46034 8FA5003C */ lw $a1, 0x003C($sp)
/* 01FE8 80B46038 8FBF002C */ lw $ra, 0x002C($sp)
.L80B4603C:
/* 01FEC 80B4603C 8FB00028 */ lw $s0, 0x0028($sp)
/* 01FF0 80B46040 27BD0038 */ addiu $sp, $sp, 0x0038 ## $sp = 00000000
/* 01FF4 80B46044 03E00008 */ jr $ra
/* 01FF8 80B46048 00000000 */ nop
| {
"pile_set_name": "Github"
} |
This file includes highlights of the changes made in the OpenOCD
source archive release.
JTAG Layer:
Boundary Scan:
Target Layer:
Flash Layer:
Board, Target, and Interface Configuration Scripts:
Server Layer:
Documentation:
Build and Release:
This release also contains a number of other important functional and
cosmetic bugfixes. For more details about what has changed since the
last release, see the git repository history:
http://sourceforge.net/p/openocd/code/ci/v0.x.0/log/?path=
For older NEWS, see the NEWS files associated with each release
(i.e. NEWS-<version>).
For more information about contributing test reports, bug fixes, or new
features and device support, please read the new Developer Manual (or
the BUGS and PATCHES.txt files in the source archive).
| {
"pile_set_name": "Github"
} |
path: "tensorflow.layers.Conv3D"
tf_class {
is_instance: "<class \'tensorflow.python.layers.convolutional.Conv3D\'>"
is_instance: "<class \'tensorflow.python.layers.convolutional._Conv\'>"
is_instance: "<class \'tensorflow.python.layers.base.Layer\'>"
is_instance: "<type \'object\'>"
member {
name: "activity_regularizer"
mtype: "<type \'property\'>"
}
member {
name: "dtype"
mtype: "<type \'property\'>"
}
member {
name: "graph"
mtype: "<type \'property\'>"
}
member {
name: "inbound_nodes"
mtype: "<type \'property\'>"
}
member {
name: "input"
mtype: "<type \'property\'>"
}
member {
name: "input_shape"
mtype: "<type \'property\'>"
}
member {
name: "losses"
mtype: "<type \'property\'>"
}
member {
name: "name"
mtype: "<type \'property\'>"
}
member {
name: "non_trainable_variables"
mtype: "<type \'property\'>"
}
member {
name: "non_trainable_weights"
mtype: "<type \'property\'>"
}
member {
name: "outbound_nodes"
mtype: "<type \'property\'>"
}
member {
name: "output"
mtype: "<type \'property\'>"
}
member {
name: "output_shape"
mtype: "<type \'property\'>"
}
member {
name: "scope_name"
mtype: "<type \'property\'>"
}
member {
name: "trainable_variables"
mtype: "<type \'property\'>"
}
member {
name: "trainable_weights"
mtype: "<type \'property\'>"
}
member {
name: "updates"
mtype: "<type \'property\'>"
}
member {
name: "variables"
mtype: "<type \'property\'>"
}
member {
name: "weights"
mtype: "<type \'property\'>"
}
member_method {
name: "__init__"
argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'dilation_rate\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\', \'trainable\', \'name\'], varargs=None, keywords=kwargs, defaults=[\'(1, 1, 1)\', \'valid\', \'channels_last\', \'(1, 1, 1)\', \'None\', \'True\', \'None\', \'<tensorflow.python.ops.init_ops.Zeros object instance>\', \'None\', \'None\', \'None\', \'None\', \'None\', \'True\', \'None\'], "
}
member_method {
name: "add_loss"
argspec: "args=[\'self\', \'losses\', \'inputs\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "add_update"
argspec: "args=[\'self\', \'updates\', \'inputs\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "add_variable"
argspec: "args=[\'self\', \'name\', \'shape\', \'dtype\', \'initializer\', \'regularizer\', \'trainable\', \'constraint\', \'partitioner\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'True\', \'None\', \'None\'], "
}
member_method {
name: "apply"
argspec: "args=[\'self\', \'inputs\'], varargs=args, keywords=kwargs, defaults=None"
}
member_method {
name: "build"
argspec: "args=[\'self\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "compute_output_shape"
argspec: "args=[\'self\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "count_params"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_input_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_input_shape_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_losses_for"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_output_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_output_shape_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_updates_for"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
}
}
| {
"pile_set_name": "Github"
} |
// +build !amd64
package cuckoo
import (
"math/bits"
"unsafe"
)
const (
x7F = uint64(0x7F7F7F7F7F7F7F7F)
x80 = uint64(0x8080808080808080)
)
func CountNonzeroBytes(buf []byte) (count uint) {
l := len(buf) - len(buf)%8
for _, v := range buf[l:] {
if v != 0 {
count++
}
}
bin := (*[1 << 20]uint64)(unsafe.Pointer(&buf[0]))[: l/8 : l/8]
for _, w := range bin {
w = (w & x80) | (((w & x7F) + x7F) & x80)
count += uint(bits.OnesCount64(w))
}
return count
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- generated on Fri Apr 17 08:19:47 2020 by Eclipse SUMO Version v1_5_0+1182-c674b91ce6
This data file and the accompanying materials
are made available under the terms of the Eclipse Public License v2.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v20.html
SPDX-License-Identifier: EPL-2.0
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/sumoConfiguration.xsd">
<input>
<net-file value="net.net.xml"/>
<route-files value="input_routes.rou.xml"/>
</input>
<output>
<write-license value="true"/>
<fcd-output value="fcd.xml"/>
<tripinfo-output value="tripinfos.xml"/>
</output>
<processing>
<step-method.ballistic value="true"/>
<lateral-resolution value="0.4"/>
<default.speeddev value="0"/>
</processing>
<report>
<xml-validation value="never"/>
<no-step-log value="true"/>
</report>
</configuration>
-->
<fcd-export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/fcd_file.xsd">
<timestep time="0.00">
<vehicle id="A" x="0.00" y="-6.00" angle="90.00" type="t0" speed="13.89" pos="0.00" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="0.00" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="0.00" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="1.00">
<vehicle id="A" x="13.89" y="-6.00" angle="90.00" type="t0" speed="13.89" pos="13.89" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="13.89" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="13.89" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="2.00">
<vehicle id="A" x="26.81" y="-6.00" angle="90.00" type="t0" speed="11.95" pos="26.81" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="27.78" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="27.78" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="3.00">
<vehicle id="A" x="37.78" y="-6.00" angle="90.00" type="t0" speed="10.00" pos="37.78" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="41.67" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="41.67" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="4.00">
<vehicle id="A" x="46.81" y="-5.00" angle="85.62" type="t0" speed="8.06" pos="46.81" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="55.56" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="55.56" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="5.00">
<vehicle id="A" x="55.44" y="-4.00" angle="85.97" type="t0" speed="9.20" pos="55.44" lane="beg_0" slope="0.00"/>
<vehicle id="B" x="69.45" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="69.45" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="6.00">
<vehicle id="A" x="65.29" y="-3.10" angle="86.68" type="t0" speed="10.52" pos="65.29" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="83.34" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="83.34" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="7.00">
<vehicle id="A" x="77.11" y="-2.10" angle="86.84" type="t0" speed="13.12" pos="77.11" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="97.23" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="97.23" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="8.00">
<vehicle id="A" x="90.49" y="-2.00" angle="89.69" type="t0" speed="13.64" pos="90.49" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="111.12" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="111.12" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="9.00">
<vehicle id="A" x="104.17" y="-2.00" angle="90.00" type="t0" speed="13.71" pos="104.17" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="125.01" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="125.01" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="10.00">
<vehicle id="A" x="117.90" y="-2.00" angle="90.00" type="t0" speed="13.76" pos="117.90" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="138.90" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="138.90" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="11.00">
<vehicle id="A" x="131.68" y="-2.00" angle="90.00" type="t0" speed="13.80" pos="131.68" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="152.79" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="152.79" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="12.00">
<vehicle id="A" x="145.49" y="-2.00" angle="90.00" type="t0" speed="13.82" pos="145.49" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="166.68" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="166.68" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="13.00">
<vehicle id="A" x="159.33" y="-2.00" angle="90.00" type="t0" speed="13.84" pos="159.33" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="180.57" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="180.57" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="14.00">
<vehicle id="A" x="173.18" y="-2.00" angle="90.00" type="t0" speed="13.86" pos="173.18" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="194.46" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="194.46" lane="beg_1" slope="0.00"/>
</timestep>
<timestep time="15.00">
<vehicle id="A" x="187.04" y="-2.00" angle="90.00" type="t0" speed="13.87" pos="187.04" lane="beg_1" slope="0.00"/>
<vehicle id="B" x="208.35" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="4.35" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="16.00">
<vehicle id="A" x="200.90" y="-2.00" angle="90.00" type="t0" speed="13.87" pos="4.90" lane=":gneJ1_0_0" slope="0.00"/>
<vehicle id="B" x="222.24" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="18.24" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="17.00">
<vehicle id="A" x="214.78" y="-2.00" angle="90.00" type="t0" speed="13.88" pos="10.78" lane="end_0" slope="0.00"/>
<vehicle id="B" x="236.13" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="32.13" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="18.00">
<vehicle id="A" x="228.66" y="-2.00" angle="90.00" type="t0" speed="13.88" pos="24.66" lane="end_0" slope="0.00"/>
<vehicle id="B" x="250.02" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="46.02" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="19.00">
<vehicle id="A" x="242.54" y="-2.00" angle="90.00" type="t0" speed="13.88" pos="38.54" lane="end_0" slope="0.00"/>
<vehicle id="B" x="263.91" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="59.91" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="20.00">
<vehicle id="A" x="256.42" y="-2.00" angle="90.00" type="t0" speed="13.89" pos="52.42" lane="end_0" slope="0.00"/>
<vehicle id="B" x="277.80" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="73.80" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="21.00">
<vehicle id="A" x="270.31" y="-2.00" angle="90.00" type="t0" speed="13.89" pos="66.31" lane="end_0" slope="0.00"/>
<vehicle id="B" x="291.69" y="-2.00" angle="90.00" type="t1" speed="13.89" pos="87.69" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="22.00">
<vehicle id="A" x="284.20" y="-2.00" angle="90.00" type="t0" speed="13.89" pos="80.20" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="23.00">
<vehicle id="A" x="298.09" y="-2.00" angle="90.00" type="t0" speed="13.89" pos="94.09" lane="end_0" slope="0.00"/>
</timestep>
<timestep time="24.00"/>
</fcd-export>
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1beta1
// CustomResourceDefinitionListerExpansion allows custom methods to be added to
// CustomResourceDefinitionLister.
type CustomResourceDefinitionListerExpansion interface{}
| {
"pile_set_name": "Github"
} |
/*!
\file SiStripLatency_PayloadInspector
\Payload Inspector Plugin for SiStrip Latency
\author Jessica Prisciandaro
\version $Revision: 1.0 $
\date $Date: 2018/05/22 17:59:56 $
*/
#include "CondCore/Utilities/interface/PayloadInspectorModule.h"
#include "CondCore/Utilities/interface/PayloadInspector.h"
#include "CondCore/CondDB/interface/Time.h"
// the data format of the condition to be inspected
#include "CondFormats/SiStripObjects/interface/SiStripLatency.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/SiStripDetId/interface/StripSubdetector.h"
#include "CondFormats/SiStripObjects/interface/SiStripDetSummary.h"
// needed for the tracker map
#include "CommonTools/TrackerMap/interface/TrackerMap.h"
// auxilliary functions
#include "CondCore/SiStripPlugins/interface/SiStripPayloadInspectorHelper.h"
#include "CalibTracker/StandaloneTrackerTopology/interface/StandaloneTrackerTopology.h"
#include <memory>
#include <sstream>
#include <iostream>
// include ROOT
#include "TProfile.h"
#include "TH2F.h"
#include "TLegend.h"
#include "TCanvas.h"
#include "TLine.h"
#include "TStyle.h"
#include "TLatex.h"
#include "TPave.h"
#include "TPaveStats.h"
namespace {
/************************************************
*************** test class ******************
*************************************************/
class SiStripLatencyTest : public cond::payloadInspector::Histogram1D<SiStripLatency> {
public:
SiStripLatencyTest()
: cond::payloadInspector::Histogram1D<SiStripLatency>(
"SiStripLatency values", "SiStripLatency values", 5, 0.0, 5.0) {
Base::setSingleIov(true);
}
bool fill() override {
auto tag = PlotBase::getTag<0>();
for (auto const& iov : tag.iovs) {
std::shared_ptr<SiStripLatency> payload = Base::fetchPayload(std::get<1>(iov));
if (payload.get()) {
std::vector<SiStripLatency::Latency> lat = payload->allLatencyAndModes();
fillWithValue(lat.size());
}
}
return true;
} // fill
};
/***********************************************
// 1d histogram of mode of 1 IOV
************************************************/
class SiStripLatencyMode : public cond::payloadInspector::Histogram1D<SiStripLatency> {
public:
SiStripLatencyMode()
: cond::payloadInspector::Histogram1D<SiStripLatency>(
"SiStripLatency mode", "SiStripLatency mode", 70, -10, 60) {
Base::setSingleIov(true);
}
bool fill() override {
auto tag = PlotBase::getTag<0>();
for (auto const& iov : tag.iovs) {
std::shared_ptr<SiStripLatency> payload = Base::fetchPayload(std::get<1>(iov));
if (payload.get()) {
std::vector<uint16_t> modes;
payload->allModes(modes);
for (const auto& mode : modes) {
if (mode != 0)
fillWithValue(mode);
else
fillWithValue(-1);
}
}
}
return true;
}
};
/****************************************************************************
*******************1D histo of mode as a function of the run****************
*****************************************************************************/
class SiStripLatencyModeHistory : public cond::payloadInspector::HistoryPlot<SiStripLatency, uint16_t> {
public:
SiStripLatencyModeHistory()
: cond::payloadInspector::HistoryPlot<SiStripLatency, uint16_t>("Mode vs run number", "Mode vs run number") {}
uint16_t getFromPayload(SiStripLatency& payload) override {
uint16_t singlemode = payload.singleMode();
return singlemode;
}
};
/****************************************************************************
*****************number of modes per run *************************************
**************************************************************************/
class SiStripLatencyNumbOfModeHistory : public cond::payloadInspector::HistoryPlot<SiStripLatency, int> {
public:
SiStripLatencyNumbOfModeHistory()
: cond::payloadInspector::HistoryPlot<SiStripLatency, int>("Number of modes vs run ",
"Number of modes vs run") {}
int getFromPayload(SiStripLatency& payload) override {
std::vector<uint16_t> modes;
payload.allModes(modes);
return modes.size();
}
};
} // namespace
// Register the classes as boost python plugin
PAYLOAD_INSPECTOR_MODULE(SiStripLatency) {
PAYLOAD_INSPECTOR_CLASS(SiStripLatencyTest);
PAYLOAD_INSPECTOR_CLASS(SiStripLatencyMode);
PAYLOAD_INSPECTOR_CLASS(SiStripLatencyModeHistory);
PAYLOAD_INSPECTOR_CLASS(SiStripLatencyNumbOfModeHistory);
}
| {
"pile_set_name": "Github"
} |
<flash_profiles>
<flash_profile version="1.0" name="Default" current="true">
<PublishFormatProperties enabled="true">
<defaultNames>1</defaultNames>
<flash>1</flash>
<projectorWin>0</projectorWin>
<projectorMac>0</projectorMac>
<html>0</html>
<gif>0</gif>
<jpeg>0</jpeg>
<png>0</png>
<qt>0</qt>
<rnwk>0</rnwk>
<swc>0</swc>
<flashDefaultName>1</flashDefaultName>
<projectorWinDefaultName>1</projectorWinDefaultName>
<projectorMacDefaultName>1</projectorMacDefaultName>
<htmlDefaultName>1</htmlDefaultName>
<gifDefaultName>1</gifDefaultName>
<jpegDefaultName>1</jpegDefaultName>
<pngDefaultName>1</pngDefaultName>
<qtDefaultName>1</qtDefaultName>
<rnwkDefaultName>1</rnwkDefaultName>
<swcDefaultName>1</swcDefaultName>
<flashFileName>squaredance.swf</flashFileName>
<projectorWinFileName>squaredance.exe</projectorWinFileName>
<projectorMacFileName>squaredance.app</projectorMacFileName>
<htmlFileName>squaredance.html</htmlFileName>
<gifFileName>squaredance.gif</gifFileName>
<jpegFileName>squaredance.jpg</jpegFileName>
<pngFileName>squaredance.png</pngFileName>
<qtFileName>squaredance.mov</qtFileName>
<rnwkFileName>squaredance.smil</rnwkFileName>
<swcFileName>squaredance.swc</swcFileName>
</PublishFormatProperties>
<PublishHtmlProperties enabled="true">
<VersionDetectionIfAvailable>0</VersionDetectionIfAvailable>
<VersionInfo>10,2,153,0;10,1,52,0;9,0,124,0;8,0,24,0;7,0,14,0;6,0,79,0;5,0,58,0;4,0,32,0;3,0,8,0;2,0,1,12;1,0,0,1;</VersionInfo>
<UsingDefaultContentFilename>1</UsingDefaultContentFilename>
<UsingDefaultAlternateFilename>1</UsingDefaultAlternateFilename>
<ContentFilename>squaredance.xfl_content.html</ContentFilename>
<AlternateFilename>squaredance.xfl_alternate.html</AlternateFilename>
<UsingOwnAlternateFile>0</UsingOwnAlternateFile>
<OwnAlternateFilename></OwnAlternateFilename>
<Width>550</Width>
<Height>400</Height>
<Align>0</Align>
<Units>0</Units>
<Loop>1</Loop>
<StartPaused>0</StartPaused>
<Scale>0</Scale>
<HorizontalAlignment>1</HorizontalAlignment>
<VerticalAlignment>1</VerticalAlignment>
<Quality>4</Quality>
<DeblockingFilter>0</DeblockingFilter>
<WindowMode>0</WindowMode>
<DisplayMenu>1</DisplayMenu>
<DeviceFont>0</DeviceFont>
<TemplateFileName>/Users/charlie/Library/Application Support/Adobe/Flash CS5.5/en_US/Configuration/HTML/Default.html</TemplateFileName>
<showTagWarnMsg>1</showTagWarnMsg>
</PublishHtmlProperties>
<PublishFlashProperties enabled="true">
<TopDown></TopDown>
<FireFox></FireFox>
<Report>0</Report>
<Protect>0</Protect>
<OmitTraceActions>0</OmitTraceActions>
<Quality>80</Quality>
<DeblockingFilter>0</DeblockingFilter>
<StreamFormat>0</StreamFormat>
<StreamCompress>7</StreamCompress>
<EventFormat>0</EventFormat>
<EventCompress>7</EventCompress>
<OverrideSounds>0</OverrideSounds>
<Version>11</Version>
<ExternalPlayer>FlashPlayer10.2</ExternalPlayer>
<ActionScriptVersion>3</ActionScriptVersion>
<PackageExportFrame>1</PackageExportFrame>
<PackagePaths></PackagePaths>
<AS3PackagePaths>.</AS3PackagePaths>
<AS3ConfigConst>CONFIG::FLASH_AUTHORING="true";</AS3ConfigConst>
<DebuggingPermitted>0</DebuggingPermitted>
<DebuggingPassword></DebuggingPassword>
<CompressMovie>1</CompressMovie>
<InvisibleLayer>1</InvisibleLayer>
<DeviceSound>0</DeviceSound>
<StreamUse8kSampleRate>0</StreamUse8kSampleRate>
<EventUse8kSampleRate>0</EventUse8kSampleRate>
<UseNetwork>0</UseNetwork>
<DocumentClass></DocumentClass>
<AS3Strict>2</AS3Strict>
<AS3Coach>4</AS3Coach>
<AS3AutoDeclare>4096</AS3AutoDeclare>
<AS3Dialect>AS3</AS3Dialect>
<AS3ExportFrame>1</AS3ExportFrame>
<AS3Optimize>1</AS3Optimize>
<ExportSwc>0</ExportSwc>
<ScriptStuckDelay>15</ScriptStuckDelay>
<IncludeXMP>1</IncludeXMP>
<HardwareAcceleration>0</HardwareAcceleration>
<AS3Flags>4102</AS3Flags>
<DefaultLibraryLinkage>rsl</DefaultLibraryLinkage>
<RSLPreloaderMethod>wrap</RSLPreloaderMethod>
<RSLPreloaderSWF>$(AppConfig)/ActionScript 3.0/rsls/loader_animation.swf</RSLPreloaderSWF>
<LibraryPath>
<library-path-entry>
<swc-path>$(AppConfig)/ActionScript 3.0/libs</swc-path>
<linkage>merge</linkage>
</library-path-entry>
<library-path-entry>
<swc-path>$(AppConfig)/ActionScript 3.0/libs/11.0/textLayout.swc</swc-path>
<linkage usesDefault="true">rsl</linkage>
<rsl-url>http://fpdownload.adobe.com/pub/swz/tlf/2.0.0.232/textLayout_2.0.0.232.swz</rsl-url>
<policy-file-url>http://fpdownload.adobe.com/pub/swz/crossdomain.xml</policy-file-url>
<rsl-url>textLayout_2.0.0.232.swz</rsl-url>
</library-path-entry>
</LibraryPath>
<LibraryVersions>
<library-version>
<swc-path>$(AppConfig)/ActionScript 3.0/libs/11.0/textLayout.swc</swc-path>
<feature name="tlfText" majorVersion="2" minorVersion="0" build="232"/>
<rsl-url>http://fpdownload.adobe.com/pub/swz/tlf/2.0.0.232/textLayout_2.0.0.232.swz</rsl-url>
<policy-file-url>http://fpdownload.adobe.com/pub/swz/crossdomain.xml</policy-file-url>
<rsl-url>textLayout_2.0.0.232.swz</rsl-url>
</library-version>
</LibraryVersions>
</PublishFlashProperties>
<PublishJpegProperties enabled="true">
<Width>550</Width>
<Height>400</Height>
<Progressive>0</Progressive>
<DPI>4718592</DPI>
<Size>0</Size>
<Quality>80</Quality>
<MatchMovieDim>1</MatchMovieDim>
</PublishJpegProperties>
<PublishRNWKProperties enabled="true">
<exportFlash>1</exportFlash>
<flashBitRate>0</flashBitRate>
<exportAudio>1</exportAudio>
<audioFormat>0</audioFormat>
<singleRateAudio>0</singleRateAudio>
<realVideoRate>100000</realVideoRate>
<speed28K>1</speed28K>
<speed56K>1</speed56K>
<speedSingleISDN>0</speedSingleISDN>
<speedDualISDN>0</speedDualISDN>
<speedCorporateLAN>0</speedCorporateLAN>
<speed256K>0</speed256K>
<speed384K>0</speed384K>
<speed512K>0</speed512K>
<exportSMIL>1</exportSMIL>
</PublishRNWKProperties>
<PublishGifProperties enabled="true">
<Width>550</Width>
<Height>400</Height>
<Animated>0</Animated>
<MatchMovieDim>1</MatchMovieDim>
<Loop>1</Loop>
<LoopCount>0</LoopCount>
<OptimizeColors>1</OptimizeColors>
<Interlace>0</Interlace>
<Smooth>1</Smooth>
<DitherSolids>0</DitherSolids>
<RemoveGradients>0</RemoveGradients>
<TransparentOption></TransparentOption>
<TransparentAlpha>128</TransparentAlpha>
<DitherOption></DitherOption>
<PaletteOption></PaletteOption>
<MaxColors>255</MaxColors>
<PaletteName></PaletteName>
</PublishGifProperties>
<PublishPNGProperties enabled="true">
<Width>550</Width>
<Height>400</Height>
<OptimizeColors>1</OptimizeColors>
<Interlace>0</Interlace>
<Transparent>0</Transparent>
<Smooth>1</Smooth>
<DitherSolids>0</DitherSolids>
<RemoveGradients>0</RemoveGradients>
<MatchMovieDim>1</MatchMovieDim>
<DitherOption></DitherOption>
<FilterOption></FilterOption>
<PaletteOption></PaletteOption>
<BitDepth>24-bit with Alpha</BitDepth>
<MaxColors>255</MaxColors>
<PaletteName></PaletteName>
</PublishPNGProperties>
<PublishQTProperties enabled="true">
<Width>550</Width>
<Height>400</Height>
<MatchMovieDim>1</MatchMovieDim>
<UseQTSoundCompression>0</UseQTSoundCompression>
<AlphaOption></AlphaOption>
<LayerOption></LayerOption>
<QTSndSettings>00000000</QTSndSettings>
<ControllerOption>0</ControllerOption>
<Looping>0</Looping>
<PausedAtStart>0</PausedAtStart>
<PlayEveryFrame>0</PlayEveryFrame>
<Flatten>1</Flatten>
</PublishQTProperties>
</flash_profile>
</flash_profiles> | {
"pile_set_name": "Github"
} |
package puppetMonitor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.*;
import java.util.Calendar;
import java.net.*;
public class PuppetMonitor {
private static String m_logFile;
private static String m_lineFile;
private static void run() {
boolean active = true;
Long end_position=0L;
while (active) {
Long position = getReaderPostion(m_lineFile);
try{
RandomAccessFile reader = new RandomAccessFile(m_logFile, "r");
reader.seek(position);
String line=null;
while((line=reader.readLine())!=null){
Alertation alertation=parse(line);
if(alertation.getDomain() != null){
sendHttp(alertation);
// break;
}
}
end_position = reader.getFilePointer();
}catch(IOException e){
System.out.println("读文件异常:"+m_logFile);
e.printStackTrace();
}finally{
setReaderPostion(m_lineFile,end_position);
}
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
break;
}
}
}
private static void sendHttp(Alertation alertation) {
String[] pars= new String[10];
pars[0]="type="+alertation.getType();
pars[1]="title="+alertation.getTitle();
pars[2]="domain="+alertation.getDomain();
pars[3]="ip="+alertation.getIp();
pars[4]="user="+alertation.getUser();
pars[5]="content="+alertation.getContent();
pars[6]="url="+alertation.getUrl();
pars[7]="op="+alertation.getOp();
pars[8]="date="+alertation.getDate();
pars[9]="hostname="+alertation.getHostname();
String url="http://10.128.120.12:2281/cat/r/alteration";
HttpPostUtils httppost=new HttpPostUtils();
httppost.setUrlAddress(url);
System.out.println(httppost.httpPost(pars));
// System.out.println(alertation.getDate()+";"+alertation.getDomain()+";"+alertation.getHostname()+";"+alertation.getIp()+";"+alertation.getTitle()+";"+alertation.getContent());
}
private static Alertation parse(String line) {
String type="puppet";
String user="puppet";
String url="";
String op="insert";
String host="";
String IP="";
String date="";
String domain="";
String content="";
String title="";
String regEx = ".*puppet-agent.*\\(\\/Stage";
Alertation alertation = new Alertation();
if (Pattern.compile(regEx).matcher(line).find()) {
String[] tmp_list = line.split(" ");
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
date = tmp_list[0] + tmp_list[1]+ " " + tmp_list[2] + " "+ tmp_list[3]+ " " +Integer.toString(year);
String all_content=line.split("\\(")[1];
title=all_content.split("\\)")[0].split("\\[main\\]\\/")[1];
content=all_content.split("\\)")[1];
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd HH:mm:ss yyyy",Locale.US);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
try {
date=sdf2.format(sdf.parse(date));
} catch (ParseException e1) {
e1.printStackTrace();
}
// System.out.println(date);
try{
InetAddress ia = InetAddress.getLocalHost();
host = ia.getHostName();
IP= ia.getHostAddress();
domain=host.split("-sl-|-gp-|-ppe")[0];
}catch(UnknownHostException e){
e.printStackTrace();
}
alertation.setDate(date);
alertation.setHostname(host);
alertation.setIp(IP);
alertation.setDomain(domain);
alertation.setTitle(title);
alertation.setContent(content);
alertation.setOp(op);
alertation.setUrl(url);
alertation.setUser(user);
alertation.setType(type);
}
return alertation;
}
// private String getNextLine(int position) {
// return null;
// }
/**
*
* @param line_file,记录文件读取位置的文件
* @return 记录的数据,否则返回0
* 读取文件失败的时候是否创建文件line_file
*
*/
private static long getReaderPostion(String line_file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(line_file));
String str = reader.readLine();
if (str != null) {
return Long.parseLong(str);
}
}catch(FileNotFoundException e1){
File filename = new File(line_file);
try {
filename.createNewFile();
} catch (IOException e2) {
System.out.println("创建文件失败:" + line_file);
e2.printStackTrace();
}
} catch (Exception e3) {
e3.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return 0L;
}
private static void setReaderPostion(String line_file,Long end_position) {
try{
BufferedWriter output = new BufferedWriter(new FileWriter(line_file));
output.write(Long.toString(end_position));
output.close();
}catch(IOException e){
System.out.println("写入文件异常:line_file");
e.printStackTrace();
}
}
public static void main(String args[]) {
// if (args.length > 2) {
// m_logFile = args[0];
// m_lineFile = args[1];
// } else {
// System.out.println("Please check pars!");
// System.exit(0);
// }
m_logFile = "/Users/River/messages";
m_lineFile = "/var/log/line_random.log";
run();
}
}
| {
"pile_set_name": "Github"
} |
qbs*oldstr3333=NULL;
if(_SUB_BUILD_STRING_PATH->tmp||_SUB_BUILD_STRING_PATH->fixed||_SUB_BUILD_STRING_PATH->readonly){
oldstr3333=_SUB_BUILD_STRING_PATH;
if (oldstr3333->cmem_descriptor){
_SUB_BUILD_STRING_PATH=qbs_new_cmem(oldstr3333->len,0);
}else{
_SUB_BUILD_STRING_PATH=qbs_new(oldstr3333->len,0);
}
memcpy(_SUB_BUILD_STRING_PATH->chr,oldstr3333->chr,oldstr3333->len);
}
qbs *_SUB_BUILD_STRING_PREVIOUS_DIR=NULL;
if (!_SUB_BUILD_STRING_PREVIOUS_DIR)_SUB_BUILD_STRING_PREVIOUS_DIR=qbs_new(0,0);
int32 *_SUB_BUILD_LONG_DEPTH=NULL;
if(_SUB_BUILD_LONG_DEPTH==NULL){
_SUB_BUILD_LONG_DEPTH=(int32*)mem_static_malloc(4);
*_SUB_BUILD_LONG_DEPTH=0;
}
int32 *_SUB_BUILD_LONG_X=NULL;
if(_SUB_BUILD_LONG_X==NULL){
_SUB_BUILD_LONG_X=(int32*)mem_static_malloc(4);
*_SUB_BUILD_LONG_X=0;
}
int64 fornext_value3335;
int64 fornext_finalvalue3335;
int64 fornext_step3335;
uint8 fornext_step_negative3335;
byte_element_struct *byte_element_3336=NULL;
if (!byte_element_3336){
if ((mem_static_pointer+=12)<mem_static_limit) byte_element_3336=(byte_element_struct*)(mem_static_pointer-12); else byte_element_3336=(byte_element_struct*)mem_static_malloc(12);
}
qbs *_SUB_BUILD_STRING_RETURN_PATH=NULL;
if (!_SUB_BUILD_STRING_RETURN_PATH)_SUB_BUILD_STRING_RETURN_PATH=qbs_new(0,0);
int64 fornext_value3338;
int64 fornext_finalvalue3338;
int64 fornext_step3338;
uint8 fornext_step_negative3338;
int32 *_SUB_BUILD_LONG_BFH=NULL;
if(_SUB_BUILD_LONG_BFH==NULL){
_SUB_BUILD_LONG_BFH=(int32*)mem_static_malloc(4);
*_SUB_BUILD_LONG_BFH=0;
}
qbs *_SUB_BUILD_STRING_C=NULL;
if (!_SUB_BUILD_STRING_C)_SUB_BUILD_STRING_C=qbs_new(0,0);
int32 *_SUB_BUILD_LONG_USE=NULL;
if(_SUB_BUILD_LONG_USE==NULL){
_SUB_BUILD_LONG_USE=(int32*)mem_static_malloc(4);
*_SUB_BUILD_LONG_USE=0;
}
byte_element_struct *byte_element_3341=NULL;
if (!byte_element_3341){
if ((mem_static_pointer+=12)<mem_static_limit) byte_element_3341=(byte_element_struct*)(mem_static_pointer-12); else byte_element_3341=(byte_element_struct*)mem_static_malloc(12);
}
| {
"pile_set_name": "Github"
} |
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnModuleInit,
} from '@nestjs/common';
import noble, { Peripheral, Advertisement } from '@abandonware/noble';
import { EntitiesService } from '../../entities/entities.service';
import { ConfigService } from '../../config/config.service';
import { XiaomiMiSensorOptions } from './xiaomi-mi.config';
import { makeId } from '../../util/id';
import { SERVICE_DATA_UUID, ServiceData, Parser, EventTypes } from './parser';
import { Sensor } from '../../entities/sensor';
import { EntityCustomization } from '../../entities/entity-customization.interface';
import { SensorConfig } from '../home-assistant/sensor-config';
@Injectable()
export class XiaomiMiService implements OnModuleInit, OnApplicationBootstrap {
private config: { [address: string]: XiaomiMiSensorOptions } = {};
private readonly logger: Logger;
constructor(
private readonly entitiesService: EntitiesService,
private readonly configService: ConfigService
) {
this.logger = new Logger(XiaomiMiService.name);
}
/**
* Lifecycle hook, called once the host module has been initialized.
*/
onModuleInit(): void {
this.config = {};
this.configService.get('xiaomiMi').sensors.forEach((options) => {
this.config[options.address] = options;
});
if (!this.hasSensors()) {
this.logger.warn(
'No sensors entries in the config, so no sensors will be created! ' +
'Enable the bluetooth-low-energy integration to log discovered IDs.'
);
}
}
/**
* Lifecycle hook, called once the application has started.
*/
onApplicationBootstrap(): void {
noble.on('stateChange', XiaomiMiService.handleStateChange);
noble.on('discover', this.handleDiscovery.bind(this));
noble.on('warning', this.onWarning.bind(this));
}
/**
* Log warnings from noble.
*/
private onWarning(message: string): void {
this.logger.warn('Warning: ', message);
}
/**
* Determines whether we have any sensors.
*
* @returns Sensors status
*/
private hasSensors(): boolean {
return Object.keys(this.config).length > 0;
}
/**
* Record a measurement.
*
* @param devName - The name of the device that took the measurement.
* @param kind - The kind of measurement.
* @param units - The units of the measurement.
* @param state - The current measurement.
*/
private recordMeasure(
devName: string,
kind: string,
units: string,
state: number | string
): void {
this.logger.debug(`${devName}: ${kind}: ${state}${units}`);
const sensorName = `${devName} ${kind}`;
const id = makeId(sensorName);
let entity = this.entitiesService.get(id);
if (!entity) {
const customizations: Array<EntityCustomization<any>> = [
{
for: SensorConfig,
overrides: {
deviceClass: kind,
unitOfMeasurement: units,
},
},
];
entity = this.entitiesService.add(
new Sensor(id, sensorName),
customizations
) as Sensor;
}
entity.state = state;
}
/**
* Filters found BLE peripherals and publishes new readings to sensors, depending on configuration.
*
* @param peripheral - BLE peripheral
*/
handleDiscovery(peripheral: Peripheral): void {
const { advertisement, id } = peripheral || {};
const options = this.config[id];
if (!options) {
return;
}
const buffer = XiaomiMiService.getValidServiceData(advertisement);
if (!buffer) {
this.logger.warn(
`${
options.name
} does not appear to be a Xiaomi device. Got advertisement ${JSON.stringify(
advertisement
)}`
);
return;
}
let serviceData: ServiceData | null = null;
try {
serviceData = XiaomiMiService.parseServiceData(buffer, options.bindKey);
} catch (error) {
this.logger.error(
`${options.name}: couldn't parse service data: ${error}`
);
return;
}
if (!serviceData.frameControl.hasEvent) {
this.logger.debug(
`${options.name}: advertisement with no event: ${buffer.toString(
'hex'
)}`
);
return;
}
const event = serviceData.event;
switch (serviceData.eventType) {
case EventTypes.temperature: {
this.recordMeasure(
options.name,
'temperature',
'°C',
event.temperature
);
break;
}
case EventTypes.humidity: {
this.recordMeasure(options.name, 'humidity', '%', event.humidity);
break;
}
case EventTypes.battery: {
this.recordMeasure(options.name, 'battery', '%', event.battery);
break;
}
case EventTypes.temperatureAndHumidity: {
this.recordMeasure(
options.name,
'temperature',
'°C',
event.temperature
);
this.recordMeasure(options.name, 'humidity', '%', event.humidity);
break;
}
case EventTypes.illuminance: {
this.recordMeasure(
options.name,
'illuminance',
'lx',
event.illuminance
);
break;
}
case EventTypes.moisture: {
this.recordMeasure(options.name, 'moisture', '%', event.moisture);
break;
}
case EventTypes.fertility: {
this.recordMeasure(options.name, 'fertility', '', event.fertility);
break;
}
default: {
this.logger.error(
`${options.name}: unknown event type: ${serviceData.eventType}, ` +
`raw data: ${buffer.toString('hex')}`
);
break;
}
}
}
/**
* Extract service data.
*
* @returns The service data buffer for the Xiamoi service data UUID or null
* if it doesn't exist.
*/
private static getValidServiceData(
advertisement: Advertisement
): Buffer | null {
if (!advertisement || !advertisement.serviceData) {
return null;
}
const uuidPair = advertisement.serviceData.find(
(data) => data.uuid.toLowerCase() === SERVICE_DATA_UUID
);
if (!uuidPair) {
return null;
}
return uuidPair.data;
}
/**
* Parses the service data buffer.
*
* @param buffer - The servie data buffer.
* @param bindKey - An optional bindKey for use in decripting the payload.
*
* @returns A ServiceData object.
*/
private static parseServiceData(
buffer: Buffer,
bindKey: string | null
): ServiceData {
return new Parser(buffer, bindKey).parse();
}
/**
* Stops or starts BLE scans based on the adapter state.
*
* @param state - Noble adapter state string
*/
private static handleStateChange(state: string): void {
if (state === 'poweredOn') {
noble.startScanning([], true);
} else {
noble.stopScanning();
}
}
}
| {
"pile_set_name": "Github"
} |
// cgo -godefs types_netbsd.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build arm,netbsd
package unix
const (
SizeofPtr = 0x4
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x4
SizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int32
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int32
Pad_cgo_0 [4]byte
}
type Timeval struct {
Sec int64
Usec int32
Pad_cgo_0 [4]byte
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int32
Ixrss int32
Idrss int32
Isrss int32
Minflt int32
Majflt int32
Nswap int32
Inblock int32
Oublock int32
Msgsnd int32
Msgrcv int32
Nsignals int32
Nvcsw int32
Nivcsw int32
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint64
Mode uint32
_ [4]byte
Ino uint64
Nlink uint32
Uid uint32
Gid uint32
_ [4]byte
Rdev uint64
Atim Timespec
Mtim Timespec
Ctim Timespec
Btim Timespec
Size int64
Blocks int64
Blksize uint32
Flags uint32
Gen uint32
Spare [2]uint32
_ [4]byte
}
type Statfs_t [0]byte
type Statvfs_t struct {
Flag uint32
Bsize uint32
Frsize uint32
Iosize uint32
Blocks uint64
Bfree uint64
Bavail uint64
Bresvd uint64
Files uint64
Ffree uint64
Favail uint64
Fresvd uint64
Syncreads uint64
Syncwrites uint64
Asyncreads uint64
Asyncwrites uint64
Fsidx Fsid
Fsid uint32
Namemax uint32
Owner uint32
Spare [4]uint32
Fstypename [32]byte
Mntonname [1024]byte
Mntfromname [1024]byte
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
}
type Dirent struct {
Fileno uint64
Reclen uint16
Namlen uint16
Type uint8
Name [512]int8
Pad_cgo_0 [3]byte
}
type Fsid struct {
X__fsid_val [2]int32
}
const (
PathMax = 0x400
)
const (
ST_WAIT = 0x1
ST_NOWAIT = 0x2
)
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint32
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Iov *Iovec
Iovlen int32
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x14
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x1c
SizeofCmsghdr = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint32
Filter uint32
Flags uint32
Fflags uint32
Data int64
Udata int32
Pad_cgo_0 [4]byte
}
type FdSet struct {
Bits [8]uint32
}
const (
SizeofIfMsghdr = 0x98
SizeofIfData = 0x88
SizeofIfaMsghdr = 0x18
SizeofIfAnnounceMsghdr = 0x18
SizeofRtMsghdr = 0x78
SizeofRtMetrics = 0x50
)
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
Data IfData
}
type IfData struct {
Type uint8
Addrlen uint8
Hdrlen uint8
Pad_cgo_0 [1]byte
Link_state int32
Mtu uint64
Metric uint64
Baudrate uint64
Ipackets uint64
Ierrors uint64
Opackets uint64
Oerrors uint64
Collisions uint64
Ibytes uint64
Obytes uint64
Imcasts uint64
Omcasts uint64
Iqdrops uint64
Noproto uint64
Lastchange Timespec
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Metric int32
Index uint16
Pad_cgo_0 [6]byte
}
type IfAnnounceMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Name [16]int8
What uint16
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Pad_cgo_0 [2]byte
Flags int32
Addrs int32
Pid int32
Seq int32
Errno int32
Use int32
Inits int32
Pad_cgo_1 [4]byte
Rmx RtMetrics
}
type RtMetrics struct {
Locks uint64
Mtu uint64
Hopcount uint64
Recvpipe uint64
Sendpipe uint64
Ssthresh uint64
Rtt uint64
Rttvar uint64
Expire int64
Pksent int64
}
type Mclpool [0]byte
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x80
SizeofBpfProgram = 0x8
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x14
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint64
Drop uint64
Capt uint64
Padding [13]uint64
}
type BpfProgram struct {
Len uint32
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp BpfTimeval
Caplen uint32
Datalen uint32
Hdrlen uint16
Pad_cgo_0 [2]byte
}
type BpfTimeval struct {
Sec int32
Usec int32
}
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]uint8
Ispeed int32
Ospeed int32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type Ptmget struct {
Cfd int32
Sfd int32
Cn [1024]byte
Sn [1024]byte
}
const (
AT_FDCWD = -0x64
AT_SYMLINK_FOLLOW = 0x400
AT_SYMLINK_NOFOLLOW = 0x200
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLERR = 0x8
POLLHUP = 0x10
POLLIN = 0x1
POLLNVAL = 0x20
POLLOUT = 0x4
POLLPRI = 0x2
POLLRDBAND = 0x80
POLLRDNORM = 0x40
POLLWRBAND = 0x100
POLLWRNORM = 0x4
)
type Sysctlnode struct {
Flags uint32
Num int32
Name [32]int8
Ver uint32
X__rsvd uint32
Un [16]byte
X_sysctl_size [8]byte
X_sysctl_func [8]byte
X_sysctl_parent [8]byte
X_sysctl_desc [8]byte
}
type Utsname struct {
Sysname [256]byte
Nodename [256]byte
Release [256]byte
Version [256]byte
Machine [256]byte
}
const SizeofClockinfo = 0x14
type Clockinfo struct {
Hz int32
Tick int32
Tickadj int32
Stathz int32
Profhz int32
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************/
/* */
/* pfrgload.h */
/* */
/* FreeType PFR glyph loader (specification). */
/* */
/* Copyright 2002-2016 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef PFRGLOAD_H_
#define PFRGLOAD_H_
#include "pfrtypes.h"
FT_BEGIN_HEADER
FT_LOCAL( void )
pfr_glyph_init( PFR_Glyph glyph,
FT_GlyphLoader loader );
FT_LOCAL( void )
pfr_glyph_done( PFR_Glyph glyph );
FT_LOCAL( FT_Error )
pfr_glyph_load( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size );
FT_END_HEADER
#endif /* PFRGLOAD_H_ */
/* END */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="ProxyField" module="Products.ERP5Form.ProxyField"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>delegated_list</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>my_column_number</string> </value>
</item>
<item>
<key> <string>message_values</string> </key>
<value>
<dictionary>
<item>
<key> <string>external_validator_failed</string> </key>
<value> <string>The input failed the external validator.</string> </value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>overrides</string> </key>
<value>
<dictionary>
<item>
<key> <string>field_id</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>form_id</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>target</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>tales</string> </key>
<value>
<dictionary>
<item>
<key> <string>field_id</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>form_id</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>target</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>values</string> </key>
<value>
<dictionary>
<item>
<key> <string>field_id</string> </key>
<value> <string>my_column_number</string> </value>
</item>
<item>
<key> <string>form_id</string> </key>
<value> <string>Base_viewBarcodeFieldLibrary</string> </value>
</item>
<item>
<key> <string>target</string> </key>
<value> <string>Click to edit the target</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
# Tests what happens if mean data dump begin time is negative
negative_begin
# Tests what happens if mean data dump begin time is not a number
broken_number
# Tests what happens if mean data dump should end before it starts
end_before_begin
| {
"pile_set_name": "Github"
} |
/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are 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 Materials.
**
** THE MATERIALS ARE 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
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 color;
void main (void)
{
float c = 10.0 * 2.0 * (color.r - 0.5);
c = c - 1.0 * floor(c / 1.0);
gl_FragColor = vec4(c, 0.0, 0.0, 1.0);
}
| {
"pile_set_name": "Github"
} |
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Shared utilities for writing scripts for Google Test/Mock."""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import re
# Matches the line from 'svn info .' output that describes what SVN
# path the current local directory corresponds to. For example, in
# a googletest SVN workspace's trunk/test directory, the output will be:
#
# URL: https://googletest.googlecode.com/svn/trunk/test
_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)')
def GetCommandOutput(command):
"""Runs the shell command and returns its stdout as a list of lines."""
f = os.popen(command, 'r')
lines = [line.strip() for line in f.readlines()]
f.close()
return lines
def GetSvnInfo():
"""Returns the project name and the current SVN workspace's root path."""
for line in GetCommandOutput('svn info .'):
m = _SVN_INFO_URL_RE.match(line)
if m:
project = m.group(1) # googletest or googlemock
rel_path = m.group(2)
root = os.path.realpath(rel_path.count('/') * '../')
return project, root
return None, None
def GetSvnTrunk():
"""Returns the current SVN workspace's trunk root path."""
_, root = GetSvnInfo()
return root + '/trunk' if root else None
def IsInGTestSvn():
project, _ = GetSvnInfo()
return project == 'googletest'
def IsInGMockSvn():
project, _ = GetSvnInfo()
return project == 'googlemock'
| {
"pile_set_name": "Github"
} |
package <% $module %>::<% $moniker %>::Dispatcher;
use strict;
use warnings;
use utf8;
use Amon2::Web::Dispatcher::RouterBoom;
use Module::Find qw(useall);
# Load all controller classes at loading time.
useall('<% $module %>::<% $moniker %>::C');
base '<% $module %>::<% $moniker %>::C';
get '/' => 'Root#index';
post '/reset_counter' => 'Root#reset_counter';
1;
| {
"pile_set_name": "Github"
} |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/libplatform/tracing/trace-writer.h"
#include <cmath>
#include "base/trace_event/common/trace_event_common.h"
#include "include/v8-platform.h"
#include "src/base/platform/platform.h"
namespace v8 {
namespace platform {
namespace tracing {
// Writes the given string to a stream, taking care to escape characters
// when necessary.
V8_INLINE static void WriteJSONStringToStream(const char* str,
std::ostream& stream) {
size_t len = strlen(str);
stream << "\"";
for (size_t i = 0; i < len; ++i) {
// All of the permitted escape sequences in JSON strings, as per
// https://mathiasbynens.be/notes/javascript-escapes
switch (str[i]) {
case '\b':
stream << "\\b";
break;
case '\f':
stream << "\\f";
break;
case '\n':
stream << "\\n";
break;
case '\r':
stream << "\\r";
break;
case '\t':
stream << "\\t";
break;
case '\"':
stream << "\\\"";
break;
case '\\':
stream << "\\\\";
break;
// Note that because we use double quotes for JSON strings,
// we don't need to escape single quotes.
default:
stream << str[i];
break;
}
}
stream << "\"";
}
void JSONTraceWriter::AppendArgValue(uint8_t type,
TraceObject::ArgValue value) {
switch (type) {
case TRACE_VALUE_TYPE_BOOL:
stream_ << (value.as_uint ? "true" : "false");
break;
case TRACE_VALUE_TYPE_UINT:
stream_ << value.as_uint;
break;
case TRACE_VALUE_TYPE_INT:
stream_ << value.as_int;
break;
case TRACE_VALUE_TYPE_DOUBLE: {
std::string real;
double val = value.as_double;
if (std::isfinite(val)) {
std::ostringstream convert_stream;
convert_stream << val;
real = convert_stream.str();
// Ensure that the number has a .0 if there's no decimal or 'e'. This
// makes sure that when we read the JSON back, it's interpreted as a
// real rather than an int.
if (real.find('.') == std::string::npos &&
real.find('e') == std::string::npos &&
real.find('E') == std::string::npos) {
real += ".0";
}
} else if (std::isnan(val)) {
// The JSON spec doesn't allow NaN and Infinity (since these are
// objects in EcmaScript). Use strings instead.
real = "\"NaN\"";
} else if (val < 0) {
real = "\"-Infinity\"";
} else {
real = "\"Infinity\"";
}
stream_ << real;
break;
}
case TRACE_VALUE_TYPE_POINTER:
// JSON only supports double and int numbers.
// So as not to lose bits from a 64-bit pointer, output as a hex string.
stream_ << "\"" << value.as_pointer << "\"";
break;
case TRACE_VALUE_TYPE_STRING:
case TRACE_VALUE_TYPE_COPY_STRING:
if (value.as_string == nullptr) {
stream_ << "\"nullptr\"";
} else {
WriteJSONStringToStream(value.as_string, stream_);
}
break;
default:
UNREACHABLE();
}
}
void JSONTraceWriter::AppendArgValue(ConvertableToTraceFormat* value) {
std::string arg_stringified;
value->AppendAsTraceFormat(&arg_stringified);
stream_ << arg_stringified;
}
JSONTraceWriter::JSONTraceWriter(std::ostream& stream)
: JSONTraceWriter(stream, "traceEvents") {}
JSONTraceWriter::JSONTraceWriter(std::ostream& stream, const std::string& tag)
: stream_(stream) {
stream_ << "{\"" << tag << "\":[";
}
JSONTraceWriter::~JSONTraceWriter() { stream_ << "]}"; }
void JSONTraceWriter::AppendTraceEvent(TraceObject* trace_event) {
if (append_comma_) stream_ << ",";
append_comma_ = true;
stream_ << "{\"pid\":" << trace_event->pid()
<< ",\"tid\":" << trace_event->tid()
<< ",\"ts\":" << trace_event->ts()
<< ",\"tts\":" << trace_event->tts() << ",\"ph\":\""
<< trace_event->phase() << "\",\"cat\":\""
<< TracingController::GetCategoryGroupName(
trace_event->category_enabled_flag())
<< "\",\"name\":\"" << trace_event->name()
<< "\",\"dur\":" << trace_event->duration()
<< ",\"tdur\":" << trace_event->cpu_duration();
if (trace_event->flags() &
(TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT)) {
stream_ << ",\"bind_id\":\"0x" << std::hex << trace_event->bind_id() << "\""
<< std::dec;
if (trace_event->flags() & TRACE_EVENT_FLAG_FLOW_IN) {
stream_ << ",\"flow_in\":true";
}
if (trace_event->flags() & TRACE_EVENT_FLAG_FLOW_OUT) {
stream_ << ",\"flow_out\":true";
}
}
if (trace_event->flags() & TRACE_EVENT_FLAG_HAS_ID) {
if (trace_event->scope() != nullptr) {
stream_ << ",\"scope\":\"" << trace_event->scope() << "\"";
}
// So as not to lose bits from a 64-bit integer, output as a hex string.
stream_ << ",\"id\":\"0x" << std::hex << trace_event->id() << "\""
<< std::dec;
}
stream_ << ",\"args\":{";
const char** arg_names = trace_event->arg_names();
const uint8_t* arg_types = trace_event->arg_types();
TraceObject::ArgValue* arg_values = trace_event->arg_values();
std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables =
trace_event->arg_convertables();
for (int i = 0; i < trace_event->num_args(); ++i) {
if (i > 0) stream_ << ",";
stream_ << "\"" << arg_names[i] << "\":";
if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
AppendArgValue(arg_convertables[i].get());
} else {
AppendArgValue(arg_types[i], arg_values[i]);
}
}
stream_ << "}}";
// TODO(fmeawad): Add support for Flow Events.
}
void JSONTraceWriter::Flush() {}
TraceWriter* TraceWriter::CreateJSONTraceWriter(std::ostream& stream) {
return new JSONTraceWriter(stream);
}
TraceWriter* TraceWriter::CreateJSONTraceWriter(std::ostream& stream,
const std::string& tag) {
return new JSONTraceWriter(stream, tag);
}
} // namespace tracing
} // namespace platform
} // namespace v8
| {
"pile_set_name": "Github"
} |
CODE SEGMENT BYTE PUBLIC
PUBLIC FILL
PUBLIC BASIC
FILL DB 1420H DUP(0CCH)
BASIC DB 8000H DUP(0FFH)
CODE ENDS
END
| {
"pile_set_name": "Github"
} |
{
"javascript": {
"main": "http://localhost:3001/public/main.a0e19c27696da51e6f1e.js"
},
"styles": {},
"assets": {}
} | {
"pile_set_name": "Github"
} |
/**
* Welcome to @reach/slider!
*
* A UI input component where the user selects a value from within a given
* range. A Slider has a handle that can be moved along a track to change its
* value. When the user's mouse or focus is on the Slider's handle, the value
* can be incremented with keyboard controls.
*
* Random thoughts/notes:
* - Currently testing this against the behavior of the native input range
* element to get our slider on par. We'll explore animated and multi-handle
* sliders next.
* - We may want to research some use cases for reversed sliders in RTL
* languages if that's a thing
*
* @see Docs https://reach.tech/slider
* @see Source https://github.com/reach/reach-ui/tree/main/packages/slider
* @see WAI-ARIA https://www.w3.org/TR/wai-aria-practices-1.2/#slider
* @see Example https://github.com/Stanko/aria-progress-range-slider
* @see Example http://www.oaa-accessibility.org/examplep/slider1/
*/
/* eslint-disable jsx-a11y/no-static-element-interactions */
import React, {
memo,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import PropTypes from "prop-types";
import { useId } from "@reach/auto-id";
import {
checkStyles,
createNamedContext,
forwardRefWithAs,
getOwnerDocument,
isFunction,
makeId,
memoWithAs,
useEventCallback,
useForkedRef,
useControlledSwitchWarning,
useControlledState,
useIsomorphicLayoutEffect,
warning,
wrapEvent,
noop,
isRightClick,
} from "@reach/utils";
// TODO: Remove in 1.0
export type SliderAlignment = "center" | "contain";
export enum SliderOrientation {
Horizontal = "horizontal",
Vertical = "vertical",
// TODO: Add support for RTL slider
}
// TODO: Remove in 1.0
export enum SliderHandleAlignment {
// Handle is centered directly over the current value marker
Center = "center",
// Handle is contained within the bounds of the track, offset slightly from
// the value's center mark to accommodate
Contain = "contain",
}
// TODO: Remove in 1.0
export const SLIDER_ORIENTATION_HORIZONTAL = SliderOrientation.Horizontal;
export const SLIDER_ORIENTATION_VERTICAL = SliderOrientation.Vertical;
export const SLIDER_HANDLE_ALIGN_CENTER = SliderHandleAlignment.Center;
export const SLIDER_HANDLE_ALIGN_CONTAIN = SliderHandleAlignment.Contain;
const SliderContext = createNamedContext<ISliderContext>(
"SliderContext",
{} as ISliderContext
);
const useSliderContext = () => useContext(SliderContext);
// These proptypes are shared between the composed SliderInput component and the
// simplified Slider
const sliderPropTypes = {
defaultValue: PropTypes.number,
disabled: PropTypes.bool,
getAriaLabel: PropTypes.func,
getAriaValueText: PropTypes.func,
getValueText: PropTypes.func,
handleAlignment: PropTypes.oneOf([
SliderHandleAlignment.Center,
SliderHandleAlignment.Contain,
]),
min: PropTypes.number,
max: PropTypes.number,
name: PropTypes.string,
orientation: PropTypes.oneOf([
SliderOrientation.Horizontal,
SliderOrientation.Vertical,
]),
onChange: PropTypes.func,
step: PropTypes.number,
value: PropTypes.number,
};
////////////////////////////////////////////////////////////////////////////////
/**
* Slider
*
* @see Docs https://reach.tech/slider#slider
*/
const Slider = forwardRefWithAs<SliderProps, "div">(function Slider(
{ children, ...props },
forwardedRef
) {
return (
<SliderInput
{...props}
ref={forwardedRef}
data-reach-slider=""
_componentName="Slider"
>
<SliderTrack>
<SliderTrackHighlight />
<SliderHandle />
{children}
</SliderTrack>
</SliderInput>
);
});
/**
* @see Docs https://reach.tech/slider#slider-props
*/
export type SliderProps = {
/**
* `Slider` can accept `SliderMarker` children to enhance display of specific
* values along the track.
*
* @see Docs https://reach.tech/slider#slider-children
*/
children?: React.ReactNode;
/**
* The defaultValue is used to set an initial value for an uncontrolled
* Slider.
*
* @see Docs https://reach.tech/slider#slider-defaultvalue
*/
defaultValue?: number;
/**
* @see Docs https://reach.tech/slider#slider-disabled
*/
disabled?: boolean;
/**
* Whether or not the slider should be disabled from user interaction.
*
* @see Docs https://reach.tech/slider#slider-value
*/
value?: number;
/**
* A function used to set a human-readable name for the slider.
*
* @see Docs https://reach.tech/slider#slider-getarialabel
*/
getAriaLabel?(value: number): string;
/**
* A function used to set a human-readable value text based on the slider's
* current value.
*
* @see Docs https://reach.tech/slider#slider-getariavaluetext
*/
getAriaValueText?(value: number): string;
/**
* Deprecated. Use `getAriaValueText` instead.
*
* @deprecated
* @param value
*/
getValueText?(value: number): string;
/**
* When set to `center`, the slider's handle will be positioned directly
* centered over the slider's curremt value on the track. This means that when
* the slider is at its min or max value, a visiable slider handle will extend
* beyond the width (or height in vertical mode) of the slider track. When set
* to `contain`, the slider handle will always be contained within the bounds
* of the track, meaning its position will be slightly offset from the actual
* value depending on where it sits on the track.
*
* @see Docs https://reach.tech/slider#slider-handlealignment
*/
handleAlignment?: "center" | "contain" | SliderAlignment;
/**
* The maximum value of the slider. Defaults to `100`.
*
* @see Docs https://reach.tech/slider#slider-max
*/
max?: number;
/**
* The minimum value of the slider. Defaults to `0`.
*
* @see Docs https://reach.tech/slider#slider-min
*/
min?: number;
/**
* If the slider is used as a form input, it should accept a `name` prop to
* identify its value in context of the form.
*
* @see Docs https://reach.tech/slider#slider-name
*/
name?: string;
/**
* Callback that fires when the slider value changes. When the `value` prop is
* set, the Slider state becomes controlled and `onChange` must be used to
* update the value in response to user interaction.
*
* @see Docs https://reach.tech/slider#slider-onchange
*/
onChange?(
newValue: number,
props?: {
min?: number;
max?: number;
handlePosition?: string;
}
): void;
// We use native DOM events for the slider since they are global
onMouseDown?(event: MouseEvent): void;
onMouseMove?(event: MouseEvent): void;
onMouseUp?(event: MouseEvent): void;
onPointerDown?(event: PointerEvent): void;
onPointerUp?(event: PointerEvent): void;
onTouchEnd?(event: TouchEvent): void;
onTouchMove?(event: TouchEvent): void;
onTouchStart?(event: TouchEvent): void;
/**
* Sets the slider to horizontal or vertical mode.
*
* @see Docs https://reach.tech/slider#slider-orientation
*/
orientation?: SliderOrientation;
/**
* The step attribute is a number that specifies the granularity that the
* value must adhere to as it changes. Step sets minimum intervals of change,
* creating a "snap" effect when the handle is moved along the track.
*
* @see Docs https://reach.tech/slider#slider-step
*/
step?: number;
};
if (__DEV__) {
Slider.displayName = "Slider";
Slider.propTypes = {
...sliderPropTypes,
children: PropTypes.node,
};
}
export { Slider };
export default Slider;
////////////////////////////////////////////////////////////////////////////////
/**
* SliderInput
*
* The parent component of the slider interface. This is a lower level component
* if you need more control over styles or rendering the slider's inner
* components.
*
* @see Docs https://reach.tech/slider#sliderinput
*/
const SliderInput = forwardRefWithAs<
SliderInputProps & { _componentName?: string }
>(function SliderInput(
{
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
"aria-valuetext": ariaValueTextProp,
as: Comp = "div",
defaultValue,
disabled = false,
value: controlledValue,
getAriaLabel,
getAriaValueText,
getValueText: DEPRECATED_getValueText, // TODO: Remove in 1.0
handleAlignment = SliderHandleAlignment.Center,
max = 100,
min = 0,
name,
onChange,
onKeyDown,
onMouseDown,
onMouseMove,
onMouseUp,
onPointerDown,
onPointerUp,
onTouchEnd,
onTouchMove,
onTouchStart,
orientation = SliderOrientation.Horizontal,
step = 1,
children,
_componentName = "SliderInput",
...rest
},
forwardedRef
) {
useControlledSwitchWarning(controlledValue, "value", _componentName);
warning(
!DEPRECATED_getValueText,
"The `getValueText` prop in @reach/slider is deprecated. Please use `getAriaValueText` instead."
);
let touchId: TouchIdRef = useRef();
let id = useId(rest.id);
// Track whether or not the pointer is down without updating the component
let pointerDownRef = useRef(false);
let trackRef: TrackRef = useRef(null);
let handleRef: HandleRef = useRef(null);
let sliderRef: SliderRef = useRef(null);
let ref = useForkedRef(sliderRef, forwardedRef);
let [hasFocus, setHasFocus] = useState(false);
let { ref: x, ...handleDimensions } = useDimensions(handleRef);
let [_value, setValue] = useControlledState(
controlledValue,
defaultValue || min
);
let value = clamp(_value, min, max);
let trackPercent = valueToPercent(value, min, max);
let isVertical = orientation === SliderOrientation.Vertical;
let handleSize = isVertical
? handleDimensions.height
: handleDimensions.width;
// TODO: Consider removing the `handleAlignment` prop
// We may want to use accept a `handlePosition` prop instead and let apps
// define their own positioning logic, similar to how we do for popovers.
let handlePosition = `calc(${trackPercent}% - ${
handleAlignment === SliderHandleAlignment.Center
? `${handleSize}px / 2`
: `${handleSize}px * ${trackPercent * 0.01}`
})`;
let handlePositionRef = useRef(handlePosition);
useIsomorphicLayoutEffect(() => {
handlePositionRef.current = handlePosition;
}, [handlePosition]);
let onChangeRef = useRef(onChange);
useIsomorphicLayoutEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);
let updateValue = useCallback(
function updateValue(newValue) {
setValue(newValue);
if (onChangeRef.current) {
// Prevent onChange from recreating the function
// TODO: Reonsider the onChange callback API
onChangeRef.current(newValue, {
min,
max,
// Prevent handlePosition from recreating the function
handlePosition: handlePositionRef.current,
});
}
},
[max, min, setValue]
);
let getNewValueFromEvent = useCallback(
(event: SomePointerEvent) => {
return getNewValue(getPointerPosition(event, touchId), trackRef.current, {
step,
orientation,
min,
max,
});
},
[max, min, orientation, step]
);
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_kbd_interaction
let handleKeyDown = useEventCallback((event: React.KeyboardEvent) => {
if (disabled) {
return;
}
let newValue: number;
let tenSteps = (max - min) / 10;
let keyStep = step || (max - min) / 100;
switch (event.key) {
// Decrease the value of the slider by one step.
case "ArrowLeft":
case "ArrowDown":
newValue = value - keyStep;
break;
// Increase the value of the slider by one step
case "ArrowRight":
case "ArrowUp":
newValue = value + keyStep;
break;
// Decrement the slider by an amount larger than the step change made by
// `ArrowDown`.
case "PageDown":
newValue = value - tenSteps;
break;
// Increment the slider by an amount larger than the step change made by
// `ArrowUp`.
case "PageUp":
newValue = value + tenSteps;
break;
// Set the slider to the first allowed value in its range.
case "Home":
newValue = min;
break;
// Set the slider to the last allowed value in its range.
case "End":
newValue = max;
break;
default:
return;
}
event.preventDefault();
newValue = clamp(
step ? roundValueToStep(newValue, step, min) : newValue,
min,
max
);
updateValue(newValue);
});
let ariaValueText = DEPRECATED_getValueText
? DEPRECATED_getValueText(value)
: getAriaValueText
? getAriaValueText(value)
: ariaValueTextProp;
let trackHighlightStyle = isVertical
? {
width: `100%`,
height: `${trackPercent}%`,
bottom: 0,
}
: {
width: `${trackPercent}%`,
height: `100%`,
left: 0,
};
let ctx: ISliderContext = {
ariaLabel: getAriaLabel ? getAriaLabel(value) : ariaLabel,
ariaLabelledBy,
ariaValueText,
handleDimensions,
handleKeyDown,
handlePosition,
handleRef,
hasFocus,
onKeyDown,
setHasFocus,
sliderId: id,
sliderMax: max,
sliderMin: min,
value,
disabled: !!disabled,
isVertical,
orientation,
trackPercent,
trackRef,
trackHighlightStyle,
updateValue,
};
// Slide events!
// We will try to use pointer events if they are supported to leverage
// setPointerCapture and releasePointerCapture. We'll fall back to separate
// mouse and touch events.
// TODO: This could be more concise
let removeMoveEvents = useRef<() => void>(noop);
let removeStartEvents = useRef<() => void>(noop);
let removeEndEvents = useRef<() => void>(noop);
// Store our event handlers in refs so we aren't attaching/detaching events
// on every render if the user doesn't useCallback
let appEvents = useRef({
onMouseMove,
onMouseDown,
onMouseUp,
onTouchStart,
onTouchEnd,
onTouchMove,
onPointerDown,
onPointerUp,
});
useIsomorphicLayoutEffect(() => {
appEvents.current.onMouseMove = onMouseMove;
appEvents.current.onMouseDown = onMouseDown;
appEvents.current.onMouseUp = onMouseUp;
appEvents.current.onTouchStart = onTouchStart;
appEvents.current.onTouchEnd = onTouchEnd;
appEvents.current.onTouchMove = onTouchMove;
appEvents.current.onPointerDown = onPointerDown;
appEvents.current.onPointerUp = onPointerUp;
}, [onMouseMove, onMouseDown, onMouseUp, onTouchStart, onTouchEnd, onTouchMove, onPointerDown, onPointerUp]);
let handleSlideStart = useEventCallback((event: SomePointerEvent) => {
if (isRightClick(event)) return;
if (disabled) {
pointerDownRef.current = false;
return;
}
pointerDownRef.current = true;
if ((event as TouchEvent).changedTouches) {
// Prevent scrolling for touch events
event.preventDefault();
let touch = (event as TouchEvent).changedTouches?.[0];
if (touch != null) {
touchId.current = touch.identifier;
}
}
let newValue = getNewValueFromEvent(event);
if (newValue == null) {
return;
}
handleRef.current?.focus();
updateValue(newValue);
removeMoveEvents.current = addMoveListener();
removeEndEvents.current = addEndListener();
});
let setPointerCapture = useEventCallback((event: PointerEvent) => {
if (isRightClick(event)) return;
if (disabled) {
pointerDownRef.current = false;
return;
}
pointerDownRef.current = true;
sliderRef.current?.setPointerCapture(event.pointerId);
});
let releasePointerCapture = useEventCallback((event: PointerEvent) => {
if (isRightClick(event)) return;
sliderRef.current?.releasePointerCapture(event.pointerId);
pointerDownRef.current = false;
});
let handlePointerMove = useEventCallback((event: SomePointerEvent) => {
if (disabled || !pointerDownRef.current) {
pointerDownRef.current = false;
return;
}
let newValue = getNewValueFromEvent(event);
if (newValue == null) {
return;
}
updateValue(newValue);
});
let handleSlideStop = useEventCallback((event: SomePointerEvent) => {
if (isRightClick(event)) return;
pointerDownRef.current = false;
let newValue = getNewValueFromEvent(event);
if (newValue == null) {
return;
}
touchId.current = undefined;
removeMoveEvents.current();
removeEndEvents.current();
});
let addMoveListener = useCallback(() => {
let ownerDocument = getOwnerDocument(sliderRef.current!) || document;
let touchListener = wrapEvent(
appEvents.current.onTouchMove,
handlePointerMove
);
let mouseListener = wrapEvent(
appEvents.current.onMouseMove,
handlePointerMove
);
ownerDocument.addEventListener("touchmove", touchListener);
ownerDocument.addEventListener("mousemove", mouseListener);
return () => {
ownerDocument.removeEventListener("touchmove", touchListener);
ownerDocument.removeEventListener("mousemove", mouseListener);
};
}, [handlePointerMove]);
let addEndListener = useCallback(() => {
let ownerDocument = getOwnerDocument(sliderRef.current!) || document;
let pointerListener = wrapEvent(
appEvents.current.onPointerUp,
releasePointerCapture
);
let touchListener = wrapEvent(
appEvents.current.onTouchEnd,
handleSlideStop
);
let mouseListener = wrapEvent(appEvents.current.onMouseUp, handleSlideStop);
if ("PointerEvent" in window) {
ownerDocument.addEventListener("pointerup", pointerListener);
}
ownerDocument.addEventListener("touchend", touchListener);
ownerDocument.addEventListener("mouseup", mouseListener);
return () => {
if ("PointerEvent" in window) {
ownerDocument.removeEventListener("pointerup", pointerListener);
}
ownerDocument.removeEventListener("touchend", touchListener);
ownerDocument.removeEventListener("mouseup", mouseListener);
};
}, [handleSlideStop, releasePointerCapture]);
let addStartListener = useCallback(() => {
let touchListener = wrapEvent(
appEvents.current.onTouchStart,
handleSlideStart
);
let mouseListener = wrapEvent(
appEvents.current.onMouseDown,
handleSlideStart
);
let pointerListener = wrapEvent(
appEvents.current.onPointerDown,
setPointerCapture
);
// e.preventDefault is ignored by React's synthetic touchStart event, so
// we attach the listener directly to the DOM node
// https://github.com/facebook/react/issues/9809#issuecomment-413978405
sliderRef.current!.addEventListener("touchstart", touchListener);
sliderRef.current!.addEventListener("mousedown", mouseListener);
if ("PointerEvent" in window) {
sliderRef.current!.addEventListener("pointerdown", pointerListener);
}
return () => {
sliderRef.current!.removeEventListener("touchstart", touchListener);
sliderRef.current!.removeEventListener("mousedown", mouseListener);
if ("PointerEvent" in window) {
sliderRef.current!.removeEventListener("pointerdown", pointerListener);
}
};
}, [setPointerCapture, handleSlideStart]);
useEffect(() => {
removeStartEvents.current = addStartListener();
return () => {
removeStartEvents.current();
removeEndEvents.current();
removeMoveEvents.current();
};
}, [addStartListener]);
useEffect(() => checkStyles("slider"), []);
return (
<SliderContext.Provider value={ctx}>
<Comp
{...rest}
ref={ref}
data-reach-slider-input=""
data-disabled={disabled ? "" : undefined}
data-orientation={orientation}
tabIndex={-1}
>
{isFunction(children)
? children({
hasFocus,
id,
max,
min,
value,
ariaValueText,
valueText: ariaValueText, // TODO: Remove in 1.0
})
: children}
{name && (
// If the slider is used in a form we'll need an input field to
// capture the value. We'll assume this when the component is given a
// form field name (A `name` prop doesn't really make sense in any
// other context).
<input
type="hidden"
value={value}
name={name}
id={id && makeId("input", id)}
/>
)}
</Comp>
</SliderContext.Provider>
);
});
/**
* @see Docs https://reach.tech/slider#sliderinput-props
*/
export type SliderInputProps = Omit<SliderProps, "children"> & {
/**
* Slider expects `<SliderTrack>` as its child; The track will accept all
* additional slider sub-components as children. It can also accept a
* function/render prop as its child to expose some of its internal state
* variables.
*
* @see Docs https://reach.tech/slider#sliderinput-children
*/
children: React.ReactNode | SliderChildrenRender;
};
if (__DEV__) {
SliderInput.displayName = "SliderInput";
SliderInput.propTypes = {
...sliderPropTypes,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
};
}
export { SliderInput };
////////////////////////////////////////////////////////////////////////////////
/**
* SliderTrack
*
* @see Docs https://reach.tech/slider#slidertrack
*/
const SliderTrackImpl = forwardRefWithAs<SliderTrackProps>(function SliderTrack(
{ as: Comp = "div", children, style = {}, ...props },
forwardedRef
) {
const { disabled, orientation, trackRef } = useSliderContext();
const ref = useForkedRef(trackRef, forwardedRef);
return (
<Comp
ref={ref}
style={{ ...style, position: "relative" }}
{...props}
data-reach-slider-track=""
data-disabled={disabled ? "" : undefined}
data-orientation={orientation}
>
{children}
</Comp>
);
});
if (__DEV__) {
SliderTrackImpl.displayName = "SliderTrack";
SliderTrackImpl.propTypes = {
children: PropTypes.node.isRequired,
};
}
const SliderTrack = memoWithAs(SliderTrackImpl);
/**
* @see Docs https://reach.tech/slider#slidertrack-props
*/
export type SliderTrackProps = {
/**
* `SliderTrack` expects `<SliderHandle>`, at minimum, for the Slider to
* function. All other Slider subcomponents should be passed as children
* inside the `SliderTrack`.
*
* @see Docs https://reach.tech/slider#slidertrack-children
*/
children: React.ReactNode;
};
if (__DEV__) {
SliderTrack.displayName = "SliderTrack";
}
export { SliderTrack };
////////////////////////////////////////////////////////////////////////////////
/**
* SliderTrackHighlight
*
* The (typically) highlighted portion of the track that represents the space
* between the slider's `min` value and its current value.
*
* TODO: Consider renaming to `SliderTrackProgress`
*
* @see Docs https://reach.tech/slider#slidertrackhighlight
*/
const SliderTrackHighlightImpl = forwardRefWithAs<SliderTrackHighlightProps>(
function SliderTrackHighlight(
{ as: Comp = "div", children, style = {}, ...props },
forwardedRef
) {
let { disabled, orientation, trackHighlightStyle } = useSliderContext();
return (
<Comp
ref={forwardedRef}
style={{ position: "absolute", ...trackHighlightStyle, ...style }}
{...props}
data-reach-slider-track-highlight=""
data-disabled={disabled ? "" : undefined}
data-orientation={orientation}
/>
);
}
);
if (__DEV__) {
SliderTrackHighlightImpl.displayName = "SliderTrackHighlight";
SliderTrackHighlightImpl.propTypes = {};
}
const SliderTrackHighlight = memoWithAs(SliderTrackHighlightImpl);
/**
* `SliderTrackHighlight` accepts any props that a HTML div component accepts.
* `SliderTrackHighlight` will not accept or render any children.
*
* @see Docs https://reach.tech/slider#slidertrackhighlight-props
*/
export type SliderTrackHighlightProps = {};
if (__DEV__) {
SliderTrackHighlight.displayName = "SliderTrackHighlight";
}
export { SliderTrackHighlight };
////////////////////////////////////////////////////////////////////////////////
/**
* SliderHandle
*
* The handle that the user drags along the track to set the slider value.
*
* @see Docs https://reach.tech/slider#sliderhandle
*/
const SliderHandleImpl = forwardRefWithAs<SliderHandleProps>(
function SliderHandle(
{
// min,
// max,
as: Comp = "div",
onBlur,
onFocus,
style = {},
onKeyDown,
...props
},
forwardedRef
) {
const {
ariaLabel,
ariaLabelledBy,
ariaValueText,
disabled,
handlePosition,
handleRef,
isVertical,
handleKeyDown,
orientation,
setHasFocus,
sliderMin,
sliderMax,
value,
} = useSliderContext();
const ref = useForkedRef(handleRef, forwardedRef);
return (
<Comp
aria-disabled={disabled || undefined}
// If the slider has a visible label, it is referenced by
// `aria-labelledby` on the slider element. Otherwise, the slider
// element has a label provided by `aria-label`.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-label={ariaLabel}
aria-labelledby={ariaLabel ? undefined : ariaLabelledBy}
// If the slider is vertically oriented, it has `aria-orientation` set
// to vertical. The default value of `aria-orientation` for a slider is
// horizontal.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-orientation={orientation}
// The slider element has the `aria-valuemax` property set to a decimal
// value representing the maximum allowed value of the slider.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-valuemax={sliderMax}
// The slider element has the `aria-valuemin` property set to a decimal
// value representing the minimum allowed value of the slider.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-valuemin={sliderMin}
// The slider element has the `aria-valuenow` property set to a decimal
// value representing the current value of the slider.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-valuenow={value}
// If the value of `aria-valuenow` is not user-friendly, e.g., the day
// of the week is represented by a number, the `aria-valuetext` property
// is set to a string that makes the slider value understandable, e.g.,
// "Monday".
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
aria-valuetext={ariaValueText}
// The element serving as the focusable slider control has role
// `slider`.
// https://www.w3.org/TR/wai-aria-practices-1.2/#slider_roles_states_props
role="slider"
tabIndex={disabled ? -1 : 0}
{...props}
data-reach-slider-handle=""
ref={ref}
onBlur={wrapEvent(onBlur, () => {
setHasFocus(false);
})}
onFocus={wrapEvent(onFocus, () => {
setHasFocus(true);
})}
onKeyDown={wrapEvent(onKeyDown, handleKeyDown)}
style={{
position: "absolute",
...(isVertical
? { bottom: handlePosition }
: { left: handlePosition }),
...style,
}}
/>
);
}
);
if (__DEV__) {
SliderHandleImpl.displayName = "SliderHandle";
SliderHandleImpl.propTypes = {};
}
const SliderHandle = memoWithAs(SliderHandleImpl);
/**
* `SliderTrackHighlight` accepts any props that a HTML div component accepts.
*
* @see Docs https://reach.tech/slider#sliderhandle-props
*/
export type SliderHandleProps = {};
if (__DEV__) {
SliderHandle.displayName = "SliderHandle";
}
export { SliderHandle };
////////////////////////////////////////////////////////////////////////////////
/**
* SliderMarker
*
* A fixed value marker. These can be used to illustrate a range of steps or
* highlight important points along the slider track.
*
* @see Docs https://reach.tech/slider#slidermarker
*/
const SliderMarkerImpl = forwardRefWithAs<SliderMarkerProps>(
function SliderMarker(
{ as: Comp = "div", children, style = {}, value, ...props },
forwardedRef
) {
const {
disabled,
isVertical,
orientation,
sliderMin,
sliderMax,
value: sliderValue,
} = useSliderContext();
let inRange = !(value < sliderMin || value > sliderMax);
let absoluteStartPosition = `${valueToPercent(
value,
sliderMin,
sliderMax
)}%`;
let state =
value < sliderValue
? "under-value"
: value === sliderValue
? "at-value"
: "over-value";
return inRange ? (
<Comp
ref={forwardedRef}
style={{
position: "absolute",
...(isVertical
? { bottom: absoluteStartPosition }
: { left: absoluteStartPosition }),
...style,
}}
{...props}
data-reach-slider-marker=""
data-disabled={disabled ? "" : undefined}
data-orientation={orientation}
data-state={state}
data-value={value}
children={children}
/>
) : null;
}
);
if (__DEV__) {
SliderMarkerImpl.displayName = "SliderMarker";
SliderMarkerImpl.propTypes = {
value: PropTypes.number.isRequired,
};
}
const SliderMarker = memoWithAs(SliderMarkerImpl);
/**
* @see Docs https://reach.tech/slider#slidermarker-props
*/
export type SliderMarkerProps = {
/**
* The value to denote where the marker should appear along the track.
*
* @see Docs https://reach.tech/slider#slidermarker-value
*/
value: number;
};
if (__DEV__) {
SliderMarker.displayName = "SliderMarker";
}
export { SliderMarker };
////////////////////////////////////////////////////////////////////////////////
function clamp(val: number, min: number, max: number) {
return val > max ? max : val < min ? min : val;
}
/**
* This handles the case when num is very small (0.00000001), js will turn
* this into 1e-8. When num is bigger than 1 or less than -1 it won't get
* converted to this notation so it's fine.
*
* @param num
* @see https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Slider/Slider.js#L69
*/
function getDecimalPrecision(num: number) {
if (Math.abs(num) < 1) {
const parts = num.toExponential().split("e-");
const matissaDecimalPart = parts[0].split(".")[1];
return (
(matissaDecimalPart ? matissaDecimalPart.length : 0) +
parseInt(parts[1], 10)
);
}
const decimalPart = num.toString().split(".")[1];
return decimalPart ? decimalPart.length : 0;
}
function percentToValue(percent: number, min: number, max: number) {
return (max - min) * percent + min;
}
function roundValueToStep(value: number, step: number, min: number) {
let nearest = Math.round((value - min) / step) * step + min;
return Number(nearest.toFixed(getDecimalPrecision(step)));
}
function getPointerPosition(event: SomePointerEvent, touchId: TouchIdRef) {
if (touchId.current !== undefined && (event as TouchEvent).changedTouches) {
for (let i = 0; i < (event as TouchEvent).changedTouches.length; i += 1) {
const touch = (event as TouchEvent).changedTouches[i];
if (touch.identifier === touchId.current) {
return {
x: touch.clientX,
y: touch.clientY,
};
}
}
return false;
}
return {
x: (event as PointerEvent | MouseEvent).clientX,
y: (event as PointerEvent | MouseEvent).clientY,
};
}
function getNewValue(
handlePosition:
| {
x: number;
y: number;
}
| false,
track: HTMLElement | null,
props: {
orientation: SliderOrientation;
min: number;
max: number;
step?: number;
}
) {
let { orientation, min, max, step } = props;
if (!track || !handlePosition) {
return null;
}
let { left, width, bottom, height } = track.getBoundingClientRect();
let isVertical = orientation === SliderOrientation.Vertical;
let diff = isVertical ? bottom - handlePosition.y : handlePosition.x - left;
let percent = diff / (isVertical ? height : width);
let newValue = percentToValue(percent, min, max);
return clamp(
step ? roundValueToStep(newValue, step, min) : newValue,
min,
max
);
}
function useDimensions(ref: React.RefObject<HTMLElement | null>) {
const [{ width, height }, setDimensions] = useState({ width: 0, height: 0 });
// Many existing `useDimensions` type hooks will use `getBoundingClientRect`
// getBoundingClientRect does not work here when borders are applied.
// getComputedStyle is not as performant so we may want to create a utility to
// check for any conflicts with box sizing first and only use
// `getComputedStyle` if neccessary.
/* const { width, height } = ref.current
? ref.current.getBoundingClientRect()
: 0; */
useIsomorphicLayoutEffect(() => {
if (ref.current) {
const { height: _newHeight, width: _newWidth } = window.getComputedStyle(
ref.current
);
let newHeight = parseFloat(_newHeight);
let newWidth = parseFloat(_newWidth);
if (newHeight !== height || newWidth !== width) {
setDimensions({ height: newHeight, width: newWidth });
}
}
}, [ref, width, height]);
return { ref, width, height };
}
function valueToPercent(value: number, min: number, max: number) {
return ((value - min) * 100) / (max - min);
}
////////////////////////////////////////////////////////////////////////////////
// Types
type TrackRef = React.RefObject<HTMLDivElement | null>;
type HandleRef = React.RefObject<HTMLDivElement | null>;
type SliderRef = React.RefObject<HTMLDivElement | null>;
type TouchIdRef = React.MutableRefObject<number | undefined>;
type SomePointerEvent = TouchEvent | MouseEvent;
interface ISliderContext {
ariaLabel: string | undefined;
ariaLabelledBy: string | undefined;
ariaValueText: string | undefined;
handleDimensions: {
width: number;
height: number;
};
handlePosition: string;
handleRef: HandleRef;
hasFocus: boolean;
onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void;
handleKeyDown: (event: React.KeyboardEvent<HTMLDivElement>) => void;
setHasFocus: React.Dispatch<React.SetStateAction<boolean>>;
sliderId: string | undefined;
sliderMax: number;
sliderMin: number;
value: number;
disabled: boolean;
isVertical: boolean;
orientation: SliderOrientation;
trackPercent: number;
trackRef: TrackRef;
trackHighlightStyle: React.CSSProperties;
updateValue: (newValue: any) => void;
}
type SliderChildrenRender = (props: {
ariaValueText?: string | undefined;
hasFocus?: boolean;
id?: string | undefined;
sliderId?: string | undefined;
max?: number;
min?: number;
value?: number;
valueText?: string | undefined; // TODO: Remove in 1.0
}) => JSX.Element;
| {
"pile_set_name": "Github"
} |
---
__openshift_logging_fluentd_image_prefix: "{{ openshift_logging_image_prefix | default('registry.access.redhat.com/openshift3/') }}"
__openshift_logging_fluentd_image_version: "{{ openshift_logging_image_version | default (openshift_image_tag) }}"
| {
"pile_set_name": "Github"
} |
// MESSAGE DEBUG_VECT PACKING
#define MAVLINK_MSG_ID_DEBUG_VECT 250
typedef struct __mavlink_debug_vect_t {
uint64_t time_usec; ///< Timestamp
float x; ///< x
float y; ///< y
float z; ///< z
char name[10]; ///< Name
} mavlink_debug_vect_t;
#define MAVLINK_MSG_ID_DEBUG_VECT_LEN 30
#define MAVLINK_MSG_ID_250_LEN 30
#define MAVLINK_MSG_DEBUG_VECT_FIELD_NAME_LEN 10
#define MAVLINK_MESSAGE_INFO_DEBUG_VECT \
{ \
"DEBUG_VECT", \
5, \
{ \
{ "time_usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_debug_vect_t, time_usec) }, \
{ "x", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_debug_vect_t, x) }, \
{ "y", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_debug_vect_t, y) }, \
{ "z", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_debug_vect_t, z) }, \
{ "name", NULL, MAVLINK_TYPE_CHAR, 10, 20, offsetof(mavlink_debug_vect_t, name) }, \
} \
}
/**
* @brief Pack a debug_vect message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param name Name
* @param time_usec Timestamp
* @param x x
* @param y y
* @param z z
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_debug_vect_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t *msg,
const char *name, uint64_t time_usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[30];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
_mav_put_char_array(buf, 20, name, 10);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 30);
#else
mavlink_debug_vect_t packet;
packet.time_usec = time_usec;
packet.x = x;
packet.y = y;
packet.z = z;
mav_array_memcpy(packet.name, name, sizeof(char) * 10);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 30);
#endif
msg->msgid = MAVLINK_MSG_ID_DEBUG_VECT;
return mavlink_finalize_message(msg, system_id, component_id, 30, 49);
}
/**
* @brief Pack a debug_vect message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message was sent over
* @param msg The MAVLink message to compress the data into
* @param name Name
* @param time_usec Timestamp
* @param x x
* @param y y
* @param z z
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_debug_vect_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t *msg,
const char *name, uint64_t time_usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[30];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
_mav_put_char_array(buf, 20, name, 10);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 30);
#else
mavlink_debug_vect_t packet;
packet.time_usec = time_usec;
packet.x = x;
packet.y = y;
packet.z = z;
mav_array_memcpy(packet.name, name, sizeof(char) * 10);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 30);
#endif
msg->msgid = MAVLINK_MSG_ID_DEBUG_VECT;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, 30, 49);
}
/**
* @brief Encode a debug_vect struct into a message
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param debug_vect C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_debug_vect_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t *msg, const mavlink_debug_vect_t *debug_vect)
{
return mavlink_msg_debug_vect_pack(system_id, component_id, msg, debug_vect->name, debug_vect->time_usec, debug_vect->x, debug_vect->y, debug_vect->z);
}
/**
* @brief Send a debug_vect message
* @param chan MAVLink channel to send the message
*
* @param name Name
* @param time_usec Timestamp
* @param x x
* @param y y
* @param z z
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_debug_vect_send(mavlink_channel_t chan, const char *name, uint64_t time_usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[30];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
_mav_put_char_array(buf, 20, name, 10);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DEBUG_VECT, buf, 30, 49);
#else
mavlink_debug_vect_t packet;
packet.time_usec = time_usec;
packet.x = x;
packet.y = y;
packet.z = z;
mav_array_memcpy(packet.name, name, sizeof(char) * 10);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DEBUG_VECT, (const char *)&packet, 30, 49);
#endif
}
#endif // ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
// MESSAGE DEBUG_VECT UNPACKING
/**
* @brief Get field name from debug_vect message
*
* @return Name
*/
static inline uint16_t mavlink_msg_debug_vect_get_name(const mavlink_message_t *msg, char *name)
{
return _MAV_RETURN_char_array(msg, name, 10, 20);
}
/**
* @brief Get field time_usec from debug_vect message
*
* @return Timestamp
*/
static inline uint64_t mavlink_msg_debug_vect_get_time_usec(const mavlink_message_t *msg)
{
return _MAV_RETURN_uint64_t(msg, 0);
}
/**
* @brief Get field x from debug_vect message
*
* @return x
*/
static inline float mavlink_msg_debug_vect_get_x(const mavlink_message_t *msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Get field y from debug_vect message
*
* @return y
*/
static inline float mavlink_msg_debug_vect_get_y(const mavlink_message_t *msg)
{
return _MAV_RETURN_float(msg, 12);
}
/**
* @brief Get field z from debug_vect message
*
* @return z
*/
static inline float mavlink_msg_debug_vect_get_z(const mavlink_message_t *msg)
{
return _MAV_RETURN_float(msg, 16);
}
/**
* @brief Decode a debug_vect message into a struct
*
* @param msg The message to decode
* @param debug_vect C-struct to decode the message contents into
*/
static inline void mavlink_msg_debug_vect_decode(const mavlink_message_t *msg, mavlink_debug_vect_t *debug_vect)
{
#if MAVLINK_NEED_BYTE_SWAP
debug_vect->time_usec = mavlink_msg_debug_vect_get_time_usec(msg);
debug_vect->x = mavlink_msg_debug_vect_get_x(msg);
debug_vect->y = mavlink_msg_debug_vect_get_y(msg);
debug_vect->z = mavlink_msg_debug_vect_get_z(msg);
mavlink_msg_debug_vect_get_name(msg, debug_vect->name);
#else
memcpy(debug_vect, _MAV_PAYLOAD(msg), 30);
#endif
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011, Ben Langmead <[email protected]>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bowtie 2 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 Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "edit.h"
using namespace std;
/**
* Print a single edit to a std::ostream. Format is
* (pos):(ref chr)>(read chr). Where 'pos' is an offset from the 5'
* end of the read, and the ref and read chrs are expressed w/r/t the
* Watson strand.
*/
ostream& operator<< (ostream& os, const Edit& e) {
os << e.pos << ":" << (char)e.chr << ">" << (char)e.qchr;
return os;
}
/**
* Print a list of edits to a std::ostream, separated by commas.
*/
void Edit::print(ostream& os, const EList<Edit>& edits, char delim) {
for(size_t i = 0; i < edits.size(); i++) {
os << edits[i];
if(i < edits.size()-1) os << delim;
}
}
/**
* Flip all the edits.pos fields so that they're with respect to
* the other end of the read (of length 'sz').
*/
void Edit::invertPoss(
EList<Edit>& edits,
size_t sz,
size_t ei,
size_t en,
bool sort)
{
// Invert elements
size_t ii = 0;
for(size_t i = ei; i < ei + en/2; i++) {
Edit tmp = edits[i];
edits[i] = edits[ei + en - ii - 1];
edits[ei + en - ii - 1] = tmp;
ii++;
}
for(size_t i = ei; i < ei + en; i++) {
assert(edits[i].pos < sz ||
(edits[i].isReadGap() && edits[i].pos == sz));
// Adjust pos
edits[i].pos =
(uint32_t)(sz - edits[i].pos - (edits[i].isReadGap() ? 0 : 1));
// Adjust pos2
if(edits[i].isReadGap()) {
int64_t pos2diff = (int64_t)(uint64_t)edits[i].pos2 - (int64_t)((uint64_t)std::numeric_limits<uint32_t>::max() >> 1);
int64_t pos2new = (int64_t)(uint64_t)edits[i].pos2 - 2*pos2diff;
assert(pos2diff == 0 || (uint32_t)pos2new != (std::numeric_limits<uint32_t>::max() >> 1));
edits[i].pos2 = (uint32_t)pos2new;
}
}
if(sort) {
// Edits might not necessarily be in same order after inversion
edits.sortPortion(ei, en);
#ifndef NDEBUG
for(size_t i = ei + 1; i < ei + en; i++) {
assert_geq(edits[i].pos, edits[i-1].pos);
}
#endif
}
}
/**
* For now, we pretend that the alignment is in the forward orientation
* and that the Edits are listed from left- to right-hand side.
*/
void Edit::printQAlign(
std::ostream& os,
const BTDnaString& read,
const EList<Edit>& edits)
{
printQAlign(os, "", read, edits);
}
/**
* For now, we pretend that the alignment is in the forward orientation
* and that the Edits are listed from left- to right-hand side.
*/
void Edit::printQAlignNoCheck(
std::ostream& os,
const BTDnaString& read,
const EList<Edit>& edits)
{
printQAlignNoCheck(os, "", read, edits);
}
/**
* For now, we pretend that the alignment is in the forward orientation
* and that the Edits are listed from left- to right-hand side.
*/
void Edit::printQAlign(
std::ostream& os,
const char *prefix,
const BTDnaString& read,
const EList<Edit>& edits)
{
size_t eidx = 0;
os << prefix;
// Print read
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << '-';
} else if(edits[eidx].isRefGap()) {
del = true;
assert_eq((int)edits[eidx].qchr, read.toChar(i));
os << read.toChar(i);
} else {
mm = true;
assert(edits[eidx].isMismatch());
assert_eq((int)edits[eidx].qchr, read.toChar(i));
os << (char)edits[eidx].qchr;
}
eidx++;
}
if(!del && !mm) os << read.toChar(i);
}
os << endl;
os << prefix;
eidx = 0;
// Print match bars
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << ' ';
} else if(edits[eidx].isRefGap()) {
del = true;
os << ' ';
} else {
mm = true;
assert(edits[eidx].isMismatch());
os << ' ';
}
eidx++;
}
if(!del && !mm) os << '|';
}
os << endl;
os << prefix;
eidx = 0;
// Print reference
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << (char)edits[eidx].chr;
} else if(edits[eidx].isRefGap()) {
del = true;
os << '-';
} else {
mm = true;
assert(edits[eidx].isMismatch());
os << (char)edits[eidx].chr;
}
eidx++;
}
if(!del && !mm) os << read.toChar(i);
}
os << endl;
}
/**
* For now, we pretend that the alignment is in the forward orientation
* and that the Edits are listed from left- to right-hand side.
*/
void Edit::printQAlignNoCheck(
std::ostream& os,
const char *prefix,
const BTDnaString& read,
const EList<Edit>& edits)
{
size_t eidx = 0;
os << prefix;
// Print read
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << '-';
} else if(edits[eidx].isRefGap()) {
del = true;
os << read.toChar(i);
} else {
mm = true;
os << (char)edits[eidx].qchr;
}
eidx++;
}
if(!del && !mm) os << read.toChar(i);
}
os << endl;
os << prefix;
eidx = 0;
// Print match bars
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << ' ';
} else if(edits[eidx].isRefGap()) {
del = true;
os << ' ';
} else {
mm = true;
os << ' ';
}
eidx++;
}
if(!del && !mm) os << '|';
}
os << endl;
os << prefix;
eidx = 0;
// Print reference
for(size_t i = 0; i < read.length(); i++) {
bool del = false, mm = false;
while(eidx < edits.size() && edits[eidx].pos == i) {
if(edits[eidx].isReadGap()) {
os << (char)edits[eidx].chr;
} else if(edits[eidx].isRefGap()) {
del = true;
os << '-';
} else {
mm = true;
os << (char)edits[eidx].chr;
}
eidx++;
}
if(!del && !mm) os << read.toChar(i);
}
os << endl;
}
/**
* Sort the edits in the provided list.
*/
void Edit::sort(EList<Edit>& edits) {
edits.sort(); // simple!
}
/**
* Given a read string and some edits, generate and append the corresponding
* reference string to 'ref'. If read aligned to the Watson strand, the caller
* should pass the original read sequence and original edits. If a read
* aligned to the Crick strand, the caller should pass the reverse complement
* of the read and a version of the edits list that has had Edit:invertPoss
* called on it to cause edits to be listed in 3'-to-5' order.
*/
void Edit::toRef(
const BTDnaString& read,
const EList<Edit>& edits,
BTDnaString& ref,
bool fw,
size_t trim5,
size_t trim3)
{
// edits should be sorted
size_t eidx = 0;
// Print reference
const size_t rdlen = read.length();
size_t trimBeg = fw ? trim5 : trim3;
size_t trimEnd = fw ? trim3 : trim5;
assert(Edit::repOk(edits, read, fw, trim5, trim3));
if(!fw) {
invertPoss(const_cast<EList<Edit>&>(edits), read.length()-trimBeg-trimEnd, false);
}
for(size_t i = 0; i < rdlen; i++) {
ASSERT_ONLY(int c = read[i]);
assert_range(0, 4, c);
bool del = false, mm = false;
bool append = i >= trimBeg && rdlen - i -1 >= trimEnd;
bool appendIns = i >= trimBeg && rdlen - i >= trimEnd;
while(eidx < edits.size() && edits[eidx].pos+trimBeg == i) {
if(edits[eidx].isReadGap()) {
// Inserted characters come before the position's
// character
if(appendIns) {
ref.appendChar((char)edits[eidx].chr);
}
} else if(edits[eidx].isRefGap()) {
assert_eq("ACGTN"[c], edits[eidx].qchr);
del = true;
} else {
mm = true;
assert(edits[eidx].isMismatch());
assert(edits[eidx].qchr != edits[eidx].chr || edits[eidx].qchr == 'N');
assert_eq("ACGTN"[c], edits[eidx].qchr);
if(append) {
ref.appendChar((char)edits[eidx].chr);
}
}
eidx++;
}
if(!del && !mm) {
if(append) {
ref.append(read[i]);
}
}
}
if(trimEnd == 0) {
while(eidx < edits.size()) {
assert_gt(rdlen, edits[eidx].pos);
if(edits[eidx].isReadGap()) {
ref.appendChar((char)edits[eidx].chr);
}
eidx++;
}
}
if(!fw) {
invertPoss(const_cast<EList<Edit>&>(edits), read.length()-trimBeg-trimEnd, false);
}
}
#ifndef NDEBUG
/**
* Check that the edit is internally consistent.
*/
bool Edit::repOk() const {
assert(inited());
// Ref and read characters cannot be the same unless they're both Ns
assert(qchr != chr || qchr == 'N');
// Type must match characters
assert(isRefGap() || chr != '-');
assert(isReadGap() || qchr != '-');
assert(!isMismatch() || (qchr != '-' && chr != '-'));
return true;
}
/**
* Given a list of edits and a DNA string representing the query
* sequence, check that the edits are consistent with respect to the
* query.
*/
bool Edit::repOk(
const EList<Edit>& edits,
const BTDnaString& s,
bool fw,
size_t trimBeg,
size_t trimEnd)
{
if(!fw) {
invertPoss(const_cast<EList<Edit>&>(edits), s.length()-trimBeg-trimEnd, false);
swap(trimBeg, trimEnd);
}
for(size_t i = 0; i < edits.size(); i++) {
const Edit& e = edits[i];
size_t pos = e.pos;
if(i > 0) {
assert_geq(pos, edits[i-1].pos);
}
bool del = false, mm = false;
while(i < edits.size() && edits[i].pos == pos) {
const Edit& ee = edits[i];
assert_lt(ee.pos, s.length());
if(ee.qchr != '-') {
assert(ee.isRefGap() || ee.isMismatch());
assert_eq((int)ee.qchr, s.toChar(ee.pos+trimBeg));
}
if(ee.isMismatch()) {
assert(!mm);
mm = true;
assert(!del);
} else if(ee.isReadGap()) {
assert(!mm);
} else if(ee.isRefGap()) {
assert(!mm);
assert(!del);
del = true;
}
i++;
}
}
if(!fw) {
invertPoss(const_cast<EList<Edit>&>(edits), s.length()-trimBeg-trimEnd, false);
}
return true;
}
#endif
/**
* Merge second argument into the first. Assume both are sorted to
* begin with.
*/
void Edit::merge(EList<Edit>& dst, const EList<Edit>& src) {
size_t di = 0, si = 0;
while(di < dst.size()) {
if(src[si].pos < dst[di].pos) {
dst.insert(src[si], di);
si++; di++;
} else if(src[si].pos == dst[di].pos) {
// There can be two inserts at a given position, but we
// can't merge them because there's no way to know their
// order
assert(src[si].isReadGap() != dst[di].isReadGap());
if(src[si].isReadGap()) {
dst.insert(src[si], di);
si++; di++;
} else if(dst[di].isReadGap()) {
di++;
}
}
}
while(si < src.size()) dst.push_back(src[si++]);
}
/**
* Clip off some of the low-numbered positions.
*/
void Edit::clipLo(EList<Edit>& ed, size_t len, size_t amt) {
size_t nrm = 0;
for(size_t i = 0; i < ed.size(); i++) {
assert_lt(ed[i].pos, len);
if(ed[i].pos < amt) {
nrm++;
} else {
// Shift everyone else up
ed[i].pos -= (uint32_t)amt;
}
}
ed.erase(0, nrm);
}
/**
* Clip off some of the high-numbered positions.
*/
void Edit::clipHi(EList<Edit>& ed, size_t len, size_t amt) {
assert_leq(amt, len);
size_t max = len - amt;
size_t nrm = 0;
for(size_t i = 0; i < ed.size(); i++) {
size_t ii = ed.size() - i - 1;
assert_lt(ed[ii].pos, len);
if(ed[ii].pos > max) {
nrm++;
} else if(ed[ii].pos == max && !ed[ii].isReadGap()) {
nrm++;
} else {
break;
}
}
ed.resize(ed.size() - nrm);
}
| {
"pile_set_name": "Github"
} |
setup
{
create extension pg_pathman;
create table test_tbl(id int not null, val real);
insert into test_tbl select i, i from generate_series(1, 1000) as i;
select create_range_partitions('test_tbl', 'id', 1, 100, 10);
}
teardown
{
drop table test_tbl cascade;
drop extension pg_pathman;
}
session "s1"
step "s1_b" { begin; }
step "s1_c" { commit; }
step "s1_r" { rollback; }
step "s1_update" { update test_tbl set id = 2 where id = 1; }
session "s2"
step "s2_b" { begin; }
step "s2_c" { commit; }
step "s2_select_locked" { select * from test_tbl where id = 1 for share; }
step "s2_select" { select * from test_tbl where id = 1; }
permutation "s1_b" "s1_update" "s2_select" "s1_r"
permutation "s1_b" "s1_update" "s2_select_locked" "s1_r"
permutation "s1_b" "s1_update" "s2_select_locked" "s1_c"
| {
"pile_set_name": "Github"
} |
require 'carto/db/migration_helper'
include Carto::Db::MigrationHelper
migration(
Proc.new do
alter_table :user_multifactor_auths do
add_unique_constraint [:user_id, :type]
end
end,
Proc.new do
alter_table :user_multifactor_auths do
drop_constraint :user_multifactor_auths_user_id_type_key
end
end
)
| {
"pile_set_name": "Github"
} |
//! This submodule provides tls support for postgres.
//!
//! ### Example
//!
//! ```rust,no_run
//! use roa::{App, Context, throw};
//! use roa::http::StatusCode;
//! use roa_pg::{Client, connect_tls};
//! use roa_pg::ClientConfig;
//! use std::sync::Arc;
//! use std::error::Error;
//! use roa::query::query_parser;
//! use roa::preload::*;
//! use async_std::task::spawn;
//!
//! #[derive(Clone)]
//! struct State {
//! pg: Arc<Client>
//! }
//!
//! impl State {
//! pub async fn new(pg_url: &str) -> Result<Self, Box<dyn Error>> {
//! let (client, conn) = connect_tls(&pg_url.parse()?, ClientConfig::new()).await?;
//! spawn(conn);
//! Ok(Self {pg: Arc::new(client)})
//! }
//! }
//!
//! async fn query(ctx: &mut Context<State>) -> roa::Result {
//! let id: u32 = ctx.must_query("id")?.parse()?;
//! match ctx.pg.query_opt("SELECT * FROM user WHERE id=$1", &[&id]).await? {
//! Some(row) => {
//! let value: String = row.get(0);
//! ctx.write(value);
//! Ok(())
//! }
//! None => throw!(StatusCode::NOT_FOUND),
//! }
//! }
//!
//! #[async_std::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//! let url = "postgres://fred:secret@localhost/test";
//! let state = State::new(url).await?;
//! App::state(state)
//! .gate(query_parser)
//! .end(query)
//! .listen("127.0.0.1:0", |addr| {
//! println!("Server is listening on {}", addr)
//! })?.await?;
//! Ok(())
//! }
//! ```
pub use tokio_rustls::rustls::ClientConfig;
use async_std::net::TcpStream;
use bytes::{Buf, BufMut};
use roa::stream::AsyncStream;
use std::future::Future;
use std::io;
use std::mem::MaybeUninit;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_postgres::config::{Config, Host};
use tokio_postgres::tls::TlsConnect;
use tokio_postgres::tls::{self, ChannelBinding};
use tokio_postgres::{Client, Connection};
use tokio_rustls::client;
use tokio_rustls::TlsConnector;
use webpki::DNSNameRef;
/// Default port of postgres.
const DEFAULT_PORT: u16 = 5432;
/// Try to get TCP hostname from postgres config.
#[inline]
fn try_tcp_host(config: &Config) -> io::Result<&str> {
match config
.get_hosts()
.iter()
.filter_map(|host| {
if let Host::Tcp(value) = host {
Some(value)
} else {
None
}
})
.next()
{
Some(host) => Ok(host),
None => Err(io::Error::new(
io::ErrorKind::Other,
"At least one tcp hostname is required",
)),
}
}
/// Establish connection to postgres server by async_std::net::TcpStream.
#[inline]
async fn connect_stream(config: &Config) -> io::Result<TcpStream> {
let host = try_tcp_host(&config)?;
let port = config
.get_ports()
.iter()
.copied()
.next()
.unwrap_or(DEFAULT_PORT);
TcpStream::connect((host, port)).await
}
/// A TLS connector.
pub struct Connector<'a> {
connector: TlsConnector,
dns_name_ref: DNSNameRef<'a>,
}
impl<'a> Connector<'a> {
/// Construct a TLS connector.
#[inline]
pub fn new(connector: TlsConnector, dns_name_ref: DNSNameRef<'a>) -> Self {
Self {
connector,
dns_name_ref,
}
}
}
/// A wrapper for tokio_rustls::Connect.
pub struct Connect<IO>(tokio_rustls::Connect<IO>);
/// A wrapper for tokio_rustls::client::TlsStream.
pub struct TlsStream<IO>(client::TlsStream<IO>);
impl<IO> Future for Connect<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
type Output = io::Result<TlsStream<IO>>;
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let stream = futures::ready!(Pin::new(&mut self.0).poll(cx))?;
Poll::Ready(Ok(TlsStream(stream)))
}
}
impl<IO> AsyncRead for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
#[inline]
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.0.prepare_uninitialized_buffer(buf)
}
#[inline]
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.0).poll_read(cx, buf)
}
#[inline]
fn poll_read_buf<B: BufMut>(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut B,
) -> Poll<io::Result<usize>>
where
Self: Sized,
{
Pin::new(&mut self.0).poll_read_buf(cx, buf)
}
}
impl<IO> AsyncWrite for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
#[inline]
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.0).poll_write(cx, buf)
}
#[inline]
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_flush(cx)
}
#[inline]
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_shutdown(cx)
}
#[inline]
fn poll_write_buf<B: Buf>(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut B,
) -> Poll<io::Result<usize>>
where
Self: Sized,
{
Pin::new(&mut self.0).poll_write_buf(cx, buf)
}
}
impl<IO> tls::TlsStream for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
#[inline]
fn channel_binding(&self) -> ChannelBinding {
ChannelBinding::none()
}
}
impl<IO> TlsConnect<IO> for Connector<'_>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
type Stream = TlsStream<IO>;
type Error = io::Error;
type Future = Connect<IO>;
#[inline]
fn connect(self, stream: IO) -> Self::Future {
let Connector {
connector,
dns_name_ref,
} = self;
Connect(connector.connect(dns_name_ref, stream))
}
}
/// Connect to postgres server with tls.
///
/// ```rust
/// use roa_pg::{Client, connect_tls, ClientConfig};
/// use std::error::Error;
/// use async_std::task::spawn;
///
/// async fn play() -> Result<(), Box<dyn Error>> {
/// let url = "host=localhost user=postgres";
/// let (client, conn) = connect_tls(&url.parse()?, ClientConfig::new()).await?;
/// spawn(conn);
/// let row = client.query_one("SELECT * FROM user WHERE id=$1", &[&0]).await?;
/// let value: &str = row.get(0);
/// println!("value: {}", value);
/// Ok(())
/// }
/// ```
#[inline]
pub async fn connect_tls(
config: &Config,
tls_config: ClientConfig,
) -> io::Result<(
Client,
Connection<AsyncStream<TcpStream>, TlsStream<AsyncStream<TcpStream>>>,
)> {
let stream = connect_stream(config).await?;
let dns_name_ref = DNSNameRef::try_from_ascii_str(try_tcp_host(config)?)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
let connector = TlsConnector::from(Arc::new(tls_config));
config
.connect_raw(AsyncStream(stream), Connector::new(connector, dns_name_ref))
.await
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
}
| {
"pile_set_name": "Github"
} |
package jetbrains.mps.lang.constraints.migration;
/*Generated by MPS */
import jetbrains.mps.lang.migration.runtime.base.MigrationScriptBase;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.mps.openapi.module.SearchScope;
import jetbrains.mps.lang.smodel.query.runtime.CommandUtil;
import jetbrains.mps.project.EditableFilteringScope;
import jetbrains.mps.lang.smodel.query.runtime.QueryExecutionContext;
import java.util.Collection;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.migration.runtime.base.MigrationScriptReference;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SConcept;
import org.jetbrains.mps.openapi.language.SContainmentLink;
public class DropMigratedRefPresentationQueries extends MigrationScriptBase {
private final String description = "Drop migrated reference presentation queries";
public String getCaption() {
return description;
}
@Override
public boolean isRerunnable() {
return true;
}
public SNode execute(final SModule m) {
doExecute(m);
return null;
}
public void doExecute(final SModule m) {
{
SearchScope scope_yimnkw_a0e = CommandUtil.createScope(m);
final SearchScope scope_yimnkw_a0e_0 = new EditableFilteringScope(scope_yimnkw_a0e);
QueryExecutionContext context = new QueryExecutionContext() {
public SearchScope getDefaultSearchScope() {
return scope_yimnkw_a0e_0;
}
};
Collection<SNode> conceptConstraints = CommandUtil.instances(CommandUtil.selectScope(null, context), CONCEPTS.ConceptConstraints$Yt, false);
for (SNode rc : Sequence.fromIterable(SLinkOperations.collectMany(conceptConstraints, LINKS.referent$k0ZK))) {
if ((SLinkOperations.getTarget(rc, LINKS.presentation$VLnP) == null)) {
continue;
}
SNode migrated = new IAttributeDescriptor.NodeAttribute(CONCEPTS.RefPresentationMigrated$T3).get(SLinkOperations.getTarget(rc, LINKS.presentation$VLnP));
if ((migrated != null) && ListSequence.fromList(SLinkOperations.getChildren(migrated, LINKS.problems$4CuI)).isEmpty()) {
SNodeOperations.deleteNode(SLinkOperations.getTarget(rc, LINKS.presentation$VLnP));
}
}
}
}
public MigrationScriptReference getDescriptor() {
return new MigrationScriptReference(MetaAdapterFactory.getLanguage(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, "jetbrains.mps.lang.constraints"), 5);
}
private static final class CONCEPTS {
/*package*/ static final SConcept ConceptConstraints$Yt = MetaAdapterFactory.getConcept(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, 0x11a7208faaeL, "jetbrains.mps.lang.constraints.structure.ConceptConstraints");
/*package*/ static final SConcept RefPresentationMigrated$T3 = MetaAdapterFactory.getConcept(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, 0x583cd121d513aabeL, "jetbrains.mps.lang.constraints.structure.RefPresentationMigrated");
}
private static final class LINKS {
/*package*/ static final SContainmentLink presentation$VLnP = MetaAdapterFactory.getContainmentLink(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, 0x10b731752daL, 0x36367902116a44c4L, "presentation");
/*package*/ static final SContainmentLink problems$4CuI = MetaAdapterFactory.getContainmentLink(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, 0x583cd121d513aabeL, 0x4fd9d41024c6d474L, "problems");
/*package*/ static final SContainmentLink referent$k0ZK = MetaAdapterFactory.getContainmentLink(0x3f4bc5f5c6c14a28L, 0x8b10c83066ffa4a1L, 0x11a7208faaeL, 0x11a726c901bL, "referent");
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 5807e8a6b8d7b32459e070d288100f8b
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614
{
using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell;
/// <summary>An error response from Kusto.</summary>
[System.ComponentModel.TypeConverter(typeof(CloudErrorBodyTypeConverter))]
public partial class CloudErrorBody
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBody"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal CloudErrorBody(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Code, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Message, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Target, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody>(__y, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBodyTypeConverter.ConvertFrom));
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBody"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal CloudErrorBody(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Code, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Message, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Target, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBodyInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody>(__y, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBodyTypeConverter.ConvertFrom));
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBody"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new CloudErrorBody(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.CloudErrorBody"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new CloudErrorBody(content);
}
/// <summary>
/// Creates a new instance of <see cref="CloudErrorBody" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudErrorBody FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// An error response from Kusto.
[System.ComponentModel.TypeConverter(typeof(CloudErrorBodyTypeConverter))]
public partial interface ICloudErrorBody
{
}
} | {
"pile_set_name": "Github"
} |
## Task and Workflow
The core of Puma is `Task`. When you call `run` method, it actually uses `Workflow`, which is a group of tasks. `Workflow` is intended for cases where you need to run tasks for multiple projects.
```swif
run {
Build
Test
}
```
is the same as
```swift
let workflow = Workflow {
Build
Test
}
workflow.run()
```
## Task protocol
At the core of Puma sits the `Task` protocol, every task has a name, isEnabled flag and an action.
```swift
public typealias TaskCompletion = (Result<(), Error>) -> Void
public protocol Task: AnyObject {
var name: String { get }
var isEnabled: Bool { get }
func run(workflow: Workflow, completion: @escaping TaskCompletion)
}
```
The `workflow` parameter in `run` function acts as the context for all the tasks. When a task completes, you need to invoke `completion` so workflow know when to execute the next task in the pipeline.
### Disable a task
Some times you want to temporarily disable a task, every task in Puma needs to conform to `Task` protocol, and there is required `isEnabled` property where you can toggle off a task
```swift
Build {
$0.isEnabled = false
}
```
### Change name of a task
Every task has a default name, and this name is used when summarizing, to change the name of a task, assign a different name to `name` property
```swift
Build {
$0.name = "Build my awesome app"
}
```
## A bunch of tasks
Puma comes with a bunch of predefined tasks for popular actions, and they are sat in respective framework.
### Puma
The facade, which exposes convenient `run` function, and includes other frameworks
### PumaCore
Contains the core utilities, Task protocol and some core tasks
- [PrintWorkingDirectory](Tasks/PrintWorkingDirectory.md): prints the current working directory
- [RunScript](Tasks/RunScript.md): run arbitrary shell script
- [Sequence](Tasks/Sequence.md): run sub tasks in sequence
- [Concurrent](Tasks/Concurrent.md): run sub tasks in parallel
- [DownloadFile](Tasks/MoveFile.md): Download and save file
- [MoveFile](Tasks/MoveFile.md): Move file to another location
- [Slack](Tasks/Slack.md): send message as a bot to Slack
- [Wait](Tasks/Wait.md): wait for some time before moving to the next task
- [Retry](Tasks/Retry.md): retry a task n number of times.
### PumaiOS
Contains iOS related tasks.
- [Build](Tasks/Build.md): build workspace or project
- [Test](Tasks/Test.md): test workspace or project
- [Archive](Tasks/Archive.md): archive to xcarchive
- [ExportArchive](Tasks/ExportArchive.md): export archive into .ipa
- [Screenshot](Tasks/Screenshot.md): automate screenshot capturing, you can specify device, sdk, version, language and locale. It also supports test plan in Xcode 11
- [UploadApp](Tasks/UploadApp.md): upload, notarize, validate app with AppStore
- [ShowDestinations](Task/ShowDestinations.md): show all available destinations when building and testing
- [BootSimulator](Tasks/BootSimulator.md): boot simulator
- [UpdateSimulator](Tasks/UpdateSimulator.md): update statusbar of simulator. This is nifty before taking screenshots
- [DownloadMetadata](Tasks/DownloadMetadata.md): download metadata from AppStore Connect
### PumaAndroid
Contains Android related tasks. TBD
### PumaExtra
Contains extra tasks
- AppStoreConnect: interact with AppStore Connect
- AppDistribution: interact with Firebase AppDistribution
- Crashlytics: interact with Firebase Crashlytics
## A bunch of tasks
| {
"pile_set_name": "Github"
} |
var paths = document.getItems(Path, { selected: true });
var rasters = document.getItems(Raster, { selected: true });
var failed;
if (!rasters.length || !paths.length) {
Dialog.alert('Please select an image with paths on top of it\n' +
'and execute the script again.\n\nColorizer will colorize the paths according to\n' +
'the average color of the pixels behind them.');
} else {
var raster = rasters.first;
for (var i = 0, l = paths.length; i < l; i++) {
var path = paths[i];
if (path.bounds.intersects(raster.bounds)) {
path.fillColor = raster.getAverageColor(path);
} else {
failed = true;
}
}
if (failed) {
Dialog.alert('Colorizer colorizes paths according to\n' +
'the average color of the pixels behind them.\n\n' +
'Some path items were not on top of the image\n' +
'and weren\'t colored.');
}
} | {
"pile_set_name": "Github"
} |
julia 0.7
GeoInterface 0.4
BinaryProvider 0.3.3
| {
"pile_set_name": "Github"
} |
;; Base16 Atelier Dune (https://github.com/chriskempson/base16)
;; Scheme: Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)
;;; base16-atelierdune-dark-theme.el
;;; Code:
(deftheme base16-atelierdune-dark)
(let ((base00 "#20201d")
(base01 "#292824")
(base02 "#6e6b5e")
(base03 "#7d7a68")
(base04 "#999580")
(base05 "#a6a28c")
(base06 "#e8e4cf")
(base07 "#fefbec")
(base08 "#d73737")
(base09 "#b65611")
(base0A "#ae9513")
(base0B "#60ac39")
(base0C "#1fad83")
(base0D "#6684e1")
(base0E "#b854d4")
(base0F "#d43552"))
(custom-theme-set-faces
'base16-atelierdune-dark
;; Built-in stuff (Emacs 23)
`(border ((t (:background ,base03))))
`(border-glyph ((t (nil))))
`(cursor ((t (:background ,base08))))
`(default ((t (:background ,base00 :foreground ,base05))))
`(fringe ((t (:background ,base02))))
`(gui-element ((t (:background ,base03 :foreground ,base06))))
`(highlight ((t (:background ,base01))))
`(link ((t (:foreground ,base0D))))
`(link-visited ((t (:foreground ,base0E))))
`(minibuffer-prompt ((t (:foreground ,base0D))))
`(mode-line ((t (:background ,base02 :foreground ,base04 :box nil))))
`(mode-line-buffer-id ((t (:foreground ,base0E :background nil))))
`(mode-line-emphasis ((t (:foreground ,base06 :slant italic))))
`(mode-line-highlight ((t (:foreground ,base0E :box nil :weight bold))))
`(mode-line-inactive ((t (:background ,base01 :foreground ,base03 :box nil))))
`(region ((t (:background ,base02))))
`(secondary-selection ((t (:background ,base03))))
`(error ((t (:foreground ,base08 :weight bold))))
`(warning ((t (:foreground ,base09 :weight bold))))
`(success ((t (:foreground ,base0B :weight bold))))
`(header-line ((t (:inherit mode-line :foreground ,base0E :background nil))))
;; Font-lock stuff
`(font-lock-builtin-face ((t (:foreground ,base0C))))
`(font-lock-comment-delimiter-face ((t (:foreground ,base02))))
`(font-lock-comment-face ((t (:foreground ,base03))))
`(font-lock-constant-face ((t (:foreground ,base09))))
`(font-lock-doc-face ((t (:foreground ,base04))))
`(font-lock-doc-string-face ((t (:foreground ,base03))))
`(font-lock-function-name-face ((t (:foreground ,base0D))))
`(font-lock-keyword-face ((t (:foreground ,base0E))))
`(font-lock-negation-char-face ((t (:foreground ,base0B))))
`(font-lock-preprocessor-face ((t (:foreground ,base0D))))
`(font-lock-regexp-grouping-backslash ((t (:foreground ,base0A))))
`(font-lock-regexp-grouping-construct ((t (:foreground ,base0E))))
`(font-lock-string-face ((t (:foreground ,base0B))))
`(font-lock-type-face ((t (:foreground ,base0A))))
`(font-lock-variable-name-face ((t (:foreground ,base0C))))
`(font-lock-warning-face ((t (:foreground ,base08))))
;; linum-mode
`(linum ((t (:background ,base01 :foreground ,base03))))
;; Search
`(match ((t (:foreground ,base0D :background ,base01 :inverse-video t))))
`(isearch ((t (:foreground ,base0A :background ,base01 :inverse-video t))))
`(isearch-lazy-highlight-face ((t (:foreground ,base0C :background ,base01 :inverse-video t))))
`(isearch-fail ((t (:background ,base01 :inherit font-lock-warning-face :inverse-video t))))
;; Flymake
`(flymake-warnline ((t (:underline ,base09 :background ,base01))))
`(flymake-errline ((t (:underline ,base08 :background ,base01))))
;; Clojure errors
`(clojure-test-failure-face ((t (:background nil :inherit flymake-warnline))))
`(clojure-test-error-face ((t (:background nil :inherit flymake-errline))))
`(clojure-test-success-face ((t (:background nil :foreground nil :underline ,base0B))))
;; For Brian Carper's extended clojure syntax table
`(clojure-keyword ((t (:foreground ,base0A))))
`(clojure-parens ((t (:foreground ,base06))))
`(clojure-braces ((t (:foreground ,base0B))))
`(clojure-brackets ((t (:foreground ,base0A))))
`(clojure-double-quote ((t (:foreground ,base0C :background nil))))
`(clojure-special ((t (:foreground ,base0D))))
`(clojure-java-call ((t (:foreground ,base0E))))
;; MMM-mode
`(mmm-code-submode-face ((t (:background ,base03))))
`(mmm-comment-submode-face ((t (:inherit font-lock-comment-face))))
`(mmm-output-submode-face ((t (:background ,base03))))
;; rainbow-delimiters
`(rainbow-delimiters-depth-1-face ((t (:foreground ,base0E))))
`(rainbow-delimiters-depth-2-face ((t (:foreground ,base0D))))
`(rainbow-delimiters-depth-3-face ((t (:foreground ,base0C))))
`(rainbow-delimiters-depth-4-face ((t (:foreground ,base0B))))
`(rainbow-delimiters-depth-5-face ((t (:foreground ,base0A))))
`(rainbow-delimiters-depth-6-face ((t (:foreground ,base09))))
`(rainbow-delimiters-depth-7-face ((t (:foreground ,base08))))
`(rainbow-delimiters-depth-8-face ((t (:foreground ,base03))))
`(rainbow-delimiters-depth-9-face ((t (:foreground ,base05))))
;; IDO
`(ido-subdir ((t (:foreground ,base04))))
`(ido-first-match ((t (:foreground ,base09 :weight bold))))
`(ido-only-match ((t (:foreground ,base08 :weight bold))))
`(ido-indicator ((t (:foreground ,base08 :background ,base01))))
`(ido-virtual ((t (:foreground ,base04))))
;; which-function
`(which-func ((t (:foreground ,base0D :background nil :weight bold))))
`(trailing-whitespace ((t (:background ,base0C :foreground ,base0A))))
`(whitespace-empty ((t (:foreground ,base08 :background ,base0A))))
`(whitespace-hspace ((t (:background ,base04 :foreground ,base04))))
`(whitespace-indentation ((t (:background ,base0A :foreground ,base08))))
`(whitespace-line ((t (:background ,base01 :foreground ,base0F))))
`(whitespace-newline ((t (:foreground ,base04))))
`(whitespace-space ((t (:background ,base01 :foreground ,base04))))
`(whitespace-space-after-tab ((t (:background ,base0A :foreground ,base08))))
`(whitespace-space-before-tab ((t (:background ,base09 :foreground ,base08))))
`(whitespace-tab ((t (:background ,base04 :foreground ,base04))))
`(whitespace-trailing ((t (:background ,base08 :foreground ,base0A))))
;; Parenthesis matching (built-in)
`(show-paren-match ((t (:background ,base0D :foreground ,base03))))
`(show-paren-mismatch ((t (:background ,base09 :foreground ,base03))))
;; Parenthesis matching (mic-paren)
`(paren-face-match ((t (:foreground nil :background nil :inherit show-paren-match))))
`(paren-face-mismatch ((t (:foreground nil :background nil :inherit show-paren-mismatch))))
`(paren-face-no-match ((t (:foreground nil :background nil :inherit show-paren-mismatch))))
;; Parenthesis dimming (parenface)
`(paren-face ((t (:foreground ,base04 :background nil))))
`(sh-heredoc ((t (:foreground nil :inherit font-lock-string-face :weight normal))))
`(sh-quoted-exec ((t (:foreground nil :inherit font-lock-preprocessor-face))))
`(slime-highlight-edits-face ((t (:weight bold))))
`(slime-repl-input-face ((t (:weight normal :underline nil))))
`(slime-repl-prompt-face ((t (:underline nil :weight bold :foreground ,base0E))))
`(slime-repl-result-face ((t (:foreground ,base0B))))
`(slime-repl-output-face ((t (:foreground ,base0D :background ,base01))))
`(csv-separator-face ((t (:foreground ,base09))))
`(diff-added ((t (:foreground ,base0B))))
`(diff-changed ((t (:foreground ,base0A))))
`(diff-removed ((t (:foreground ,base08))))
`(diff-header ((t (:background ,base01))))
`(diff-file-header ((t (:background ,base02))))
`(diff-hunk-header ((t (:background ,base01 :foreground ,base0E))))
`(ediff-even-diff-A ((t (:foreground nil :background nil :inverse-video t))))
`(ediff-even-diff-B ((t (:foreground nil :background nil :inverse-video t))))
`(ediff-odd-diff-A ((t (:foreground ,base04 :background nil :inverse-video t))))
`(ediff-odd-diff-B ((t (:foreground ,base04 :background nil :inverse-video t))))
`(eldoc-highlight-function-argument ((t (:foreground ,base0B :weight bold))))
;; undo-tree
`(undo-tree-visualizer-default-face ((t (:foreground ,base06))))
`(undo-tree-visualizer-current-face ((t (:foreground ,base0B :weight bold))))
`(undo-tree-visualizer-active-branch-face ((t (:foreground ,base08))))
`(undo-tree-visualizer-register-face ((t (:foreground ,base0A))))
;; auctex
`(font-latex-bold-face ((t (:foreground ,base0B))))
`(font-latex-doctex-documentation-face ((t (:background ,base03))))
`(font-latex-italic-face ((t (:foreground ,base0B))))
`(font-latex-math-face ((t (:foreground ,base09))))
`(font-latex-sectioning-0-face ((t (:foreground ,base0A))))
`(font-latex-sectioning-1-face ((t (:foreground ,base0A))))
`(font-latex-sectioning-2-face ((t (:foreground ,base0A))))
`(font-latex-sectioning-3-face ((t (:foreground ,base0A))))
`(font-latex-sectioning-4-face ((t (:foreground ,base0A))))
`(font-latex-sectioning-5-face ((t (:foreground ,base0A))))
`(font-latex-sedate-face ((t (:foreground ,base0C))))
`(font-latex-string-face ((t (:foreground ,base0A))))
`(font-latex-verbatim-face ((t (:foreground ,base09))))
`(font-latex-warning-face ((t (:foreground ,base08))))
;; dired+
`(diredp-compressed-file-suffix ((t (:foreground ,base0D))))
`(diredp-dir-heading ((t (:foreground nil :background nil :inherit heading))))
`(diredp-dir-priv ((t (:foreground ,base0C :background nil))))
`(diredp-exec-priv ((t (:foreground ,base0D :background nil))))
`(diredp-executable-tag ((t (:foreground ,base08 :background nil))))
`(diredp-file-name ((t (:foreground ,base0A))))
`(diredp-file-suffix ((t (:foreground ,base0B))))
`(diredp-flag-mark-line ((t (:background nil :inherit highlight))))
`(diredp-ignored-file-name ((t (:foreground ,base04))))
`(diredp-link-priv ((t (:background nil :foreground ,base0E))))
`(diredp-mode-line-flagged ((t (:foreground ,base08))))
`(diredp-mode-line-marked ((t (:foreground ,base0B))))
`(diredp-no-priv ((t (:background nil))))
`(diredp-number ((t (:foreground ,base0A))))
`(diredp-other-priv ((t (:background nil :foreground ,base0E))))
`(diredp-rare-priv ((t (:foreground ,base08 :background nil))))
`(diredp-read-priv ((t (:foreground ,base0B :background nil))))
`(diredp-symlink ((t (:foreground ,base0E))))
`(diredp-write-priv ((t (:foreground ,base0A :background nil))))
;; term and ansi-term
`(term-color-black ((t (:foreground ,base02 :background ,base00))))
`(term-color-white ((t (:foreground ,base05 :background ,base07))))
`(term-color-red ((t (:foreground ,base08 :background ,base08))))
`(term-color-yellow ((t (:foreground ,base0A :background ,base0A))))
`(term-color-green ((t (:foreground ,base0B :background ,base0B))))
`(term-color-cyan ((t (:foreground ,base0C :background ,base0C))))
`(term-color-blue ((t (:foreground ,base0D :background ,base0D))))
`(term-color-magenta ((t (:foreground ,base0E :background ,base0E))))
;; Magit (a patch is pending in magit to make these standard upstream)
`(magit-branch ((t (:foreground ,base0B))))
`(magit-header ((t (:inherit nil :weight bold))))
`(magit-item-highlight ((t (:inherit highlight :background nil))))
`(magit-log-graph ((t (:foreground ,base04))))
`(magit-log-sha1 ((t (:foreground ,base0E))))
`(magit-log-head-label-bisect-bad ((t (:foreground ,base08))))
`(magit-log-head-label-bisect-good ((t (:foreground ,base0B))))
`(magit-log-head-label-default ((t (:foreground ,base0A :box nil :weight bold))))
`(magit-log-head-label-local ((t (:foreground ,base0D))))
`(magit-log-head-label-remote ((t (:foreground ,base0B))))
`(magit-log-head-label-tags ((t (:foreground ,base0C :box nil :weight bold))))
`(magit-section-title ((t (:inherit diff-hunk-header))))
`(link ((t (:foreground nil :underline t))))
`(widget-button ((t (:underline t))))
`(widget-field ((t (:background ,base03 :box (:line-width 1 :color ,base06)))))
;; Compilation (most faces politely inherit from 'success, 'error, 'warning etc.)
`(compilation-column-number ((t (:foreground ,base0A))))
`(compilation-line-number ((t (:foreground ,base0A))))
`(compilation-message-face ((t (:foreground ,base0D))))
`(compilation-mode-line-exit ((t (:foreground ,base0B))))
`(compilation-mode-line-fail ((t (:foreground ,base08))))
`(compilation-mode-line-run ((t (:foreground ,base0D))))
;; Grep
`(grep-context-face ((t (:foreground ,base04))))
`(grep-error-face ((t (:foreground ,base08 :weight bold :underline t))))
`(grep-hit-face ((t (:foreground ,base0D))))
`(grep-match-face ((t (:foreground nil :background nil :inherit match))))
`(regex-tool-matched-face ((t (:foreground nil :background nil :inherit match))))
;; mark-multiple
`(mm/master-face ((t (:inherit region :foreground nil :background nil))))
`(mm/mirror-face ((t (:inherit region :foreground nil :background nil))))
;; org-mode
`(org-agenda-structure ((t (:foreground ,base0E))))
`(org-agenda-date ((t (:foreground ,base0D :underline nil))))
`(org-agenda-done ((t (:foreground ,base0B))))
`(org-agenda-dimmed-todo-face ((t (:foreground ,base04))))
`(org-block ((t (:foreground ,base09))))
`(org-code ((t (:foreground ,base0A))))
`(org-column ((t (:background ,base03))))
`(org-column-title ((t (:inherit org-column :weight bold :underline t))))
`(org-date ((t (:foreground ,base0E :underline t))))
`(org-document-info ((t (:foreground ,base0C))))
`(org-document-info-keyword ((t (:foreground ,base0B))))
`(org-document-title ((t (:weight bold :foreground ,base09 :height 1.44))))
`(org-done ((t (:foreground ,base0B))))
`(org-ellipsis ((t (:foreground ,base04))))
`(org-footnote ((t (:foreground ,base0C))))
`(org-formula ((t (:foreground ,base08))))
`(org-hide ((t (:foreground ,base03))))
`(org-link ((t (:foreground ,base0D))))
`(org-scheduled ((t (:foreground ,base0B))))
`(org-scheduled-previously ((t (:foreground ,base09))))
`(org-scheduled-today ((t (:foreground ,base0B))))
`(org-special-keyword ((t (:foreground ,base09))))
`(org-table ((t (:foreground ,base0E))))
`(org-todo ((t (:foreground ,base08))))
`(org-upcoming-deadline ((t (:foreground ,base09))))
`(org-warning ((t (:weight bold :foreground ,base08))))
`(markdown-url-face ((t (:inherit link))))
`(markdown-link-face ((t (:foreground ,base0D :underline t))))
`(hl-sexp-face ((t (:background ,base03))))
`(highlight-80+ ((t (:background ,base03))))
;; Python-specific overrides
`(py-builtins-face ((t (:foreground ,base09 :weight normal))))
;; js2-mode
`(js2-warning-face ((t (:underline ,base09))))
`(js2-error-face ((t (:foreground nil :underline ,base08))))
`(js2-external-variable-face ((t (:foreground ,base0E))))
`(js2-function-param-face ((t (:foreground ,base0D))))
`(js2-instance-member-face ((t (:foreground ,base0D))))
`(js2-private-function-call-face ((t (:foreground ,base08))))
;; js3-mode
`(js3-warning-face ((t (:underline ,base09))))
`(js3-error-face ((t (:foreground nil :underline ,base08))))
`(js3-external-variable-face ((t (:foreground ,base0E))))
`(js3-function-param-face ((t (:foreground ,base0D))))
`(js3-jsdoc-tag-face ((t (:foreground ,base09))))
`(js3-jsdoc-type-face ((t (:foreground ,base0C))))
`(js3-jsdoc-value-face ((t (:foreground ,base0A))))
`(js3-jsdoc-html-tag-name-face ((t (:foreground ,base0D))))
`(js3-jsdoc-html-tag-delimiter-face ((t (:foreground ,base0B))))
`(js3-instance-member-face ((t (:foreground ,base0D))))
`(js3-private-function-call-face ((t (:foreground ,base08))))
;; nxml
`(nxml-name-face ((t (:foreground unspecified :inherit font-lock-constant-face))))
`(nxml-attribute-local-name-face ((t (:foreground unspecified :inherit font-lock-variable-name-face))))
`(nxml-ref-face ((t (:foreground unspecified :inherit font-lock-preprocessor-face))))
`(nxml-delimiter-face ((t (:foreground unspecified :inherit font-lock-keyword-face))))
`(nxml-delimited-data-face ((t (:foreground unspecified :inherit font-lock-string-face))))
`(rng-error-face ((t (:underline ,base08))))
;; RHTML
`(erb-delim-face ((t (:background ,base03))))
`(erb-exec-face ((t (:background ,base03 :weight bold))))
`(erb-exec-delim-face ((t (:background ,base03))))
`(erb-out-face ((t (:background ,base03 :weight bold))))
`(erb-out-delim-face ((t (:background ,base03))))
`(erb-comment-face ((t (:background ,base03 :weight bold :slant italic))))
`(erb-comment-delim-face ((t (:background ,base03))))
;; Message-mode
`(message-header-other ((t (:foreground nil :background nil :weight normal))))
`(message-header-subject ((t (:inherit message-header-other :weight bold :foreground ,base0A))))
`(message-header-to ((t (:inherit message-header-other :weight bold :foreground ,base09))))
`(message-header-cc ((t (:inherit message-header-to :foreground nil))))
`(message-header-name ((t (:foreground ,base0D :background nil))))
`(message-header-newsgroups ((t (:foreground ,base0C :background nil :slant normal))))
`(message-separator ((t (:foreground ,base0E))))
;; Jabber
`(jabber-chat-prompt-local ((t (:foreground ,base0A))))
`(jabber-chat-prompt-foreign ((t (:foreground ,base09))))
`(jabber-chat-prompt-system ((t (:foreground ,base0A :weight bold))))
`(jabber-chat-text-local ((t (:foreground ,base0A))))
`(jabber-chat-text-foreign ((t (:foreground ,base09))))
`(jabber-chat-text-error ((t (:foreground ,base08))))
`(jabber-roster-user-online ((t (:foreground ,base0B))))
`(jabber-roster-user-xa ((t :foreground ,base04)))
`(jabber-roster-user-dnd ((t :foreground ,base0A)))
`(jabber-roster-user-away ((t (:foreground ,base09))))
`(jabber-roster-user-chatty ((t (:foreground ,base0E))))
`(jabber-roster-user-error ((t (:foreground ,base08))))
`(jabber-roster-user-offline ((t (:foreground ,base04))))
`(jabber-rare-time-face ((t (:foreground ,base04))))
`(jabber-activity-face ((t (:foreground ,base0E))))
`(jabber-activity-personal-face ((t (:foreground ,base0C))))
;; Gnus
`(gnus-cite-1 ((t (:inherit outline-1 :foreground nil))))
`(gnus-cite-2 ((t (:inherit outline-2 :foreground nil))))
`(gnus-cite-3 ((t (:inherit outline-3 :foreground nil))))
`(gnus-cite-4 ((t (:inherit outline-4 :foreground nil))))
`(gnus-cite-5 ((t (:inherit outline-5 :foreground nil))))
`(gnus-cite-6 ((t (:inherit outline-6 :foreground nil))))
`(gnus-cite-7 ((t (:inherit outline-7 :foreground nil))))
`(gnus-cite-8 ((t (:inherit outline-8 :foreground nil))))
;; there are several more -cite- faces...
`(gnus-header-content ((t (:inherit message-header-other))))
`(gnus-header-subject ((t (:inherit message-header-subject))))
`(gnus-header-from ((t (:inherit message-header-other-face :weight bold :foreground ,base09))))
`(gnus-header-name ((t (:inherit message-header-name))))
`(gnus-button ((t (:inherit link :foreground nil))))
`(gnus-signature ((t (:inherit font-lock-comment-face))))
`(gnus-summary-normal-unread ((t (:foreground ,base0D :weight normal))))
`(gnus-summary-normal-read ((t (:foreground ,base06 :weight normal))))
`(gnus-summary-normal-ancient ((t (:foreground ,base0C :weight normal))))
`(gnus-summary-normal-ticked ((t (:foreground ,base09 :weight normal))))
`(gnus-summary-low-unread ((t (:foreground ,base04 :weight normal))))
`(gnus-summary-low-read ((t (:foreground ,base04 :weight normal))))
`(gnus-summary-low-ancient ((t (:foreground ,base04 :weight normal))))
`(gnus-summary-high-unread ((t (:foreground ,base0A :weight normal))))
`(gnus-summary-high-read ((t (:foreground ,base0B :weight normal))))
`(gnus-summary-high-ancient ((t (:foreground ,base0B :weight normal))))
`(gnus-summary-high-ticked ((t (:foreground ,base09 :weight normal))))
`(gnus-summary-cancelled ((t (:foreground ,base08 :background nil :weight normal))))
`(gnus-group-mail-low ((t (:foreground ,base04))))
`(gnus-group-mail-low-empty ((t (:foreground ,base04))))
`(gnus-group-mail-1 ((t (:foreground nil :weight normal :inherit outline-1))))
`(gnus-group-mail-2 ((t (:foreground nil :weight normal :inherit outline-2))))
`(gnus-group-mail-3 ((t (:foreground nil :weight normal :inherit outline-3))))
`(gnus-group-mail-4 ((t (:foreground nil :weight normal :inherit outline-4))))
`(gnus-group-mail-5 ((t (:foreground nil :weight normal :inherit outline-5))))
`(gnus-group-mail-6 ((t (:foreground nil :weight normal :inherit outline-6))))
`(gnus-group-mail-1-empty ((t (:inherit gnus-group-mail-1 :foreground ,base04))))
`(gnus-group-mail-2-empty ((t (:inherit gnus-group-mail-2 :foreground ,base04))))
`(gnus-group-mail-3-empty ((t (:inherit gnus-group-mail-3 :foreground ,base04))))
`(gnus-group-mail-4-empty ((t (:inherit gnus-group-mail-4 :foreground ,base04))))
`(gnus-group-mail-5-empty ((t (:inherit gnus-group-mail-5 :foreground ,base04))))
`(gnus-group-mail-6-empty ((t (:inherit gnus-group-mail-6 :foreground ,base04))))
`(gnus-group-news-1 ((t (:foreground nil :weight normal :inherit outline-5))))
`(gnus-group-news-2 ((t (:foreground nil :weight normal :inherit outline-6))))
`(gnus-group-news-3 ((t (:foreground nil :weight normal :inherit outline-7))))
`(gnus-group-news-4 ((t (:foreground nil :weight normal :inherit outline-8))))
`(gnus-group-news-5 ((t (:foreground nil :weight normal :inherit outline-1))))
`(gnus-group-news-6 ((t (:foreground nil :weight normal :inherit outline-2))))
`(gnus-group-news-1-empty ((t (:inherit gnus-group-news-1 :foreground ,base04))))
`(gnus-group-news-2-empty ((t (:inherit gnus-group-news-2 :foreground ,base04))))
`(gnus-group-news-3-empty ((t (:inherit gnus-group-news-3 :foreground ,base04))))
`(gnus-group-news-4-empty ((t (:inherit gnus-group-news-4 :foreground ,base04))))
`(gnus-group-news-5-empty ((t (:inherit gnus-group-news-5 :foreground ,base04))))
`(gnus-group-news-6-empty ((t (:inherit gnus-group-news-6 :foreground ,base04))))
`(erc-direct-msg-face ((t (:foreground ,base09))))
`(erc-error-face ((t (:foreground ,base08))))
`(erc-header-face ((t (:foreground ,base06 :background ,base04))))
`(erc-input-face ((t (:foreground ,base0B))))
`(erc-keyword-face ((t (:foreground ,base0A))))
`(erc-current-nick-face ((t (:foreground ,base0B))))
`(erc-my-nick-face ((t (:foreground ,base0B))))
`(erc-nick-default-face ((t (:weight normal :foreground ,base0E))))
`(erc-nick-msg-face ((t (:weight normal :foreground ,base0A))))
`(erc-notice-face ((t (:foreground ,base04))))
`(erc-pal-face ((t (:foreground ,base09))))
`(erc-prompt-face ((t (:foreground ,base0D))))
`(erc-timestamp-face ((t (:foreground ,base0C))))
`(custom-variable-tag ((t (:foreground ,base0D))))
`(custom-group-tag ((t (:foreground ,base0D))))
`(custom-state ((t (:foreground ,base0B)))))
(custom-theme-set-variables
'base16-atelierdune-dark
`(ansi-color-names-vector
;; black, base08, base0B, base0A, base0D, magenta, cyan, white
[,base00 ,base08 ,base0B ,base0A ,base0D ,base0E ,base0D ,base05])
`(ansi-term-color-vector
;; black, base08, base0B, base0A, base0D, magenta, cyan, white
[unspecified ,base00 ,base08 ,base0B ,base0A ,base0D ,base0E ,base0D ,base05])))
(provide-theme 'base16-atelierdune-dark)
;;; base16-atelierdune-dark-theme.el ends here
| {
"pile_set_name": "Github"
} |
apply = (f, list) -->
f.apply null, list
curry = (f) ->
curry$ f # using util method curry$ from livescript
flip = (f, x, y) --> f y, x
fix = (f) ->
( (g) -> -> f(g g) ...arguments ) do
(g) -> -> f(g g) ...arguments
over = (f, g, x, y) --> f (g x), (g y)
memoize = (f) ->
memo = {}
(...args) ->
key = [arg + typeof! arg for arg in args].join ''
memo[key] = if key of memo then memo[key] else f ...args
#? wrap
module.exports = {
curry, flip, fix, apply, over, memoize
}
| {
"pile_set_name": "Github"
} |
name: _rasterio
channels:
- defaults
dependencies:
- python=3.6.*
- libgdal=2.3.*
| {
"pile_set_name": "Github"
} |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Set default logging level before any logging happens.
import os as _os
_os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '1')
del _os
# flake8: noqa: F401
from .config import config
from .api import (
ad, # TODO(phawkins): update users to avoid this.
argnums_partial, # TODO(phawkins): update Haiku to not use this.
checkpoint,
curry, # TODO(phawkins): update users to avoid this.
custom_ivjp,
custom_gradient,
custom_jvp,
custom_vjp,
custom_transforms,
defjvp,
defjvp_all,
defvjp,
defvjp_all,
device_count,
device_get,
device_put,
devices,
disable_jit,
eval_shape,
flatten_fun_nokwargs, # TODO(phawkins): update users to avoid this.
grad,
hessian,
host_count,
host_id,
host_ids,
invertible,
jacobian,
jacfwd,
jacrev,
jit,
jvp,
local_device_count,
local_devices,
linearize,
linear_transpose,
make_jaxpr,
mask,
partial, # TODO(phawkins): update callers to use functools.partial.
pmap,
pxla, # TODO(phawkins): update users to avoid this.
remat,
shapecheck,
ShapedArray,
ShapeDtypeStruct,
soft_pmap,
# TODO(phawkins): hide tree* functions from jax, update callers to use
# jax.tree_util.
treedef_is_leaf,
tree_flatten,
tree_leaves,
tree_map,
tree_multimap,
tree_structure,
tree_transpose,
tree_unflatten,
value_and_grad,
vjp,
vmap,
xla, # TODO(phawkins): update users to avoid this.
xla_computation,
)
from .version import __version__
# These submodules are separate because they are in an import cycle with
# jax and rely on the names imported above.
from . import image
from . import lax
from . import nn
from . import profiler
from . import random
def _init():
from . import numpy # side-effecting import sets up operator overloads
_init()
del _init
| {
"pile_set_name": "Github"
} |
<!--
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.
-->
<a href="#commands/create" class='btn btn-default btn-small' style="margin:0px 4px;">
Create
</a>
<button class='btn btn-default checkbox-button' style="margin:0px 4px;">
<span class="checkbox"></span>
<span id="selectedCount"></span>
</button>
<div class='btn-group'>
<button id="deleteCommandButton" class='btn btn-default btn-red btn-hide-zero'>
Delete
</button>
</div>
| {
"pile_set_name": "Github"
} |
you can find the full article <b><a href='https://towardsdatascience.com/predictive-maintenance-with-lstm-siamese-network-51ee7df29767'>here</a></b>
| {
"pile_set_name": "Github"
} |
INCLUDES = ../lib ../monoid
| {
"pile_set_name": "Github"
} |
import macro from 'vtk.js/Sources/macro';
import {
Device,
Input,
} from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor/Constants';
// ----------------------------------------------------------------------------
// vtkCompositeVRManipulator methods
// ----------------------------------------------------------------------------
function vtkCompositeVRManipulator(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkCompositeVRManipulator');
publicAPI.onButton3D = (
interactor,
renderer,
state,
device,
input,
pressed
) => {};
publicAPI.onMove3D = (
interactor,
renderer,
state,
device,
input,
pressed
) => {};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
// device: null, // Device.RightController
// input: null, // Input.TrackPad
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
// Create get-set macros
macro.setGet(publicAPI, model, ['device', 'input']);
// Object specific methods
vtkCompositeVRManipulator(publicAPI, model);
}
// ----------------------------------------------------------------------------
export default { extend, Device, Input };
| {
"pile_set_name": "Github"
} |
//===----------- ImmutableSetTest.cpp - ImmutableSet unit tests ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/ImmutableSet.h"
using namespace llvm;
namespace {
class ImmutableSetTest : public testing::Test {
protected:
// for callback tests
static char buffer[10];
struct MyIter {
int counter;
char *ptr;
MyIter() : counter(0), ptr(buffer) {
for (unsigned i=0; i<sizeof(buffer);++i) buffer[i]='\0';
}
void operator()(char c) {
*ptr++ = c;
++counter;
}
};
};
char ImmutableSetTest::buffer[10];
TEST_F(ImmutableSetTest, EmptyIntSetTest) {
ImmutableSet<int>::Factory f;
EXPECT_TRUE(f.getEmptySet() == f.getEmptySet());
EXPECT_FALSE(f.getEmptySet() != f.getEmptySet());
EXPECT_TRUE(f.getEmptySet().isEmpty());
ImmutableSet<int> S = f.getEmptySet();
EXPECT_EQ(0u, S.getHeight());
EXPECT_TRUE(S.begin() == S.end());
EXPECT_FALSE(S.begin() != S.end());
}
TEST_F(ImmutableSetTest, OneElemIntSetTest) {
ImmutableSet<int>::Factory f;
ImmutableSet<int> S = f.getEmptySet();
ImmutableSet<int> S2 = f.add(S, 3);
EXPECT_TRUE(S.isEmpty());
EXPECT_FALSE(S2.isEmpty());
EXPECT_FALSE(S == S2);
EXPECT_TRUE(S != S2);
EXPECT_FALSE(S.contains(3));
EXPECT_TRUE(S2.contains(3));
EXPECT_FALSE(S2.begin() == S2.end());
EXPECT_TRUE(S2.begin() != S2.end());
ImmutableSet<int> S3 = f.add(S, 2);
EXPECT_TRUE(S.isEmpty());
EXPECT_FALSE(S3.isEmpty());
EXPECT_FALSE(S == S3);
EXPECT_TRUE(S != S3);
EXPECT_FALSE(S.contains(2));
EXPECT_TRUE(S3.contains(2));
EXPECT_FALSE(S2 == S3);
EXPECT_TRUE(S2 != S3);
EXPECT_FALSE(S2.contains(2));
EXPECT_FALSE(S3.contains(3));
}
TEST_F(ImmutableSetTest, MultiElemIntSetTest) {
ImmutableSet<int>::Factory f;
ImmutableSet<int> S = f.getEmptySet();
ImmutableSet<int> S2 = f.add(f.add(f.add(S, 3), 4), 5);
ImmutableSet<int> S3 = f.add(f.add(f.add(S2, 9), 20), 43);
ImmutableSet<int> S4 = f.add(S2, 9);
EXPECT_TRUE(S.isEmpty());
EXPECT_FALSE(S2.isEmpty());
EXPECT_FALSE(S3.isEmpty());
EXPECT_FALSE(S4.isEmpty());
EXPECT_FALSE(S.contains(3));
EXPECT_FALSE(S.contains(9));
EXPECT_TRUE(S2.contains(3));
EXPECT_TRUE(S2.contains(4));
EXPECT_TRUE(S2.contains(5));
EXPECT_FALSE(S2.contains(9));
EXPECT_FALSE(S2.contains(0));
EXPECT_TRUE(S3.contains(43));
EXPECT_TRUE(S3.contains(20));
EXPECT_TRUE(S3.contains(9));
EXPECT_TRUE(S3.contains(3));
EXPECT_TRUE(S3.contains(4));
EXPECT_TRUE(S3.contains(5));
EXPECT_FALSE(S3.contains(0));
EXPECT_TRUE(S4.contains(9));
EXPECT_TRUE(S4.contains(3));
EXPECT_TRUE(S4.contains(4));
EXPECT_TRUE(S4.contains(5));
EXPECT_FALSE(S4.contains(20));
EXPECT_FALSE(S4.contains(43));
}
TEST_F(ImmutableSetTest, RemoveIntSetTest) {
ImmutableSet<int>::Factory f;
ImmutableSet<int> S = f.getEmptySet();
ImmutableSet<int> S2 = f.add(f.add(S, 4), 5);
ImmutableSet<int> S3 = f.add(S2, 3);
ImmutableSet<int> S4 = f.remove(S3, 3);
EXPECT_TRUE(S3.contains(3));
EXPECT_FALSE(S2.contains(3));
EXPECT_FALSE(S4.contains(3));
EXPECT_TRUE(S2 == S4);
EXPECT_TRUE(S3 != S2);
EXPECT_TRUE(S3 != S4);
EXPECT_TRUE(S3.contains(4));
EXPECT_TRUE(S3.contains(5));
EXPECT_TRUE(S4.contains(4));
EXPECT_TRUE(S4.contains(5));
}
TEST_F(ImmutableSetTest, CallbackCharSetTest) {
ImmutableSet<char>::Factory f;
ImmutableSet<char> S = f.getEmptySet();
ImmutableSet<char> S2 = f.add(f.add(f.add(S, 'a'), 'e'), 'i');
ImmutableSet<char> S3 = f.add(f.add(S2, 'o'), 'u');
S3.foreach<MyIter>();
ASSERT_STREQ("aeiou", buffer);
}
TEST_F(ImmutableSetTest, Callback2CharSetTest) {
ImmutableSet<char>::Factory f;
ImmutableSet<char> S = f.getEmptySet();
ImmutableSet<char> S2 = f.add(f.add(f.add(S, 'b'), 'c'), 'd');
ImmutableSet<char> S3 = f.add(f.add(f.add(S2, 'f'), 'g'), 'h');
MyIter obj;
S3.foreach<MyIter>(obj);
ASSERT_STREQ("bcdfgh", buffer);
ASSERT_EQ(6, obj.counter);
MyIter obj2;
S2.foreach<MyIter>(obj2);
ASSERT_STREQ("bcd", buffer);
ASSERT_EQ(3, obj2.counter);
MyIter obj3;
S.foreach<MyIter>(obj);
ASSERT_STREQ("", buffer);
ASSERT_EQ(0, obj3.counter);
}
TEST_F(ImmutableSetTest, IterLongSetTest) {
ImmutableSet<long>::Factory f;
ImmutableSet<long> S = f.getEmptySet();
ImmutableSet<long> S2 = f.add(f.add(f.add(S, 0), 1), 2);
ImmutableSet<long> S3 = f.add(f.add(f.add(S2, 3), 4), 5);
int i = 0;
for (ImmutableSet<long>::iterator I = S.begin(), E = S.end(); I != E; ++I) {
ASSERT_EQ(i++, *I);
}
ASSERT_EQ(0, i);
i = 0;
for (ImmutableSet<long>::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
ASSERT_EQ(i++, *I);
}
ASSERT_EQ(3, i);
i = 0;
for (ImmutableSet<long>::iterator I = S3.begin(), E = S3.end(); I != E; I++) {
ASSERT_EQ(i++, *I);
}
ASSERT_EQ(6, i);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Setup|Win32">
<Configuration>Setup</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Setup|x64">
<Configuration>Setup</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{87D5FE20-AF86-458A-9AA3-3131EB06179B}</ProjectGuid>
<RootNamespace>ClassicStartMenu</RootNamespace>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Setup|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Setup|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Setup|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Setup|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\Version.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(Configuration)64\</OutDir>
<IntDir>$(Configuration)64\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(Configuration)64\</OutDir>
<IntDir>$(Configuration)64\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Setup|Win32'">
<OutDir>$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Setup|x64'">
<OutDir>$(Configuration)64\</OutDir>
<IntDir>$(Configuration)64\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Setup|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;BUILD_SETUP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Setup|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>..\ClassicShellLib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;BUILD_SETUP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Image Include="..\ClassicShellSetup\ClassicShell.ico" />
</ItemGroup>
<ItemGroup>
<Text Include="..\Localization\English\ClassicShellADMX.txt" />
<Text Include="..\Localization\English\ClassicStartMenuADMX.txt" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="ClassicStartMenu.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Manifest Include="ClassicStartMenu.manifest" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="ClassicStartMenu.rc" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="resource.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<None Include="StartMenuL10N.ini" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ClassicShellLib\ClassicShellLib.vcxproj">
<Project>{d42fe717-485b-492d-884a-1999f6d51154}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\ClassicSkin7\ClassicSkin7.vcxproj">
<Project>{31c016fb-9ea1-4af5-987a-37210c04da06}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\ClassicSkin\ClassicSkin.vcxproj">
<Project>{9ec23ca9-384a-4eeb-979e-69879dc1a78c}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\FullGlass\FullGlass.vcxproj">
<Project>{066c9721-26d5-4c4d-868e-50c2ba0a8196}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Metallic7\Metallic7.vcxproj">
<Project>{ca5bfc96-428d-42f5-9f7d-cdde048a357c}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Metro7\Metro7.vcxproj">
<Project>{598ab4ac-008e-4501-90b3-c5213834c1da}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Metro\Metro.vcxproj">
<Project>{63baf573-170b-4fa0-aee3-16e04f3e9df5}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Midnight7\Midnight7.vcxproj">
<Project>{7bd26cb3-5280-48fd-9a86-c13e321018d5}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\SmokedGlass\SmokedGlass.vcxproj">
<Project>{66d1eaa4-65d1-45cc-9989-e616fc0575eb}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Win7Aero7\Win7Aero7.vcxproj">
<Project>{a2ccde9f-17ce-461e-8bd9-00261b8855a6}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Win7Aero\Win7Aero.vcxproj">
<Project>{ea65fddd-cb77-417f-8bb4-2f3ecb5b3e75}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Win7Basic\Win7Basic.vcxproj">
<Project>{404821c5-4ee4-4908-a759-5ef6dac14ab6}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Win87\Win87.vcxproj">
<Project>{5c875214-0e3a-4cf0-bc0c-bff6faa4c089}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\Win8\Win8.vcxproj">
<Project>{ed74eba9-1bcb-4b8f-9ae1-dc63b3c24a94}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Skins\WinXP\WinXP.vcxproj">
<Project>{81eb6336-366c-47dd-82cf-ff6c36ccd2b5}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="ClassicStartMenuDLL\ClassicStartMenuDLL.vcxproj">
<Project>{85deecbb-1f9b-4983-9d54-3bf42182b7e7}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/gradle/gradle.iml" filepath="$PROJECT_DIR$/gradle/gradle.iml" />
</modules>
</component>
</project>
| {
"pile_set_name": "Github"
} |
/*
Gruvbox style (dark) (c) Pavel Pertsev (original style at https://github.com/morhetz/gruvbox)
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: #282828;
}
.hljs,
.hljs-subst {
color: #ebdbb2;
}
/* Gruvbox Red */
.hljs-deletion,
.hljs-formula,
.hljs-keyword,
.hljs-link,
.hljs-selector-tag {
color: #fb4934;
}
/* Gruvbox Blue */
.hljs-built_in,
.hljs-emphasis,
.hljs-name,
.hljs-quote,
.hljs-strong,
.hljs-title,
.hljs-variable {
color: #83a598;
}
/* Gruvbox Yellow */
.hljs-attr,
.hljs-params,
.hljs-template-tag,
.hljs-type {
color: #fabd2f;
}
/* Gruvbox Purple */
.hljs-builtin-name,
.hljs-doctag,
.hljs-literal,
.hljs-number {
color: #8f3f71;
}
/* Gruvbox Orange */
.hljs-code,
.hljs-meta,
.hljs-regexp,
.hljs-selector-id,
.hljs-template-variable {
color: #fe8019;
}
/* Gruvbox Green */
.hljs-addition,
.hljs-meta-string,
.hljs-section,
.hljs-selector-attr,
.hljs-selector-class,
.hljs-string,
.hljs-symbol {
color: #b8bb26;
}
/* Gruvbox Aqua */
.hljs-attribute,
.hljs-bullet,
.hljs-class,
.hljs-function,
.hljs-function .hljs-keyword,
.hljs-meta-keyword,
.hljs-selector-pseudo,
.hljs-tag {
color: #8ec07c;
}
/* Gruvbox Gray */
.hljs-comment {
color: #928374;
}
/* Gruvbox Purple */
.hljs-link_label,
.hljs-literal,
.hljs-number {
color: #d3869b;
}
.hljs-comment,
.hljs-emphasis {
font-style: italic;
}
.hljs-section,
.hljs-strong,
.hljs-tag {
font-weight: bold;
}
| {
"pile_set_name": "Github"
} |
{
"word": "Purchase",
"definitions": [
"The action of buying something.",
"A thing that has been bought.",
"The acquisition of property by one's personal action rather than by inheritance.",
"The annual rent or return from land.",
"Firm contact or grip.",
"A pulley or similar device for moving heavy objects."
],
"parts-of-speech": "Noun"
} | {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Text;
using MineCase.Block.State;
using MineCase.Item;
namespace MineCase.Block
{
public class BlockBedrock : Block
{
public BlockBedrock()
{
FullBlock = true;
LightOpacity = 255;
Translucent = false;
LightValue = 0;
UseNeighborBrightness = false;
BlockHardness = 60000.0f;
BlockResistance = 60000.0f;
EnableStats = false;
NeedsRandomTick = true;
IsBlockContainer = false;
BlockSoundType = null;
BlockParticleGravity = 1.0f;
Name = "bedrock";
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project> | {
"pile_set_name": "Github"
} |
using TinaX;
using TinaX.UIKit;
using TinaX.VFSKit;
using TinaX.XComponent;
using UnityEngine;
using UnityEngine.UI;
namespace Nekonya.UI
{
public class FetchData : XUIBehaviour
{
[Binding("btn_exit")]
public Button Btn_Close { get; set; }
[Binding("txt_content")]
public Text Txt_Content { get; set; }
[Inject]
public IVFS VFS { get; set; }
public async override void Start()
{
using(var text_asset = await VFS.LoadAssetAsync<TextAsset>("Assets/App/Data/text/hello.txt"))
{
Txt_Content.text = text_asset.Get<TextAsset>().text;
}
Btn_Close.onClick.AddListener(() =>
{
this.Close();
});
}
}
}
| {
"pile_set_name": "Github"
} |
[](https://travis-ci.org/kondrak/rust64)
[](https://ci.appveyor.com/project/kondrak/rust64)
# Rust64 - a C64 emulator written in Rust
This is my attempt to study the Rust programming language and have fun at the same time. The goal is to present in the least obfuscated way how the Commodore 64 works and what's happening behind the scenes once you start a program. Emulation is cycle based and fairly accurate at this point.
The emulator has a built-in visual debugger which lets you view the contents of each memory page in RAM, Color RAM, VIC registers, CIA registers and SID registers. The VIC window is a ICU64-style raster debugger where each pixel represents one VIC cycle and any events occuring at that time.
Major dependencies
------------------
- minifb: https://crates.io/crates/minifb (works out of the box)
- sdl2: https://crates.io/crates/sdl2 (requires extra steps, see [here](https://github.com/AngryLawyer/rust-sdl2) for instructions)
Requires Rust 1.5.0 or higher to compile and run.
### Youtube demo #1:
[](https://www.youtube.com/watch?v=b6OSsTPwLaE)
### Youtube demo #2:
[](https://www.youtube.com/watch?v=g4d_1vPV6So)
### Screenshot:
[](images/rust64_github.png?raw=true)
Build instructions
------------------
```
cargo build
cargo run --release
```
You can pass a .prg file as a command line parameter to load it into memory once the emulator boots (just type RUN to start the program):
```
cargo run --release prgs/colors.prg
```
To run with double-sized window:
```
cargo run --release x2 prgs/colors.prg
```
To run with double-sized window and debug windows enabled:
```
cargo run --release x2 debugger prgs/colors.prg
```
C64 and special key mappings
-------------------
```
ESC - Run/Stop
END - Restore
TAB - Control
LCTRL - C=
` - <-
- - +
INS - &
HOME - CLR/Home
BSPACE - INST/DEL
[ - @
] - *
DEL - ^
; - :
' - ;
\ - =
F11 - start asm output to console (very slow!)
F12 - reset C64
RCTRL - joystick fire button
NUMLOCK - toggle between joystick ports 1 and 2 (default: port 2)
In debugger window:
PGUP/PGDWN - flip currently displayed memory page
HOME/END - switch currently displayed memory banks between RAM, Color RAM, VIC, CIA and SID
```
TODO
------------------
- serial bus/disk drives (d64, t64, tap)
- implement remaining undocumented ops
- switch from SDL2 to [cpal](https://github.com/tomaka/cpal) for audio once it supports OSX
- improve SID emulation
Known Issues
------------------
- missing serial bus may cause some very specific programs to perform incorrectly or get stuck in infinite loops
- elaborate programs that require very precise timing are not running correctly yet
This is an on-off WIP project, so update frequency may vary.
Resources
------------------
The following documents and websites have been used to create this emulator:
- http://www.zimmers.net/cbmpics/cbm/c64/vic-ii.txt
- http://frodo.cebix.net/ (inspired the VIC-II and SID implementaiton)
- https://www.c64-wiki.com
- http://www.oxyron.de/html/opcodes02.html
- http://www.6502.org/tutorials/6502opcodes.html
- http://www.pagetable.com/c64rom/c64rom_en.html
- http://archive.6502.org/datasheets/mos_6526_cia.pdf
- https://www.yoyogames.com/tech_blog/95
- http://code.google.com/p/hmc-6502/source/browse/trunk/emu/testvectors/AllSuiteA.asm
- https://t.co/J40UKu7RBf
- http://www.waitingforfriday.com/index.php/Commodore_SID_6581_Datasheet
- http://sta.c64.org/cbm64mem.html
- https://svn.code.sf.net/p/vice-emu/code/testprogs/
- http://www.classiccmp.org/cini/pdf/Commodore/ds_6581.pdf
Special thanks
------------------
- [Daniel Collin](https://twitter.com/daniel_collin) and Magnus "Pantaloon" Sjöberg for excessive test programs!
- [Jake Taylor](https://twitter.com/ferristweetsnow) for general Rust tips!
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho
import android.graphics.drawable.Drawable
import com.facebook.yoga.YogaAlign
import com.facebook.yoga.YogaEdge
import com.facebook.yoga.YogaPositionType
// TODO should be `data` if we want to consider it for comparison as a Prop.
open class Style(
val width: Dp? = null,
val height: Dp? = null,
val widthPercent: Float? = null,
val heightPercent: Float? = null,
val minWidth: Dp? = null,
val minHeight: Dp? = null,
val maxWidth: Dp? = null,
val maxHeight: Dp? = null,
val minWidthPercent: Float? = null,
val minHeightPercent: Float? = null,
val maxWidthPercent: Float? = null,
val maxHeightPercent: Float? = null,
val alignSelf: YogaAlign? = null,
val flex: Float? = null,
val flexGrow: Float? = null,
val flexShrink: Float? = null,
val flexBasis: Dp? = null,
val aspectRatio: Float? = null,
val paddingStart: Dp? = null,
val paddingTop: Dp? = null,
val paddingEnd: Dp? = null,
val paddingBottom: Dp? = null,
val paddingHorizontal: Dp? = null,
val paddingVertical: Dp? = null,
val paddingAll: Dp? = null,
val marginStart: Dp? = null,
val marginTop: Dp? = null,
val marginEnd: Dp? = null,
val marginBottom: Dp? = null,
val marginHorizontal: Dp? = null,
val marginVertical: Dp? = null,
val marginAll: Dp? = null,
val positionStart: Dp? = null,
val positionTop: Dp? = null,
val positionEnd: Dp? = null,
val positionBottom: Dp? = null,
val positionType: YogaPositionType? = null,
val background: Drawable? = null,
val foreground: Drawable? = null
) {
operator fun plus(other: Style): Style {
return Style(
width = other.width ?: width,
height = other.height ?: height,
widthPercent = other.widthPercent ?: widthPercent,
heightPercent = other.heightPercent ?: heightPercent,
minWidth = other.minWidth ?: minWidth,
minHeight = other.minHeight ?: minHeight,
maxWidth = other.maxWidth ?: maxWidth,
maxHeight = other.maxHeight ?: maxHeight,
minWidthPercent = other.minWidthPercent ?: minWidthPercent,
minHeightPercent = other.minHeightPercent ?: minHeightPercent,
maxWidthPercent = other.maxWidthPercent ?: maxWidthPercent,
maxHeightPercent = other.maxHeightPercent ?: maxHeightPercent,
alignSelf = other.alignSelf ?: alignSelf,
flex = other.flex ?: flex,
flexGrow = other.flexGrow ?: flexGrow,
flexShrink = other.flexShrink ?: flexShrink,
flexBasis = other.flexBasis ?: flexBasis,
aspectRatio = other.aspectRatio ?: aspectRatio,
paddingStart = paddingStart plusSafe other.paddingStart,
paddingTop = paddingTop plusSafe other.paddingTop,
paddingEnd = paddingEnd plusSafe other.paddingEnd,
paddingBottom = paddingBottom plusSafe other.paddingBottom,
paddingHorizontal = paddingHorizontal plusSafe other.paddingHorizontal,
paddingVertical = paddingVertical plusSafe other.paddingVertical,
paddingAll = paddingAll plusSafe other.paddingAll,
marginStart = marginStart plusSafe other.marginStart,
marginTop = marginTop plusSafe other.marginTop,
marginEnd = marginEnd plusSafe other.marginEnd,
marginBottom = marginBottom plusSafe other.marginBottom,
marginHorizontal = marginHorizontal plusSafe other.marginHorizontal,
marginVertical = marginVertical plusSafe other.marginVertical,
marginAll = marginAll plusSafe other.marginAll,
positionStart = other.positionStart ?: positionStart,
positionTop = other.positionTop ?: positionTop,
positionEnd = other.positionEnd ?: positionEnd,
positionBottom = other.positionBottom ?: positionBottom,
positionType = other.positionType ?: positionType,
background = other.background ?: background,
foreground = other.foreground ?: foreground
)
}
companion object : Style()
}
infix fun Dp?.plusSafe(other: Dp?) = (this ?: 0.dp) + (other ?: 0.dp)
internal fun DslScope.copyStyleToProps(style: Style, props: CommonProps) {
props.apply {
style.width?.let { widthPx(if (it == Dp.Hairline) 1 else it.toPx().value) }
style.height?.let { heightPx(if (it == Dp.Hairline) 1 else it.toPx().value) }
style.widthPercent?.let { widthPercent(it) }
style.heightPercent?.let { heightPercent(it) }
style.minWidth?.let { minWidthPx(it.toPx().value) }
style.minHeight?.let { minHeightPx(it.toPx().value) }
style.maxWidth?.let { maxWidthPx(it.toPx().value) }
style.maxHeight?.let { maxHeightPx(it.toPx().value) }
style.minWidthPercent?.let { minWidthPercent(it) }
style.minHeightPercent?.let { minHeightPercent(it) }
style.maxWidthPercent?.let { maxWidthPercent(it) }
style.maxHeightPercent?.let { maxHeightPercent(it) }
style.alignSelf?.let { alignSelf(it) }
style.flex?.let { flex(it) }
style.flexGrow?.let { flexGrow(it) }
style.flexShrink?.let { flexShrink(it) }
style.flexBasis?.let { flexBasisPx(it.toPx().value) }
style.aspectRatio?.let { aspectRatio(it) }
style.paddingStart?.let { paddingPx(YogaEdge.START, it.toPx().value) }
style.paddingTop?.let { paddingPx(YogaEdge.TOP, it.toPx().value) }
style.paddingEnd?.let { paddingPx(YogaEdge.END, it.toPx().value) }
style.paddingBottom?.let { paddingPx(YogaEdge.BOTTOM, it.toPx().value) }
style.paddingHorizontal?.let { paddingPx(YogaEdge.HORIZONTAL, it.toPx().value) }
style.paddingVertical?.let { paddingPx(YogaEdge.VERTICAL, it.toPx().value) }
style.paddingAll?.let { paddingPx(YogaEdge.ALL, it.toPx().value) }
style.marginStart?.let { marginPx(YogaEdge.START, it.toPx().value) }
style.marginTop?.let { marginPx(YogaEdge.TOP, it.toPx().value) }
style.marginEnd?.let { marginPx(YogaEdge.END, it.toPx().value) }
style.marginBottom?.let { marginPx(YogaEdge.BOTTOM, it.toPx().value) }
style.marginHorizontal?.let { marginPx(YogaEdge.HORIZONTAL, it.toPx().value) }
style.marginVertical?.let { marginPx(YogaEdge.VERTICAL, it.toPx().value) }
style.marginAll?.let { marginPx(YogaEdge.ALL, it.toPx().value) }
style.positionStart?.let { positionPx(YogaEdge.START, it.toPx().value) }
style.positionTop?.let { positionPx(YogaEdge.TOP, it.toPx().value) }
style.positionEnd?.let { positionPx(YogaEdge.END, it.toPx().value) }
style.positionBottom?.let { positionPx(YogaEdge.BOTTOM, it.toPx().value) }
style.positionType?.let { positionType(it) }
style.background?.let { background(it) }
style.foreground?.let { foreground(it) }
}
}
fun size(size: Dp) = Style(width = size, height = size)
fun Style.size(size: Dp) = this + com.facebook.litho.size(size)
fun size(width: Dp? = null, height: Dp? = null) = Style(width, height)
fun Style.size(width: Dp? = null, height: Dp? = null) =
this + com.facebook.litho.size(width, height)
fun width(minWidth: Dp? = null, maxWidth: Dp? = null) =
Style(minWidth = minWidth, maxWidth = maxWidth)
fun Style.width(minWidth: Dp? = null, maxWidth: Dp? = null) =
this + com.facebook.litho.width(minWidth, maxWidth)
fun height(minHeight: Dp? = null, maxHeight: Dp? = null) =
Style(minHeight = minHeight, maxHeight = maxHeight)
fun Style.height(minHeight: Dp? = null, maxHeight: Dp? = null) =
this + com.facebook.litho.height(minHeight, maxHeight)
fun flex(grow: Float? = null, shrink: Float? = null, basis: Dp? = null) =
Style(flexGrow = grow, flexShrink = shrink, flexBasis = basis)
fun Style.flex(grow: Float? = null, shrink: Float? = null, basis: Dp? = null) =
this + com.facebook.litho.flex(grow, shrink, basis)
fun aspectRatio(aspectRatio: Float) = Style(aspectRatio = aspectRatio)
fun Style.aspectRatio(aspectRatio: Float) = this + com.facebook.litho.aspectRatio(aspectRatio)
fun padding(all: Dp) = Style(paddingAll = all)
fun Style.padding(all: Dp) = this + com.facebook.litho.padding(all)
fun padding(horizontal: Dp? = null, vertical: Dp? = null) =
Style(
paddingStart = horizontal,
paddingTop = vertical,
paddingEnd = horizontal,
paddingBottom = vertical)
fun Style.padding(horizontal: Dp? = null, vertical: Dp? = null) =
this + com.facebook.litho.padding(horizontal, vertical)
fun padding(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
Style(paddingStart = start, paddingTop = top, paddingEnd = end, paddingBottom = bottom)
fun Style.padding(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
this + com.facebook.litho.padding(start, top, end, bottom)
fun margin(all: Dp) = Style(marginAll = all)
fun Style.margin(all: Dp) = this + com.facebook.litho.margin(all)
fun margin(horizontal: Dp? = null, vertical: Dp? = null) =
Style(
marginStart = horizontal,
marginTop = vertical,
marginEnd = horizontal,
marginBottom = vertical)
fun Style.margin(horizontal: Dp? = null, vertical: Dp? = null) =
this + com.facebook.litho.margin(horizontal, vertical)
fun margin(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
Style(marginStart = start, marginTop = top, marginEnd = end, marginBottom = bottom)
fun Style.margin(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
this + com.facebook.litho.margin(start, top, end, bottom)
fun position(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
Style(
positionStart = start,
positionTop = top,
positionEnd = end,
positionBottom = bottom,
positionType = YogaPositionType.ABSOLUTE)
fun Style.position(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
this + com.facebook.litho.position(start, top, end, bottom)
fun positionRelative(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
Style(
positionStart = start,
positionTop = top,
positionEnd = end,
positionBottom = bottom,
positionType = YogaPositionType.RELATIVE)
fun Style.positionRelative(start: Dp? = null, top: Dp? = null, end: Dp? = null, bottom: Dp? = null) =
this + com.facebook.litho.positionRelative(start, top, end, bottom)
fun background(background: Drawable) = Style(background = background)
fun Style.background(background: Drawable) = this + com.facebook.litho.background(background)
fun foreground(foreground: Drawable) = Style(foreground = foreground)
fun Style.foreground(foreground: Drawable) = this + com.facebook.litho.foreground(foreground)
| {
"pile_set_name": "Github"
} |
<?php
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\Store;
class ArrayStore extends TaggableStore implements Store
{
use RetrievesMultipleKeys;
/**
* The array of stored values.
*
* @var array
*/
protected $storage = [];
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key)
{
if (array_key_exists($key, $this->storage)) {
return $this->storage[$key];
}
}
/**
* Store an item in the cache for a given number of minutes.
*
* @param string $key
* @param mixed $value
* @param float|int $minutes
* @return void
*/
public function put($key, $value, $minutes)
{
$this->storage[$key] = $value;
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int
*/
public function increment($key, $value = 1)
{
$this->storage[$key] = ! isset($this->storage[$key])
? $value : ((int) $this->storage[$key]) + $value;
return $this->storage[$key];
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int
*/
public function decrement($key, $value = 1)
{
return $this->increment($key, $value * -1);
}
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->put($key, $value, 0);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key)
{
unset($this->storage[$key]);
return true;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
$this->storage = [];
return true;
}
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix()
{
return '';
}
}
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
// var SECTION = "7.2-6";
// var VERSION = "ECMA_1";
// var TITLE = "Line Terminators";
var testcases = getTestCases();
function getTestCases() {
var array = new Array();
var item = 0;
var a=10;
var b=10;
var c;
c=
a
*
b
array[item++] = Assert.expectEq( "7.2 c<cr>a<cr>*<cr>b", 100, c);
return ( array );
}
| {
"pile_set_name": "Github"
} |
Configuration SecurityBaselineConfigWS2016
{
Import-DSCResource -ModuleName 'PSDesiredStateConfiguration'
Import-DSCResource -ModuleName 'AuditPolicyDSC'
Import-DSCResource -ModuleName 'SecurityPolicyDSC'
Node localhost
{
Registry "CCE-37615-2: Ensure 'Accounts: Limit local account use of blank passwords to console logon only' is set to 'Enabled'"
{
ValueName = 'LimitBlankPasswordUse'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-36254-1: Ensure 'Allow Basic authentication' is set to 'Disabled'"
{
ValueName = 'AllowBasic'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\WinRM\Client'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Allow Cortana above lock screen' is set to 'Disabled'"
{
ValueName = 'AllowCortanaAboveLock'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Windows Search'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Allow Cortana' is set to 'Disabled'"
{
ValueName = 'AllowCortana'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Windows Search'
ValueData = 0
}
Registry "CCE-38277-0: Ensure 'Allow indexing of encrypted files' is set to 'Disabled'"
{
ValueName = 'AllowIndexingEncryptedStoresOrItems'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Windows Search'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Allow Input Personalization' is set to 'Disabled'"
{
ValueName = 'AllowInputPersonalization'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\InputPersonalization'
ValueData = 0
}
Registry "CCE-38354-7: Ensure 'Allow Microsoft accounts to be optional' is set to 'Enabled'"
{
ValueName = 'MSAOptional'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "NOT_ASSIGNED: Ensure 'Allow search and Cortana to use location' is set to 'Disabled'"
{
ValueName = 'AllowSearchToUseLocation'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Windows Search'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Allow Telemetry' is set to 'Enabled: 0 - Security [Enterprise Only]'"
{
ValueName = 'AllowTelemetry'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\DataCollection'
ValueData = 2
}
Registry "CCE-38223-4: Ensure 'Allow unencrypted traffic' is set to 'Disabled'"
{
ValueName = 'AllowUnencryptedTraffic'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\WinRM\Client'
ValueData = 0
}
Registry "CCE-36400-0: Ensure 'Allow user control over installs' is set to 'Disabled'"
{
ValueName = 'EnableUserControl'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Installer'
ValueData = 0
}
Registry "CCE-37490-0: Ensure 'Always install with elevated privileges' is set to 'Disabled'"
{
ValueName = 'AlwaysInstallElevated'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Installer'
ValueData = 0
}
Registry "CCE-37929-7: Ensure 'Always prompt for password upon connection' is set to 'Enabled'"
{
ValueName = 'fPromptForPassword'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 1
}
Registry "CCE-37775-4: Ensure 'Application: Control Event Log behavior when the log file reaches its maximum size' is set to 'Disabled'"
{
ValueName = 'Retention'
ValueType = 'String'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Application'
ValueData = '0'
}
Registry "CCE-37948-7: Ensure 'Application: Specify the maximum log file size ' is set to 'Enabled: 32,768 or greater'"
{
ValueName = 'MaxSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Application'
ValueData = 32768
}
Registry "CCE-37850-5: Ensure 'Audit: Force audit policy subcategory settings to override audit policy category settings' is set to 'Enabled'"
{
ValueName = 'SCENoApplyLegacyAuditPolicy'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-35907-5: Ensure 'Audit: Shut down system immediately if unable to log security audits' is set to 'Disabled'"
{
ValueName = 'CrashOnAuditFail'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Block user from showing account details on sign-in' is set to 'Enabled'"
{
ValueName = 'BlockUserFromShowingAccountDetailsOnSignin'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 1
}
Registry "CCE-37912-3: Ensure 'Boot-Start Driver Initialization Policy' is set to 'Enabled: Good, unknown and bad but critical'"
{
ValueName = 'DriverLoadPolicy'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Policies\EarlyLaunch'
ValueData = 3
}
Registry "CCE-36388-7: Ensure 'Configure Offer Remote Assistance' is set to 'Disabled'"
{
ValueName = 'fAllowUnsolicited'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 0
}
Registry "CCE-36169-1: Ensure 'Configure registry policy processing: Do not apply during periodic background processing' is set to 'Enabled: FALSE'"
{
ValueName = 'NoBackgroundPolicy'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Group Policy\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}'
ValueData = 0
}
Registry "CCE-36169-1: Ensure 'Configure registry policy processing: Process even if the Group Policy objects have not changed' is set to 'Enabled: TRUE'"
{
ValueName = 'NoGPOListChanges'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Group Policy\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}'
ValueData = 0
}
Registry "CCE-37281-3: Ensure 'Configure Solicited Remote Assistance' is set to 'Disabled'"
{
ValueName = 'fAllowToGetHelp'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 0
}
Registry "CCE-35859-8: Ensure 'Configure Windows SmartScreen' is set to 'Enabled'"
{
ValueName = 'EnableSmartScreen'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 1
}
Registry "NOT_ASSIGNED: Ensure 'Continue experiences on this device' is set to 'Disabled'"
{
ValueName = 'EnableCdp'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 0
}
Registry "CCE-37701-0: Ensure 'Devices: Allowed to format and eject removable media' is set to 'Administrators'"
{
ValueName = 'AllocateDASD'
ValueType = 'String'
Key = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon'
ValueData = '0'
}
Registry "CCE-37942-0: Ensure 'Devices: Prevent users from installing printer drivers' is set to 'Enabled'"
{
ValueName = 'AddPrinterDrivers'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers'
ValueData = 1
}
Registry "CCE-37636-8: Ensure 'Disallow Autoplay for non-volume devices' is set to 'Enabled'"
{
ValueName = 'NoAutoplayfornonVolume'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Explorer'
ValueData = 1
}
Registry "CCE-38318-2: Ensure 'Disallow Digest authentication' is set to 'Enabled'"
{
ValueName = 'AllowDigest'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\WinRM\Client'
ValueData = 0
}
Registry "CCE-36000-8: Ensure 'Disallow WinRM from storing RunAs credentials' is set to 'Enabled'"
{
ValueName = 'DisableRunAs'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\WinRM\Service'
ValueData = 1
}
Registry "CCE-36223-6: Ensure 'Do not allow passwords to be saved' is set to 'Enabled'"
{
ValueName = 'DisablePasswordSaving'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 1
}
Registry "CCE-38353-9: Ensure 'Do not display network selection UI' is set to 'Enabled'"
{
ValueName = 'DontDisplayNetworkSelectionUI'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 1
}
Registry "CCE-37534-5: Ensure 'Do not display the password reveal button' is set to 'Enabled'"
{
ValueName = 'DisablePasswordReveal'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\CredUI'
ValueData = 1
}
Registry "CCE-37838-0: Ensure 'Do not enumerate connected users on domain-joined computers' is set to 'Enabled'"
{
ValueName = 'DontEnumerateConnectedUsers'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Do not show feedback notifications' is set to 'Enabled'"
{
ValueName = 'DoNotShowFeedbackNotifications'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\DataCollection'
ValueData = 1
}
Registry "CCE-38180-6: Ensure 'Do not use temporary folders per session' is set to 'Disabled'"
{
ValueName = 'PerSessionTempDir'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 1
}
Registry "CCE-36142-8: Ensure 'Domain member: Digitally encrypt or sign secure channel data ' is set to 'Enabled'"
{
ValueName = 'RequireSignOrSeal'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 1
}
Registry "CCE-37130-2: Ensure 'Domain member: Digitally encrypt secure channel data ' is set to 'Enabled'"
{
ValueName = 'SealSecureChannel'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 1
}
Registry "CCE-37222-7: Ensure 'Domain member: Digitally sign secure channel data (when possible)' is set to 'Enabled'"
{
ValueName = 'SignSecureChannel'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 1
}
Registry "CCE-37508-9: Ensure 'Domain member: Disable machine account password changes' is set to 'Disabled'"
{
ValueName = 'DisablePasswordChange'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 0
}
Registry "CCE-37431-4: Ensure 'Domain member: Maximum machine account password age' is set to '30 or fewer days, but not 0'"
{
ValueName = 'MaximumPasswordAge'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 30
}
Registry "CCE-37614-5: Ensure 'Domain member: Require strong session key' is set to 'Enabled'"
{
ValueName = 'RequireStrongKey'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Netlogon\Parameters'
ValueData = 1
}
Registry "NOT_ASSIGNED: Ensure 'Enable insecure guest logons' is set to 'Disabled'"
{
ValueName = 'AllowInsecureGuestAuth'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\LanmanWorkstation'
ValueData = 0
}
Registry "CCE-37346-4: Ensure 'Enable RPC Endpoint Mapper Client Authentication' is set to 'Enabled'"
{
ValueName = 'EnableAuthEpResolution'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Rpc'
ValueData = 1
}
Registry "CCE-36512-2: Ensure 'Enumerate administrator accounts on elevation' is set to 'Disabled'"
{
ValueName = 'EnumerateAdministrators'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\CredUI'
ValueData = 0
}
Registry "CCE-35894-5: Ensure 'Enumerate local users on domain-joined computers' is set to 'Disabled'"
{
ValueName = 'EnumerateLocalUsers'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 0
}
Registry "CCE-36056-0: Ensure 'Interactive logon: Do not display last user name' is set to 'Enabled'"
{
ValueName = 'DontDisplayLastUserName'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-37637-6: Ensure 'Interactive logon: Do not require CTRL+ALT+DEL' is set to 'Disabled'"
{
ValueName = 'DisableCAD'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "CCE-36325-9: Ensure 'Microsoft network client: Digitally sign communications (always)' is set to 'Enabled'"
{
ValueName = 'RequireSecuritySignature'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanmanWorkstation\Parameters'
ValueData = 1
}
Registry "CCE-36269-9: Ensure 'Microsoft network client: Digitally sign communications (if server agrees)' is set to 'Enabled'"
{
ValueName = 'EnableSecuritySignature'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanmanWorkstation\Parameters'
ValueData = 1
}
Registry "CCE-37863-8: Ensure 'Microsoft network client: Send unencrypted password to third-party SMB servers' is set to 'Disabled'"
{
ValueName = 'EnablePlainTextPassword'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanmanWorkstation\Parameters'
ValueData = 0
}
Registry "CCE-38046-9: Ensure 'Microsoft network server: Amount of idle time required before suspending session' is set to '15 or fewer minute, but not 0'"
{
ValueName = 'AutoDisconnect'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = 15
}
Registry "CCE-37864-6: Ensure 'Microsoft network server: Digitally sign communications (always)' is set to 'Enabled'"
{
ValueName = 'RequireSecuritySignature'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = 1
}
Registry "CCE-35988-5: Ensure 'Microsoft network server: Digitally sign communications (if client agrees)' is set to 'Enabled'"
{
ValueName = 'EnableSecuritySignature'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = 1
}
Registry "CCE-37972-7: Ensure 'Microsoft network server: Disconnect clients when logon hours expire' is set to 'Enabled'"
{
ValueName = 'EnableForcedLogoff'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = 1
}
Registry "CCE-38338-0: Ensure 'Minimize the number of simultaneous connections to the Internet or a Windows Domain' is set to 'Enabled'"
{
ValueName = 'fMinimizeConnections'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\WcmSvc\GroupPolicy'
ValueData = 1
}
Registry "CCE-36077-6: Ensure 'Network access: Do not allow anonymous enumeration of SAM accounts and shares' is set to 'Enabled'"
{
ValueName = 'RestrictAnonymous'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-36316-8: Ensure 'Network access: Do not allow anonymous enumeration of SAM accounts' is set to 'Enabled'"
{
ValueName = 'RestrictAnonymousSAM'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-36148-5: Ensure 'Network access: Let Everyone permissions apply to anonymous users' is set to 'Disabled'"
{
ValueName = 'EveryoneIncludesAnonymous'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 0
}
Registry "CCE-36021-4: Ensure 'Network access: Restrict anonymous access to Named Pipes and Shares' is set to 'Enabled'"
{
ValueName = 'RestrictNullSessAccess'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = 1
}
Registry "NOT_ASSIGNED: Ensure 'Network access: Restrict clients allowed to make remote calls to SAM' is set to 'Administrators: Remote Access: Allow'"
{
ValueName = 'RestrictRemoteSAM'
ValueType = 'String'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 'O:BAG:BAD:(A;;RC;;;BA)'
}
Registry "CCE-38095-6: Ensure 'Network access: Shares that can be accessed anonymously' is set to 'None'"
{
ValueName = 'NullSessionShares'
ValueType = 'MultiString'
Key = 'HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters'
ValueData = '0'
}
Registry "CCE-37623-6: Ensure 'Network access: Sharing and security model for local accounts' is set to 'Classic - local users authenticate as themselves'"
{
ValueName = 'ForceGuest'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 0
}
Registry "CCE-38341-4: Ensure 'Network security: Allow Local System to use computer identity for NTLM' is set to 'Enabled'"
{
ValueName = 'UseMachineId'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-37035-3: Ensure 'Network security: Allow LocalSystem NULL session fallback' is set to 'Disabled'"
{
ValueName = 'AllowNullSessionFallback'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa\MSV1_0'
ValueData = 0
}
Registry "CCE-38047-7: Ensure 'Network Security: Allow PKU2U authentication requests to this computer to use online identities' is set to 'Disabled'"
{
ValueName = 'AllowOnlineID'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa\pku2u'
ValueData = 0
}
Registry "CCE-37755-6: Ensure 'Network Security: Configure encryption types allowed for Kerberos' is set to 'RC4_HMAC_MD5, AES128_HMAC_SHA1, AES256_HMAC_SHA1, Future encryption types'"
{
ValueName = 'SupportedEncryptionTypes'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\Kerberos\Parameters'
ValueData = 2147483644
}
Registry "CCE-36326-7: Ensure 'Network security: Do not store LAN Manager hash value on next password change' is set to 'Enabled'"
{
ValueName = 'NoLMHash'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 1
}
Registry "CCE-36173-3: Ensure 'Network security: LAN Manager authentication level' is set to 'Send NTLMv2 response only. Refuse LM & NTLM'"
{
ValueName = 'LmCompatibilityLevel'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa'
ValueData = 5
}
Registry "CCE-36858-9: Ensure 'Network security: LDAP client signing requirements' is set to 'Negotiate signing' or higher"
{
ValueName = 'LDAPClientIntegrity'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LDAP'
ValueData = 1
}
Registry "CCE-37553-5: Ensure 'Network security: Minimum session security for NTLM SSP based clients' is set to 'Require NTLMv2 session security, Require 128-bit encryption'"
{
ValueName = 'NTLMMinClientSec'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa\MSV1_0'
ValueData = 537395200
}
Registry "CCE-37835-6: Ensure 'Network security: Minimum session security for NTLM SSP based servers' is set to 'Require NTLMv2 session security, Require 128-bit encryption'"
{
ValueName = 'NTLMMinServerSec'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Lsa\MSV1_0'
ValueData = 537395200
}
Registry "CCE-37126-0: Ensure 'Prevent downloading of enclosures' is set to 'Enabled'"
{
ValueName = 'DisableEnclosureDownload'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Internet Explorer\Feeds'
ValueData = 1
}
Registry "CCE-38347-1: Ensure 'Prevent enabling lock screen camera' is set to 'Enabled'"
{
ValueName = 'NoLockScreenCamera'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Personalization'
ValueData = 1
}
Registry "CCE-38348-9: Ensure 'Prevent enabling lock screen slide show' is set to 'Enabled'"
{
ValueName = 'NoLockScreenSlideshow'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Personalization'
ValueData = 1
}
Registry "CCE-38002-2: Ensure 'Prohibit installation and configuration of Network Bridge on your DNS domain network' is set to 'Enabled'"
{
ValueName = 'NC_AllowNetBridge_NLA'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Network Connections'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Prohibit use of Internet Connection Sharing on your DNS domain network' is set to 'Enabled'"
{
ValueName = 'NC_PersonalFirewallConfig'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Network Connections'
ValueData = 0
}
Registry "CCE-38188-9: Ensure 'Require domain users to elevate when setting a network's location' is set to 'Enabled'"
{
ValueName = 'NC_StdDomainUserSetLocation'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Network Connections'
ValueData = 1
}
Registry "CCE-37567-5: Ensure 'Require secure RPC communication' is set to 'Enabled'"
{
ValueName = 'fEncryptRPCTraffic'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 1
}
Registry "CCE-37145-0: Ensure 'Security: Control Event Log behavior when the log file reaches its maximum size' is set to 'Disabled'"
{
ValueName = 'Retention'
ValueType = 'String'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Security'
ValueData = '0'
}
Registry "CCE-37695-4: Ensure 'Security: Specify the maximum log file size ' is set to 'Enabled: 196,608 or greater'"
{
ValueName = 'MaxSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Security'
ValueData = 196608
}
Registry "CCE-36627-8: Ensure 'Set client connection encryption level' is set to 'Enabled: High Level'"
{
ValueName = 'MinEncryptionLevel'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 3
}
Registry "CCE-38217-6: Ensure 'Set the default behavior for AutoRun' is set to 'Enabled: Do not execute any autorun commands'"
{
ValueName = 'NoAutorun'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
ValueData = 1
}
Registry "CCE-38276-2: Ensure 'Setup: Control Event Log behavior when the log file reaches its maximum size' is set to 'Disabled'"
{
ValueName = 'Retention'
ValueType = 'String'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Setup'
ValueData = '0'
}
Registry "CCE-37526-1: Ensure 'Setup: Specify the maximum log file size ' is set to 'Enabled: 32,768 or greater'"
{
ValueName = 'MaxSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\Setup'
ValueData = 32768
}
Registry "CCE-36788-8: Ensure 'Shutdown: Allow system to be shut down without having to log on' is set to 'Disabled'"
{
ValueName = 'ShutdownWithoutLogon'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "CCE-36977-7: Ensure 'Sign-in last interactive user automatically after a system-initiated restart' is set to 'Disabled'"
{
ValueName = 'DisableAutomaticRestartSignOn'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-37885-1: Ensure 'System objects: Require case insensitivity for non-Windows subsystems' is set to 'Enabled'"
{
ValueName = 'ObCaseInsensitive'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Kernel'
ValueData = 1
}
Registry "CCE-37644-2: Ensure 'System objects: Strengthen default permissions of internal system objects ' is set to 'Enabled'"
{
ValueName = 'ProtectionMode'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Session Manager'
ValueData = 1
}
Registry "CCE-35921-6: Ensure 'System settings: Optional subsystems' is set to 'Defined: '"
{
ValueName = 'Optional'
ValueType = 'MultiString'
Key = 'HKLM:\System\CurrentControlSet\Control\Session Manager\SubSYSTEMs'
ValueData = '0'
}
Registry "CCE-36160-0: Ensure 'System: Control Event Log behavior when the log file reaches its maximum size' is set to 'Disabled'"
{
ValueName = 'Retention'
ValueType = 'String'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\System'
ValueData = '0'
}
Registry "CCE-36092-5: Ensure 'System: Specify the maximum log file size ' is set to 'Enabled: 32,768 or greater'"
{
ValueName = 'MaxSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\EventLog\System'
ValueData = 32768
}
Registry "CCE-35893-7: Ensure 'Turn off app notifications on the lock screen' is set to 'Enabled'"
{
ValueName = 'DisableLockScreenAppNotifications'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 1
}
Registry "CCE-36875-3: Ensure 'Turn off Autoplay' is set to 'Enabled: All drives'"
{
ValueName = 'NoDriveTypeAutoRun'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
ValueData = 255
}
Registry "CCE-37712-7: Ensure 'Turn off background refresh of Group Policy' is set to 'Disabled'"
{
ValueName = 'DisableBkGndGroupPolicy'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "CCE-37809-1: Ensure 'Turn off Data Execution Prevention for Explorer' is set to 'Disabled'"
{
ValueName = 'NoDataExecutionPrevention'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Explorer'
ValueData = 0
}
Registry "CCE-36660-9: Ensure 'Turn off heap termination on corruption' is set to 'Disabled'"
{
ValueName = 'NoHeapTerminationOnCorruption'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Explorer'
ValueData = 0
}
Registry "NOT_ASSIGNED: Ensure 'Turn off Microsoft consumer experiences' is set to 'Enabled'"
{
ValueName = 'DisableWindowsConsumerFeatures'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\CloudContent'
ValueData = 1
}
Registry "NOT_ASSIGNED: Ensure 'Turn off multicast name resolution' is set to 'Enabled'"
{
ValueName = 'EnableMulticast'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient'
ValueData = 1
}
Registry "CCE-36809-2: Ensure 'Turn off shell protocol protected mode' is set to 'Disabled'"
{
ValueName = 'PreXPSP2ShellProtocolBehavior'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
ValueData = 0
}
Registry "CCE-37528-7: Ensure 'Turn on convenience PIN sign-in' is set to 'Disabled'"
{
ValueName = 'AllowDomainPINLogon'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\System'
ValueData = 0
}
Registry "CCE-36494-3: Ensure 'User Account Control: Admin Approval Mode for the Built-in Administrator account' is set to 'Enabled'"
{
ValueName = 'FilterAdministratorToken'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-36863-9: Ensure 'User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop' is set to 'Disabled'"
{
ValueName = 'EnableUIADesktopToggle'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "CCE-37029-6: Ensure 'User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode' is set to 'Prompt for consent on the secure desktop'"
{
ValueName = 'ConsentPromptBehaviorAdmin'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 5
}
Registry "CCE-36864-7: Ensure 'User Account Control: Behavior of the elevation prompt for standard users' is set to 'Automatically deny elevation requests'"
{
ValueName = 'ConsentPromptBehaviorUser'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "CCE-36533-8: Ensure 'User Account Control: Detect application installations and prompt for elevation' is set to 'Enabled'"
{
ValueName = 'EnableInstallerDetection'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-37057-7: Ensure 'User Account Control: Only elevate UIAccess applications that are installed in secure locations' is set to 'Enabled'"
{
ValueName = 'EnableSecureUIAPaths'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-36869-6: Ensure 'User Account Control: Run all administrators in Admin Approval Mode' is set to 'Enabled'"
{
ValueName = 'EnableLUA'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-36866-2: Ensure 'User Account Control: Switch to the secure desktop when prompting for elevation' is set to 'Enabled'"
{
ValueName = 'PromptOnSecureDesktop'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-37064-3: Ensure 'User Account Control: Virtualize file and registry write failures to per-user locations' is set to 'Enabled'"
{
ValueName = 'EnableVirtualization'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 1
}
Registry "CCE-36062-8: Ensure 'Windows Firewall: Domain: Firewall state' is set to 'On '"
{
ValueName = 'EnableFirewall'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 1
}
Registry "CCE-38117-8: Ensure 'Windows Firewall: Domain: Inbound connections' is set to 'Block '"
{
ValueName = 'DefaultInboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 1
}
Registry "CCE-37523-8: Ensure 'Windows Firewall: Domain: Logging: Log dropped packets' is set to 'Yes'"
{
ValueName = 'LogDroppedPackets'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile\Logging'
ValueData = 1
}
Registry "CCE-36393-7: Ensure 'Windows Firewall: Domain: Logging: Log successful connections' is set to 'Yes'"
{
ValueName = 'LogSuccessfulConnections'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile\Logging'
ValueData = 1
}
Registry "CCE-36088-3: Ensure 'Windows Firewall: Domain: Logging: Size limit ' is set to '16,384 KB or greater'"
{
ValueName = 'LogFileSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile\Logging'
ValueData = 16384
}
Registry "CCE-36146-9: Ensure 'Windows Firewall: Domain: Outbound connections' is set to 'Allow '"
{
ValueName = 'DefaultOutboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 0
}
Registry "CCE-38040-2: Ensure 'Windows Firewall: Domain: Settings: Apply local connection security rules' is set to 'Yes '"
{
ValueName = 'AllowLocalIPsecPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 1
}
Registry "CCE-37860-4: Ensure 'Windows Firewall: Domain: Settings: Apply local firewall rules' is set to 'Yes '"
{
ValueName = 'AllowLocalPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 1
}
Registry "CCE-38041-0: Ensure 'Windows Firewall: Domain: Settings: Display a notification' is set to 'No'"
{
ValueName = 'DisableNotifications'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 1
}
Registry "CCE-38239-0: Ensure 'Windows Firewall: Private: Firewall state' is set to 'On '"
{
ValueName = 'EnableFirewall'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 1
}
Registry "CCE-38042-8: Ensure 'Windows Firewall: Private: Inbound connections' is set to 'Block '"
{
ValueName = 'DefaultInboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 1
}
Registry "CCE-35972-9: Ensure 'Windows Firewall: Private: Logging: Log dropped packets' is set to 'Yes'"
{
ValueName = 'LogDroppedPackets'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile\Logging'
ValueData = 1
}
Registry "CCE-37387-8: Ensure 'Windows Firewall: Private: Logging: Log successful connections' is set to 'Yes'"
{
ValueName = 'LogSuccessfulConnections'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile\Logging'
ValueData = 1
}
Registry "CCE-38178-0: Ensure 'Windows Firewall: Private: Logging: Size limit ' is set to '16,384 KB or greater'"
{
ValueName = 'LogFileSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile\Logging'
ValueData = 16384
}
Registry "CCE-38332-3: Ensure 'Windows Firewall: Private: Outbound connections' is set to 'Allow '"
{
ValueName = 'DefaultOutboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 0
}
Registry "CCE-36063-6: Ensure 'Windows Firewall: Private: Settings: Apply local connection security rules' is set to 'Yes '"
{
ValueName = 'AllowLocalIPsecPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 1
}
Registry "CCE-37438-9: Ensure 'Windows Firewall: Private: Settings: Apply local firewall rules' is set to 'Yes '"
{
ValueName = 'AllowLocalPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 1
}
Registry "CCE-37621-0: Ensure 'Windows Firewall: Private: Settings: Display a notification' is set to 'No'"
{
ValueName = 'DisableNotifications'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 1
}
Registry "CCE-37862-0: Ensure 'Windows Firewall: Public: Firewall state' is set to 'On '"
{
ValueName = 'EnableFirewall'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
Registry "CCE-36057-8: Ensure 'Windows Firewall: Public: Inbound connections' is set to 'Block '"
{
ValueName = 'DefaultInboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
Registry "CCE-37265-6: Ensure 'Windows Firewall: Public: Logging: Log dropped packets' is set to 'Yes'"
{
ValueName = 'LogDroppedPackets'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile\Logging'
ValueData = 1
}
Registry "CCE-36394-5: Ensure 'Windows Firewall: Public: Logging: Log successful connections' is set to 'Yes'"
{
ValueName = 'LogSuccessfulConnections'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile\Logging'
ValueData = 1
}
Registry "CCE-36395-2: Ensure 'Windows Firewall: Public: Logging: Size limit ' is set to '16,384 KB or greater'"
{
ValueName = 'LogFileSize'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile\Logging'
ValueData = 16384
}
Registry "CCE-37434-8: Ensure 'Windows Firewall: Public: Outbound connections' is set to 'Allow '"
{
ValueName = 'DefaultOutboundAction'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 0
}
Registry "CCE-36268-1: Ensure 'Windows Firewall: Public: Settings: Apply local connection security rules' is set to 'No'"
{
ValueName = 'AllowLocalIPsecPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
Registry "CCE-37861-2: Ensure 'Windows Firewall: Public: Settings: Apply local firewall rules' is set to 'No'"
{
ValueName = 'AllowLocalPolicyMerge'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
Registry "CCE-38043-6: Ensure 'Windows Firewall: Public: Settings: Display a notification' is set to 'Yes'"
{
ValueName = 'DisableNotifications'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
Registry "CCE-37843-0: Ensure 'Enable Windows NTP Client' is set to 'Enabled'"
{
ValueName = 'Enabled'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\W32Time\TimeProviders\NtpClient'
ValueData = 1
}
Registry "CCE-36625-2: Ensure 'Turn off downloading of print drivers over HTTP' is set to 'Enabled'"
{
ValueName = 'DisableWebPnPDownload'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Printers'
ValueData = 1
}
Registry "CCE-37163-3: Ensure 'Turn off Internet Connection Wizard if URL connection is referring to Microsoft.com' is set to 'Enabled'"
{
ValueName = 'ExitOnMSICW'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Internet Connection Wizard'
ValueData = 1
}
Registry "NOT_ASSIGNED: Devices: Allow undock without having to log on"
{
ValueName = 'UndockWithoutLogon'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System'
ValueData = 0
}
Registry "NOT_ASSIGNED: Disable 'Configure local setting override for reporting to Microsoft MAPS'"
{
ValueName = 'LocalSettingOverrideSpynetReporting'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows Defender\SpyNet'
ValueData = 0
}
Registry "NOT_ASSIGNED: Disable SMB v1 client"
{
ValueName = 'DependsOnService'
ValueType = 'MultiString'
Key = 'HKLM:\System\CurrentControlSet\Services\LanmanWorkstation'
ValueData = 'Bowser","MRxSmb20","NSI'
}
Registry "NOT_ASSIGNED: Disable SMB v1 server"
{
ValueName = 'SMB1'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\LanmanServer\Parameters'
ValueData = 0
}
Registry "NOT_ASSIGNED: Disable Windows Search Service"
{
ValueName = 'Start'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Services\Wsearch'
ValueData = 4
}
Registry "NOT_ASSIGNED: Enable 'Scan removable drives' by setting DisableRemovableDriveScanning to 0"
{
ValueName = 'DisableRemovableDriveScanning'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows Defender\Scan'
ValueData = 0
}
Registry "NOT_ASSIGNED: Enable 'Send file samples when further analysis is required' for 'Send Safe Samples'"
{
ValueName = 'SubmitSamplesConsent'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows Defender\SpyNet'
ValueData = 1
}
Registry "NOT_ASSIGNED: Enable 'Turn on behavior monitoring'"
{
ValueName = 'DisableBehaviorMonitoring'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows Defender\Real-Time Protection'
ValueData = 0
}
Registry "NOT_ASSIGNED: Enable Windows Error Reporting"
{
ValueName = 'Disabled'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows\Windows Error Reporting'
ValueData = 0
}
Registry "NOT_ASSIGNED: Recovery console: Allow floppy copy and access to all drives and all folders"
{
ValueName = 'setcommand'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole'
ValueData = 0
}
Registry "NOT_ASSIGNED: Require user authentication for remote connections by using Network Level Authentication"
{
ValueName = 'UserAuthentication'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services'
ValueData = 1
}
Registry "NOT_ASSIGNED: Shutdown: Clear virtual memory pagefile"
{
ValueName = 'ClearPageFileAtShutdown'
ValueType = 'DWORD'
Key = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Memory Management'
ValueData = 0
}
Registry "NOT_ASSIGNED: Specify the interval to check for definition updates"
{
ValueName = 'SignatureUpdateInterval'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Microsoft Antimalware\Signature Updates'
ValueData = 8
}
Registry "NOT_ASSIGNED: System settings: Use Certificate Rules on Windows Executables for Software Restriction Policies"
{
ValueName = 'AuthenticodeEnabled'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers'
ValueData = 1
}
Registry "NOT_ASSIGNED: Windows Firewall: Domain: Allow unicast response"
{
ValueName = 'DisableUnicastResponsesToMulticastBroadcast'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\DomainProfile'
ValueData = 0
}
Registry "NOT_ASSIGNED: Windows Firewall: Private: Allow unicast response"
{
ValueName = 'DisableUnicastResponsesToMulticastBroadcast'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile'
ValueData = 0
}
Registry "NOT_ASSIGNED: Windows Firewall: Public: Allow unicast response"
{
ValueName = 'DisableUnicastResponsesToMulticastBroadcast'
ValueType = 'DWORD'
Key = 'HKLM:\Software\Policies\Microsoft\WindowsFirewall\PublicProfile'
ValueData = 1
}
AuditPolicySubcategory "CCE-38329-9: Ensure 'Audit Application Group Management' is set to 'Success and Failure' (Success)"
{
Name = 'Application Group Management'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-38329-9: Ensure 'Audit Application Group Management' is set to 'Success and Failure' (Failure)"
{
Name = 'Application Group Management'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "CCE-38004-8: Ensure 'Audit Computer Account Management' is set to 'Success and Failure' (Success)"
{
Name = 'Computer Account Management'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-38004-8: Ensure 'Audit Computer Account Management' is set to 'Success and Failure' (Failure)"
{
Name = 'Computer Account Management'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubCategory "CCE-37741-6: Ensure 'Audit Credential Validation' is set to 'Success and Failure' (Success)"
{
Name = 'Credential Validation'
Ensure = 'Present'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-37741-6: Ensure 'Audit Credential Validation' is set to 'Success and Failure' (Failure)"
{
Name = 'Credential Validation'
Ensure = 'Present'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "CCE-36265-7: Ensure 'Audit Distribution Group Management' is set to 'Success and Failure' (Success)"
{
Name = 'Distribution Group Management'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-36265-7: Ensure 'Audit Distribution Group Management' is set to 'Success and Failure' (Failure)"
{
Name = 'Distribution Group Management'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "CCE-38237-4: Ensure 'Audit Logoff' is set to 'Success'"
{
Name = 'Logoff'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-38036-0: Ensure 'Audit Logon' is set to 'Success and Failure' (Success)"
{
Name = 'Logon'
Ensure = 'Present'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-38036-0: Ensure 'Audit Logon' is set to 'Success and Failure' (Failure)"
{
Name = 'Logon'
Ensure = 'Present'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "CCE-37855-4: Ensure 'Audit Other Account Management Events' is set to 'Success and Failure' (Success)"
{
Name = 'Other Account Management Events'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-37855-4: Ensure 'Audit Other Account Management Events' is set to 'Success and Failure' (Failure)"
{
Name = 'Other Account Management Events'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "NOT_ASSIGNED: Ensure 'Audit PNP Activity' is set to 'Success'"
{
Name = 'Plug and Play Events'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-36059-4: Ensure 'Audit Process Creation' is set to 'Success'"
{
Name = 'Process Creation'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-37617-8: Ensure 'Audit Removable Storage' is set to 'Success and Failure' (Success)"
{
Name = 'Removable Storage'
Ensure = 'Present'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-37617-8: Ensure 'Audit Removable Storage' is set to 'Success and Failure' (Failure)"
{
Name = 'Removable Storage'
Ensure = 'Present'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "CCE-38034-5: Ensure 'Audit Security Group Management' is set to 'Success and Failure'"
{
Name = 'Security Group Management'
AuditFlag = 'Success'
}
AuditPolicySubcategory "CCE-36266-5: Ensure 'Audit Special Logon' is set to 'Success'"
{
Name = 'Special Logon'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-37856-2: Ensure 'Audit User Account Management' is set to 'Success and Failure' (Success)"
{
Name = 'User Account Management'
Ensure = 'Present'
AuditFlag = 'Success'
}
AuditPolicySubCategory "CCE-37856-2: Ensure 'Audit User Account Management' is set to 'Success and Failure' (Failure)"
{
Name = 'User Account Management'
Ensure = 'Present'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Kerberos Authentication Service (Success)"
{
Name = 'Kerberos Authentication Service'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Kerberos Authentication Service (Failure)"
{
Name = 'Kerberos Authentication Service'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Kerberos Service Ticket Operations (Success)"
{
Name = 'Kerberos Service Ticket Operations'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Kerberos Service Ticket Operations (Failure)"
{
Name = 'Kerberos Service Ticket Operations'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Non Sensitive Privilege Use (Success)"
{
Name = 'Non Sensitive Privilege Use'
Ensure = 'Absent'
AuditFlag = 'Success'
}
AuditPolicySubcategory "NOT_ASSIGNED: Audit Non Sensitive Privilege Use (Failure)"
{
Name = 'Non Sensitive Privilege Use'
Ensure = 'Absent'
AuditFlag = 'Failure'
}
UserRightsAssignment "CCE-35818-4: Configure 'Access this computer from the network'"
{
Policy = 'Access_this_computer_from_the_network'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\AUTHENTICATED USERS'
)
}
UserRightsAssignment "CCE-37072-6: Configure 'Allow log on through Remote Desktop Services'"
{
Policy = 'Allow_log_on_through_Remote_Desktop_Services'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-35823-4: Configure 'Create symbolic links'"
{
Policy = 'Create_symbolic_links'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37954-5: Configure 'Deny access to this computer from the network'"
{
Policy = 'Deny_access_to_this_computer_from_the_network'
Identity = @('BUILTIN\Guests'
)
}
UserRightsAssignment "CCE-36860-5: Configure 'Enable computer and user accounts to be trusted for delegation'"
{
Policy = 'Enable_computer_and_user_accounts_to_be_trusted_for_delegation'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-35906-7: Configure 'Manage auditing and security log'"
{
Policy = 'Manage_auditing_and_security_log'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37056-9: Ensure 'Access Credential Manager as a trusted caller' is set to 'No One'"
{
Policy = 'Access_Credential_Manager_as_a_trusted_caller'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-36876-1: Ensure 'Act as part of the operating system' is set to 'No One'"
{
Policy = 'Act_as_part_of_the_operating_system'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-35912-5: Ensure 'Back up files and directories' is set to 'Administrators'"
{
Policy = 'Back_up_files_and_directories'
Identity = @('BUILTIN\Backup Operators'
)
}
UserRightsAssignment "CCE-37452-0: Ensure 'Change the system time' is set to 'Administrators, LOCAL SERVICE'"
{
Policy = 'Change_the_system_time'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\LOCAL SERVICE'
)
}
UserRightsAssignment "CCE-37700-2: Ensure 'Change the time zone' is set to 'Administrators, LOCAL SERVICE'"
{
Policy = 'Change_the_time_zone'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\LOCAL SERVICE'
)
}
UserRightsAssignment "CCE-35821-8: Ensure 'Create a pagefile' is set to 'Administrators'"
{
Policy = 'Create_a_pagefile'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-36861-3: Ensure 'Create a token object' is set to 'No One'"
{
Policy = 'Create_a_token_object'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-37453-8: Ensure 'Create global objects' is set to 'Administrators, LOCAL SERVICE, NETWORK SERVICE, SERVICE'"
{
Policy = 'Create_global_objects'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\SERVICE', 'NT AUTHORITY\LOCAL SERVICE', 'NT AUTHORITY\NETWORK SERVICE'
)
}
UserRightsAssignment "CCE-36532-0: Ensure 'Create permanent shared objects' is set to 'No One'"
{
Policy = 'Create_permanent_shared_objects'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-36923-1: Ensure 'Deny log on as a batch job' to include 'Guests'"
{
Policy = 'Deny_log_on_as_a_batch_job'
Identity = @('BUILTIN\Guests'
)
}
UserRightsAssignment "CCE-36877-9: Ensure 'Deny log on as a service' to include 'Guests'"
{
Policy = 'Deny_log_on_as_a_service'
Identity = @('BUILTIN\Guests'
)
}
UserRightsAssignment "CCE-37146-8: Ensure 'Deny log on locally' to include 'Guests'"
{
Policy = 'Deny_log_on_locally'
Identity = @('BUILTIN\Guests'
)
}
UserRightsAssignment "CCE-36867-0: Ensure 'Deny log on through Remote Desktop Services' to include 'Guests, Local account'"
{
Policy = 'Deny_log_on_through_Remote_Desktop_Services'
Identity = @('BUILTIN\Guests'
)
}
UserRightsAssignment "CCE-37877-8: Ensure 'Force shutdown from a remote system' is set to 'Administrators'"
{
Policy = 'Force_shutdown_from_a_remote_system'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37639-2: Ensure 'Generate security audits' is set to 'LOCAL SERVICE, NETWORK SERVICE'"
{
Policy = 'Generate_security_audits'
Identity = @('NT AUTHORITY\LOCAL SERVICE', 'NT AUTHORITY\NETWORK SERVICE'
)
}
UserRightsAssignment "CCE-38326-5: Ensure 'Increase scheduling priority' is set to 'Administrators'"
{
Policy = 'Increase_scheduling_priority'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-36318-4: Ensure 'Load and unload device drivers' is set to 'Administrators'"
{
Policy = 'Load_and_unload_device_drivers'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-36495-0: Ensure 'Lock pages in memory' is set to 'No One'"
{
Policy = 'Lock_pages_in_memory'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-36054-5: Ensure 'Modify an object label' is set to 'No One'"
{
Policy = 'Modify_an_object_label'
Force = $True
Identity = @(
)
}
UserRightsAssignment "CCE-38113-7: Ensure 'Modify firmware environment values' is set to 'Administrators'"
{
Policy = 'Modify_firmware_environment_values'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-36143-6: Ensure 'Perform volume maintenance tasks' is set to 'Administrators'"
{
Policy = 'Perform_volume_maintenance_tasks'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37131-0: Ensure 'Profile single process' is set to 'Administrators'"
{
Policy = 'Profile_single_process'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-36052-9: Ensure 'Profile system performance' is set to 'Administrators, NT SERVICE\WdiServiceHost'"
{
Policy = 'Profile_system_performance'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37430-6: Ensure 'Replace a process level token' is set to 'LOCAL SERVICE, NETWORK SERVICE'"
{
Policy = 'Replace_a_process_level_token'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-37613-7: Ensure 'Restore files and directories' is set to 'Administrators'"
{
Policy = 'Restore_files_and_directories'
Identity = @('BUILTIN\Administrators', 'BUILTIN\Backup Operators'
)
}
UserRightsAssignment "CCE-38328-1: Ensure 'Shut down the system' is set to 'Administrators'"
{
Policy = 'Shut_down_the_system'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "CCE-38325-7: Ensure 'Take ownership of files or other objects' is set to 'Administrators'"
{
Policy = 'Take_ownership_of_files_or_other_objects'
Identity = @('BUILTIN\Administrators'
)
}
UserRightsAssignment "NOT_ASSIGNED: Bypass traverse checking"
{
Policy = 'Bypass_traverse_checking'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\AUTHENTICATED USERS', 'BUILTIN\Backup Operators', 'NT AUTHORITY\LOCAL SERVICE', 'NT AUTHORITY\NETWORK SERVICE'
)
}
UserRightsAssignment "NOT_ASSIGNED: Increase a process working set"
{
Policy = 'Increase_a_process_working_set'
Identity = @('BUILTIN\Administrators', 'NT AUTHORITY\LOCAL SERVICE'
)
}
UserRightsAssignment "NOT_ASSIGNED: Remove computer from docking station"
{
Policy = 'Remove_computer_from_docking_station'
Identity = @('BUILTIN\Administrators'
)
}
}
} | {
"pile_set_name": "Github"
} |
# Bundle js-ipfs-http-client with Webpack!
> In this example, you will find a boilerplate you can use to guide yourself into bundling js-ipfs-http-client with webpack, so that you can use it in your own web app!
## Setup
As for any js-ipfs-http-client example, **you need a running IPFS daemon**, you learn how to do that here:
- [Spawn a go-ipfs daemon](https://ipfs.io/docs/getting-started/)
- [Spawn a js-ipfs daemon](https://github.com/ipfs/js-ipfs#usage)
**Note:** If you load your app from a different domain than the one the daemon is running (most probably), you will need to set up CORS, see https://github.com/ipfs/js-ipfs-http-client#cors to learn how to do that.
A quick (and dirty) way to get it done is:
```bash
> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]"
> ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]"
```
## Run this example
Once the daemon is on, run the following commands within this folder:
```bash
> npm install
> npm start
```
Now open your browser at `http://localhost:8888`
You should see the following:

| {
"pile_set_name": "Github"
} |
<?php
/**
* Created by PhpStorm.
* User: mac
* Date: 14-5-26
* Time: 下午12:18
*/
namespace ZPHP\Common;
class AsyncHttpClient
{
private static $buffer = [];
public static function request(callable $callback, $url, $method='GET', array $headers=[], array $params=[])
{
$parsed_url = parse_url($url);
\swoole_async_dns_lookup($parsed_url['host'], function($host, $ip) use ($parsed_url, $callback, $url, $method, $headers, $params) {
$port = isset($parsed_url['port']) ? $parsed_url['port'] : 'https' == $parsed_url['scheme'] ? 443 : 80;
$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$method = strtoupper($method);
$client->on("connect", function($cli) use($url, $method, $parsed_url, $headers, $params) {
\ZPHP\Common\AsyncHttpClient::clear($cli);
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
if(!empty($params)) {
$query = http_build_query($params);
if ('GET' == $method) {
$path .= "?" . $query;
}
}
$sendData = $method." {$path} HTTP/1.1\r\n";
$headers = array(
'Host'=>$parsed_url['host'],
'Connection'=>'keep-alive',
'Pragma'=>'no-cache',
'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent'=>'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36',
'Referer'=>$url,
'Accept-Encoding'=>'gzip, deflate, sdch',
'Accept-Language'=>'zh-CN,zh;q=0.8',
) + $headers;
foreach($headers as $key=>$val) {
$sendData.="{$key}: {$val}\r\n";
}
if('POST' === $method) {
$sendData.="Content-Length: ".strlen($query)."\r\n";
$sendData.="\r\n".$query;
} else {
$sendData.="\r\n";
}
$cli->send($sendData);
});
$client->on("receive", function($cli, $data) use ($callback) {
$ret = self::parseBody($cli, $data, $callback);
if(is_array($ret)) {
call_user_func_array($callback, array($cli, $ret));
}
});
$client->on("error", function($cli){
\ZPHP\Common\AsyncHttpClient::clear($cli);
});
$client->on("close", function($cli){
\ZPHP\Common\AsyncHttpClient::clear($cli);
});
$client->connect($ip, $port);
});
}
public static function clear($cli)
{
self::$buffer[$cli->sock] = null;
}
public static function parseBody($cli, $content, $callback)
{
if(empty(self::$buffer[$cli->sock])) {
list($header, $body) = explode("\r\n\r\n", $content, 2);
$headers = explode("\r\n", $header);
$status = array_shift($headers);
$statusArr = explode(" ", $status, 3);
$headerArr = [];
foreach($headers as $item) {
$tmp = explode(':', $item, 2);
$headerArr[$tmp[0]] = trim($tmp[1]);
}
self::$buffer[$cli->sock]['result']['status'] = $statusArr;
self::$buffer[$cli->sock]['result']['header'] = $headerArr;
if(in_array($statusArr[1], [301, 302])) {
return \ZPHP\Common\AsyncHttpClient::request($callback, $headerArr['Location']);
}
self::outPut($cli, $body);
} else {
self::outPut($cli, $content);
}
if(!empty(self::$buffer[$cli->sock]['err'])) {
self::clear($cli);
return false;
}
if(!empty(self::$buffer[$cli->sock]['finish'])) {
if(!empty(self::$buffer[$cli->sock]['result']['header']['Content-Encoding'])) {
switch (self::$buffer[$cli->sock]['result']['header']['Content-Encoding']) {
case 'gzip':
self::$buffer[$cli->sock]['result']['body'] = gzdecode(self::$buffer[$cli->sock]['buffer']);
break;
case 'deflate':
self::$buffer[$cli->sock]['result']['body'] = gzinflate(self::$buffer[$cli->sock]['buffer']);
break;
case 'compress':
self::$buffer[$cli->sock]['result']['body'] = gzinflate(substr(self::$buffer[$cli->sock]['buffer'], 2, -4));
break;
default:
self::$buffer[$cli->sock]['result']['body'] = self::$buffer[$cli->sock]['buffer'];
break;
}
} else {
self::$buffer[$cli->sock]['result']['body'] = self::$buffer[$cli->sock]['buffer'];
}
$result = self::$buffer[$cli->sock]['result'];
self::clear($cli);
return $result;
}
}
public static function outPut($cli, $content)
{
if(isset(self::$buffer[$cli->sock]['result']['header']['Transfer-Encoding'])
&& 'chunked' == self::$buffer[$cli->sock]['result']['header']['Transfer-Encoding']
) {
if(empty(self::$buffer[$cli->sock]['chunkLen'])) {
$len = strstr($content, "\r\n", true);
$length = hexdec($len);
if ($length == 0) {
self::$buffer[$cli->sock]['finish'] = 1;
self::$buffer[$cli->sock]['buffer'] = substr(self::$buffer[$cli->sock]['buffer'], 0, strlen(self::$buffer[$cli->sock]['buffer']) - strlen($content));
return;
}
self::$buffer[$cli->sock]['chunkLen'] = $length;
self::$buffer[$cli->sock]['buffer'].= substr($content, strlen($len)+2);
} else {
self::$buffer[$cli->sock]['buffer'].= $content;
}
if(strlen(self::$buffer[$cli->sock]['buffer']) >= self::$buffer[$cli->sock]['chunkLen']) {
$len = self::$buffer[$cli->sock]['chunkLen'];
self::$buffer[$cli->sock]['chunkLen'] = 0;
self::outPut($cli, substr(self::$buffer[$cli->sock]['buffer'], $len));
}
} else {
self::$buffer[$cli->sock]['buffer'] .= $content;
if(strlen(self::$buffer[$cli->sock]['buffer']) >= self::$buffer[$cli->sock]['result']['header']['Content-Length']) {
self::$buffer[$cli->sock]['finish'] = 1;
self::$buffer[$cli->sock]['buffer'] = substr(self::$buffer[$cli->sock]['buffer'], 0, self::$buffer[$cli->sock]['result']['header']['Content-Length']);
return;
}
}
}
} | {
"pile_set_name": "Github"
} |
#!/usr/bin/env node
var path = require('path');
var argv = require('yargs')
.usage('Usage: markn [path]')
.example('markn', 'Run Markn')
.example('markn foo.md', 'Open the markdown file with Markn')
.help('h')
.alias('h', 'help')
.argv;
var spawn = require('child_process').spawn;
var platform = process.platform;
var arch = process.arch;
var app = path.join(__dirname, '../build/Markn-' + platform + '-' + arch + '/');
var cmd, args;
switch (platform) {
case 'darwin':
app += 'Markn.app/Contents/MacOS/Electron';
cmd = app
args = argv._
break;
case 'linux':
app += 'Markn';
cmd = app;
args = argv._;
break;
case 'win32':
app += 'Markn.exe';
cmd = app;
args = argv._;
break;
default:
console.error('Unsupported platform:', platform);
process.exit(1);
break;
}
console.log('spawn:', cmd, args);
var Markn = spawn(cmd, args);
Markn.stdout.on('data', function (data) {
console.log(data.toString('utf8'));
});
Markn.stderr.on('data', function (data) {
console.error(data.toString('utf8'));
});
Markn.on('close', function (code) {
console.log('closed:', code);
});
| {
"pile_set_name": "Github"
} |
#ifndef __NV50_DEVINIT_H__
#define __NV50_DEVINIT_H__
#define nv50_devinit(p) container_of((p), struct nv50_devinit, base)
#include "priv.h"
struct nv50_devinit {
struct nvkm_devinit base;
u32 r001540;
};
int nv50_devinit_new_(const struct nvkm_devinit_func *, struct nvkm_device *,
int, struct nvkm_devinit **);
void nv50_devinit_preinit(struct nvkm_devinit *);
void nv50_devinit_init(struct nvkm_devinit *);
int nv50_devinit_pll_set(struct nvkm_devinit *, u32, u32);
int gt215_devinit_pll_set(struct nvkm_devinit *, u32, u32);
int gf100_devinit_ctor(struct nvkm_object *, struct nvkm_object *,
struct nvkm_oclass *, void *, u32,
struct nvkm_object **);
int gf100_devinit_pll_set(struct nvkm_devinit *, u32, u32);
void gf100_devinit_preinit(struct nvkm_devinit *);
u64 gm107_devinit_disable(struct nvkm_devinit *);
#endif
| {
"pile_set_name": "Github"
} |
{
"type": "array",
"items": {
"type": "object",
"properties" : {
"basename": { "type": "string" },
"data": { "type": "string" },
"path": { "type": ["string"] },
"filename": { "type": ["string"] },
"id": { "type": ["string", "null"] },
"project_id": { "type": "integer" },
"ref": { "type": "string" },
"startline": { "type": "integer" }
},
"required": [
"basename", "data", "path", "filename", "id", "ref", "startline", "project_id"
],
"additionalProperties": false
}
}
| {
"pile_set_name": "Github"
} |
Erase all
Times
12
depth = 200
sweep = Create Sound from formula: "sweep", 1, 0, 10, 16000,
... ~ sin (2 * pi * 400 * x^2)
To Spectrogram: 0.05, 8000, 0.002, 20, "Gaussian"
Select outer viewport: 0, 6, 0, 3
Paint: 0, 0, 0, 8000, 100, "yes", 90, 0, 0, "yes"
Remove
selectObject: sweep
sweep_8k = Resample: 8000, 50
To Spectrogram: 0.05, 8000, 0.002, 20, "Gaussian"
Select outer viewport: 0, 6, 3, 6
Paint: 0, 0, 0, 8000, 100, "yes", 90, 0, 0, "yes"
Remove
cutoff = 3800
filter_mat = Create Matrix: "filter1", -depth / 16000, depth / 16000,
... depth*2, 1 / 16000, (-depth+0.5) / 16000,
... 1, 1, 1, 1, 1, ~ if x = 0 then 1 else sin (2*pi*x*cutoff) / (2*pi*x*cutoff)
... * (0.5 + 0.5 * cos (pi * x*16000 / depth)) fi
sum = Get sum
Formula: ~ self / sum
filter = To Sound
selectObject: sweep, filter
sweep_low = Convolve: "sum", "zero"
mooi = Create Sound from formula: "mooi", 1, 0, 10, 16000/2, ~ object [sweep_low, col*2]
To Spectrogram: 0.05, 8000, 0.002, 20, "Gaussian"
Select outer viewport: 0, 6, 6, 9
Paint: 0, 0, 0, 8000, 100, "yes", 90, 0, 0, "yes"
Remove
#
# Write to Info window in base-0 C format.
#
writeInfo: "static double filter_2 [", depth*2, "] = { "
for i to depth*2
value = object [filter, i]
appendInfo: if abs (value) < 1e-12 then 0 else fixed$ (value, 12) fi, ", "
endfor
appendInfoLine: "};"
removeObject: filter_mat, filter, sweep_low, sweep, sweep_8k, mooi
| {
"pile_set_name": "Github"
} |
<?php
namespace Sabre\DAV\Sync;
use Sabre\DAV;
/**
* If a class extends ISyncCollection, it supports WebDAV-sync.
*
* You are responsible for maintaining a changelist for this collection. This
* means that if any child nodes in this collection was created, modified or
* deleted in any way, you should maintain an updated changelist.
*
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @author Evert Pot (http://evertpot.com/)
* @license http://sabre.io/license/ Modified BSD License
*/
interface ISyncCollection extends DAV\ICollection {
/**
* This method returns the current sync-token for this collection.
* This can be any string.
*
* If null is returned from this function, the plugin assumes there's no
* sync information available.
*
* @return string|null
*/
function getSyncToken();
/**
* The getChanges method returns all the changes that have happened, since
* the specified syncToken and the current collection.
*
* This function should return an array, such as the following:
*
* [
* 'syncToken' => 'The current synctoken',
* 'added' => [
* 'new.txt',
* ],
* 'modified' => [
* 'modified.txt',
* ],
* 'deleted' => array(
* 'foo.php.bak',
* 'old.txt'
* )
* ];
*
* The syncToken property should reflect the *current* syncToken of the
* collection, as reported getSyncToken(). This is needed here too, to
* ensure the operation is atomic.
*
* If the syncToken is specified as null, this is an initial sync, and all
* members should be reported.
*
* The modified property is an array of nodenames that have changed since
* the last token.
*
* The deleted property is an array with nodenames, that have been deleted
* from collection.
*
* The second argument is basically the 'depth' of the report. If it's 1,
* you only have to report changes that happened only directly in immediate
* descendants. If it's 2, it should also include changes from the nodes
* below the child collections. (grandchildren)
*
* The third (optional) argument allows a client to specify how many
* results should be returned at most. If the limit is not specified, it
* should be treated as infinite.
*
* If the limit (infinite or not) is higher than you're willing to return,
* you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
*
* If the syncToken is expired (due to data cleanup) or unknown, you must
* return null.
*
* The limit is 'suggestive'. You are free to ignore it.
*
* @param string $syncToken
* @param int $syncLevel
* @param int $limit
* @return array
*/
function getChanges($syncToken, $syncLevel, $limit = null);
}
| {
"pile_set_name": "Github"
} |
// The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <[email protected]>
//
// 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.
use gfx::canvas::Canvas;
use gfx::pencil::Pencil;
use gfx::scene::{Scene, SceneAction};
use gfx::ui_helper;
use core::camera::Camera;
use core::constants::*;
use core::resource_manager::resource::Resource;
use core::resource_manager::resource_type::ResourceType;
use core::resource_manager::ResourceManager;
use glium::Frame;
use conrod::position::rect::Rect;
/// How many time we should wait before changing our wallpaper
const WALLPAPER_DELAY: u32 = 40;
widget_ids! {
struct Ids {
master,
header,
header_left_column,
header_right_column,
title,
logo_left,
logo_right,
body,
body_footer,
body_footer_left,
body_footer_right,
singleplayer,
multiplayer,
realms,
options,
quit,
footer,
version,
copyright,
}
}
/// Show Litecraft logo and start resource loading
pub struct MainMenu {
ids: Ids,
camera: Camera,
}
impl MainMenu {
pub fn new(canvas: &mut Canvas) -> MainMenu {
let ids = Ids::new(canvas.ui_mut().widget_id_generator());
let mut camera = Camera::new();
camera.set_fov(55.0);
MainMenu { ids, camera }
}
/// Main menu's background
fn draw_wallpaper(&mut self, canvas: &mut Canvas, frame: &mut Frame) {
let i = ResourceManager::time() as u32 / WALLPAPER_DELAY % 5;
let wallpaper = canvas.resources().textures().get(&Resource::minecraft_path(
format!("panorama_{}", i),
"gui/title/background",
ResourceType::Texture,
));
if let Some(wallpaper) = wallpaper {
Pencil::new(frame, "wallpaper", &canvas)
.texture(wallpaper)
.camera(&self.camera)
.linear(true)
.draw();
}
}
}
impl Scene for MainMenu {
/// Do resource load
fn load(&mut self, canvas: &mut Canvas) {
canvas
.resources_mut()
.textures_mut()
.load_ui(Resource::minecraft_path(
"minecraft",
"gui/title",
ResourceType::Texture,
));
canvas
.resources_mut()
.textures_mut()
.load_ui(Resource::minecraft_path("widgets", "gui", ResourceType::Texture));
}
/// Draw scene
fn draw(&mut self, canvas: &mut Canvas, frame: &mut Frame) -> SceneAction {
use conrod::{color, widget, Colorable, Labelable, Positionable, Sizeable, Widget};
let logo = canvas.resources().textures().get_ui(&Resource::minecraft_path(
"minecraft",
"gui/title",
ResourceType::Texture,
));
let widgets = canvas.resources().textures().get_ui(&Resource::minecraft_path(
"widgets",
"gui",
ResourceType::Texture,
));
self.draw_wallpaper(canvas, frame);
let scale = canvas.settings().scale();
let mut ui = canvas.ui_mut().set_widgets();
// Construct our main `Canvas` tree.
widget::Canvas::new()
.flow_down(&[
(
self.ids.header,
widget::Canvas::new().pad(85.0).flow_right(&[
(self.ids.header_left_column, widget::Canvas::new()),
(self.ids.header_right_column, widget::Canvas::new()),
]),
),
(self.ids.body, widget::Canvas::new().length(300.0)),
(
self.ids.footer,
widget::Canvas::new().pad(20.0).scroll_kids_vertically(),
),
])
.set(self.ids.master, &mut ui);
// Draw the beloved Minecraft logo
if let Some(logo) = logo {
// Texture coordinates
let base = 256.0;
let size = [280.0 * scale, 85.0 * scale];
let (w, h) = logo.1;
// Draw logo first part
widget::Image::new(logo.0)
.bottom_right_of(self.ids.header_left_column)
.wh(size)
.source_rectangle(Rect::from_corners(
[0.0, 212.0 * h / base],
[156.0 * w / base, 256.0 * h / base],
))
.set(self.ids.logo_left, &mut ui);
// Draw logo second part
widget::Image::new(logo.0)
.bottom_left_of(self.ids.header_right_column)
.wh(size)
.source_rectangle(Rect::from_corners(
[0.0, 168.0 * h / base],
[156.0 * w / base, 211.0 * h / base],
))
.set(self.ids.logo_right, &mut ui);
}
if let Some(widgets) = widgets {
ui_helper::button(&widgets, scale)
.label("Singleplayer")
.up_from(self.ids.multiplayer, 15.0 * scale)
.set(self.ids.singleplayer, &mut ui);
ui_helper::button(&widgets, scale)
.label("Multiplayer")
.middle_of(self.ids.body)
.set(self.ids.multiplayer, &mut ui);
ui_helper::button(&widgets, scale)
.label("Minecraft Realms")
.down_from(self.ids.multiplayer, 15.0 * scale)
.set(self.ids.realms, &mut ui);
widget::Canvas::new()
.flow_right(&[
(self.ids.body_footer_left, widget::Canvas::new()),
(self.ids.body_footer_right, widget::Canvas::new()),
])
.w(480.0 * scale)
.down_from(self.ids.realms, 50.0 * scale)
.set(self.ids.body_footer, &mut ui);
ui_helper::button(&widgets, scale)
.label("Options")
.top_left_of(self.ids.body_footer_left)
.padded_w_of(self.ids.body_footer_left, 5.0)
.set(self.ids.options, &mut ui);
if ui_helper::button(&widgets, scale)
.label("Quit Game")
.top_right_of(self.ids.body_footer_right)
.padded_w_of(self.ids.body_footer_right, 5.0)
.set(self.ids.quit, &mut ui)
.was_clicked()
{
return SceneAction::Quit;
}
}
// Litecraft and Minecraft version
widget::Text::new(VERSION_TEXT)
.color(color::WHITE)
.font_size(16)
.bottom_left_of(self.ids.footer)
.set(self.ids.version, &mut ui);
// Credits
widget::Text::new("© Litecraft Team")
.color(color::WHITE)
.font_size(16)
.bottom_right_of(self.ids.footer)
.set(self.ids.copyright, &mut ui);
SceneAction::None
}
}
| {
"pile_set_name": "Github"
} |
HTMLImports.whenReady(function() {
Polymer({
is: 'x-list',
properties: {
items: {
type: Array,
value: function() {
var data = [];
for (var i = 1; i <= 64; i++) {
data.push(i);
}
return data;
}
}
},
removeItems:function() {
for (var i = 0; i < 16; i++ ) {
this.shift("items");
}
console.log("16 items removed")
},
});
});
| {
"pile_set_name": "Github"
} |
<?php
namespace MySociety\TheyWorkForYou;
class Stripe {
static private $instance;
public function __construct($stripeSecretKey) {
if (self::$instance) {
throw new \RuntimeException('Stripe could not be instantiate more than once. Check PHP implementation : https://github.com/stripe/stripe-php');
}
self::$instance = $this;
\Stripe\Stripe::setApiKey($stripeSecretKey);
}
public function getSubscription($args) {
return \Stripe\Subscription::retrieve($args);
}
public function getUpcomingInvoice($args) {
return \Stripe\Invoice::upcoming($args);
}
public function createCustomer($args) {
return \Stripe\Customer::create($args);
}
public function updateCustomer($id, $args) {
return \Stripe\Customer::update($id, $args);
}
public function createSubscription($args) {
return \Stripe\Subscription::create($args);
}
public function getInvoices($args) {
return \Stripe\Invoice::all($args);
}
}
| {
"pile_set_name": "Github"
} |
MBR - Master Boot Record
by: Joe Allen ([email protected]) original March 1998
John F. Reiser ([email protected]) extensively modified July 21, 1998
archived: ftp://ftp.teleport.com/pub/users/jreiser/mbr02.tgz
This is a boot manager which boots from primary and logical partitions,
including those beyond the 528MB (1024 cylinder) limit, and multiple drives.
If the BIOS date is mid-1995 or newer, then the BIOS probably handles
large disks using LBA (linear block addressing) via INT 0x13 with AH=0x42.
If the BIOS date is early 1996 or newer, then the BIOS may supervise
booting from multiple drives. MBR interfaces with these BIOS facilities,
but does so dynamically so that MBR still functions with older BIOSes.
However, if the BIOS does not support the newer interfaces, then MBR
might be restricted to primary and logical partitions on the first 1024
cylinders of the first hard drive.
As with any software which modifies your boot sector, use caution. Backup
your files. Back up your boot sector (dd </dev/hda >backup count=1 bs=512).
Make boot floppies. You get the idea.
MBR packs a lot into only 440 bytes, so its interface is spartan.
A typical console and keyboard dialog might look like
a:dos selection letter : user-specified label
b:OS/2
c:swap
d*linux asterisk indicates default partition to boot
e:usr
f:home
g:src
:d prompt for selection letter; 'd' entered to boot linux
Then the partition list repeats until the selected partition 'd'
is reached; that partition's boot block is then read and executed.
The default drive is the one chosen by the BIOS. The default partition
is chosen when MBR is installed. Entering \r also selects the default.
Keyboard input offers timeout and a no-wait mode. The selection letters
must be consecutive, but can begin with any characater.
MBR can be tested from a floppy without modifying the existing
master boot record on the hard drive.
MBR can also make a machine-independent "universal" boot floppy
that lists sizes instead of label strings. The five-digit number
is the decimal partition size in megabytes:
mbr02 splash screen
:1 prompt for drive number; '1' entered for 1st hard drive
06:00012:a: type byte in hex : decimal megabytes : selection letter :
07:00350:b:
82:00070:c:
83:00050:d:
83:00060:e:
83:00400:f:
83:00300:g:
: prompt for partition selection
Use of MBR as the master boot record does not remove the need
for each bootable partition to have its own boot block.
Linux users still need LILO (or bootext2) in the boot block.
MBR uses 32-bit registers, and therefore requires a 386 or higher,
just like Linux.
----
Files:
COPYING license information (FSF GNU GPL v.2)
Makefile Requires adjustment for other than /dev/hda.
Uses as86 from the Linux bin86 package.
README This file.
flop_off.a86 Files which set conditional compilation flags.
flop_on.a86
flp2hard.mbr Pre-compiled "universal" booter for use from a floppy.
mbr.a86 Assembly source code for master boot record.
testhard.bin Pre-compiled, ready for tuning.
tune_mbr.c Installer
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.