content
stringlengths 10
4.9M
|
---|
import java.io.*;
import java.util.*;
public class P601D {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int i=0; i<t; i++) {
String[] line = br.readLine().split(" ");
int r = Integer.parseInt(line[0]);
int c = Integer.parseInt(line[1]);
int k = Integer.parseInt(line[2]);
boolean[][] farm = new boolean[r][c];
int riceAmount = 0;
for(int j=0; j<r; j++) {
String rowString = br.readLine();
for(int a=0; a<c; a++) {
if(rowString.charAt(a) == '.')
farm[j][a] = false;
else {
farm[j][a] = true;
riceAmount++;
}
}
}
int ricePerChicken = riceAmount / k;
int extraRiceChickens = riceAmount - (ricePerChicken) * k;
if(extraRiceChickens > 0) {
ricePerChicken++;
}
int curRiceAmount = 0;
int curChar = 0;
char[][] print = new char[r][c];
for(int y=0; y<r; y++) {
int startPoint, increment;
if(y%2 == 0) {
startPoint = 0;
increment = 1;
} else {
startPoint = c-1;
increment = -1;
}
for(int x=startPoint; x>=0 && x<c; x += increment) {
if(farm[y][x]) {
if(curRiceAmount == ricePerChicken) {
curChar++;
curRiceAmount = 0;
extraRiceChickens--;
if(extraRiceChickens == 0) {
ricePerChicken--;
}
}
curRiceAmount++;
}
if(curChar < 26) {
print[y][x] = (char)(((int)'a') + curChar);
} else if(curChar < 52) {
print[y][x] = (char)(((int)'A') + curChar-26);
} else {
print[y][x] = (char)(((int)'0') + curChar-52);
}
}
}
for(int y=0; y<r; y++) {
for(int x=0; x<c; x++) {
System.out.print(print[y][x]);
}
System.out.println();
}
}
}
}
|
package testtelemetry
import (
"encoding/json"
"fmt"
"github.com/StackVista/stackstate-agent/pkg/metrics"
"io/ioutil"
"log"
"os"
"runtime"
"strings"
"unsafe"
common "github.com/StackVista/stackstate-agent/rtloader/test/common"
"github.com/StackVista/stackstate-agent/rtloader/test/helpers"
)
/*
#include "rtloader_mem.h"
#include "datadog_agent_rtloader.h"
extern void submitTopologyEvent(char *, char *);
extern void submitRawMetricsData(char *, char *, float, char **, char *, long long);
static void initTelemetryTests(rtloader_t *rtloader) {
set_submit_topology_event_cb(rtloader, submitTopologyEvent);
set_submit_raw_metrics_data_cb(rtloader, submitRawMetricsData);
}
*/
import "C"
var (
rtloader *C.rtloader_t
checkID string
_data map[string]interface{}
_topoEvt metrics.Event
rawName string
rawHostname string
rawValue float64
rawTags []string
rawTimestamp int64
)
func resetOuputValues() {
checkID = ""
_data = nil
_topoEvt = metrics.Event{}
rawName = ""
rawHostname = ""
rawValue = 0
rawTags = nil
rawTimestamp = 0
}
func setUp() error {
// Initialize memory tracking
helpers.InitMemoryTracker()
rtloader = (*C.rtloader_t)(common.GetRtLoader())
if rtloader == nil {
return fmt.Errorf("make failed")
}
C.initTelemetryTests(rtloader)
// Updates sys.path so testing Check can be found
C.add_python_path(rtloader, C.CString("../python"))
if ok := C.init(rtloader); ok != 1 {
return fmt.Errorf("`init` failed: %s", C.GoString(C.get_error(rtloader)))
}
return nil
}
func run(call string) (string, error) {
resetOuputValues()
tmpfile, err := ioutil.TempFile("", "testout")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpfile.Name())
code := (*C.char)(helpers.TrackedCString(fmt.Sprintf(`
try:
import telemetry
%s
except Exception as e:
with open(r'%s', 'w') as f:
f.write("{}: {}\n".format(type(e).__name__, e))
`, call, tmpfile.Name())))
defer C._free(unsafe.Pointer(code))
runtime.LockOSThread()
state := C.ensure_gil(rtloader)
ret := C.run_simple_string(rtloader, code) == 1
C.release_gil(rtloader, state)
runtime.UnlockOSThread()
if !ret {
return "", fmt.Errorf("`run_simple_string` errored")
}
var output []byte
output, err = ioutil.ReadFile(tmpfile.Name())
return strings.TrimSpace(string(output)), err
}
func charArrayToSlice(array **C.char) (res []string) {
pTags := uintptr(unsafe.Pointer(array))
ptrSize := unsafe.Sizeof(*array)
for i := uintptr(0); ; i++ {
tagPtr := *(**C.char)(unsafe.Pointer(pTags + ptrSize*i))
if tagPtr == nil {
return
}
tag := C.GoString(tagPtr)
res = append(res, tag)
}
}
//export submitTopologyEvent
func submitTopologyEvent(id *C.char, data *C.char) {
checkID = C.GoString(id)
result := C.GoString(data)
json.Unmarshal([]byte(result), &_topoEvt)
}
//export submitRawMetricsData
func submitRawMetricsData(id *C.char, name *C.char, value C.float, tags **C.char, hostname *C.char, timestamp C.longlong) {
checkID = C.GoString(id)
rawName = C.GoString(name)
rawHostname = C.GoString(hostname)
rawValue = float64(value)
rawTimestamp = int64(timestamp)
if tags != nil {
rawTags = append(rawTags, charArrayToSlice(tags)...)
}
}
|
<reponame>prsolucoes/pickman
package main
import (
"flag"
"io/ioutil"
"github.com/prsolucoes/pickman/app"
"encoding/json"
"github.com/prsolucoes/pickman/managers"
"github.com/prsolucoes/pickman/logger"
_ "github.com/prsolucoes/pickman/loaders"
)
var (
Config *app.Config
CollectorNameToExecute string
)
func main() {
LoadConfigurations()
LoadCredentialPlugins()
LoadDataSourcePlugins()
LoadCollectorPlugins()
Execute()
}
func LoadConfigurations() {
var configFileName = ""
var configCollectorName = ""
flag.StringVar(&configFileName, "c", "", "Example: -c config.json")
flag.StringVar(&configCollectorName, "n", "", "Example: -n MyCollectorName")
flag.Parse()
if configFileName == "" {
logger.F("You need set configuration file in JSON format. Type -h for help.")
}
if configCollectorName == "" {
logger.F("You need set collector name to execute. Type -h for help.")
}
file, err := ioutil.ReadFile(configFileName)
if err != nil {
logger.F("Read file error (%v)", err)
}
// parse configuration file
err = json.Unmarshal(file, &Config)
if err != nil {
logger.F("Parse file error (%v)", err)
}
// collector name to execute after load
CollectorNameToExecute = configCollectorName
}
func Execute() {
collector, err := managers.GetCollectorByName(CollectorNameToExecute)
if err != nil {
logger.F("Failed to get collector (%v - %v)", CollectorNameToExecute, err)
}
err = collector.Collect()
if err != nil {
logger.F("Failed to collect data (%v - %v)", CollectorNameToExecute, err)
}
logger.I("Data was collected with success")
}
func LoadCollectorPlugins() {
if len(Config.Collectors) > 0 {
for _, config := range Config.Collectors {
collector, err := managers.GetCollectorAvailableByPluginName(config.Plugin)
if err != nil {
logger.F("Failed to load collector plugin (%v - %v)", config, err)
}
err = collector.Configure(config.Name, config.Params)
if err != nil {
logger.F("Failed to configure collector plugin (%v - %v)", config.Name, err)
}
logger.I("Collector plugin was configured (%v)", config.Name)
// initialize plugin
err = collector.Initialize()
if err != nil {
logger.F("Failed to initialize collector plugin (%v - %v)", config.Name, err)
}
logger.I("Collector plugin was initialized (%v)", config.Name)
// add to collection
managers.Collectors = append(managers.Collectors, collector)
}
} else {
logger.I("You didn't configure any collector plugin in your configuration file")
}
}
func LoadDataSourcePlugins() {
if len(Config.DataSources) > 0 {
for _, config := range Config.DataSources {
datasource, err := managers.GetDataSourceAvailableByPluginName(config.Plugin)
if err != nil {
logger.F("Failed to load datasource plugin (%v - %v)", config, err)
}
err = datasource.Configure(config.Name, config.Params)
if err != nil {
logger.F("Failed to configure datasource plugin (%v - %v)", config.Name, err)
}
logger.I("DataSource plugin was configured (%v)", config.Name)
// initialize plugin
err = datasource.Initialize()
if err != nil {
logger.F("Failed to initialize datasource plugin (%v - %v)", config.Name, err)
}
logger.I("DataSource plugin was initialized (%v)", config.Name)
// add to collection
managers.DataSources = append(managers.DataSources, datasource)
}
} else {
logger.I("You didn't configure any datasource plugin in your configuration file")
}
}
func LoadCredentialPlugins() {
if len(Config.Credentials) > 0 {
for _, config := range Config.Credentials {
credential, err := managers.GetCredentialAvailableByPluginName(config.Plugin)
if err != nil {
logger.F("Failed to load credential plugin (%v - %v)", config, err)
}
err = credential.Configure(config.Name, config.Params)
if err != nil {
logger.F("Failed to configure credential plugin (%v - %v)", config.Name, err)
}
logger.I("Credential plugin was configured (%v)", config.Name)
// initialize plugin
err = credential.Initialize()
if err != nil {
logger.F("Failed to initialize credential plugin (%v - %v)", config.Name, err)
}
logger.I("Credential plugin was initialized (%v)", config.Name)
// add to collection
managers.Credentials = append(managers.Credentials, credential)
}
} else {
logger.I("You didn't configure any credential plugin in your configuration file")
}
} |
/**
* Default {@code ExecutorService} used for scheduling concurrent tasks.
* This default spawns as many threads as required with a priority of
* {@code Thread.MIN_PRIORITY}. Idle threads are pruned after one minute.
* @return fresh ExecutorService
*/
public static ExecutorService defaultExecutorService() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(@Nonnull Runnable r) {
Thread thread = new Thread(r, createName());
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
return thread;
}
private String createName() {
return "oak-executor-" + counter.getAndIncrement();
}
});
executor.setKeepAliveTime(1, TimeUnit.MINUTES);
executor.allowCoreThreadTimeOut(true);
return executor;
} |
#include <iostream>
#include <queue>
#include <array>
#include <algorithm>
using namespace std;
int main() {
int t;
cin >> t;
vector<int> tot = {2};
int delta = 2;
int s = 2;
while (tot.back() <= int(1e9)) {
delta += 3;
s = s + delta;
tot.push_back(s);
}
while (t--) {
int n;
cin >> n;
int k = 0;
while (1) {
int i = upper_bound(tot.begin(), tot.end(), n) - tot.begin();
--i;
if (i < 0) break;
n -= tot[i];
++k;
}
cout << k << '\n';
}
} |
L-NMMA (a nitric oxide synthase inhibitor) is effective in the treatment of cardiogenic shock.
BACKGROUND
The objective was to assess the safety and efficacy of L-NMMA in the treatment of cardiogenic shock.
METHODS
We enrolled 11 consecutive patients with cardiogenic shock that persisted after >24 hours from admission, despite coronary catheterization and primary percutaneous transluminal coronary revascularization, when feasible, and treatment with mechanical ventilation, intraaortic balloon pump (IABP), and high doses of catecholamines. L-NMMA was administered as an IV bolus of 1 mg/kg and continuous drip of 1 mg. kg(-1). h(-1) for 5 hours. Treatment with catecholamines, mechanical ventilation, and IABP was kept constant throughout the study.
RESULTS
Within 10 minutes of L-NMMA administration, mean arterial blood pressure (MAP) increased from 76+/-9 to 109+/-22 mm Hg (+43%). Urine output increased within 5 hours from 63+/-25 to 156+/-63 cc/h (+148%). Cardiac index decreased during the steep increase in MAP from 2. 0+/-0.5 to 1.7+/-0.4 L/(min. m(2)) (-15%); however, it gradually increased to 1.85+/-0.4 L/(min. m(2)) after 5 hours. The heart rate and the wedge pressure remained stable. Twenty-four hours after L-NMMA discontinuation, MAP (+36%) and urine output (+189%) remained increased; however, cardiac index returned to pretreatment level. No adverse events were detected. Ten out of eleven patients could be weaned off mechanical ventilation and IABP. Eight patients were discharged from the coronary intensive care unit, and seven (64%) were alive at 1-month follow-up.
CONCLUSIONS
L-NMMA administration in patients with cardiogenic shock is safe and has favorable clinical and hemodynamic effects. |
import { GitHistory, Log } from "../src";
import * as glob from "fast-glob";
import * as path from "path";
import * as fs from "fs";
import * as util from "util";
import { Lang, ts, elm, rs } from "./lang";
type Langs = { [key: string]: number };
type Result = { hash: string; date: string; langs: Langs };
export async function run(url: string, branch: string, out: string) {
const langs = [ts, elm, rs];
const analyzer = new GitHistory("work/test", url, branch);
const result = await analyzer.analyze({
format: {
hash: "%h",
date: "%cd",
message: "%s",
refs: "%D"
},
dateFormat: "%Y/%m/%d",
filter: log => {
return log.message.startsWith("Merge pull request ");
},
map: async log => {
return analyze(analyzer.getRepoPath(), log, langs);
}
});
const data = await result.all();
const html = render(data, langs);
await util.promisify(fs.writeFile)(out, html);
}
async function analyze(
repoPath: string,
log: Log,
languages: Lang[]
): Promise<Result> {
const entries = await glob(languages.map(l => `**/*${l.ext}`), {
cwd: repoPath
});
const langs: Langs = {};
for (const entry of entries) {
const ext = path.extname(entry as string);
langs[ext] = (langs[ext] || 0) + 1;
}
return { ...log, langs };
}
function makeDataset(lang: Lang, result: Result[]) {
const data = result.map(d => d.langs[lang.ext] || 0);
return {
label: lang.ext,
borderColor: lang.color,
borderWidth: 1,
radius: 0,
data
};
}
function render(result: Result[], langs: Lang[]): string {
const data = {
labels: result.map(r => r.date),
datasets: langs.map(l => makeDataset(l, result))
};
return `
<div class="chart-container" style="position: relative; height:40vh; width:80vw;">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: ${JSON.stringify(data)}
});
</script>
`;
}
|
INTERESTS OF CHILDREN AND YOUTH IN THE CONTEXT OF PREVALENCE OF PHYSICAL ACTIVITIES AND SPORT
The results of qualitative research aimed at finding personal views of children and youth are presented in this paper. The research was conducted in consideration of children’s surroundings: school, family and local community. The main objectives of the research were to establish main opinions from the children and youth perspective about their generation problems, possibilities, solutions and ideas for these problems and situations. The interests of children were researched (ways of choosing activities of interest and the conditions that influences the selection were identified). The special objective of this research was to gain an insight into whether and to what extent movement activities and different aspects of physical activity are included in their overall structure of interest. The target group for this study were children and young people aged 10 to 18 years. According to the spatial location, respondents came from schools of four counties in Croatia. The main research method was focus groups. Eight focus groups were organised with a total number of 83 students, with an individual group comprised of 9 to 12 students. Then result analysis was performed, which included the collection of impressions, careful analysis of sets of transcripts and encoding of each group. Audio recordings were transcribed, and the resulting transcripts were the basis for the qualitative analysis. Frequency of appearance as well as the percentage of representation of certain codes in the total of transcripts indicated that “interests” were predominantly represented (396, 14.27%). “The problem” as the code in the researched population of students was presented in a series of representationa (302; 10.88%), followed by “solution” (259; 9.33%) and “ideas” (252; 9.08%). The registered predominant interests of primary school students, observed through the aspect of kinetic activities, showed that the movement gets its own dimension separate from the context of games and entertainment. Also, it was observed exclusively in relations with various organized sporting activities. In the context of the practice of movement and physical activity for secondary school students, the results indicated that the movement and physical activity played a key role in their interests, but practically were not implemented in their everyday life. |
package kafka
import (
"context"
encoding "encoding/json"
"fmt"
"time"
"github.com/Shopify/sarama"
"github.com/cenkalti/backoff/v4"
"github.com/consensys/orchestrate/pkg/errors"
authutils "github.com/consensys/orchestrate/pkg/toolkit/app/auth/utils"
"github.com/consensys/orchestrate/pkg/toolkit/app/log"
"github.com/consensys/orchestrate/pkg/toolkit/app/multitenancy"
"github.com/consensys/orchestrate/pkg/utils"
"github.com/consensys/orchestrate/src/entities"
"github.com/consensys/orchestrate/src/infra/kafka"
kafkasarama "github.com/consensys/orchestrate/src/infra/kafka/sarama"
"github.com/consensys/orchestrate/src/infra/messenger"
)
type Consumer struct {
consumerGroup kafka.ConsumerGroup
handler map[entities.RequestMessageType]messenger.MessageHandler
topics []string
cancel context.CancelFunc
logger *log.Logger
asyncCommit bool
committedMessages map[int32]*utils.SortedList
partitionOffset map[int32]int64
err error
cerr chan error
}
var _ messenger.Consumer = &Consumer{}
func NewMessageConsumer(id string, cfg *kafkasarama.Config, topics []string) (*Consumer, error) {
consumerGroup, err := kafkasarama.NewConsumerGroup(cfg)
if err != nil {
return nil, err
}
consumer := &Consumer{
consumerGroup: consumerGroup,
topics: topics,
asyncCommit: cfg.AsyncCommit,
committedMessages: make(map[int32]*utils.SortedList),
partitionOffset: make(map[int32]int64),
logger: log.NewLogger().SetComponent(id),
handler: map[entities.RequestMessageType]messenger.MessageHandler{},
cerr: make(chan error, 1),
}
return consumer, nil
}
func (cl *Consumer) Consume(ctx context.Context) error {
return cl.consumerGroup.Consume(ctx, cl.topics, cl)
}
func (cl *Consumer) Checker() error {
return cl.consumerGroup.Checker()
}
func (cl *Consumer) Close() error {
return cl.consumerGroup.Close()
}
func (cl *Consumer) Setup(session sarama.ConsumerGroupSession) error {
cl.logger.WithContext(session.Context()).
WithField("kafka.generation_id", session.GenerationID()).
WithField("kafka.member_id", session.MemberID()).
WithField("claims", session.Claims()).
Info("ready to consume messages")
return nil
}
func (cl *Consumer) Cleanup(session sarama.ConsumerGroupSession) error {
logger := cl.logger.WithContext(session.Context())
logger.Debug("clean up consumer claims")
if cl.cancel != nil {
cl.cancel()
}
return cl.err
}
func (cl *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
var ctx context.Context
ctx, cl.cancel = context.WithCancel(session.Context())
cl.err = cl.consumeClaimLoop(ctx, session, claim)
return cl.err
}
func (cl *Consumer) AppendHandler(msgType entities.RequestMessageType, msgHandler messenger.MessageHandler) {
cl.handler[msgType] = msgHandler
}
func (cl *Consumer) consumeClaimLoop(ctx context.Context, session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
logger := cl.logger.WithContext(ctx).WithField("partition", claim.Partition()).WithField("topic", claim.Topic())
logger.Debug("started consuming claims loop")
cl.committedMessages[claim.Partition()] = utils.NewSortedList()
for {
select {
case <-ctx.Done():
logger.WithError(ctx.Err()).Info("gracefully stopping message claims")
return cl.err
case err := <-cl.cerr:
logger.WithError(err).Info("stopping message claims with errors")
return cl.err
case msg, ok := <-claim.Messages():
// Input channel has been close so we leave the loop
if !ok {
return nil
}
logger.WithField("timestamp", msg.Timestamp).Trace("message consumed")
if _, ok2 := cl.partitionOffset[msg.Partition]; !ok2 {
cl.partitionOffset[msg.Partition] = msg.Offset
}
reqMsg, err := NewMessage(msg)
if err != nil {
cl.markMessage(session, msg, logger, err)
continue
}
handlerFunc, ok := cl.handler[reqMsg.Type]
if !ok {
cl.markMessage(session, msg, logger.WithField("msg_type", reqMsg.Type),
fmt.Errorf("missing handler for request type"))
continue
}
for _, h := range msg.Headers {
if string(h.Key) == authutils.UserInfoHeader {
userInfo := &multitenancy.UserInfo{}
_ = encoding.Unmarshal(h.Value, userInfo)
ctx = multitenancy.WithUserInfo(ctx, userInfo)
}
}
if cl.asyncCommit {
go func() {
err = cl.handleMessage(ctx, session, msg, handlerFunc, reqMsg, logger)
if err != nil {
cl.cerr <- err
}
}()
} else {
err = cl.handleMessage(ctx, session, msg, handlerFunc, reqMsg, logger)
if err != nil {
return err
}
}
}
}
}
func (cl *Consumer) handleMessage(ctx context.Context, session sarama.ConsumerGroupSession, msg *sarama.ConsumerMessage,
handlerFunc messenger.MessageHandler, reqMsg *entities.Message, logger *log.Logger) error {
return backoff.RetryNotify(
func() error {
err := handlerFunc(ctx, reqMsg)
switch {
// Exits if not errors
case err == nil:
cl.markMessage(session, msg, logger, nil)
return nil
case err == context.DeadlineExceeded || err == context.Canceled || errors.IsHTTPConnectionNotFoundError(err):
return backoff.Permanent(err)
case ctx.Err() != nil:
return backoff.Permanent(ctx.Err())
case errors.IsDependencyFailureError(err) || errors.IsEthereumClientError(err):
return err
default:
cl.markMessage(session, msg, logger, err)
return backoff.Permanent(err)
}
},
backoff.NewConstantBackOff(time.Second),
func(err error, duration time.Duration) {
logger.WithError(err).WithField("duration", duration).Warn("error processing message, retrying")
},
)
}
func (cl *Consumer) markMessage(session sarama.ConsumerGroupSession, msg *sarama.ConsumerMessage, logger *log.Logger, err error) {
logger.WithError(err).Debug("message processed successfully")
if !cl.asyncCommit {
cl.commitMessage(session, msg, logger, err)
return
}
cl.committedMessages[msg.Partition].Append(msg, msg.Offset)
for {
headMsg := cl.committedMessages[msg.Partition].Head()
if headMsg == nil {
break
}
if headMsg.(*sarama.ConsumerMessage).Offset != cl.partitionOffset[msg.Partition] {
break
}
cl.commitMessage(session, headMsg.(*sarama.ConsumerMessage), logger, nil)
_ = cl.committedMessages[msg.Partition].RemoveByKey(headMsg.(*sarama.ConsumerMessage).Offset)
cl.partitionOffset[msg.Partition]++
}
}
func (cl *Consumer) commitMessage(session sarama.ConsumerGroupSession, msg *sarama.ConsumerMessage, logger *log.Logger, err error) {
session.MarkMessage(msg, "")
session.Commit()
logger.WithError(err).WithField("offset", msg.Offset+1).Debug("message has been committed")
}
|
<filename>modules/io/crypto.cpp
#include "modules/io/crypto.h"
#include <endian.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <string.h>
#include "modules/io/hash.h"
#include "modules/io/hexdump.h"
#include "modules/io/log.h"
extern "C" {
// WTF openssl did you forget this one?
#include <openssl/modes.h>
}
constexpr size_t k_max_block_size = 64UL * 1024UL * 1024UL * 1024UL;
void generate_salt(char* salt) { RAND_bytes((unsigned char*)salt, 16); }
struct iv_struct {
iv_struct(uint64_t _iv) : iv(htole64(_iv)), pad(0) {}
uint64_t iv;
uint32_t pad;
} __attribute__((packed));
struct block_header {
block_header() {}
block_header(uint32_t _block_size) : check(0), block_size(htole32(_block_size)), reserved(0) {}
uint32_t get_size() {
if (check != 0) {
throw io_exception("Block decrypt failed: Check your decryption key");
}
return le32toh(block_size);
}
uint64_t check; // Used to quick check key
uint32_t block_size;
uint32_t reserved;
} __attribute__((packed));
crypto_ctx::crypto_ctx(const char* salt, const char* key, size_t size) {
unsigned char sha_key[32];
// Hash the key + salt
SHA256_CTX sha_ctx;
SHA256_Init(&sha_ctx);
SHA256_Update(&sha_ctx, salt, 16);
SHA256_Update(&sha_ctx, key, size);
SHA256_Final(sha_key, &sha_ctx);
// Setup key, GCM only uses encrypt side
AES_set_encrypt_key(sha_key, 256, &m_key);
}
void crypto_ctx::encrypt(uint64_t iv, char* tag, char* out, const char* in, size_t size) const {
GCM128_CONTEXT* ctx;
iv_struct ivs(iv);
ctx = CRYPTO_gcm128_new(const_cast<void*>(static_cast<const void*>(&m_key)),
block128_f(AES_encrypt));
CRYPTO_gcm128_setiv(ctx, (const unsigned char*)&ivs, sizeof(iv_struct));
CRYPTO_gcm128_encrypt(ctx, (const unsigned char*)in, (unsigned char*)out, size);
CRYPTO_gcm128_tag(ctx, (unsigned char*)tag, 16);
// SPLOG("Tag: %s", hexdump(std::string(tag, 16)).c_str());
CRYPTO_gcm128_release(ctx);
}
bool crypto_ctx::decrypt(uint64_t iv, const char* tag, char* out, const char* in,
size_t size) const {
GCM128_CONTEXT* ctx;
iv_struct ivs(iv);
unsigned char vtag[16];
ctx = CRYPTO_gcm128_new(const_cast<void*>(static_cast<const void*>(&m_key)),
block128_f(AES_encrypt));
CRYPTO_gcm128_setiv(ctx, (const unsigned char*)&ivs, sizeof(iv_struct));
CRYPTO_gcm128_decrypt(ctx, (const unsigned char*)in, (unsigned char*)out, size);
CRYPTO_gcm128_tag(ctx, vtag, 16);
// SPLOG("Tag: %s", hexdump(std::string((char*) vtag, 16)).c_str());
CRYPTO_gcm128_release(ctx);
return memcmp(tag, vtag, 16) == 0;
}
uint64_t crypto_ctx::encrypt(writable& out, uint64_t iv, mem_io&& block) {
if (block.size() > k_max_block_size) {
throw io_exception(boost::format("Encrypted block size %1% too large") % block.size());
}
GCM128_CONTEXT* ctx;
// Setup context
iv_struct ivs(iv);
ctx = CRYPTO_gcm128_new(const_cast<void*>(static_cast<const void*>(&m_key)),
block128_f(AES_encrypt));
CRYPTO_gcm128_setiv(ctx, (const unsigned char*)&ivs, sizeof(iv_struct));
// Write out the block header (encrypted of course)
block_header hdr(block.size());
CRYPTO_gcm128_encrypt(ctx, (unsigned char*)&hdr, (unsigned char*)&hdr, sizeof(block_header));
out.write((const char*)&hdr, sizeof(block_header));
// Write out the main block
CRYPTO_gcm128_encrypt(ctx, (unsigned char*)block.buffer(), (unsigned char*)block.buffer(),
block.size());
out.write(block.buffer(), block.size());
// Write the tag
unsigned char tag_buf[16];
CRYPTO_gcm128_tag(ctx, (unsigned char*)tag_buf, 16);
out.write((const char*)tag_buf, 16);
// Goodbye context
CRYPTO_gcm128_release(ctx);
return 16 + sizeof(block_header) + block.size();
}
void crypto_ctx::decrypt(mem_io& out, uint64_t iv, readable& in) {
GCM128_CONTEXT* ctx;
// Setup IV
iv_struct ivs(iv);
ctx = CRYPTO_gcm128_new(const_cast<void*>(static_cast<const void*>(&m_key)),
block128_f(AES_encrypt));
CRYPTO_gcm128_setiv(ctx, (const unsigned char*)&ivs, sizeof(iv_struct));
// Read the block header
block_header hdr;
size_t r = in.read((char*)&hdr, sizeof(block_header));
if (r != sizeof(block_header)) {
throw io_exception("EOF encountered while reading block header");
}
CRYPTO_gcm128_decrypt(ctx, (unsigned char*)&hdr, (unsigned char*)&hdr, sizeof(block_header));
size_t size = hdr.get_size();
;
// Check size, implode if too large
if (size > k_max_block_size) {
throw io_exception(boost::format("Decrypted block size %1% too large") % size);
}
// Read in the main block
out.resize(size);
out.reset();
r = in.read(out.buffer(), size);
if (r != size) {
throw io_exception("EOF encountered while reading block data");
}
CRYPTO_gcm128_decrypt(ctx, (unsigned char*)out.buffer(), (unsigned char*)out.buffer(),
out.size());
// Validate tag
char tag_buf[16];
unsigned char vtag_buf[16];
r = in.read(tag_buf, 16);
if (r != 16) {
throw io_exception("EOF encountered while reading block tag");
}
CRYPTO_gcm128_tag(ctx, (unsigned char*)vtag_buf, 16);
if (memcmp(tag_buf, vtag_buf, 16) != 0) {
throw io_exception("Cyptographic checksum of block failed, data corruption");
}
// Goodbye context
CRYPTO_gcm128_release(ctx);
}
// Basic RSA signature support inspired by:
// https://eclipsesource.com/blogs/2016/09/07/tutorial-code-signing-and-verification-with-openssl/
// https://gist.github.com/irbull/08339ddcd5686f509e9826964b17bb59
void rsa_ctx::Base64Encode(const unsigned char* buffer, size_t length, char** base64Text) {
BIO *bio, *b64;
BUF_MEM* bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_write(bio, buffer, length);
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
BIO_set_close(bio, BIO_NOCLOSE);
BIO_free_all(bio);
*base64Text = (*bufferPtr).data;
}
size_t calcDecodeLength(const char* b64input) {
size_t len = strlen(b64input), padding = 0;
if (b64input[len - 1] == '=' && b64input[len - 2] == '=') // last two chars are =
padding = 2;
else if (b64input[len - 1] == '=') // last char is =
padding = 1;
return (len * 3) / 4 - padding;
}
void rsa_ctx::Base64Decode(const char* b64message, unsigned char** buffer, size_t* length) {
BIO *bio, *b64;
int decodeLen = calcDecodeLength(b64message);
*buffer = (unsigned char*)malloc(decodeLen + 1);
(*buffer)[decodeLen] = '\0';
bio = BIO_new_mem_buf(b64message, -1);
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
*length = BIO_read(bio, *buffer, strlen(b64message));
BIO_free_all(bio);
}
// Make an RSA public key from a string
RSA* rsa_ctx::createPublicRSA(std::string key) {
RSA* rsa = NULL;
BIO* keybio;
const char* c_string = key.c_str();
keybio = BIO_new_mem_buf((void*)c_string, -1);
if (keybio == NULL) {
return 0;
}
rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);
return rsa;
}
// Returns true if verification ran (ie. the signature could be checked).
// Sets Authentic to true if the signature is verified vs. the public key.
// You probably want crypto_ctx::verifySignature instead.
bool rsa_ctx::RSAVerifySignature(RSA* rsa, unsigned char* MsgHash, size_t MsgHashLen,
const char* Msg, size_t MsgLen, bool* Authentic) {
// default: fail closed
*Authentic = false;
EVP_PKEY* pubKey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pubKey, rsa);
EVP_MD_CTX* m_RSAVerifyCtx = EVP_MD_CTX_create();
if (EVP_DigestVerifyInit(m_RSAVerifyCtx, NULL, EVP_sha256(), NULL, pubKey) <= 0) {
return false;
}
if (EVP_DigestVerifyUpdate(m_RSAVerifyCtx, Msg, MsgLen) <= 0) {
return false;
}
int AuthStatus = EVP_DigestVerifyFinal(m_RSAVerifyCtx, MsgHash, MsgHashLen);
if (AuthStatus == 1) {
*Authentic = true;
return true;
} else if (AuthStatus == 0) {
return true;
}
// default: fail closed.
return false;
}
// Verify that the publicKey used to sign plainText matches the Base64-encoded signature.
// Returns true on success.
bool rsa_ctx::verifySignature(std::string publicKey, std::string plainText,
const char* signatureBase64) {
RSA* publicRSA = createPublicRSA(publicKey);
if (!publicRSA) {
std::cerr << "rsa_ctx::verifySignature: invalid public key, aborting." << std::endl;
return false;
}
unsigned char* encMessage;
size_t encMessageLength;
bool authentic;
Base64Decode(signatureBase64, &encMessage, &encMessageLength);
bool result = RSAVerifySignature(publicRSA, encMessage, encMessageLength, plainText.c_str(),
plainText.length(), &authentic);
return result & authentic;
}
|
import Control.Monad
import Data.List
main = do
t <- readLn
replicateM t $ getLine >>= print.solve
solve = (+1).foldl max 0.map length.filter((=='L').head).group |
<gh_stars>1-10
import * as Sentry from "@sentry/node"
import debug from "debug"
const log = debug("resync:sentry")
if (process.env.NODE_ENV !== "development") {
Sentry.init({
dsn: "https://[email protected]/5712866",
tracesSampleRate: 1.0,
environment: process.env.NODE_ENV,
})
log("initialized sentry.io")
}
|
/**
* Returns joint index computed from {@code #toIndices} and if
* {@code removedJointIndexRef} is non-null and {@code #converter}
* has non-null for {@link JointDomainReindexer#getRemovedDomains()},
* this will compute a joint index from {@code #removedIndices} and set
* it in that {@code removedJointIndexRef}. Returns -1 if {@code #toIndices}
* contains negative value.
*/
@SuppressWarnings("null")
public int readIndices(@Nullable AtomicInteger removedJointIndexRef)
{
if (toIndices[0] < 0)
{
return -1;
}
int toJointIndex = converter._toDomains.jointIndexFromIndices(toIndices);
if (removedJointIndexRef != null && removedIndices.length > 0)
{
removedJointIndexRef.set(converter._removedDomains.jointIndexFromIndices(removedIndices));
}
return toJointIndex;
} |
def update_info(self):
index = pd.MultiIndex(
levels=[[], []], labels=[[], []], names=['period', 'name'])
df = DataFrame(data=None, index=index)
norm_cols = ['{}_loading_norm_value'.format(f) for f in self.factors]
cols = self.factors + norm_cols
for t, (f, factor) in product(self.periods, enumerate(self.factors)):
stage = self.stagemap[t]
load_norm_column = '{}_loading_norm_value'.format(factor)
measurements = self.measurements[factor][t].copy()
if t == self.nperiods - 1 and factor in self.anchored_factors:
measurements.append(self.anch_outcome)
load_norminfo = self.normalizations[factor]['loadings'][t]
load_normed_meas, load_norm_value = \
load_norminfo if len(load_norminfo) == 2 else [None, None]
intercept_norminfo = self.normalizations[factor]['intercepts'][t]
intercept_normed_meas, intercept_norm_value = \
intercept_norminfo if len(intercept_norminfo) == 2 else [None, None]
for m, meas in enumerate(measurements):
if (f > 0 or m > 0) and meas in df.loc[t].index:
df.loc[(t, meas), factor] = 1
if meas == load_normed_meas:
df.loc[(t, meas), load_norm_column] = load_norm_value
if meas == intercept_normed_meas:
df.loc[(t, meas), 'intercept_norm_value'] = \
intercept_norm_value
else:
ind = pd.MultiIndex.from_tuples(
[(t, meas)], names=['period', 'variable'])
dat = np.zeros((1, len(cols)))
df2 = DataFrame(data=dat, columns=cols, index=ind)
df2[factor] = 1
if meas == load_normed_meas:
df2[load_norm_column] = load_norm_value
if meas == intercept_normed_meas:
df2['intercept_norm_value'] = intercept_norm_value
else:
df2['intercept_norm_value'] = np.nan
df2['stage'] = stage
df = df.append(df2)
df['has_normalized_loading'] = df[norm_cols].sum(axis=1).astype(bool)
df['has_normalized_intercept'] = pd.notnull(df['intercept_norm_value'])
df['purpose'] = 'measurement'
if self.anchoring is True:
anch_index = (self.nperiods - 1, self.anch_outcome)
df.loc[anch_index, 'purpose'] = 'anchoring'
if self.anchoring is True:
anch_row = df.loc[anch_index]
df.drop(anch_index, axis=0, inplace=True)
df = df.append(anch_row)
df['update_type'] = 'linear'
for t, variable in list(df.index):
if self._is_dummy(variable, t) and self.probit_measurements is True:
df.loc[(t, variable), 'update_type'] = 'probit'
return df |
// RenameFileInGuest rename a file in Guest OS.
func RenameFileInGuest(app, vmx, username, password, src, dst string) error {
if _, err := vmrun(app, "-gu", username, "-gp", password, "renameFileInGuest", vmx, src, dst); err != nil {
return err
}
return nil
} |
def __top_x_by_cat(self, sorted_items):
best_with_score = []
item_types = [
'container_course', 'container_workspace', 'engage_article', 'engage_microlearning', 'totara_playlist'
]
for i_type in item_types:
type_recommended = [(x[0], x[1]) for x in sorted_items if x[2] == i_type][:self.num_items]
best_with_score.extend(type_recommended)
return best_with_score |
<filename>packages/easy/test/ref/DevTable.ts<gh_stars>10-100
import { convert, Database, DefaultProvider, MapOptions, Table } from '../../src';
export class DevDatabase extends Database {
static readonly DevDB = new Database('DevDB', DefaultProvider);
}
export class DevTable extends Table {
readonly id = this.map.column('Id', { dflt: 42 });
readonly name = this.map.column('Name');
readonly language = this.map.column('Language', { dflt: 'TypeScript' });
readonly level = this.map.column('CodingLevel', { dflt: 3, convert: convert.toNumber.fromString });
constructor(options: MapOptions = { startFrom: 'scratch' }) {
super(options);
}
get db(): Database {
return DevDatabase.DevDB;
}
}
|
Not long before my wife and I had our first child, we had dinner with another married couple — both writers — who at the time had a toddler of their own. I asked them for some advice. Instead, they gave me a caution. "Don't write about your kid," they said. "Being a parent is going to change your life, and it's all you're going to be able to think about. You're going to want to turn those experiences and feelings into words. But there's nothing you can say that hasn't been said already, and probably better."
I have two children now — a son and a daughter, both adolescents — and over the past decade-plus, I've ignored my friends' advice on multiple occasions. My son, who's on the autism spectrum, has inspired about a half-dozen or so essays (which isn't that excessive, given that he's now 14); and I've penned the occasional piece about my daughter, who shares a lot of my nerdy enthusiasms. Still, every time I sit down to write about children or parenting, I remember that conversation from 15 years ago.
I think about it even more during my daily perusal of the internet, which sometimes seems choked with articles penned by new moms and dads, all feeling overwhelmed and transformed — just as I once was, and just as our friends warned me I'd be.
Outside of websites specifically devoted to raising kids, the published discourse about child rearing in the mainstream media seems dominated by panicked think pieces, many of the "Holy crap, what just happened to my life?" variety.
I do wonder if the glut of anxious "oh no, what now?" articles gives the wrong idea about what raising kids is like
Type "having a baby" into Google, and auto-complete suggests "changes everything." That search then turns up 14 million hits and page after page of laments about how infants and toddlers mess up work, sleep, TV watching, sex, being a cool person ... you name it.
All these heaping piles of verbiage serve a purpose. They're therapeutic for the author, undoubtedly. And for anyone dealing with similar situations — and unaware of the millions of words that have been penned on the topic over the centuries — stumbling on an article that articulates that vague sense of dissatisfaction can be both reassuring and revelatory.
Plus, some of those pieces are good! Gifted writers can transform even the most played-out subject into something worthwhile. My friend Nathan Rabin, for example, writes movingly and entertainingly about being a stay-at-home dad at the website Mom.me. (In fact, if you're an acquaintance of mine and you've ever written one of these kinds of pieces, let's just pretend that I'm not talking about you, if only for the sake of cordiality.)
But the preponderance of these articles reminds me a little of what eco-essayist Bill McKibben has written about our excess of professional nature photography. We really don't need all that many new pictures of birds and bears each year, because there's really not much new to see. And in the process of tramping through the wilderness to get the prettiest shot, photographers could be harming habitats and warping our understanding of the environment.
I don't think parenting essays are destroying childhood. But I do wonder if the glut of anxious "oh no, what now?" articles gives the wrong idea about what raising kids is like.
Here, to my mind, is the problem:
Early childhood is just one chapter in a long, long book
Every parent's experiences are different, with ebbs and flows of joy and despair that hit at different times. But by and large, new mothers and fathers endure three distinct patches of deep, deep regret:
1) During the first few months, when the novelty's worn off and the baby becomes a noisy, smelly lump of unhappiness.
2) Around the age of 2, when the barely articulate toddler still needs help with almost everything, and gets sloppy drunk on the power of ordering adults around.
3) Around the age of 3, when the child's growing independence has him or her questioning whether mealtime etiquette or sleeping schedules must be respected.
Each of these phases seems to last forever. But they're really more like a few months, with the occasional relapse. (The relapses are the worst.) Babies become more likable once they start to smile, at which point getting up in the middle of the night to take care of them becomes more rewarding. Toddlers are maddening because they can be sweet one minute and satanic the next, but if parents hold the line on discipline and structure, eventually nature takes its course. Children mature.
Parents, too, grow into the job. What might initially seem unnatural — like being charged with sustaining the life of a tiny human being — becomes second nature through repetition. Later, as children become more capable of feeding, dressing, cleaning, and entertaining themselves, their moms and dads get back small chunks of time that they hadn't even noticed they'd been losing to daily child maintenance. Suddenly they can read a long book again, or catch up on their Netflix queue.
Then, guess what? If all goes well, those folks get to spend 15 or so more years living in a home alongside reasonably well-behaved sons and daughters, who develop personalities and passions of their own and become active participants in whatever adventures the family has.
So to sum up: That's roughly three or four years of mind-numbing kiddie shows and young parents feeling like they're losing their identities, followed by a lifetime of rich, often highly rewarding relationships, marked by some of the most lasting memories that anyone can make.
Which of these stages of parenting really deserves more emphasis?
Obsessing over exhaustion and existential anxiety scares off potential parents
I have many friends who don't have kids — some intentionally, some not — and I'd never tell any of them that having children is a crucial, essential part of the human experience. Life offers a lot of opportunities. Being a parent is just one of a multitude of possible paths; and it's one that comes with costs and limitations that many are just fine doing without.
But while it's presumptuous (and rude) to say, "Oh, you'll change your mind one day" to anyone who insists they don't want kids, the reason why the childless-by-choice deal with doubters is that people do change their minds, all the time. I've known plenty who were once adamant about never becoming a parent until one day, almost out of the blue, they started to entertain the possibility.
If you're curious whether you should see a movie, never lean too heavily on the opinion of someone who's only seen the first five minutes
So this bit is directed at those who are warming to the idea of spawning, and not to those who are a hard "nope." Don't hesitate just because the early years have such bad PR. All those essays from new moms who worry that they lack maternal instincts? Or from new dads who complain that they haven't gone out to a bar with their buddies in months? They're undoubtedly coming from a place of sincerity — and the experiences they relate are genuine — but the perspective is often limited.
It's never a bad idea to be prepared for all the downsides of something so life-changing. But if you're curious whether you should see a movie, never lean too heavily on the opinion of someone who's only seen the first five minutes.
Focusing on the very young shortchanges their older peers
Boys and girls develop quirks and habits fairly early, but it's nothing like what happens later on, when they become artsy 8-year-olds, bookish 10-year-olds, athletic 12-year-olds, or what have you. Little kids turn their folks' brains to mush because they require a lot of dull routine, which — coupled with how demanding they can be — can make them, frankly, kind of hard to like sometimes.
It's this side of children that's too often the public face of youth. Either the little ones themselves are making a scene in a restaurant or airport or their parents are writing exasperated blog posts about them. The quieter, calmer, more multifaceted kids don't get the same kind of exposure, either out in the world or on the web.
The non-print media doesn't help in this regard. In sitcoms and TV dramas — or at least those not aimed at preadolescents — children are typically presented as obnoxiously precocious, whiny, and self-absorbed. It's not hard to trace a line from the popular depiction of annoying toddlers and snotty teens to the pervasive complaints about spoiled, egotistical "millennials," who've been warped by years of technology-aided instant gratification and our convoluted, coddling educational system.
And that's incredibly unfair. What I see every day — not just with my son and daughter but with their classmates — is a rising generation that's kind, curious, and creative, making amazing use of resources I never had at their age. Yes, they're glued to their phones, but on those screens these kids are talking to each other, taking quizzes, reading the news, or sharing things they've made ... all traits of well-rounded individuals.
There are upsides aplenty to parenting kids once they get over the toddler hump: teaching them about life and culture, reliving some of the best experiences of youth through their eyes, curating their experiences of holidays, and so on. Plus, as children age they typically get smarter and funnier, and develop actual talents. Soccer games and school concerts are a grind at the elementary level; later, they're a genuine pleasure.
It's easy to groan about the awfulness of "these kids today," but getting to know them personally reveals another, more hopeful story. If nothing else, it shows that there are plenty of reasons to feel good about our leaders of tomorrow.
Who knows this? Parents do, whether they write it down for posterity or not.
There are so many other tales to tell
Here's something else that many parents know: Nearly every age between 4 and 14 is "a great age." And there are even extended stretches of babyhood and toddlerhood that are absolutely delightful. (Babies who sleep through the night, nap twice a day, and can sit up and play enthusiastically when they're awake? They're the absolute best.)
I don't mean to give the impression that everything goes smoothly after the age of 4 for every parent — or any parent. Kids can be the source of all kinds of worry: They cost money, they get sick, they wreck the house, they pick fights with their siblings, they get bullied, they have their hearts broken, and they have all kinds of other problems that get piled onto whatever else adults are going through. And sometimes, no matter how much they love each other, the generations just butt heads, day after day.
My own children are in their early teenage years, which means there are challenges ahead that I haven't faced yet. But while there's plenty of writing out there about raising teens — in self-help books, family magazines, and blogs — it's more of the "dos and don'ts" variety. Once kids are old enough to get report cards, there seems to be a lot less soul searching by their folks.
And that's all I'm really seeking: a little variety. There's nothing inherently wrong with writers having the umpteenth insight into the dreadful grind of the terrible twos. But every time I come across one of the articles, I want it to be accompanied by the same author tackling the subject of parenting four, six, and 10 years later. I want the follow-ups. Because from personal experience and thousands of other articles, by now I'm pretty sure I know how those toddler years are going to go.
Noel Murray is a freelance writer living in Arkansas with his wife and two kids. His articles about film, TV, music, and comics appear regularly in the A.V. Club, Rolling Stone, and the Los Angeles Times.
First Person is Vox's home for compelling, provocative narrative essays. Do you have a story to share? Read our submission guidelines, and pitch us at [email protected]. |
def sll(vals: List) -> Optional[ListNode]:
if not vals:
return None
head = ListNode(vals[0])
if len(vals) > 1:
prev = head
for val in vals[1:]:
node = ListNode(val)
prev.next = node
prev = node
return head |
Multi-Feature Bio-Inspired Model for Scene Classification
A multi-feature bio-inspired model for scene image classification (MFBIM) is presented in this work; it extends the hierarchical feedforward model of the visual cortex. Firstly, each of three paths of classification uses each image property (i.e. shape, edge or color based features) independently. Then, BPNN assigns the category of an image based on the previous outputs. Experiments show that the model boosts the classification accuracy over the shape based model. Meanwhile, the proposed approach achieves a high accuracy comparable to other reported methods on publicly available color image dataset. |
# -*- coding: utf-8 -*-
import pytest
import env # noqa: F401
m = pytest.importorskip("pybind11_tests.virtual_functions")
from pybind11_tests import ConstructorStats # noqa: E402
def test_override(capture, msg):
class ExtendedExampleVirt(m.ExampleVirt):
def __init__(self, state):
super(ExtendedExampleVirt, self).__init__(state + 1)
self.data = "Hello world"
def run(self, value):
print("ExtendedExampleVirt::run(%i), calling parent.." % value)
return super(ExtendedExampleVirt, self).run(value + 1)
def run_bool(self):
print("ExtendedExampleVirt::run_bool()")
return False
def get_string1(self):
return "override1"
def pure_virtual(self):
print("ExtendedExampleVirt::pure_virtual(): %s" % self.data)
class ExtendedExampleVirt2(ExtendedExampleVirt):
def __init__(self, state):
super(ExtendedExampleVirt2, self).__init__(state + 1)
def get_string2(self):
return "override2"
ex12 = m.ExampleVirt(10)
with capture:
assert m.runExampleVirt(ex12, 20) == 30
assert (
capture
== """
Original implementation of ExampleVirt::run(state=10, value=20, str1=default1, str2=default2)
""" # noqa: E501 line too long
)
with pytest.raises(RuntimeError) as excinfo:
m.runExampleVirtVirtual(ex12)
assert (
msg(excinfo.value)
== 'Tried to call pure virtual function "ExampleVirt::pure_virtual"'
)
ex12p = ExtendedExampleVirt(10)
with capture:
assert m.runExampleVirt(ex12p, 20) == 32
assert (
capture
== """
ExtendedExampleVirt::run(20), calling parent..
Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)
""" # noqa: E501 line too long
)
with capture:
assert m.runExampleVirtBool(ex12p) is False
assert capture == "ExtendedExampleVirt::run_bool()"
with capture:
m.runExampleVirtVirtual(ex12p)
assert capture == "ExtendedExampleVirt::pure_virtual(): Hello world"
ex12p2 = ExtendedExampleVirt2(15)
with capture:
assert m.runExampleVirt(ex12p2, 50) == 68
assert (
capture
== """
ExtendedExampleVirt::run(50), calling parent..
Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)
""" # noqa: E501 line too long
)
cstats = ConstructorStats.get(m.ExampleVirt)
assert cstats.alive() == 3
del ex12, ex12p, ex12p2
assert cstats.alive() == 0
assert cstats.values() == ["10", "11", "17"]
assert cstats.copy_constructions == 0
assert cstats.move_constructions >= 0
def test_alias_delay_initialization1(capture):
"""`A` only initializes its trampoline class when we inherit from it
If we just create and use an A instance directly, the trampoline initialization is
bypassed and we only initialize an A() instead (for performance reasons).
"""
class B(m.A):
def __init__(self):
super(B, self).__init__()
def f(self):
print("In python f()")
# C++ version
with capture:
a = m.A()
m.call_f(a)
del a
pytest.gc_collect()
assert capture == "A.f()"
# Python version
with capture:
b = B()
m.call_f(b)
del b
pytest.gc_collect()
assert (
capture
== """
PyA.PyA()
PyA.f()
In python f()
PyA.~PyA()
"""
)
def test_alias_delay_initialization2(capture):
"""`A2`, unlike the above, is configured to always initialize the alias
While the extra initialization and extra class layer has small virtual dispatch
performance penalty, it also allows us to do more things with the trampoline
class such as defining local variables and performing construction/destruction.
"""
class B2(m.A2):
def __init__(self):
super(B2, self).__init__()
def f(self):
print("In python B2.f()")
# No python subclass version
with capture:
a2 = m.A2()
m.call_f(a2)
del a2
pytest.gc_collect()
a3 = m.A2(1)
m.call_f(a3)
del a3
pytest.gc_collect()
assert (
capture
== """
PyA2.PyA2()
PyA2.f()
A2.f()
PyA2.~PyA2()
PyA2.PyA2()
PyA2.f()
A2.f()
PyA2.~PyA2()
"""
)
# Python subclass version
with capture:
b2 = B2()
m.call_f(b2)
del b2
pytest.gc_collect()
assert (
capture
== """
PyA2.PyA2()
PyA2.f()
In python B2.f()
PyA2.~PyA2()
"""
)
# PyPy: Reference count > 1 causes call with noncopyable instance
# to fail in ncv1.print_nc()
@pytest.mark.xfail("env.PYPY")
@pytest.mark.skipif(
not hasattr(m, "NCVirt"), reason="NCVirt does not work on Intel/PGI/NVCC compilers"
)
def test_move_support():
class NCVirtExt(m.NCVirt):
def get_noncopyable(self, a, b):
# Constructs and returns a new instance:
nc = m.NonCopyable(a * a, b * b)
return nc
def get_movable(self, a, b):
# Return a referenced copy
self.movable = m.Movable(a, b)
return self.movable
class NCVirtExt2(m.NCVirt):
def get_noncopyable(self, a, b):
# Keep a reference: this is going to throw an exception
self.nc = m.NonCopyable(a, b)
return self.nc
def get_movable(self, a, b):
# Return a new instance without storing it
return m.Movable(a, b)
ncv1 = NCVirtExt()
assert ncv1.print_nc(2, 3) == "36"
assert ncv1.print_movable(4, 5) == "9"
ncv2 = NCVirtExt2()
assert ncv2.print_movable(7, 7) == "14"
# Don't check the exception message here because it differs under debug/non-debug mode
with pytest.raises(RuntimeError):
ncv2.print_nc(9, 9)
nc_stats = ConstructorStats.get(m.NonCopyable)
mv_stats = ConstructorStats.get(m.Movable)
assert nc_stats.alive() == 1
assert mv_stats.alive() == 1
del ncv1, ncv2
assert nc_stats.alive() == 0
assert mv_stats.alive() == 0
assert nc_stats.values() == ["4", "9", "9", "9"]
assert mv_stats.values() == ["4", "5", "7", "7"]
assert nc_stats.copy_constructions == 0
assert mv_stats.copy_constructions == 1
assert nc_stats.move_constructions >= 0
assert mv_stats.move_constructions >= 0
def test_dispatch_issue(msg):
"""#159: virtual function dispatch has problems with similar-named functions"""
class PyClass1(m.DispatchIssue):
def dispatch(self):
return "Yay.."
class PyClass2(m.DispatchIssue):
def dispatch(self):
with pytest.raises(RuntimeError) as excinfo:
super(PyClass2, self).dispatch()
assert (
msg(excinfo.value)
== 'Tried to call pure virtual function "Base::dispatch"'
)
return m.dispatch_issue_go(PyClass1())
b = PyClass2()
assert m.dispatch_issue_go(b) == "Yay.."
def test_override_ref():
"""#392/397: overriding reference-returning functions"""
o = m.OverrideTest("asdf")
# Not allowed (see associated .cpp comment)
# i = o.str_ref()
# assert o.str_ref() == "asdf"
assert o.str_value() == "asdf"
assert o.A_value().value == "hi"
a = o.A_ref()
assert a.value == "hi"
a.value = "bye"
assert a.value == "bye"
def test_inherited_virtuals():
class AR(m.A_Repeat):
def unlucky_number(self):
return 99
class AT(m.A_Tpl):
def unlucky_number(self):
return 999
obj = AR()
assert obj.say_something(3) == "hihihi"
assert obj.unlucky_number() == 99
assert obj.say_everything() == "hi 99"
obj = AT()
assert obj.say_something(3) == "hihihi"
assert obj.unlucky_number() == 999
assert obj.say_everything() == "hi 999"
for obj in [m.B_Repeat(), m.B_Tpl()]:
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 13
assert obj.lucky_number() == 7.0
assert obj.say_everything() == "B says hi 1 times 13"
for obj in [m.C_Repeat(), m.C_Tpl()]:
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 888.0
assert obj.say_everything() == "B says hi 1 times 4444"
class CR(m.C_Repeat):
def lucky_number(self):
return m.C_Repeat.lucky_number(self) + 1.25
obj = CR()
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 889.25
assert obj.say_everything() == "B says hi 1 times 4444"
class CT(m.C_Tpl):
pass
obj = CT()
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 888.0
assert obj.say_everything() == "B says hi 1 times 4444"
class CCR(CR):
def lucky_number(self):
return CR.lucky_number(self) * 10
obj = CCR()
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 8892.5
assert obj.say_everything() == "B says hi 1 times 4444"
class CCT(CT):
def lucky_number(self):
return CT.lucky_number(self) * 1000
obj = CCT()
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 888000.0
assert obj.say_everything() == "B says hi 1 times 4444"
class DR(m.D_Repeat):
def unlucky_number(self):
return 123
def lucky_number(self):
return 42.0
for obj in [m.D_Repeat(), m.D_Tpl()]:
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 4444
assert obj.lucky_number() == 888.0
assert obj.say_everything() == "B says hi 1 times 4444"
obj = DR()
assert obj.say_something(3) == "B says hi 3 times"
assert obj.unlucky_number() == 123
assert obj.lucky_number() == 42.0
assert obj.say_everything() == "B says hi 1 times 123"
class DT(m.D_Tpl):
def say_something(self, times):
return "DT says:" + (" quack" * times)
def unlucky_number(self):
return 1234
def lucky_number(self):
return -4.25
obj = DT()
assert obj.say_something(3) == "DT says: quack quack quack"
assert obj.unlucky_number() == 1234
assert obj.lucky_number() == -4.25
assert obj.say_everything() == "DT says: quack 1234"
class DT2(DT):
def say_something(self, times):
return "DT2: " + ("QUACK" * times)
def unlucky_number(self):
return -3
class BT(m.B_Tpl):
def say_something(self, times):
return "BT" * times
def unlucky_number(self):
return -7
def lucky_number(self):
return -1.375
obj = BT()
assert obj.say_something(3) == "BTBTBT"
assert obj.unlucky_number() == -7
assert obj.lucky_number() == -1.375
assert obj.say_everything() == "BT -7"
def test_issue_1454():
# Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
m.test_gil()
m.test_gil_from_thread()
|
{-|
[@ISO639-1@] -
[@ISO639-2@] -
[@ISO639-3@] nen
[@Native name@] -
[@English name@] Nengone
-}
module Text.Numeral.Language.NEN.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
http://www.languagesandnumbers.com/how-to-count-in-nengone/en/nen/
-}
cardinals :: (Num i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "sa")
, (2, "rewe")
, (3, "tini")
, (4, "ece")
, (5, "sedong")
, (6, "sedong ne sa")
, (7, "sedong ne rew")
, (8, "sedong ne tin")
, (9, "sedong ne ec")
, (10, "ruenin")
, (11, "ruenin ne sa")
, (12, "ruenin ne rew")
, (13, "ruenin ne tin")
, (14, "ruenin ne ec")
, (15, "adenin")
, (16, "adenin ne sa")
, (17, "adenin ne rew")
, (18, "adenin ne tin")
, (19, "adenin ne ec")
, (20, "sarengom")
, (21, "sarengom ne sa")
, (22, "sarengom ne rew")
, (23, "sarengom ne tin")
, (24, "sarengom ne ec")
, (25, "sarengom ne sedong")
, (26, "sarengom ne sedosa")
, (27, "sarengom ne sedorew")
, (28, "sarengom ne sedotin")
, (29, "sarengom ne sedoec")
, (30, "sarengom ne ruenin")
]
)
]
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define INFL 0x6fffffffffffffffLL
int main() {
ll a,b,c,d,h,i,j,k,l,m,n,v,w,x,y,z;
ll ans = 0;
string s;
cin >> s;
if (s[s.size()-1]=='s') s = s + "es";
else s = s + "s";
//vector<ll> aa(n);
//for(i=0;i<n;i++) cin >> aa[i];
//vector<ll> dp(n+1,INFL);
//vector<vector<ll>> dp2(x , vector<ll>(y,INFL));
cout << s << endl;
return 0;
}
|
// find fs from udevadm info
func parseFS(output string) string {
m := parseUdevInfo(output)
if v, ok := m["ID_FS_TYPE"]; ok {
return v
}
return ""
} |
// sets up psplit, so split is performed with no
// user-requested operation
//
VOID BTISelectSplitWithOperNone( SPLIT *psplit, FUCB *pfucb )
{
if ( splitoperInsert == psplit->splitoper )
{
INT iLine = psplit->ilineOper;
for ( ; iLine < psplit->clines - 1 ; iLine++ )
{
psplit->rglineinfo[iLine] = psplit->rglineinfo[iLine + 1];
}
psplit->clines--;
}
else
{
Assert( psplit->psplitPath->csr.Cpage().FLeafPage( ) );
psplit->psplitPath->csr.SetILine( psplit->ilineOper );
NDGet( pfucb, &psplit->psplitPath->csr );
psplit->rglineinfo[psplit->ilineOper].kdf = pfucb->kdfCurr;
psplit->rglineinfo[psplit->ilineOper].cbSize =
CbNDNodeSizeTotal( pfucb->kdfCurr );
ULONG cbMax = CbBTIMaxSizeOfNode( pfucb, &psplit->psplitPath->csr );
Assert( cbMax >= psplit->rglineinfo[psplit->ilineOper].cbSize );
psplit->rglineinfo[psplit->ilineOper].cbSizeMax = cbMax;
}
psplit->ilineOper = 0;
BTIRecalcWeightsLE( psplit );
psplit->splitoper = splitoperNone;
psplit->prefixinfoNew.Nullify();
psplit->prefixinfoSplit.Nullify();
} |
25 Marble sized sphere th at, when placed in the mouth, a llows you to se e the visual output of nearby electronic devices in your mind. 26 Button that, wh en pressed, causes nearby computer systems to be able to feel pain. 27 Cylindrical electrical power source that feeds on nearby life (-1 Might point per hour). 28 Rounded container that e tches a sy mbol in to any object placed inside, allowing computers to wirelessly control that object from now on. 29 Metal sphere that appears to be magnetically attracted to large sources of information. 30 Nose plugs that cause you to smell any corrupted data in a com puter sy stem. 31 Container of bright orange paint that protects an electrical object covered in it from being controlled by Datasphere entities. 32 Shard of glowing, tangible data left over from a Ghost Storm attack (see page 8). 33 Handheld tool that detects the presence of computer viruses in a device. 34 Device which fires a narrow beam that disassembles small machines. 35 Contact lens that allows you to s ee through the eye of a nea rby robot. 36 Silver necklace that gets hot when near hostile machines. 37 Shoulder pads that draw and absorb electricity. Provides Armor 3 against electrical damage. 38 Metallic emblem that floats around y our head in a circle. For s ome reason it makes y ou feel safe from hostile Datasphere entities, but whether it actually protects you or not is unknown. 39 Glass tube filled w ith an oil that protects cybernetic parts from corrosion and wear. 40 Floating sphere that follows you around, displaying tidbits of random information from the surrounding Datasphere on a small screen. 41 Animal skull that inhibits the Datasphere in its immediate area. 42 Thin, transparent card that is capable of storing information when inserted into m ost computers. The data lasts for twenty eight hours. 43 Metal nodule that encrypts your thoughts against mind reading, but causes nose bleeds. 44 Holographic pet that eats data to survive. 45 Unpowered head of an android. 46 Set of black dice that always adds up to prime numbers. 47 Metal loop that constricts in the presence of computers. 48
Tinted window that reveals the inner components of machines when they’re viewed through it.
49 Long black glove that protects you from electrocution by the things you touch. 50 Helmet that allows
you to hear the “thoughts” of all of the robots around you, but that causes you to think |
.
OBJECTIVE
To assess the value of SYNTAX score to predict major adverse cardiac and cerebrovascular events (MACCE) among patients with three-vessel or left-main coronary artery disease undergoing percutaneous coronary intervention.
METHODS
190 patients with three-vessel or left-main coronary artery disease undergoing percutaneous coronary intervention (PCI) with Cypher select drug-eluting stent were enrolled. SYNTAX score and clinical SYNTAX score were retrospectively calculated. Our clinical Endpoint focused on MACCE, a composite of death, nonfatal myocardial infarction (MI), stroke and repeat revascularization. The value of SYNTAX score and clinical SYNTAX score to predict MACCE were studied respectively.
RESULTS
29 patients were observed to suffer from MACCE, accounting 18.5% of the overall 190 patients. MACCE rates of low (≤ 20.5), intermediate (21.0 - 31.0), and high (≥ 31.5) tertiles according to SYNTAX score were 9.1%, 16.2% and 30.9% respectively. Both univariate and multivariate analysis showed that SYNTAX score was the independent predictor of MACCE. MACCE rates of low (≤ 19.5), intermediate (19.6 - 29.1), and high (≥ 29.2) tertiles according to clinical SYNTAX score were 14.9%, 9.8% and 30.6% respectively. Both univariate and multivariate analysis showed that clinical SYNTAX score was the independent predictor of MACCE. ROC analysis showed both SYNTAX score (AUC = 0.667, P = 0.004) and clinical SYNTAX score (AUC = 0.636, P = 0.020) had predictive value of MACCE. Clinical SYNTAX score failed to show better predictive ability than the SYNTAX score.
CONCLUSIONS
Both SYNTAX score and clinical SYNTAX score could be independent risk predictors for MACCE among patients with three-vessel or left-main coronary artery disease undergoing percutaneous coronary intervention. Clinical SYNTAX score failed to show better predictive ability than the SYNTAX score in this group of patients. |
/*
* Copyright 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.stem.transport;
import io.netty.buffer.ByteBuf;
public class Frame // TODO: rename to Packet
{
public final Header header;
public final ByteBuf body;
public Connection connection;
public Frame(Header header, ByteBuf body, Connection connection) {
this.body = body;
this.header = header;
this.connection = connection;
}
public static Frame create(ByteBuf in, Connection connection) {
int opcode = in.readByte();
Message.Type opType = Message.Type.fromOpcode(opcode);
int streamId = in.readInt();
Frame.Header header = new Frame.Header(opType, streamId);
int length = in.readInt();
assert length == in.readableBytes();
return new Frame(header, in, connection);
}
public static Frame create(Message.Type type, int streamId, ByteBuf body, Connection connection) {
Frame.Header header = new Frame.Header(type, streamId);
return new Frame(header, body, connection);
}
public static class Header {
public static final int LENGTH = 1 + 4 + 4;
public Message.Type opType;
int streamId;
public Header(Message.Type opType, int streamId) {
this.opType = opType;
this.streamId = streamId;
}
}
}
|
package sqlite.feature.custombean.case2;
import java.util.Calendar;
import java.util.Date;
import com.abubusoft.kripton.android.sqlite.SQLitePopulator;
import com.abubusoft.kripton.android.sqlite.TransactionResult;
import android.support.annotation.NonNull;
import android.util.Log;
import sqlite.feature.custombean.case2.BindAppDataSource.Transaction;
public class DataSourcePopulator implements SQLitePopulator {
// Simulate a blocking operation delaying each Loan insertion with a delay:
private static final int DELAY_MILLIS = 500;
public void populateSync(@NonNull final BindAppDataSource db) {
populateWithTestData(db);
}
private void addLoan(final BindAppDaoFactory daoFactory, final String id, final User user, final Book book, Date from, Date to) {
Loan loan = new Loan();
loan.id = id;
loan.bookId = book.id;
loan.userId = user.id;
loan.startTime = from;
loan.endTime = to;
daoFactory.getLoanDao().insertLoan(loan);
}
private Book addBook(final BindAppDaoFactory daoFactory, final String id, final String title) {
Book book = new Book();
book.id = id;
book.title = title;
daoFactory.getBookDao().insertBook(book);
return book;
}
private User addUser(final BindAppDaoFactory daoFactory, final String id, final String name, final String lastName, final int age) {
User user = new User();
user.id = id;
user.age = age;
user.name = name;
user.lastName = lastName;
daoFactory.getUserDao().insertUser(user);
return user;
}
private void populateWithTestData(BindAppDaoFactory daoFactory) {
daoFactory.getLoanDao().deleteAll();
daoFactory.getUserDao().deleteAll();
daoFactory.getBookDao().deleteAll();
User user1 = addUser(daoFactory, "1", "Jason", "Seaver", 40);
User user2 = addUser(daoFactory, "2", "Mike", "Seaver", 12);
addUser(daoFactory, "3", "Carol", "Seaver", 15);
Book book1 = addBook(daoFactory, "1", "Dune");
Book book2 = addBook(daoFactory, "2", "1984");
Book book3 = addBook(daoFactory, "3", "The War of the Worlds");
Book book4 = addBook(daoFactory, "4", "Brave New World");
addBook(daoFactory, "5", "Foundation");
try {
// Loans are added with a delay, to have time for the UI to react to
// changes.
Date today = getTodayPlusDays(0);
Date yesterday = getTodayPlusDays(-1);
Date twoDaysAgo = getTodayPlusDays(-2);
Date lastWeek = getTodayPlusDays(-7);
Date twoWeeksAgo = getTodayPlusDays(-14);
addLoan(daoFactory, "1", user1, book1, twoWeeksAgo, lastWeek);
Thread.sleep(DELAY_MILLIS);
addLoan(daoFactory, "2", user2, book1, lastWeek, yesterday);
Thread.sleep(DELAY_MILLIS);
addLoan(daoFactory, "3", user2, book2, lastWeek, today);
Thread.sleep(DELAY_MILLIS);
addLoan(daoFactory, "4", user2, book3, lastWeek, twoDaysAgo);
Thread.sleep(DELAY_MILLIS);
addLoan(daoFactory, "5", user2, book4, lastWeek, today);
Log.d("DB", "Added loans");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Date getTodayPlusDays(int daysAgo) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, daysAgo);
return calendar.getTime();
}
/**
* Execute the populator.
*/
@Override
public void execute() {
BindAppDataSource.getInstance().executeAsync(new Transaction() {
@Override
public TransactionResult onExecute(BindAppDaoFactory daoFactory) {
populateWithTestData(daoFactory);
return TransactionResult.COMMIT;
}
});
}
/*
* private static class PopulateDbAsync extends BindAppAsynTask
* AsyncTask<Void, Void, Void> {
*
* private final AppDatabase mDb;
*
* PopulateDbAsync(AppDatabase db) { mDb = db; }
*
* @Override protected Void doInBackground(final Void... params) {
* populateWithTestData(mDb); return null; }
*
* }
*/
}
|
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file 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.
from typing import List, Optional, Tuple
from mxnet.gluon import nn
from gluonts.core.component import validated
from gluonts.mx import Tensor
from .representation import Representation
# LearnedBinning = Union[GlobalRelativeBinning, LocalAbsoluteBinning]
class DiscretePIT(Representation):
"""
A class representing a discrete probability integral transform of a given
quantile-based learned binning. Note that this representation is intended
to be applied on top of a quantile-based binning representation.
Parameters
----------
num_bins
Number of bins used by the data on which this representation is
applied.
mlp_tranf
Whether we want to post-process the pit-transformed valued using a MLP
which can learn an appropriate binning, which would ensure that pit
models have the same expressiveness as standard quantile binning with
embedding.
(default: False)
embedding_size
The desired layer output size if mlp_tranf=True. By default, the
following heuristic is used:
https://developers.googleblog.com/2017/11/introducing-tensorflow-feature-columns.html
(default: round(num_bins**(1/4)))
"""
@validated()
def __init__(
self,
num_bins: int,
mlp_transf: bool = False,
embedding_size: Optional[int] = None,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self.num_bins = num_bins
self.mlp_transf = mlp_transf
if embedding_size is None:
self.embedding_size = round(self.num_bins ** (1 / 4))
else:
self.embedding_size = embedding_size
if mlp_transf:
self.mlp = nn.HybridSequential()
self.mlp.add(
nn.Dense(units=self.num_bins, activation="relu", flatten=False)
)
self.mlp.add(nn.Dense(units=self.embedding_size, flatten=False))
else:
self.mlp = None
def hybrid_forward(
self,
F,
data: Tensor,
observed_indicator: Tensor,
scale: Optional[Tensor],
rep_params: List[Tensor],
**kwargs,
) -> Tuple[Tensor, Tensor, List[Tensor]]:
data = data / self.num_bins
if self.mlp_transf:
data = F.expand_dims(data, axis=-1)
data = self.mlp(data)
return data, scale, rep_params
def post_transform(
self, F, samples: Tensor, scale: Tensor, rep_params: List[Tensor]
) -> Tensor:
samples = samples * F.full(1, self.num_bins)
samples = F.Custom(
samples, F.arange(self.num_bins), op_type="digitize"
)
return samples
|
n = int(input())
dollarBills = [100, 20, 10, 5, 1]
minBills = 0
for dollar in dollarBills:
minBills += n // dollar
n %= dollar
print(minBills) |
#include<stdio.h>
int l,r,k,d[1000001],D[10][1000001],i,j;
int f(int n){
if(n==0)return 1;
else return f(n/10)*((n%10)?n%10:1);
}
int g(int n){
if(n<1000000)if(d[n])return d[n];
if(n<10)return n;
if(n<1000000)return d[n]=g(f(n));
else return g(f(n));
}
int main(){
int T;
scanf("%d",&T);
for(i=1;i<=1000000;i++){
if(d[i])continue;
else d[i]=g(i);
}
for(i=1;i<=9;i++){
for(j=1;j<=1000000;j++){
if(d[j]==i)D[i][j]=D[i][j-1]+1;
else D[i][j]=D[i][j-1];
}
}
while(T--){
scanf("%d %d %d",&l,&r,&k);
printf("%d\n",D[k][r]-D[k][l-1]);
}
} |
America, meet the Minnesota Vikings, the best team in the NFC North—both in record and in actuality. During the summer, many predicted the Vikings would take that Next Step under second-year coach Mike Zimmer. But no one forecast that a Week 10 victory at Oakland would be their seventh of the year. This morning, they lead the North for three reasons:
1. Their offense has a distinct identity, centered around Adrian Peterson and the power running game.
2. Their defense is young, fast in all the right places and very well-schemed.
3. The rival Packers currently have a poorly coached, mediocre offense that happens to be led by a phenomenal quarterback. (And that quarterback has been inconsistent lately.)
But the purpose of this article is not to condemn the Packers, who entered Week 10 amidst a two-game skid and came out of it home losers to the Lions for the first time since 1991. (If you’re interested in what’s triggering Green Bay’s struggles, read my Extra Point from two weeks ago, which followed their first loss of the season. The ills of that game were repeated last week at Carolina. And, presumably, without yet confirming on the coaches film, repeated again this week against Detroit.)
The purpose of this article is to introduce casual fans to the upstart Vikings, necessary considering Minnesota hasn’t had a nationally televised game since a dreadful Week 1 Monday Night showing at San Francisco. Let’s take the tour.
• MIDSEASON ALL-PRO TEAM: Two Vikings appear on the All-Pro team Andy Benoit unveiled last week
Start with that offense. Chances are people know two guys: Adrian Peterson and Teddy Bridgewater. And chances are, people believe that Peterson is every bit as good as he really is, while Bridgewater is better than he actually is. For reasons unknown, it’s become heretical in the Upper Midwest to say anything the least bit negative about the second-year quarterback. Many believe him to be the best young signal-caller in the game, and Sunday’s win over the league’s actual best young signal-caller, Derek Carr, will only intensify this misnomer.
In reality, Bridgewater has limitations that Carr—and other upper-echelon young quarterbacks—do not. Namely, arm strength. Bridgewater is not a guy who can “make all the throws,” as they say. He doesn’t have a Chad Pennington-type noodle, but he cannot consistently drive the ball at the deep-intermediate levels. In the last two weeks the Vikings have played in windy conditions and, not coincidentally, their downfield passing attack has disappeared.
Limited arm strength doesn’t mean Bridgewater can’t play. Rather, it means, like Pennington, he can only play a certain way. His ascension as a pro will hinge on his ability to anticipate throwing windows. To overcome his limitations, he’ll have to be great in this realm. Quarterbacks with declining arm strength can target these tight windows because, having once had the arm strength, they’ve spent their careers identifying them (see: Brees, Drew). When you’re relatively meager-armed, it’s never occurred to you to target the tight windows because you’ve never been able to.
Some—in fact, many—modest-armed passers remain big-window guys their entire careers. Alex Smith is a good example; and so far Bridgewater resembles Alex Smith. That may seem unflattering, but it’s not necessarily. Smith, after all, is a smart QB. He doesn’t make many big plays because he doesn’t take a lot of chances, but on the flip side, he doesn’t make many negative plays either. He plays in a well-constructed scheme under Andy Reid, emphasizing his strengths while avoiding his weaknesses. This is where Bridgewater is. Vikings offensive coordinator Norv Turner is a brilliant play-designer and play-caller. And while Turner prefers vertical passing and aggression at the deep intermediate levels, he realizes he’s no longer coaching Troy Aikman or Philip Rivers, and he has subtly amended his approach accordingly. The Vikings’ passing game features reads that are not strictly defined, per se, like in a remedial system. But overall, many of the reads are at least somewhat defined, or inherently contained in a way that simplifies the QB’s progressions. Evidence of this are the rollout passes, wide receiver misdirection concepts (plus screens) and high-low route combinations, on which Bridgewater can read two receivers and one defender all within the same line of vision. This controlled approach has lifted some of the pressure off Bridgewater and has served to neutralize a Vikings offensive line that has tackles (Matt Kalil and especially rookie T.J. Clemmings) who can be vulnerable in pass protection, and an interior (guards Mike Harris and Brandon Fusco plus backup center Joe Berger) that lacks athleticism.
The Vikings have an offense that plays to Teddy Bridgewater’s strengths and minimizes the reliance on his modest arm. Beck Diefenbach/AP
So far, this article probably sounds negative given that it’s describing a legitimate 7-2 division leader. Limited quarterback, subpar O-line. But you can’t overemphasize the “well-designed system” factor, and, oh, also, that other big-name offensive player everyone knows. Adrian Peterson, the league’s leading rusher (961 yards, including 203 at Oakland), remains the most explosive runner in the game, particularly on his first step after changing directions. To play to this explosiveness, Turner has built his game plans around Peterson and instituted more classic inside run concepts, with Peterson lined up eight yards deep in the backfield (so he can build up a head of steam). From there he attacks between the tackles, behind double-teams at the point. Minnesota’s offensive linemen might not be great, but two of them will still overpower one of the opponent’s defensive lineman. From there, Peterson can consistently beat linebackers.
Peterson’s dominance allows the Vikings to keep Bridgewater on a leash (one that’s retractable per the situation). Also giving teeth to an otherwise safe offense are the playmakers at wide receiver, most notably Stefon Diggs. With a mixture of quickness, acceleration and body control, the fifth-rounder is easily the NFL’s best rookie receiver not named Amari Cooper. Averaging 84.5 receiving yards per game, Diggs has fully supplanted up-and-comer Charles Johnson atop the pecking order. Johnson, in fact, has battled injuries and fallen to No. 4—a testament, as much as anything, to the depth and dimension of Minnesota’s receiving corps.
• VIKINGS’ SECRET DONUT CLUB: On Saturday mornings during the season, a group of Vikings convene in the athletic trainers’ room for a sugary, frosted tradition like no other in the NFL
So Bridgewater is a limited but well-coached young quarterback who is steadily improving and surrounded by a strong cast of skill players. That’s enough for sustained success when you put this grouping opposite a top-five defense, which the Vikings have. Zimmer is one of the best defensive teachers and schemers in all of football. He’s installed the full scope of his patented double-A-gap pressure foundation in Minnesota, and the results have been outstanding. The beauty of a pressure scheme—and particularly one like double-A-gap, where the inside blitz looks before the snap create one-on-one pass rushing scenarios for everyone across the board—is that it engenders coverage disguises as well as unpredictability in the pass rush. Consequently, opposing quarterbacks play with a reactionary unease. The benefits here for the defense reach far beyond sacks and turnovers (where the Vikings rank 14th and 22nd, respectively). It’s very difficult for an offense to establish rhythm against a defense that schematically dictates the terms of engagement.
In double-A-gap, the disguises stem from defenders’ ability to drop into coverage. In Cincinnati, where Zimmer had an inordinate number of highly athletic defensive lineman, you often saw an end or tackle dropping as part of a zone blitz. In Minnesota, Zimmer’s best speed is concentrated at linebacker and safety. Players at these positions have been the primary blitzers and coverage droppers for the Vikings. At ’backer, second-year man Anthony Barr is big and versatile. Next to him, rookie Eric Kendricks (who has missed the last two games with a rib injury) offers good enough speed to have supplanted heady veteran Chad Greenway in the nickel package. That means Kendricks, when healthy, plays every snap, while the still-stellar Greenway sees under half of them. At safety, Harrison Smith’s high football IQ and flexibility as a box thumper or rangy route jumper in space form the backbone of the pressure packages and disguises. And at the other safety, Andrew Sendejo, a lower-case version of Smith, is markedly more comfortable in Year Two in this scheme. He’s playing as fast as almost any player at his position.
With speed in the second and third levels up the middle of his defense, Zimmer has more leeway for aggressiveness in disguise. That is to say, he can ask his men to cover more ground when rotating out of a pressure look into coverage, or vice versa. More ground equals more possibilities the offense must consider. Or, when thing really go Minnesota’s way, the more possibilities the offense fails to consider.
Last item with the Vikings’ top-ranked scoring defense: There are a handful of role players who are simply playing at a really high level. The one who stands out every week is nose shade tackle Linval Joseph, the best inside point of attack front line run defender in the league this season. In the secondary, cornerback Xavier Rhodes offers size and physicality, though lately it’s been veteran Terence Newman making most of the plays. The 37-year-old corner—which, by the way, is the equivalent of something like a 52-year-old quarterback, or a 64-year-old kicker—had two sensational interceptions as well as critical back-to-back solo pass breakups at Oakland on Sunday.
All of Minnesota’s victories this season have come against teams that now sit below .500. Don’t read too much into this; any NFL game is hard to win, and if the Vikings hadn’t won their seven games, then three of their opponents—the Bears, Rams and Raiders—would have winning records. But the point is: Yes, this week’s home test against the Packers is the stiffest the Vikings have faced in 2015 (save for the road contest at Denver). They likely won’t be favored since betting lines are a reflection of popular opinion, not expert opinion. But heading into the game against Green Bay, the Vikings are, without question, the better team.
• Questions or comments? Email us at [email protected]. |
import * as React from 'react';
import { Adsense } from '@client/services/service-proxies';
import { withNamespaces } from '@client/i18n';
const Fragment = React.Fragment;
interface Props {
adsense: Adsense[];
t: (key: string) => string;
}
interface State {}
class BaseRightSideBar extends React.PureComponent<Props, State> {
render () {
const adsPosition5 = this.props.adsense.filter((item) => item.position === 5)[0];
const adsPosition6 = this.props.adsense.filter((item) => item.position === 6)[0];
const adsPosition7 = this.props.adsense.filter((item) => item.position === 7)[0];
const adsPosition8 = this.props.adsense.filter((item) => item.position === 8)[0];
const adsPosition9 = this.props.adsense.filter((item) => item.position === 9)[0];
const adsPosition10 = this.props.adsense.filter((item) => item.position === 10)[0];
return (
<Fragment>
<a href={adsPosition5 && adsPosition5.hyperlink ? adsPosition5.hyperlink : '#'} target='_blank'>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
height: '200px',
backgroundImage: `url(${adsPosition5 && adsPosition5.imageUrl ? adsPosition5.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition5 && adsPosition5.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition5 && adsPosition5.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
<a href={adsPosition6 && adsPosition6.hyperlink ? adsPosition6.hyperlink : '#'}>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
marginTop: '30px',
height: '200px',
backgroundImage: `url(${adsPosition6 && adsPosition6.imageUrl ? adsPosition6.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition6 && adsPosition6.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition6 && adsPosition6.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
<a href={adsPosition7 && adsPosition7.hyperlink ? adsPosition7.hyperlink : '#'} target='_blank'>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
marginTop: '30px',
height: '200px',
backgroundImage: `url(${adsPosition7 && adsPosition7.imageUrl ? adsPosition7.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition7 && adsPosition7.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition7 && adsPosition7.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
<a href={adsPosition8 && adsPosition8.hyperlink ? adsPosition8.hyperlink : '#'} target='_blank'>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
marginTop: '30px',
height: '200px',
backgroundImage: `url(${adsPosition8 && adsPosition8.imageUrl ? adsPosition8.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition8 && adsPosition8.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition8 && adsPosition8.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
<a href={adsPosition9 && adsPosition9.hyperlink ? adsPosition9.hyperlink : '#'} target='_blank'>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
marginTop: '30px',
height: '400px',
backgroundImage: `url(${adsPosition9 && adsPosition9.imageUrl ? adsPosition9.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition9 && adsPosition9.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition9 && adsPosition9.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
<a href={adsPosition10 && adsPosition10.hyperlink ? adsPosition10.hyperlink : '#'} target='_blank'>
<div
className='image-promote'
style={{
backgroundColor: '#F6F6F6',
marginTop: '30px',
height: '400px',
backgroundImage: `url(${adsPosition10 && adsPosition10.imageUrl ? adsPosition10.imageUrl : ''})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
border: adsPosition10 && adsPosition10.imageUrl ? '' : '1px dashed black',
color: '#000',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{adsPosition10 && adsPosition10.imageUrl ? '' : this.props.t('common:contact-for-ads')}
</div>
</a>
</Fragment>
);
}
}
export const RightSideBar = withNamespaces(['common'])(BaseRightSideBar);
|
/****************************************************************************
* Name: sam_shutdown
*
* Description:
* Disable the USART. This method is called when the serial
* port is closed
*
****************************************************************************/
static void sam_shutdown(struct uart_dev_s *dev)
{
struct sam_dev_s *priv = (struct sam_dev_s *)dev->priv;
sam_serialout(priv, SAM_UART_CR_OFFSET,
(UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS |
UART_CR_TXDIS));
sam_disableallints(priv, NULL);
} |
/**
* Two subsequent builds should not change the last modified if none of the
* source inputs have been modified.
*
* @throws Exception
*/
public void testLastModified() throws Exception {
Workspace ws = getWorkspace("testresources/ws");
Project project = ws.getProject("p6");
File bnd = IO.getFile("testresources/ws/p6/bnd.bnd");
assertTrue(bnd.exists());
project.clean();
File pt = project.getTarget();
if (!pt.exists() && !pt.mkdirs()) {
throw new IOException("Could not create directory " + pt);
}
try {
File[] files = project.build();
assertTrue(project.check());
assertNotNull(files);
assertEquals(1, files.length);
Jar older = new Jar(files[0]);
byte[] olderDigest = older.getTimelessDigest();
older.close();
System.out.println();
Thread.sleep(3000);
files[0].delete();
project.build();
assertTrue(project.check());
assertNotNull(files);
assertEquals(1, files.length);
Jar newer = new Jar(files[0]);
byte[] newerDigest = newer.getTimelessDigest();
newer.close();
assertTrue(Arrays.equals(olderDigest, newerDigest));
}
finally {
project.clean();
}
} |
/**
*
* @author Miguel Angel Diaz
*/
public class NotasServicios {
public Nota guardarNota(Nota n){
NotasDAO dao = new NotasDAO();
return dao.guardarNota(n);
}
public Nota getNota(Long idalu, Long idasig){
NotasDAO dao = new NotasDAO();
return dao.getNota(idalu, idasig);
}
public int delNota(Nota n){
NotasDAO dao = new NotasDAO();
return dao.delNota(n);
}
public List<Asociaciones2> getNotas(Long idusuario){
Alumnos_profesoresServicios ap = new Alumnos_profesoresServicios();
NotasDAO dao = new NotasDAO();
return dao.getNotas( ap.getIdAlumno((int)(long)idusuario));
}
} |
National and Northern New England Opioid Prescribing Patterns, 2013–2014
Objective
To evaluate current opioid prescribing patterns nationally and regionally across several northern New England states and compare with prescription data on an institutional level over a two-year period, between 2013 and 2014.
Design, Setting, and Subjects
The IMS Health National Prescription Audit (NPA) database was used to obtain prescription data from US retail pharmacies between 2013 and 2014.
Methods
Our study compared noninjectable opioid dispensing between two time periods: January-June 2013 and July-December 2014. Opioid prescription data were obtained nationally and in New Hampshire, Vermont, Maine, and Massachusetts. Institutional prescription data were supplied by Dartmouth Hitchcock Medical Center (DHMC) and University of Vermont Medical Center (UVMC) pharmacies.
Results
There was a 3.4% ( P = 0.81) decrease in opioid prescriptions filled nationally. Among New England states, opioid prescribing decreased in Maine (-5.20%, P = 0.72), Massachusetts (-4.4%, P = 0.78), and Vermont (-2.2%, P = 0.89) but increased in New Hampshire by 1.3% ( P = 0.94). Examination of local institutional opioid utilization revealed a 13.6% decline in prescriptions filled at UVMC, and only a 0.4% decrease at DHMC.
Conclusions
The review of opioid prescriptions filled in 2013-14 suggests that national opioid utilization may be reaching a plateau. Initiatives such as prescription monitoring programs, prescriber opioid education, addiction treatment programs, public addiction awareness, and availability of medical cannabis may play a role in interstate variability of opioid use. National and regional data served as a benchmark for local institutional comparison, laying groundwork for efforts to explore areas where opioids can be prescribed more judiciously. |
/**
* Preprocessor to encrypted OutputStream using GPG codec
*
* This is backwards compatible with PGP algorithms
*
*/
public class GpgEncryptProcessor extends OutputStreamProcessor {
private static final String FILE_EXT = "gpg";
public StreamCodec getCodec() {
return codec;
}
public void setCodec(StreamCodec codec) {
this.codec = codec;
}
private StreamCodec codec;
public GpgEncryptProcessor(JsonObject params) {
super(params);
this.codec = EncryptionUtils.getGpgCodec(parameters);
}
@Override
public OutputStream process(OutputStream origStream) throws IOException {
return codec.encodeOutputStream(origStream);
}
@Override
public String convertFileName(String fileName) {
if (!FilenameUtils.getExtension(fileName).equals(FILE_EXT)) {
return fileName + ".gpg";
}
return fileName;
}
} |
<reponame>juliomrqz/scrits-django<filename>angular/src/app/articles/articles-detail.component.ts<gh_stars>1-10
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ArticlesService } from '../shared/backend/articles.service';
import { Article, ArticleExtended, Category } from '../shared/backend/interfaces';
import { WindowRefService } from '../shared/window/window-ref.service';
/**
* This class represents the lazy loaded ArticlesDetailComponent.
*/
@Component({
selector: 'scrits-articles-detail',
templateUrl: 'articles-detail.component.html'
})
export class ArticlesDetailComponent implements AfterViewInit, OnInit {
article: ArticleExtended;
articleErrorMessage: string;
articleId: number;
errorMessage: string;
showSpinner = true;
toolbar = {
'title': 'Article detail',
'subtitle': 'Details of your article'
};
private window: Window;
/**
* Creates an instance of the ArticlesEditComponent with the injected
* ArticlesService and FormBuilder.
*
* @param {ArticlesService} articlesService - The injected ArticlesService.
* @param {FormBuilder} fb - The injected FormBuilder.
* @param {ActivatedRoute} route - The injected ActivatedRoute.
* @param {Router} router - The injected Router.
*/
constructor(
public articlesService: ArticlesService,
private route: ActivatedRoute,
private router: Router,
windowRef: WindowRefService) {
// Store the browser native window
this.window = windowRef.nativeWindow;
}
ngOnInit() {
this.getArticleId();
}
ngAfterViewInit() {
this.getArticleInformation();
}
/**
* Handle the categoriesService observable
*/
getArticleInformation() {
this.articlesService.detail(this.articleId)
.subscribe(
article => {
// Update the aticle form
this.article = article;
// Update the title bar
this.toolbar = {
'title': this.article.title,
'subtitle': '<i class="fa fa-folder-o"></i> ' + this.article.category.title
};
this.showSpinner = false;
},
error => this.articleErrorMessage = <any>error
);
}
/**
* Get the article ID
*/
getArticleId() {
this.route.params.subscribe(params => {
this.articleId = Number(params['id']);
});
}
/**
* Handle the article remotion
*/
removeArticle() {
event.preventDefault();
if (this.window.confirm('Are you sure you want to remove this article?')) {
this.articlesService.remove(this.articleId).subscribe(
response => {
this.router.navigate(['articles']);
},
error => this.errorMessage = <any>error
);
}
}
}
|
DOA Estimation of Distributed mmWave Radar System via Fast Iterative Adaptive Approach
In this paper, we propose a fast algorithm based on iterative adaptive approach to address the DOA estimation for the distributed mmWave radar system under the challenging conditions of a single snapshot and coherent sources. In order to improve angular resolution, let each transmit sensor emit the same signal in time-sharing to construct a large aperture virtual array. We first roughly derive azimuth angles with one mmWave radar using conventional beamforming. Then, resorting to iterative adaptive approach, we search for the accurate DOA estimations within a very small region based on the estimated azimuth to improve computational efficiency and angular resolution. Finally, numerical simulation results are provided to demonstrate superior performance of the proposed algorithm over some counterparts. |
<filename>mgs/v1.2/ais_thread.py
#!/usr/bin/env python
#########################################
# Title: Rocksat Data Server Class #
# Project: Rocksat #
# Version: 1.0 #
# Date: August, 2017 #
# Author: <NAME>, KJ4QLP #
# Comment: Initial Version #
#########################################
import socket
import threading
import sys
import os
import errno
import time
import binascii
import numpy
from Queue import Queue
import datetime as dt
from logger import *
class AIS_Thread(threading.Thread):
def __init__ (self, options):
threading.Thread.__init__(self,name = 'AISThread')
self._stop = threading.Event()
self.ip = options.ais_ip
self.port = options.ais_port
self.id = options.id
self.ts = options.ts
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Socket
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.settimeout(1)
self.connected = False
self.log_fh = setup_logger(self.id, 'ais_msg', self.ts)
self.logger = logging.getLogger('ais_msg')
self.last_frame_ts = dt.datetime.utcnow() #Time Stamp of last received frame
self.ais_count = 0 #number of individual ADSB messages received
self.msgs = None
self.q = Queue()
def run(self):
print "AIS Thread Running..."
try:
print 'trying to connect to OpenCPN'
self.sock.connect((self.ip, self.port))
self.connected = True
print self.utc_ts() + "Connected to OpenCPN..."
except Exception as e:
self.Handle_Connection_Exception(e)
while (not self._stop.isSet()):
if (not self.q.empty()): #new message in Queue for downlink
ais_frame = self.q.get() #should be 256 byte messages
self.msgs = self.Decode_AIS_Frame(ais_frame)
if self.connected == True:
self.send_to_plotter(self.msgs)
elif self.connected == False:
print self.utc_ts() + "Disconnected from OpenCPN..."
time.sleep(1)
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Socket
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#self.sock.settimeout(1)
self.sock.connect((self.ip, self.port))
self.connected = True
print self.utc_ts() + "Connected to OpenCPN..."
except Exception as e:
self.Handle_Connection_Exception(e)
def Decode_AIS_Frame(self,frame):
data = frame[11:]
#print data
data_lines = data.split('!')
#print data_lines
msgs = []
for dl in data_lines:
if len(dl) > 0:
msgs.append("!" + dl)
#print msgs
for msg in msgs:
self.ais_count +=1
self.logger.info(str(self.ais_count)+','+msg)
return msgs
def send_to_plotter(self,msgs):
if msgs != None:
for msg in msgs:
try:
self.sock.send(msg)
except Exception as e:
self.Handle_Connection_Exception(e)
self.msgs = None
def Decode_ADSB_Frame(self, frame):
msgs = []
#print binascii.hexlify(frame)
#msg_type = numpy.uint8(struct.unpack('>B',rx_frame[10]))[0] #message type, 0=ADSB, 1=AIS, 2=HW
msg_cnt = numpy.uint8(struct.unpack('>B',frame[11]))[0] #Number of ADSB Messages
length = numpy.uint32(struct.unpack('<I',frame[12:16]))[0] #Length indicator field
data = frame[16:]
#print msg_cnt, "{0:032b}".format(length), len(data)
MASK = numpy.uint32(1) #initialize 32 bit number to 31 0s and a 1
#print "{0:032b}".format(MASK)
idx = 0 #first byte in data field index
for i in range(msg_cnt):
self.adsb_count += 1
msg_len = 0 #in bytes
if (MASK & length) > 0: #long message
msg_len = 14
msg = data[idx:]
else: msg_len = 7
msg = data[idx:idx+msg_len]
idx = idx+msg_len
#print i, "{0:032b}".format(MASK), "{0:032b}".format(MASK & length), msg_len, binascii.hexlify(msg)
msgs.append(msg)
self.logger.info(str(self.adsb_count)+','+binascii.hexlify(msg))
MASK = MASK << 1 #bit shift MASK for next iteration
return msgs
def send_to_plotter_old(self,msgs):
for msg in msgs:
msg_str = '*' + str(binascii.hexlify(msg)) + ';\n'
#print 'sending', msg_str
try:
self.sock.send(msg_str)
except Exception as e:
self.Handle_Connection_Exception(e)
def Handle_Connection_Exception(self, e):
#print e, type(e)
errorcode = e[0]
if errorcode==errno.ECONNREFUSED:
pass
#print errorcode, "Connection refused"
elif errorcode==errno.EISCONN:
print errorcode, "Transport endpoint is already connected"
self.sock.close()
else:
print e
self.sock.close()
self.connected = False
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def utc_ts(self):
return str(dt.datetime.utcnow()) + " UTC | "
|
def calc_mdl(yx_dist, y_dist):
prior = multinomLog2(y_dist.values())
prior += multinomLog2([len(y_dist.keys()) - 1, sum(y_dist.values())])
post = 0
for x_val in yx_dist:
post += multinomLog2([x_val.get(c, 0) for c in y_dist.keys()])
post += multinomLog2([len(y_dist.keys()) - 1, sum(x_val.values())])
return (prior - post) / float(sum(y_dist.values())) |
As the IRS Threatens to Shut Down Medical Cannabis, a New Campaign Fights Back The 280E Reform effort plans to bring an end to the current IRS campaign to close medical cannabis dispensaries.
OAKLAND, CA — As the IRS threatens to turn back the clock on medical cannabis, a national alliance of industry leaders, patients and elected officials are fighting back with a new project aimed at education and policy change. The 280E Reform effort plans to bring an end to the current IRS campaign to close medical cannabis dispensaries.
The IRS campaign of aggressive audits was launched about 2 years ago, using section 280E of the IRS code to deny dispensaries the ability to deduct legitimate business expenses. Denied expenses include items such as rent, payroll, and all other necessary business expenses.
These denials result in astronomical back tax bills for the affected dispensaries that, if not changed, threaten to destroy the financial viability of every medical cannabis dispensary in the country—thereby ending safe and affordable access to cannabis for legally qualified patients.
Article continues after ad Advertisement
Section 280E was passed by Congress in 1982, long before the passage of medical cannabis laws and was intended to apply to traffickers of dangerous drugs. Last year, Congressman Pete Stark (D-CA) introduced the Small Business Tax Equity Act (H.R. 1985), which would create an exception to 280E for legal medical marijuana businesses, allowing them to take the full range of business expense deductions on their federal tax returns.
With fear looming that these audits will eventually shut down all legally operating medical cannabis businesses that have been operating according to their state laws—and some paying taxes for years—time is of the essence.
Campaign spokesperson Steve DeAngelo outlined the consequences: “Should the IRS campaign be successful, it will throw millions of patients back in to the hands of street dealers, eliminate tens of thousands of well-paying jobs, destroy hundreds of millions of dollars of tax revenue, enrich the criminal underground, and endanger the safety of communities in the 17 medical cannabis states.”
In response to these dangers, the 280E Reform project is announcing a nationwide campaign to bring awareness to legislators, provide legal and tax counsel for threatened organizations and prepare a grassroots educational effort to enlighten the public on the need to reform 280E.
Article continues after ad Advertisement
“We are going to challenge this tax code to make sure that patients all over America have the ability to safely fill their health care needs with safe access from medical cannabis providers who are operating clearly with state laws,” said lead tax attorney Henry Wykowski. “This is a public safety issue and a healthcare right.”
An impressive team has been assembled to lead this effort, including Don Duncan, co-founder of American for Safe Access (ASA) and medical cannabis supporter who has been featured on 60 minutes, Dan Rather Reports and the LA Times; Henry Wykowski, legal tax counsel who successfully defended CHAMP in a similar IRS audit; Troy Dayton, co-founder of Students for Sensible Drug Policy (SSDP), former Senior Development Officer of the Marijuana Policy Project (MPP) and current CEO of ArcView Group; Amir Daliri, entrepreneur and co-founder of California Cannabis Association and President of CannLobby, LLC, a medical cannabis focused political consultancy; and Steve DeAngelo, Executive Director of Harborside Health Center and activist, whose accomplishments include the passage of Proposition 59, the Washington D.C. medical cannabis initiative.
A graduate of the University of Maryland (summa cum laude), DeAngelo is a charter member of Americans for Safe Access and co-creator of Hemp Tour and Ecolution Inc., which produced hemp garments and accessories. He is the star of the new Discovery Channel series “Weed Wars.”
Workshops announced: The IRS is Coming! Are you Ready? IRS Tax Audit Seminars to aid medical cannabis businesses ‘How to Get Ready?’ will take place on February 25th from 1 to 6 pm at the Main Ballroom of Just Dance, which is located at 2500 Embarcadero in Oakland.
The same workshop will also be held on March 10th from 1 to 6 pm at the Courtyard Marriott, located at 925 Westlake Ave. N in Seattle. Enroll online: http://www.280Ereform.org or (206) 466-1766. |
#include<stdio.h>
int main()
{
int a,d=0,m=0,i;
scanf("%d",&a);
double b[a];
int c[a];
for(i=0;i<a;i++)
{
scanf("%lf",&b[i]);
c[i]=b[i];
d=d+c[i];
}
/* for(i=0;i<a;i++)
{
printf("%d\n",c[i]);
}**/
// printf("d=%d\n",d);
i=0;
if(d>0)
{
for(i=0;i<a;i++)
{
if(b[i]<0){
if(c[i]==b[i])
{
continue;
}
c[i]--;
d--;
if(d==0)
{
break;
}
}
}
}
else if(d<0)
{
for(i=0;i<a;i++)
{
if(b[i]>0){
if(c[i]==b[i])
{
continue;
}
c[i]++;
d++;
if(d==0)
{
break;
}
}
}
}
for(i=0;i<a;i++)
{
printf("%d\n",c[i]);
}
}
|
#!/usr/local/bin/python
# encoding: utf-8
"""
*Send documents or webpage articles to a kindle device or app*
:Author:
<NAME>
:Date Created:
October 10, 2016
"""
################# GLOBAL IMPORTS ####################
import sys
import os
os.environ['TERM'] = 'vt100'
from fundamentals import tools
from .ebook import ebook
import shutil
import getpass
import optparse
import os
import smtplib
import sys
import traceback
from StringIO import StringIO
from email import encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.generator import Generator
class kindle(ebook):
"""
*Send documents or webpage articles to a kindle device or app*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``urlOrPath`` -- the url or path to the content source
- ``title`` -- the title of the output document. I. False then use the title of the original source. Default *False*
- ``header`` -- content to add before the article/book content in the resulting ebook. Default *False*
- ``footer`` -- content to add at the end of the article/book content in the resulting ebook. Default *False*
**Usage:**
To send content from a webpage article straight to your kindle device or smart phone app, you will first need to populate the email settings with polyglot's settings file at ``~.config/polyglot/polyglot.yaml``, then use the following code:
.. code-block:: python
from polyglot import kindle
sender = kindle(
log=log,
settings=settings,
urlOrPath="http://www.thespacedoctor.co.uk/blog/2016/09/26/mysqlSucker-index.html",
header='<a href="http://www.thespacedoctor.co.uk">thespacedoctor</a>',
footer='<a href="http://www.thespacedoctor.co.uk">thespacedoctor</a>'
)
success = sender.send()
Success is True or False depending on the success/failure of sending the email to the kindle email address(es).
"""
# Initialisation
def __init__(
self,
log,
settings,
urlOrPath,
title=False,
header=False,
footer=False
):
self.log = log
log.debug("instansiating a new 'ebook' object")
self.settings = settings
self.title = title
self.header = header
self.footer = footer
self.urlOrPath = urlOrPath
self.outputDirectory = "/tmp"
self.format = "mobi"
# Initial Actions
return None
def send(
self):
"""*send the mobi book generated to kindle email address(es)*
**Return:**
- ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es).
"""
self.log.debug('starting the ``send`` method')
if self.urlOrPath.split(".")[-1] == "docx":
if self.title:
pathToMobi = self.outputDirectory + "/" + self.title + ".docx"
else:
pathToMobi = self.outputDirectory + "/" + \
os.path.basename(self.urlOrPath)
shutil.copyfile(self.urlOrPath, pathToMobi)
else:
pathToMobi = self.get()
if not pathToMobi:
return 404
# create MIME message
msg = MIMEMultipart()
msg['From'] = self.settings["email"]["user_email"]
msg['To'] = ", ".join(self.settings["email"]["kindle_emails"])
msg['Subject'] = 'Polyglot to Kindle'
text = 'This email has been automatically sent by polyglot'
msg.attach(MIMEText(text))
basename = os.path.basename(pathToMobi)
print "Sending the book `%(pathToMobi)s` to Kindle device(s)" % locals()
msg.attach(self.get_attachment(pathToMobi))
# convert MIME message to string
fp = StringIO()
gen = Generator(fp, mangle_from_=False)
gen.flatten(msg)
msg = fp.getvalue()
# send email
try:
mail_server = smtplib.SMTP_SSL(host=self.settings["email"]["smtp_server"],
port=self.settings["email"]["smtp_port"])
mail_server.login(self.settings["email"]["smtp_login"], self.settings[
"email"]["smtp_password"])
mail_server.sendmail(self.settings["email"]["user_email"], ", ".join(self.settings[
"email"]["kindle_emails"]), msg)
mail_server.close()
except smtplib.SMTPException:
os.remove(pathToMobi)
self.log.error(
'Communication with your SMTP server failed. Maybe wrong connection details? Check exception details and your headjack settings file')
return False
os.remove(pathToMobi)
self.log.debug('completed the ``send`` method')
return True
def get_attachment(self, file_path):
'''Get file as MIMEBase message'''
try:
file_ = open(file_path, 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(file_.read())
file_.close()
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(file_path))
return attachment
except IOError:
traceback.print_exc()
message = ('The requested file could not be read. Maybe wrong '
'permissions?')
print >> sys.stderr, message
sys.exit(6)
# xt-class-method
|
<reponame>Blackbaud-ColbyWhite/skyux-flyout<filename>src/app/visual/flyout/flyout-modal.component.ts
import {
Component
} from '@angular/core';
import {
SkyModalInstance
} from '@skyux/modals';
@Component({
selector: 'sky-flyout-modal-demo',
template: `
<sky-modal>
<sky-modal-content>
Modal content...
</sky-modal-content>
<sky-modal-footer>
<button
class="sky-btn sky-btn-primary"
type="button"
(click)="close()"
>
Close
</button>
</sky-modal-footer>
</sky-modal>
`
})
export class SkyFlyoutModalDemoComponent {
constructor(
private instance: SkyModalInstance
) { }
public close(): void {
this.instance.close();
}
}
|
// Tries to repeatedly pause the game until it succeeds
void GeckoSafePauseCmd()
{
bool WasRunning = (GeckoStatus() == WiiStatusRunning);
while (WasRunning)
{
GeckoPauseCmd();
usleep(100000);
WasRunning = (GeckoStatus() == WiiStatusRunning);
}
} |
'To Pimp A Butterfly' Aspires To Be Music's Great American Novel
Enlarge this image toggle caption Christian San Jose/Courtesy of the artist Christian San Jose/Courtesy of the artist
When Kendrick Lamar released his major label debut in 2012, he vaulted onto pop's leaderboard as one of the best rappers of his generation. He wasn't just a skilled lyricist, but a vivid storyteller able to create scenes with vivid detail and intrigue.
Lamar took nearly two and half years to make his new record, an eternity in pop time. But once To Pimp a Butterfly arrived on Sunday night — nine days ahead of the announced release date — it's easy to see where he put all that time. He doesn't just live up to outsized expectations, he upends them with an ambitious effort to craft the musical equivalent to the Great American Novel.
Listen On Spotify
Like Lamar's native Los Angeles, To Pimp a Butterfly feels both dense and sprawling with its panoply of ideas, styles and sounds. Backing the rapper is a young cohort of L.A.'s best beat makers and musicians, including Digi+Phonics, Terrace Martin and Thundercat. Their collaboration creates songs-within-songs that hold multitudes, from updated P-Funk romps ("King Kunta") to coffee-shop poetry slams ("For Free?") to tete-a-tetes with ghosts ("Mortal Man").
To Pimp a Butterfly doesn't remind me of other contemporary hip-hop albums so much as the musicals of Melvin Van Peebles. Both that playwright and this rapper invite us into noisy conversations between eclectic characters debating personal triumphs and social failures, black love and white hate, all under the looming shadow of America.
It's telling that two of the album's songs are simply titled "u" and "i," but don't confuse that for a universal "we." Lamar wades into our moment of peril around race, inequality and brutality, but he's not speaking to the rest of the nation as much as penning both an admonishment of, and love letter to, Black America. That's the "we" he sets himself both above and below, and yet always within. |
import { Request, Response } from 'express';
import { UNPROCESSABLE_ENTITY, INTERNAL_SERVER_ERROR, NOT_FOUND } from 'http-status-codes';
import logger from '../util/logger';
import { NotFoundError } from '../errors';
import { ValidationError } from '../errors';
/**
* Middlware for handling validation errors from controllers
*/
export const validationErrorMiddleware = (error: Error, req: Request, res: Response, next: any) => {
if (error instanceof ValidationError) {
const url = req.url;
const method = req.method;
const validationErrors = error.getValidationErrors();
logger.error(`Request to ${method} ${url} VALIDATION ERROR`, { message: error.message, errors: validationErrors});
const failedResponse = {
status: false,
message: error.message,
};
res.status(UNPROCESSABLE_ENTITY);
return res.json({
...failedResponse,
data: { 'errors': validationErrors }
});
}
next(error);
};
/**
* Middlware for handling 404 errors from controllers
*/
export const notFoundErrorMiddleware = (error: Error, req: Request, res: Response, next: any) => {
if (error instanceof NotFoundError) {
const url = req.url;
const method = req.method;
logger.error(`Request to ${method} ${url} NOT FOUND`, { message: error.message });
const failedResponse = {
status: false,
message: error.message,
};
res.status(NOT_FOUND);
return res.json(failedResponse);
}
next(error);
};
/**
* Middlware for handling general errors from controllers
*/
export const generalErrorMiddleware = (error: Error, req: Request, res: Response, next: any) => {
const url = req.url;
const method = req.method;
logger.error(`Request to ${method} ${url} FAILED`, { error: error.message });
res.status(INTERNAL_SERVER_ERROR);
return res.json({
status: false,
message: error.message,
});
};
|
Addressing the Machine: Victorian Working-Class Poetry and Industrial Machinery
This article explores the representation of machinery by industrial workers in the Victorian period, and argues that their writings have a qualitatively different literary approach to machinery than that found in the work of established Victorian authors. It uses little-known poems by Scottish and Northern working-class writers to investigate how they use language and form to reflect upon the place of machinery in their working lives. |
/**
* Created by IntelliJ IDEA.
* User: astoev
* Date: 2/12/12
* Time: 11:37 AM
*
* @author astoev
* @author jmitrev
*/
public class InfoActivity extends MainMenuActivity {
public static final String MIME_OPEN_DIRECTORY = "vnd.android.document/directory";
@Override
protected boolean showBaseOptionsMenu() {
return false;
}
public static final String MIME_RESOURCE_FOLDER = "resource/folder";
public static final String MIME_RESOURCE_FILE = "file/*";
public static final String MIME_TYPE_ANY = "*/*";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
if (findViewById(R.id.projectInfoContainer) != null){
if (savedInstanceState == null){
ProjectConfig projectConfig = DaoUtil.getProjectConfig();
ProjectFragment projectFragment = ProjectFragment.newInstance(projectConfig);
getSupportFragmentManager().beginTransaction().add(R.id.projectInfoContainer, projectFragment).commit();
}
}
}
@Override
protected void onResume() {
super.onResume();
try {
ProjectInfo projectInfo = DaoUtil.getProjectInfo();
TextView projectCreated = findViewById(R.id.infoProjectCreated);
projectCreated.setText(projectInfo.getCreationDate());
TextView projectNumGalleries = findViewById(R.id.infoNumGalleries);
projectNumGalleries.setText(String.valueOf(projectInfo.getGalleries()));
TextView projectNumLegs = findViewById(R.id.infoNumLegs);
projectNumLegs.setText(String.valueOf(projectInfo.getLegs()));
TextView projectTotalLength = findViewById(R.id.infoRawDistance);
String lengthLabel = StringUtils.floatToLabel(projectInfo.getLength()) + " " + Options.getOptionValue(Option.CODE_DISTANCE_UNITS);
projectTotalLength.setText(lengthLabel);
TextView projectNumNotes = findViewById(R.id.infoNumNotes);
projectNumNotes.setText(StringUtils.intToLabel(projectInfo.getNotes()));
TextView projectNumDrawings = findViewById(R.id.infoNumDrawings);
projectNumDrawings.setText(StringUtils.intToLabel(projectInfo.getSketches()));
TextView projectNumCoordinates = findViewById(R.id.infoNumCoordinates);
projectNumCoordinates.setText(StringUtils.intToLabel(projectInfo.getLocations()));
TextView projectNumPhotos = findViewById(R.id.infoNumPhotos);
projectNumPhotos.setText(StringUtils.intToLabel(projectInfo.getPhotos()));
TextView projectNumVectors = findViewById(R.id.infoNumVectors);
projectNumVectors.setText(StringUtils.intToLabel(projectInfo.getVectors()));
// set the value for azimuth build in processor
if (Option.CODE_SENSOR_INTERNAL.equals(Options.getOption(Option.CODE_AZIMUTH_SENSOR).getValue())) {
TextView azimuthSensor = findViewById(R.id.info_azimuth_sensor);
OrientationProcessor orientationProcessor = OrientationProcessorFactory.getOrientationProcessor(this, null);
if (orientationProcessor.canReadOrientation()) {
if (orientationProcessor instanceof RotationOrientationProcessor) {
azimuthSensor.setText(getString(R.string.rotation_sensor));
} else if (orientationProcessor instanceof MagneticOrientationProcessor) {
azimuthSensor.setText(getString(R.string.magnetic_sensor));
} else if (orientationProcessor instanceof OrientationDeprecatedProcessor) {
azimuthSensor.setText(getString(R.string.orientation_sensor));
}
}
}
TextView projectHome = findViewById(R.id.info_project_home);
String projectHomeFolder = FileStorageUtil.getProjectHome(projectInfo.getName()).getAbsolutePath();
projectHome.setText(projectHomeFolder);
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to render info activity", e);
UIUtilities.showNotification(R.string.error);
}
}
private void exportProjectXls() {
try {
Log.i(Constants.LOG_TAG_SERVICE, "Start excel export");
// export legs
ExcelExport export = new ExcelExport(this);
String exportPath = export.runExport(getWorkspace().getActiveProject());
if (StringUtils.isEmpty(exportPath)) {
UIUtilities.showNotification(this, R.string.export_io_error, exportPath);
} else {
UIUtilities.showNotification(this, R.string.export_done, exportPath);
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to export project", e);
UIUtilities.showNotification(R.string.error);
}
}
private void exportProjectVTopo() {
try {
Log.i(Constants.LOG_TAG_SERVICE, "Start vtopo_logo export");
// export legs
VisualTopoExport export = new VisualTopoExport(this);
String exportPath = export.runExport(getWorkspace().getActiveProject());
if (StringUtils.isEmpty(exportPath)) {
UIUtilities.showNotification(this, R.string.export_io_error, exportPath);
} else {
UIUtilities.showNotification(this, R.string.export_done, exportPath);
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to export project", e);
UIUtilities.showNotification(R.string.error);
}
}
/**
* Handles click on Files button. Tries to find an activity to show project's folder by sending
* ACTION_VIEW intent. Sequentially tries to find a compatible activity. First looks for activity to just
* handle a file path. Second tries to for mime-type "resource/folder" and finally executes a search for
* mime-type "*.*" and leaves the user to select a matching application.
*/
private void onViewFiles() {
String projectName = getWorkspace().getActiveProject().getName();
Log.i(Constants.LOG_TAG_SERVICE, "View files selected for project:" + projectName);
File projectHome = FileStorageUtil.getProjectHome(projectName);
if (projectHome != null) {
Uri contentUri = FileUtils.getFileUri(projectHome);
Log.i(Constants.LOG_TAG_SERVICE, "Uri:" + contentUri);
String chooserTitle = getResources().getString(R.string.info_chooser_open_folder);
Intent intent = new Intent(Intent.ACTION_VIEW);
PackageManager packageManager = getPackageManager();
// Works with ES file manager
intent.setDataAndType(contentUri, MIME_RESOURCE_FOLDER);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(packageManager) != null) {
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW with resource/folder resolved");
startActivity(Intent.createChooser(intent, chooserTitle));
return;
}
// works with OI File manager
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(contentUri);
if (intent.resolveActivity(packageManager) != null) {
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW resolved");
startActivity(Intent.createChooser(intent, chooserTitle));
return;
}
// another test
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(contentUri);
intent.putExtra("org.openintents.extra.ABSOLUTE_PATH", projectHome.getPath());
if (intent.resolveActivity(packageManager) != null) {
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW with extra resolved");
startActivity(Intent.createChooser(intent, chooserTitle));
return;
}
// generic folder
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, MIME_RESOURCE_FOLDER);
if (intent.resolveActivity(packageManager) != null) {
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW with folder resolved");
startActivity(Intent.createChooser(intent, chooserTitle));
return;
}
// open intent
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, MIME_OPEN_DIRECTORY);
if (intent.resolveActivity(packageManager) != null) {
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW with directory resolved");
startActivity(Intent.createChooser(intent, chooserTitle));
return;
}
// brute force to choose a file manager
intent = new Intent(Intent.ACTION_VIEW);
Log.i(Constants.LOG_TAG_SERVICE, "ACTION_VIEW with */* resolved");
intent.setDataAndType(contentUri, MIME_TYPE_ANY);
startActivity(Intent.createChooser(intent, chooserTitle));
} else {
Log.e(Constants.LOG_TAG_SERVICE, "No project folder for project:" + projectName);
UIUtilities.showNotification(R.string.io_error);
}
}//end of onViewFiles
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#getChildsOptionsMenu()
*/
@Override
protected int getChildsOptionsMenu() {
return R.menu.infomenu;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean flag = super.onCreateOptionsMenu(menu);
// disable openstopo for older devices that will not render the data properly
// and HONEYCOMB for the content access property ...
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
MenuItem opensTopoItem = menu.findItem(R.id.info_action_openstopo);
if (opensTopoItem != null) {
opensTopoItem.setVisible(true);
}
// }
return flag;
}
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(Constants.LOG_TAG_UI, "Info activity's menu selected - " + item.toString());
switch (item.getItemId()) {
case R.id.info_action_export_xls: {
exportProjectXls();
return true;
}
case R.id.info_action_export_vtopo: {
exportProjectVTopo();
return true;
}
case R.id.info_action_openstopo: {
try {
// export
Log.i(Constants.LOG_TAG_SERVICE, "Start json export");
OpensTopoJsonExport export = new OpensTopoJsonExport(this);
String exportPath = export.runExport(getWorkspace().getActiveProject());
if (StringUtils.isEmpty(exportPath)) {
UIUtilities.showNotification(this, R.string.export_io_error, exportPath);
} else {
// load ui
Log.i(Constants.LOG_TAG_SERVICE, "exported to " + exportPath);
Intent intent = new Intent(InfoActivity.this, WebViewActivity.class);
intent.putExtra("path", exportPath);
intent.putExtra("projectName", getWorkspace().getActiveProject().getName());
startActivity(intent);
}
return true;
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to export project", e);
UIUtilities.showNotification(R.string.error);
}
}
case R.id.info_action_view_files: {
onViewFiles();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Button action method to update a project configuration
*
* @param viewArg - view
*/
public void update(View viewArg){
Log.v(Constants.LOG_TAG_UI, "Updating project");
ProjectFragment projectFragment = (ProjectFragment)getSupportFragmentManager().findFragmentById(R.id.projectInfoContainer);
final ProjectConfig projectConfig = projectFragment.getProjectConfig();
// project name is not editable for the moment, so not checking for empty string
// EditText projectNameField = (EditText) findViewById(R.id.new_projectname);
// final String newProjectName = projectNameField.getText().toString();
// if (newProjectName.trim().equals("")) {
// projectNameField.setError(getString(R.string.project_name_required));
// return;
// }
try {
ProjectManager.instance().updateProject(projectConfig);
finish();
UIUtilities.showNotification(R.string.message_project_udpated);
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to update project", e);
UIUtilities.showNotification(R.string.error);
}
}
@Override
protected String getScreenTitle() {
// set the name of the chosen project as title in the action bar
Project activeProject = getWorkspace().getActiveProject();
if (activeProject != null){
return activeProject.getName();
}
return null;
}
} |
Electrical and Structural Properties of CuBa2LaCa2Cu4O11+δ Superconducting System
In this work, the superconducting CuBa2LaCa2Cu4O11+δ compound was prepared by citrate precursor method and the electrical and structural properties were studied. The electrical resistivity has been measured using four probe test to find the critical temperature Tc(offset) and Tc(onset). It was found that Tc (offset) at zero resistivity has 101 K and Tc (onset) has 116 K. The X-ray diffraction (XRD) analysis exhibited that a prepared compound has a tetragonal structure. The crystal size and microscopic strain due to lattice deformation of CuBa2LaCa2Cu4O11+δ were estimated by four methods, namely Scherer(S), Halder-Wagner(H-W), size-strain plot (SSP) and Williamson-Hall, (W-H) methods. Results of crystal sizes obtained by these methods were compared with each other. In all these methods, the values of βhkl (full-width half-maximum (FWHM) for diffraction peaks) and miler indices (hkl) are determined from the results obtained from Fullprof, Mach, Origin and VESTA software. The lattice parameters a, b and c, lattice shape, d and degree of crystallization were calculated. It was found that the crystal size which are calculating by S, W-H, SSP and H-W were (174.8472, 171.1776, 173.1009 and 175.4386) A0 respectively while the lattice strain values were (none, 0.0025, 0.004 and 0.003464), respectively. |
<gh_stars>1-10
import { Block, TextField } from '@stage-ui/core'
import { useEffect, useState } from 'react'
import { context } from '../../../..'
import React from 'react'
let timer: NodeJS.Timeout | null = null
const TextControls = () => {
if (!context.tools.focused) {
return null
}
const [value, setValue] = useState('')
useEffect(() => {
if (context.tools.focused) {
setValue(context.tools.focused.text || '')
}
}, [context.tools.focused?.id])
const handleChange = (value: string) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
if (context.tools.focused) {
context.tools.focused.text = value
if (!value) {
delete context.tools.focused.text
}
context.tools.update()
}
}, 100)
}
return (
<Block pb="0.5rem">
<TextField
w="100%"
size="s"
label="Text"
multiline
value={value}
onChange={e => {
setValue(e.target.value)
handleChange(e.target.value)
}}
/>
</Block>
)
}
export default TextControls |
<reponame>gigaclood/phoenix
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
/**
* Static class for various methods that would be nice to have added to {@link org.apache.hadoop.hbase.client.Result}.
* These methods work off of the raw bytes preventing the explosion of Result into object form.
*
*
* @since 0.1
*/
public class ResultUtil {
public static final Result EMPTY_RESULT = new Result() {
@Override
public final boolean isEmpty() { return true; }
};
private ResultUtil() {
}
public static Result toResult(ImmutableBytesWritable bytes) {
byte [] buf = bytes.get();
int offset = bytes.getOffset();
int finalOffset = bytes.getSize() + offset;
List<Cell> kvs = new ArrayList<Cell>();
while(offset < finalOffset) {
int keyLength = Bytes.toInt(buf, offset);
offset += Bytes.SIZEOF_INT;
kvs.add(new KeyValue(buf, offset, keyLength));
offset += keyLength;
}
return Result.create(kvs);
}
/**
* Return a pointer into a potentially much bigger byte buffer that points to the key of a Result.
* @param r
*/
public static ImmutableBytesWritable getKey(Result r) {
return getKey(r, 0);
}
public static void getKey(Result r, ImmutableBytesWritable key) {
key.set(r.getRow());
//key.set(getRawBytes(r), getKeyOffset(r), getKeyLength(r));
}
@SuppressWarnings("deprecation")
public static void getKey(KeyValue value, ImmutableBytesWritable key) {
key.set(value.getBuffer(), value.getRowOffset(), value.getRowLength());
}
/**
* Return a pointer into a potentially much bigger byte buffer that points to the key of a Result.
* Use offset to return a subset of the key bytes, for example to skip the organization ID embedded
* in all of our keys.
* @param r
* @param offset offset added to start of key and subtracted from key length (to select subset of key bytes)
*/
public static ImmutableBytesWritable getKey(Result r, int offset) {
return new ImmutableBytesWritable(getRawBytes(r), getKeyOffset(r) + offset, getKeyLength(r) - offset);
}
public static void getKey(Result r, int offset, int length, ImmutableBytesWritable key) {
key.set(getRawBytes(r), getKeyOffset(r) + offset, length);
}
/**
* Comparator for comparing the keys from two Results in-place, without allocating new byte arrays
*/
public static final Comparator<Result> KEY_COMPARATOR = new Comparator<Result>() {
@Override
public int compare(Result r1, Result r2) {
byte[] r1Bytes = getRawBytes(r1);
byte[] r2Bytes = getRawBytes(r2);
return Bytes.compareTo(r1Bytes, getKeyOffset(r1), getKeyLength(r1), r2Bytes, getKeyOffset(r2), getKeyLength(r2));
}
};
/**
* Get the offset into the Result byte array to the key.
* @param r
*/
static int getKeyOffset(Result r) {
KeyValue firstKV = org.apache.hadoop.hbase.KeyValueUtil.ensureKeyValue(r.rawCells()[0]);
return firstKV.getOffset();
}
static int getKeyLength(Result r) {
// Key length stored right before key as a short
return Bytes.toShort(getRawBytes(r), getKeyOffset(r) - Bytes.SIZEOF_SHORT);
}
@SuppressWarnings("deprecation")
static byte[] getRawBytes(Result r) {
KeyValue firstKV = org.apache.hadoop.hbase.KeyValueUtil.ensureKeyValue(r.rawCells()[0]);
return firstKV.getBuffer();
}
public static int compareKeys(Result r1, Result r2) {
return Bytes.compareTo(getRawBytes(r1), getKeyOffset(r1), getKeyLength(r1), getRawBytes(r2), getKeyOffset(r2), getKeyLength(r2));
}
/**
* Binary search for latest column value without allocating memory in the process
*/
public static KeyValue getColumnLatest(Result r, byte[] family, byte[] qualifier) {
byte[] rbytes = getRawBytes(r);
int roffset = getKeyOffset(r);
int rlength = getKeyLength(r);
return getColumnLatest(r, rbytes, roffset, rlength, family, 0, family.length, qualifier, 0, qualifier.length);
}
public static KeyValue getSearchTerm(Result r, byte[] family, byte[] qualifier) {
byte[] rbytes = getRawBytes(r);
int roffset = getKeyOffset(r);
int rlength = getKeyLength(r);
return KeyValue.createFirstOnRow(rbytes, roffset, rlength, family, 0, family.length, qualifier, 0, qualifier.length);
}
/**
* Binary search for latest column value without allocating memory in the process
*/
public static KeyValue getColumnLatest(Result r, byte[] row, int roffset, int rlength, byte[] family, int foffset, int flength, byte[] qualifier, int qoffset, int qlength) {
KeyValue searchTerm = KeyValue.createFirstOnRow(row, roffset, rlength, family, foffset, flength, qualifier, qoffset, qlength);
return getColumnLatest(r,searchTerm);
}
/**
* Binary search for latest column value without allocating memory in the process
* @param r
* @param searchTerm
*/
@SuppressWarnings("deprecation")
public static KeyValue getColumnLatest(Result r, KeyValue searchTerm) {
KeyValue [] kvs = r.raw(); // side effect possibly.
if (kvs == null || kvs.length == 0) {
return null;
}
// pos === ( -(insertion point) - 1)
int pos = Arrays.binarySearch(kvs, searchTerm, KeyValue.COMPARATOR);
// never will exact match
if (pos < 0) {
pos = (pos+1) * -1;
// pos is now insertion point
}
if (pos == kvs.length) {
return null; // doesn't exist
}
KeyValue kv = kvs[pos];
if (Bytes.compareTo(kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
searchTerm.getBuffer(), searchTerm.getFamilyOffset(), searchTerm.getFamilyLength()) != 0) {
return null;
}
if (Bytes.compareTo(kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength(),
searchTerm.getBuffer(), searchTerm.getQualifierOffset(), searchTerm.getQualifierLength()) != 0) {
return null;
}
return kv;
}
}
|
// NewPhysicalHashJoin creates a new PhysicalHashJoin from LogicalJoin.
func NewPhysicalHashJoin(p *LogicalJoin, innerIdx int, useOuterToBuild bool, newStats *property.StatsInfo, prop ...*property.PhysicalProperty) *PhysicalHashJoin {
leftJoinKeys, rightJoinKeys, isNullEQ, _ := p.GetJoinKeys()
baseJoin := basePhysicalJoin{
LeftConditions: p.LeftConditions,
RightConditions: p.RightConditions,
OtherConditions: p.OtherConditions,
LeftJoinKeys: leftJoinKeys,
RightJoinKeys: rightJoinKeys,
IsNullEQ: isNullEQ,
JoinType: p.JoinType,
DefaultValues: p.DefaultValues,
InnerChildIdx: innerIdx,
}
hashJoin := PhysicalHashJoin{
basePhysicalJoin: baseJoin,
EqualConditions: p.EqualConditions,
Concurrency: uint(p.ctx.GetStochastikVars().HashJoinConcurrency()),
UseOuterToBuild: useOuterToBuild,
}.Init(p.ctx, newStats, p.blockOffset, prop...)
return hashJoin
} |
/**
* Test of getAllPaymentsByAccount method, of class ExpenseManagerImpl.
*/
@Test
public void testGetAllPaymentsByAccount_Long() {
System.out.println("getAllPaymentsByAccount");
Long accountId1 = new Long(5);
Long accountId2 = new Long(4);
Long subjectId = new Long(6);
Long categoryId = new Long(7);
BigDecimal price1 = new BigDecimal(130.00);
Payment payment1 = newPayment("Running shoes Nike",date("2015-05-20"),price1,accountId1,subjectId,categoryId);
paymentManager.createPayment(payment1);
BigDecimal price2 = new BigDecimal(100.00);
Payment payment2 = newPayment("Running shoes Adidas",date("2015-05-21"),price2,accountId1,subjectId,categoryId);
paymentManager.createPayment(payment2);
BigDecimal price3 = new BigDecimal(1000.00);
Payment payment3 = newPayment("Running shoes Puma",date("2015-05-14"),price3,accountId2,subjectId,categoryId);
paymentManager.createPayment(payment3);
List<Payment> expResult = new ArrayList<>();
expResult.add(payment1);
expResult.add(payment2);
List<Payment> result = expenseManager.getAllPaymentsByAccount(accountId1);
assertEquals(expResult.size(), result.size());
assertDeepEquals(expResult, result);
paymentManager.deletePayment(payment1.getId());
paymentManager.deletePayment(payment2.getId());
paymentManager.deletePayment(payment3.getId());
} |
<reponame>iqoption/yabs<gh_stars>1-10
package format
import (
"io/ioutil"
"encoding/json"
"strconv"
"yabs/common/utils"
log "github.com/sirupsen/logrus"
)
type GPUInfo struct {
Vendor string `json:"vendor"`
Renderer string `json:"renderer"`
}
type Info struct {
Version string `json:"version"`
Browser string `json:"browser"`
Gpu GPUInfo `json:"gpu"`
Platform string `json:"platform"`
Cpu string `json:"cpu"`
Ram string `json:"ram"`
UserId string `json:"userid"`
}
func InfoFromFile(path string) (info *Info, err error) {
file, err := ioutil.ReadFile(path)
if err != nil {
log.WithError(err).Error("Can't read info file")
return nil, err
}
var i Info
err = json.Unmarshal(file, &i)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"data": string(file),
}).Error("Can't parse info file")
return nil, err
}
i.Version = utils.Trim(i.Version)
return &i, nil
}
func (i *Info) GetUserId() uint64 {
var userId uint64 = 0
if (len(i.UserId) != 0) && (i.UserId != "-1") {
var err error = nil
userId, err = strconv.ParseUint(i.UserId, 10, 64)
if err != nil {
log.WithError(err).Error("Can't convert user id to uint64")
}
}
return userId
}
|
// ConvertAddr converts legacy public key to XWC address
func ConvertAddr(buf []byte) (addr string) {
sum := sha512.Sum512(buf)
addrBuf := hash.Rmd160(sum[:])
addrBuf = append([]byte{0x35}, addrBuf...)
checksum := hash.Rmd160(addrBuf)[:4]
addrBuf = append(addrBuf, checksum...)
addr = "XWC" + base58.Encode(addrBuf)
return
} |
LOS ANGELES (Reuters) - A man arrested on Thursday for defacing Republican presidential nominee Donald Trump’s star on the Hollywood Walk of Fame in Los Angeles with a sledgehammer and a pickax said he did it because he was angry at the candidate.
James Otis, the man who admits vandalizing Donald Trump's star on the Hollywood Walk of Fame, speaks to the media with his attorney Mieke ter Poorten about his arrest outside of the LAPD Metropolitan Detention Center in Los Angeles, California October 27, 2016. REUTERS/Patrick T. Fallon
James Otis, 52, speaking to reporters a short time after he was released from jail on $20,000 bail, also said he did it to show support for women who have accused Trump of groping them.
Otis was arrested for felony vandalism and is due in court on Nov. 18, authorities said.
His attack on Wednesday on the star, which Donald Trump received in 2007 for starring in the NBC show “The Apprentice,” made national headlines.
Otis was captured on video in a hard hat and reflective vest as he hacked at the star before dawn on a sidewalk in the Los Angeles neighborhood of Hollywood.
The stunt left Trump’s name scratched out of the star, the emblem in the middle dislodged and chips missing.
Trump drew widespread condemnations from voters and a number of Republican elected officials after a 2005 video emerged in which he was heard talking on an open microphone about groping women and trying to seduce a married woman.
Trump has denied the allegations made by several women that he groped them.
Otis, in his news conference, said he is taking responsibility for hacking at Trump’s star and he criticized Trump for what he described as dodging his responsibility.
“He’s a serial liar and misogynist and that’s why we’re here: to try to address that and help those women who told Mr. Trump they won’t stand for it anymore,” Otis said.
Otis said that he has been arrested multiple times over the years for civil disobedience.
Trump, a real estate developer and former reality TV star, has faced several large protests during his campaign appearances in California, where opinion polls show him far behind Democratic opponent Hillary Clinton.
A spokeswoman for Trump did not return emails seeking comment on Thursday.
Leron Gubler, president and chief executive of the Hollywood Chamber of Commerce, which administers the hundreds of star plaques on sidewalks in the Los Angeles neighborhood, has said the star would be covered for days during repairs. |
#ifndef TESTING_H
#define TESTING_H
#ifdef TESTING
#include <string>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64)
#include <crtdbg.h>
#endif
using std::string;
struct CrtCheckMemory
{
#if defined(_WIN32) || defined(_WIN64)
_CrtMemState state1;
_CrtMemState state2;
_CrtMemState state3;
#endif
CrtCheckMemory();
~CrtCheckMemory();
};
static int testCount = 0;
static int passedTests = 0;
int RunAllTests();
template<typename T>
void AssertEqual(T actual, T expected, string error){
testCount++;
if(actual == expected){
passedTests++;
}
else{
cerr << "Test Failed! Msg: " << error << endl;
}
}
void AssertTrue(bool check, string error);
void AssertApprox(float expected, float actual, string error, float maxDifference = 0.0001f);
double PerformanceTest(void (*func) (void), int count, string name);
static void BoxBoxPerformance();
static void BoxSpherePerformance();
static void SphereSpherePerformance();
static void MatrixMultPerformance();
static void SeparateAxisPerformance();
#endif
#endif |
def _GaeBuilderPackagePath(runtime):
return 'gcr.io/gae-runtimes/buildpacks/%s/builder:latest' % runtime |
import ExtendedClient from "../../src/Client/index";
import { GuildMember } from "discord.js";
class CheckRole {
idRolesWithPermission: string[];
guildMemberUser: GuildMember;
constructor(
private client: ExtendedClient,
guildMemberUser: GuildMember,
idRolesWithPermission?: string[]
) {
this.idRolesWithPermission = idRolesWithPermission;
this.guildMemberUser = guildMemberUser;
}
/**
* 🔰 - Verifica se o usuario tem, pelo menos uma, das roles informadas.
* @returns Verdadeiro quando encontra e, caso contrario, falso.
*/
CheckReturnBoolean(): boolean {
//Caso não sejá informado nem um ID, será impossivel usar esse metodo, retornando então, nulo.
if (!this.idRolesWithPermission)
throw "Não foi informado os ids dos cargos no cosntrutor da classe.";
const userRolesMap: string[] = this.guildMemberUser.roles.cache.map(
(roles) => roles.id
);
for (const keyPerm in this.idRolesWithPermission) {
for (const keyPermUser in userRolesMap) {
if (this.idRolesWithPermission[keyPerm] === userRolesMap[keyPermUser]) {
return true;
}
}
}
return false;
}
/**
* 🔰 - Verifica se o usuario tem, pelo menos uma, das roles informadas.
* @returns Os IDs das roles que o usuario possui.
*/
CheckReturnId(): string[] {
//Caso não sejá informado nem um ID, será impossivel usar esse metodo, retornando então, nulo.
if (!this.idRolesWithPermission)
throw "Não foi informado os ids dos cargos no cosntrutor da classe.";
const userRolesMap: string[] = this.guildMemberUser.roles.cache.map(
(roles) => roles.id
);
const newArrayList: string[] = [];
for (const keyPerm in this.idRolesWithPermission) {
for (const keyPermUser in userRolesMap) {
if (this.idRolesWithPermission[keyPerm] === userRolesMap[keyPermUser]) {
if (
this.idRolesWithPermission[keyPerm] !==
this.guildMemberUser.guild.id
) {
newArrayList.push(userRolesMap[keyPermUser]);
}
}
}
}
return newArrayList;
}
/**
* 🔰 - Verifica se o usuario tem, pelo menos uma, das roles de alto nivel.
* @returns Verdadeiro quando encontra e, caso contrario, falso.
*/
CheckHighRoleBool(): boolean {
this.idRolesWithPermission = [
"929426173673500673", //Role "Fei" > brioco
"929418031795408916", //Role "Adm" > brioco
"932132044727795712", //Role "Tio do RH" brioco
"929435905926791168", //Role "Mod" > brioco
"735147189432483920", //Role "Zé" > Peach Server
"716006513818468404", //Role "MACACOS" > Muquifo
"716008029396533349", //Role "FUNAI" > Muquifo
"731199687981400097", //Role "MOD" > Muquifo
];
return this.CheckReturnBoolean();
}
}
export default CheckRole;
|
<gh_stars>100-1000
package com.github.czyzby.lml.uedi.music;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.github.czyzby.kiwi.util.common.Exceptions;
/** Allows to stop the chosen {@link Music} instance in {@link Action}.
*
* @author MJ */
public class MusicStopAction extends Action {
private Music music;
@Override
public boolean act(final float delta) {
if (music != null) {
try {
music.stop();
} catch (final Exception exception) {
Exceptions.ignore(exception);
}
music = null;
}
return true;
}
@Override
public void reset() {
super.reset();
music = null;
}
/** @return will be stopped. Null if already stopped. */
public Music getMusic() {
return music;
}
/** @param music will be stopped. */
public void setMusic(final Music music) {
this.music = music;
}
/** @param music will be stopped.
* @return a {@link MusicStopAction} instance, which will stop the theme once executed. */
public static MusicStopAction stop(final Music music) {
final MusicStopAction action = Actions.action(MusicStopAction.class);
action.music = music;
return action;
}
}
|
def write_json(input_path, input_data):
with open(input_path, 'w') as outfile:
json.dump(input_data, outfile) |
<gh_stars>0
package ru.sbtqa.tag.pagefactory.transformer;
import cucumber.api.Transformer;
import ru.sbtqa.tag.pagefactory.transformer.enums.ClickVariation;
public class ClickVariationTransformer extends Transformer<ClickVariation> {
@Override
public ClickVariation transform(String value) {
return ClickVariation.fromString(value);
}
}
|
Pope Francis speaks during his general audience at St Peter's square on June 11, 2014 at the Vatican. AFP PHOTO / VINCENZO PINTO (Photo credit should read VINCENZO PINTO/AFP/Getty Images)
The global economic system is near collapse, according to Pope Francis.
An economy built on money-worship and war and scarred by yawning inequality and youth unemployment cannot survive, the 77-year-old Roman Catholic leader suggested in a newly published interview.
The pontiff said he was especially concerned about youth unemployment, which hit 13.1 percent last year, according to a report by the International Labor Organization.
"The rate of unemployment is very worrisome to me, which in some countries is over 50 percent," he said. "Someone told me that 75 million young Europeans under 25 years of age are unemployed. That is an atrocity."
That 75 million is actually the total for the whole world, according to the ILO, but that is still too much youth unemployment.
Pope Francis denounced the influence of war and the military on the global economy in particular:
“We discard a whole generation to maintain an economic system that no longer endures, a system that to survive has to make war, as the big empires have always done,” he said.
"But since we cannot wage the Third World War, we make regional wars," he added. "And what does that mean? That we make and sell arms. And with that the balance sheets of the idolatrous economies -- the big world economies that sacrifice man at the feet of the idol of money -- are obviously cleaned up."
Pope Francis is gaining a reputation for pointed comments on the global economy. In April, amid feverish media coverage of French economist Thomas Piketty's bombshell book on income inequality, he made clear his stance on the widening wealth gap with a tweet saying: "Inequality is the root of social evil."
Fittingly, the pope commemorated Thursday's kick-off game of the World Cup – a global tournament that has so far cost host nation Brazil at least $15 billion and sparked violent protest by the country’s disenfranchised poor – with this message to his 4.14 million Twitter followers: |
Chapter 22. Long-lived Spin Order in CH2D Groups
The ubiquitous nature of methyl groups makes the potential exploitation of methyl long-lived states particularly attractive. However, access to methyl group long-lived states is only provided by inefficient cross-relaxation processes that greatly reduce the available intensity of the resulting proton signal. Monodeuterated methyl groups provide a plausible alternative to pump long-lived states with high efficiency in this common moiety. In this chapter, the proton long-lived state in the monodeuterated group of a unique piperidine complex is presented, with the ratio of the singlet lifetime to the spin–lattice decay time found to be remarkably constant over a wide range of experimental conditions. These results demonstrate the advantages of accessing methyl long-lived states coherently without exploiting weak cross-relaxation phenomena. |
MSNBC's Rachel Maddow said Friday that deceased Fox News head Roger Ailes once offered to hire her "so no one else could put her on."
“He would just hire me so no one else could put me on,” Maddow told SiriusXM radio host Howard Stern. “I was like, ‘So, you’d pay me a full contract to not work?'”
“Would you consider that?” Stern asked.
“Who would not consider that?” an amused Maddow replied.
Despite their significant political differences, Ailes and Maddow became friends after meeting at a White House Christmas Party in 2009.
Ailes died last week at the age of 77 due to complications from a head injury sustained in a fall.
Ailes was fired from Fox last year in the face of multiple allegations of sexual harassment.
ADVERTISEMENT
The late media titan wrote a blurb in support of Maddow's 2012 non-fiction book, "Drift: The Unmooring of American Military Power."
“Drift never makes the case that war might be necessary," wrote Ailes. "America would be weakened dramatically if we had underreacted to 9/11."
"However, Rachel Maddow makes valid arguments that our country has been drifting towards questionable wars, draining our resources, without sufficient input and time," he continued. "People who like Rachel will love the book. People who don’t will get angry, but aggressive debate is good for America. Drift is a book worth reading.”
The top-rated MSNBC host told Stern about a time that she turned to Ailes for advice.
“He was really, really kind about it,” Maddow said. “If somebody came to you about that and said, ‘Howard, you know more about radio than anyone in the world, help me get better.'”
“I’d say, ‘Do you compete with me?’ I’d say, ‘F--- you,'” Stern answered.
Maddow admitted her bond with Ailes didn't play well with her progressive viewers.
“There were a lot of people who were mad at me for saying anything nice about him given the other things we learned about him before he died,” she said.
“I’m not downplaying those things to also be able say, ‘Listen, this is a true thing about the way he interacted with me and he was a friend.'” |
The Value of Photo Biological Regulation Based on Nano Semiconductor Laser Technology in the Treatment of Hypertension Fundus Disease.
With the development of nanometer semiconductor laser technology, due to the wide range of photobiological regulation and non-invasive advantages, it is widely used in clinical research, including reducing pain, accelerating wound healing, nerve injury repair and regeneration. Increase tissue blood flow, improve anxiety and depression, and treat Parkinson's and retinal diseases. However, in many studies, the role of photobiological regulation is still controversial. There are two main problems, one is that the mechanism of photo biological regulation is not fully understood, and the other is that the specific parameters are not uniform in different treatments, such as wavelength density, power density, pulse, treatment timing, and number of treatments. In this paper, through the second question, the parameters of low-energy near-infrared light (810 nm semiconductor laser) in the treatment of fundus diseases are the main research objects. Based on understanding the parameters of low-energy lasers, cyan blue is irradiated with different energy near-infrared light. Data analysis of the actual energy obtained after the retina of the rabbit and observation and research on the cell morphology of each layer of the retina, to obtain relatively safe treatment parameters for the retina, provide theoretical data for near-infrared light in the treatment of clinical fundus disease, and make it safer to use in clinical treatment. |
<filename>min3d-source/min3d/core/Vertices.java
package min3d.core;
import min3d.vos.Color4;
import min3d.vos.Number3d;
import min3d.vos.Uv;
public class Vertices
{
private Number3dBufferList _points;
private UvBufferList _uvs;
private Number3dBufferList _normals;
private Color4BufferList _colors;
private boolean _hasUvs;
private boolean _hasNormals;
private boolean _hasColors;
/**
* Used by Object3d to hold the lists of vertex points, texture coordinates (UV), normals, and vertex colors.
* Use "addVertex()" to build the vertex data for the Object3d instance associated with this instance.
*
* Direct manipulation of position, UV, normal, or color data can be done directly through the associated
* 'buffer list' instances contained herein.
*/
public Vertices(int $maxElements)
{
_points = new Number3dBufferList($maxElements);
_hasUvs = true;
_hasNormals = true;
_hasColors = true;
if (_hasUvs) _uvs = new UvBufferList($maxElements);
if (_hasNormals) _normals = new Number3dBufferList($maxElements);
if (_hasColors) _colors = new Color4BufferList($maxElements);
}
/**
* This version of the constructor adds 3 boolean arguments determine whether
* uv, normal, and color lists will be used by this instance.
* Set to false when appropriate to save memory, increase performance.
*/
public Vertices(int $maxElements, Boolean $useUvs, Boolean $useNormals, Boolean $useColors)
{
_points = new Number3dBufferList($maxElements);
_hasUvs = $useUvs;
_hasNormals = $useNormals;
_hasColors = $useColors;
if (_hasUvs) _uvs = new UvBufferList($maxElements);
if (_hasNormals) _normals = new Number3dBufferList($maxElements);
if (_hasColors) _colors = new Color4BufferList($maxElements);
}
public Vertices(Number3dBufferList $points, UvBufferList $uvs, Number3dBufferList $normals,
Color4BufferList $colors)
{
_points = $points;
_uvs = $uvs;
_normals = $normals;
_colors = $colors;
_hasUvs = _uvs != null && _uvs.size() > 0;
_hasNormals = _normals != null && _normals.size() > 0;
_hasColors = _colors != null && _colors.size() > 0;
}
public int size()
{
return _points.size();
}
public int capacity()
{
return _points.capacity();
}
public boolean hasUvs()
{
return _hasUvs;
}
public boolean hasNormals()
{
return _hasNormals;
}
public boolean hasColors()
{
return _hasColors;
}
/**
* Use this to populate an Object3d's vertex data.
* Return's newly added vertex's index
*
* If hasUvs, hasNormals, or hasColors was set to false,
* their corresponding arguments are just ignored.
*/
public short addVertex(
float $pointX, float $pointY, float $pointZ,
float $textureU, float $textureV,
float $normalX, float $normalY, float $normalZ,
short $colorR, short $colorG, short $colorB, short $colorA)
{
_points.add($pointX, $pointY, $pointZ);
if (_hasUvs) _uvs.add($textureU, $textureV);
if (_hasNormals) _normals.add($normalX, $normalY, $normalZ);
if (_hasColors) _colors.add($colorR, $colorG, $colorB, $colorA);
return (short)(_points.size()-1);
}
/**
* More structured-looking way of adding a vertex (but potentially wasteful).
* The VO's taken in as arguments are only used to read the values they hold
* (no references are kept to them).
* Return's newly added vertex's index
*
* If hasUvs, hasNormals, or hasColors was set to false,
* their corresponding arguments are just ignored.
*/
public short addVertex(Number3d $point, Uv $textureUv, Number3d $normal, Color4 $color)
{
_points.add($point);
if (_hasUvs) _uvs.add($textureUv);
if (_hasNormals) _normals.add($normal);
if (_hasColors) _colors.add($color);
return (short)(_points.size()-1);
}
public void overwriteVerts(float[] $newVerts)
{
_points.overwrite($newVerts);
}
public void overwriteNormals(float[] $newNormals)
{
_normals.overwrite($newNormals);
}
Number3dBufferList points() /*package-private*/
{
return _points;
}
/**
* List of texture coordinates
*/
UvBufferList uvs() /*package-private*/
{
return _uvs;
}
/**
* List of normal values
*/
Number3dBufferList normals() /*package-private*/
{
return _normals;
}
/**
* List of color values
*/
Color4BufferList colors() /*package-private*/
{
return _colors;
}
public Vertices clone()
{
Vertices v = new Vertices(_points.clone(), _uvs.clone(), _normals.clone(), _colors.clone());
return v;
}
}
|
// generate the opcode function name
func opcodeFuncName(code uint8) string {
x := opcodeLookup(code)
if x.ins == "ill" {
return "opXX"
}
return fmt.Sprintf("op%02X", code)
} |
<commit_msg>Exclude user from to string
<commit_before>package ee.tuleva.onboarding.aml;
import ee.tuleva.onboarding.user.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.*;
import java.time.Instant;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AmlCheck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private User user;
@Enumerated(value = EnumType.STRING)
private AmlCheckType type;
private boolean success;
@CreatedDate
private Instant createdTime;
@PrePersist
protected void onCreate() {
createdTime = Instant.now();
}
}
<commit_after>package ee.tuleva.onboarding.aml;
import ee.tuleva.onboarding.user.User;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.*;
import java.time.Instant;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString(exclude = {"user"})
public class AmlCheck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private User user;
@Enumerated(value = EnumType.STRING)
private AmlCheckType type;
private boolean success;
@CreatedDate
private Instant createdTime;
@PrePersist
protected void onCreate() {
createdTime = Instant.now();
}
}
|
Charlie Wilson, Cleveland Larkin, and Willustus “Lusk” Holley were walking down a dirt road in rural Slocum, Texas when they were blindsided by a mob of armed white men. On their way to tend to family livestock on July 29, 1910, the three black teenagers became the first casualties of what would turn out to be a shameful massacre — with groups of white Texans going from road to road, house to house, shooting black citizens. Wilson and Holley survived the attack, but Larkin succumbed to the injuries.
The ensuing bloodshed lasted for at least two days, spilling to the south in Houston County. Black residents hastily gathered what belongings they could and escaped across creeks to wooded areas and marshes. Some families fled to the nearby town of Palestine, while others trekked farther. During the panic, they had no choice but to leave behind loved ones who’d been killed along the roads and in the woods of Slocum.
As the violence intensified, local officials turned to Texas Governor Thomas Campbell, and a company of U.S. cavalry troops and Texas Rangers were brought in to quell the situation.
Newspapers reported the incident as a “race war” or riot, rather than the massacre it was.
No one is certain how many people died. The official count lists eight dead — Cleveland Larkin, Alex Holley, Sam Baker, Dick Wilson, Jeff Wilson, Ben Dancer, John Hays and Will Burly — but even at the time, authorities believed many more were murdered.
“Many of the bodies were in a state of decomposition, and the action was taken as a measure to insure public health,” The Houston Post reported. “A trench twelve feet in depth had been dug during the early hours of the day and in this ditch the bodies were placed and covered. In many cases relatives of the Negroes discovered the whereabouts of a body and dragged it to a secluded spot during the hours of the night. On account of the fact that several bodies have been thus disposed of, the exact number of Negroes killed will never be known. A conservative estimate places the number killed at eighteen, while many men of standing in the community declare not less than forty were killed. No white man was injured during the trouble.”
News traveled remarkably fast. Anderson County Sheriff William H. Black, a white man, was quoted in The New York Times on August 1, 1910. “Men were going about killing Negroes as fast as they could find them, and so far as I was able to ascertain, without any real cause,” he told the paper. “These Negroes have done no wrong that I could discover. There was just a hotheaded gang hunting them down and killing them. I don’t know how many were in the mob, but I think there must have been 200 or 300. Some of them cut telephone wires. They hunted the Negroes down like sheep.”
Jack Holley lost his son—and everything he owned—in the massacre.
There are several theories as to what motivated the massacre. According to an account in the Semi-Weekly Courier Times of Tyler, the incident was attributed to a dispute between black businessman Marsh Holley — father of Lusk and Alex Holley — and a white farmer over an unpaid debt. Marsh’s father, Jack Holley, owned several hundred acres of land and sold goods from his store to both black and white customers. He was among those who escaped the violence, leaving behind all he’d worked for.
Another account involved Jim Spurger, a white man alleged to have instigated the event because he reportedly didn’t want to take orders from a black boss on a road maintenance crew. Some said the killings were simply a land grab, as they believed white residents begrudged the prosperity of their black neighbors.
Another theory, according to newspaper reports, claimed white residents believed black people were planning an attack against them. “The third and the most serious reason which is believed to be directly responsible for the tragedies is the seemingly baseless and unfounded wild reports and rumors which gained currency and which were magnified as they were repeated from mouth to mouth,” read The Dallas Morning News on August 1, 1910. “These were to the effect that the negroes were preparing to rise and kill all of the white people.”
But as news of the violence captured national attention, most newspaper reports framed Slocum as a “race riot” or “race war,” rather than an unprovoked massacre.
A group of black ministers in Washington, D.C. felt it was an opportune time to address an issue they felt had been ignored by the federal government. They pleaded with President William H. Taft to focus on racial violence in America and specifically “the murdering of 20 or more innocent and unarmed colored men near Palestine, Texas.”
Historians speculate that the white mob mentality was fueled by envy and racist attitudes toward black people who were striving despite their treatment in society—a narrative that has been seen repeatedly in American history.
Around the turn of the century, resentment toward black people was intense. Although the first wave of Ku Klux Klan activity had died down by the 1870s, racial violence continued. In Texas, there were 23 lynchings reported in 1908 and 15 in 1909, the same year the National Association for the Advancement of Colored People was founded. On March 3, 1910, thousands of people gathered in Dallas for the lynching of Allen Brooks, a black man accused of sexually assaulting a 2-year-old white girl.
Later that summer, black boxer Jack Johnson defeated Jim Jeffries, a white man, for the heavyweight title in Reno, Nevada. Race riots erupted around the country, including in Fort Worth.
Less than a month later, the bustling black community in Slocum would be erased. |
package libraryManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import models.Book;
import models.Dvd;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;
import service.BookService;
import service.DvdService;
import util.JsonServiceUtil;
import util.ResponseWrapper;
import javax.inject.Inject;
import java.util.List;
public class WestminsterLibraryManager extends Controller implements LibraryManager {
@Inject
ObjectMapper objectMapper;
@Inject
BookService bookService;
@Inject
DvdService dvdService;
@Override
@BodyParser.Of(BodyParser.Json.class)
public Result addBook() {
JsonNode jsonNode = request().body().asJson();
Book bookToAdd = null;
try {
bookToAdd = objectMapper.treeToValue(jsonNode, Book.class);
Book addedBook = bookService.addBook(bookToAdd);
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Book added", addedBook)));
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
@Override
public Result deleteBook(long id) {
try{
Book bookToDelete = bookService.deleteBook(id);
if (bookToDelete != null) {
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Book deleted", bookToDelete)));
}else {
return null;
}
}catch (Exception e){
return null;
}
}
@Override
public Result addDvd() {
JsonNode jsonNode = request().body().asJson();
Dvd dvdToAdd = null;
try {
dvdToAdd = objectMapper.treeToValue(jsonNode, Dvd.class);
Dvd addedDvd = dvdService.addDvd(dvdToAdd);
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("DVD added", addedDvd)));
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
@Override
public Result deleteDvd(long id) {
try{
Book bookToDelete = bookService.deleteBook(id);
if (bookToDelete != null) {
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("DVD deleted", bookToDelete)));
}else {
return null;
}
}catch (Exception e){
return null;
}
}
@Override
public Result listRemainingBooks() {
List<Book> remainingBooks = bookService.listRemainingBooks();
if(remainingBooks ==null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("All Books", remainingBooks)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Failed", null)));
}
@Override
public Result listRemainingDvds() {
List<Book> remainingDvds = bookService.listRemainingBooks();
if(remainingDvds ==null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("All Dvds", remainingDvds)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Failed", null)));
}
@Override
public Result borrowBook(String title) {
Book bookToBorrow = bookService.borrowBook(title);
if(bookToBorrow !=null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Borrowed", bookToBorrow)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Item Not Available", null)));
}
@Override
public Result borrowDvd(String title) {
Dvd dvdToBorrow = dvdService.borrowDvd(title);
if(dvdToBorrow !=null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Borrowed", dvdToBorrow)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Item Not Available", null)));
}
@Override
public Result returnBook() {
return null;
}
@Override
public Result returnDvd() {
return null;
}
@Override
public Result searchBook(String title) {
Book searchedBook = bookService.search(title);
if(searchedBook ==null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Found in DB",searchedBook)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Failed", null)));
}
@Override
public Result searchDvd(String title) {
Dvd searcherDvd = dvdService.search(title);
if(searcherDvd ==null){
return ok(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Found in DB", searcherDvd)));
}
return badRequest(JsonServiceUtil.toJsonNode(new ResponseWrapper<>("Failed", null)));
}
}
|
<filename>cmd/discover/main.go
package main
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/eandre/discover"
"golang.org/x/tools/cover"
)
func usage() {
fmt.Fprintf(os.Stderr, `Usage: \n\ndiscover [flags] command [<args>...]
The commands are:
discover [-output=<dir>] test [<testRegexp>]
Runs "go test -run <testRegexp>" to output a cover profile,
and then parses it and outputs the result.
discover [-output=<dir>] parse <cover profile>
Parses the given cover profile and outputs the result.
For both commands, the output flag specifies a directory to write files to,
as opposed to printing to stdout. If any of the files exist already, they will
be overwritten.
`)
}
var output = flag.String("output", "", "Directory to write output files to (will overwrite existing files)")
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() == 0 {
usage()
os.Exit(1)
}
switch flag.Arg(0) {
case "test":
// run tests
if err := runTests(flag.Arg(1)); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
case "parse":
if flag.NArg() <= 1 {
fmt.Fprintln(os.Stderr, "missing cover profile")
os.Exit(1)
}
if err := parseProfile(flag.Arg(1)); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
}
func runTests(testRegexp string) error {
tmpDir, err := ioutil.TempDir("", "discover")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
profilePath := filepath.Join(tmpDir, "coverprofile.out")
args := []string{"test", "-coverprofile", profilePath}
if testRegexp != "" {
args = append(args, "-run", testRegexp)
}
cmd := exec.Command("go", args...)
cmd.Stdin = nil
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
if _, err := os.Stat(profilePath); os.IsNotExist(err) {
return errors.New("No tests found? (no cover profile generated)")
} else if err != nil {
return err
}
fmt.Printf("\n") // newline between "go test" output and ours
return parseProfile(profilePath)
}
func parseProfile(fileName string) error {
profiles, err := cover.ParseProfiles(fileName)
if err != nil {
return err
}
prof, err := discover.ParseProfile(profiles)
if err != nil {
return err
}
for _, f := range prof.Files {
prof.Trim(f)
// If we filtered out all decls, don't print at all
if len(f.Decls) == 0 {
continue
}
fn := filepath.Base(prof.Fset.File(f.Pos()).Name())
importPath := prof.ImportPaths[f]
if importPath == "" {
return fmt.Errorf("No import path found for %q", fn)
}
if err := outputFile(importPath, fn, prof.Fset, f); err != nil {
return err
}
}
return nil
}
func outputFile(importPath, name string, fset *token.FileSet, file *ast.File) error {
if *output != "" {
// Write to file
dir := filepath.Join(*output, importPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
target := filepath.Join(dir, name)
f, err := os.Create(target)
if err != nil {
return err
}
if err := format.Node(f, fset, file); err != nil {
return err
}
return nil
}
// Print to stdout
fmt.Printf("%s:\n%s\n", name, strings.Repeat("=", len(name)))
format.Node(os.Stdout, fset, file)
fmt.Printf("\n\n")
return nil
}
|
#include "RecoLuminosity/LumiProducer/interface/LumiCorrector.h"
/**
these are corrections including unit conversion /mb to /ub
if unit is already /ub, use e-03
**/
LumiCorrector::LumiCorrector() {
Occ1Norm_ = 6.36e3; // For 2.76TeV 1.34e3, for HI 2.214e6
Occ2Norm_ = 7.97e3;
ETNorm_ = 1.59e3;
PUNorm_ = 6.37e3;
Alpha1_ = 0.063;
Alpha2_ = -0.0037;
// map doesn't provide any initialization -> do brute force // For HI Afterglow=1.
AfterglowMap_[213] = 0.992;
AfterglowMap_[321] = 0.990;
AfterglowMap_[423] = 0.988;
AfterglowMap_[597] = 0.985;
AfterglowMap_[700] = 0.984;
AfterglowMap_[873] = 0.981;
AfterglowMap_[1041] = 0.979;
AfterglowMap_[1179] = 0.977;
AfterglowMap_[1317] = 0.975;
}
void LumiCorrector::setNormForAlgo(const std::string& algo, float value) {
if (algo == "OCC1") {
Occ1Norm_ = value;
return;
}
if (algo == "OCC2") {
Occ2Norm_ = value;
return;
}
if (algo == "ET") {
ETNorm_ = value;
return;
}
if (algo == "PU") {
PUNorm_ = value;
return;
}
}
void LumiCorrector::setCoefficient(const std::string& name, float value) {
if (name == "ALPHA1") {
Alpha1_ = value;
return;
}
if (name == "ALPHA2") {
Alpha2_ = value;
return;
}
}
float LumiCorrector::getNormForAlgo(const std::string& algo) const {
if (algo == "OCC1") {
return Occ1Norm_;
}
if (algo == "OCC2") {
return Occ2Norm_;
}
if (algo == "ET") {
return ETNorm_;
}
if (algo == "PU") {
return PUNorm_;
}
return 1.0;
}
float LumiCorrector::getCoefficient(const std::string& name) const {
if (name == "ALPHA1") {
return Alpha1_;
}
if (name == "ALPHA2") {
return Alpha2_;
}
return 0.0;
}
float LumiCorrector::AfterglowFactor(int nBXs) {
float Afterglow = 1.;
for (std::map<int, float>::iterator it = AfterglowMap_.begin(); it != AfterglowMap_.end(); ++it) {
if (nBXs >= it->first) {
Afterglow = it->second;
}
}
return Afterglow;
}
float LumiCorrector::TotalNormOcc1(float TotLumi_noNorm, int nBXs) {
float AvgLumi = (nBXs > 0) ? PUNorm_ * TotLumi_noNorm / nBXs : 0.;
return Occ1Norm_ * AfterglowFactor(nBXs) / (1 + Alpha1_ * AvgLumi + Alpha2_ * AvgLumi * AvgLumi);
}
float LumiCorrector::TotalNormOcc2(float TotLumi_noNorm, int nBXs) { return Occ2Norm_; }
float LumiCorrector::TotalNormET(float TotLumi_noNorm, int nBXs) { return ETNorm_; }
|
def resource(self):
resource = self._get_resource()
if resource and resource.exists():
return resource |
/**
* Defines the 'role' of a Druid service, utilized to strongly type announcement and service discovery.
*
* Originally, this was an enum to add type safety for discovery and announcement purposes, but was expanded
* into a class to allow for extensibility while retaining the type safety of using defined types instead of raw
* strings. As such, this class tries to mimic the interface provided by the previous enum.
*
* Built in node roles define a {@link #name} that is distinct from {@link #jsonName}, and is the previous value
* which would occur when the enum was used in a 'toString' context. Custom node roles allow extension to participate
* in announcement and discovery, but are limited to only using {@link #jsonName} for both toString and JSON serde.
*
* The historical context of why the enum was different from {@link org.apache.druid.server.coordination.ServerType}
* (also called "node type" in various places) is because while they are essentially the same abstraction, merging them
* could only increase the complexity and drop the code safety, because they name the same types differently
* ("peon" - "indexer-executor" and "middleManager" - "realtime") and both expose them via JSON APIs.
*
* These abstractions can all potentially be merged when Druid updates to Jackson 2.9 that supports JsonAliases,
* see https://github.com/apache/druid/issues/7152.
*/
public class NodeRole
{
public static final String COORDINATOR_JSON_NAME = "coordinator";
public static final String HISTORICAL_JSON_NAME = "historical";
public static final String BROKER_JSON_NAME = "broker";
public static final String OVERLORD_JSON_NAME = "overlord";
public static final String PEON_JSON_NAME = "peon";
public static final String ROUTER_JSON_NAME = "router";
public static final String MIDDLE_MANAGER_JSON_NAME = "middleManager";
public static final String INDEXER_JSON_NAME = "indexer";
public static final NodeRole COORDINATOR = new NodeRole("COORDINATOR", COORDINATOR_JSON_NAME);
public static final NodeRole HISTORICAL = new NodeRole("HISTORICAL", HISTORICAL_JSON_NAME);
public static final NodeRole BROKER = new NodeRole("BROKER", BROKER_JSON_NAME);
public static final NodeRole OVERLORD = new NodeRole("OVERLORD", OVERLORD_JSON_NAME);
public static final NodeRole PEON = new NodeRole("PEON", PEON_JSON_NAME);
public static final NodeRole ROUTER = new NodeRole("ROUTER", ROUTER_JSON_NAME);
public static final NodeRole MIDDLE_MANAGER = new NodeRole("MIDDLE_MANAGER", MIDDLE_MANAGER_JSON_NAME);
public static final NodeRole INDEXER = new NodeRole("INDEXER", INDEXER_JSON_NAME);
private static final NodeRole[] BUILT_IN = new NodeRole[]{
COORDINATOR,
HISTORICAL,
BROKER,
OVERLORD,
PEON,
ROUTER,
MIDDLE_MANAGER,
INDEXER
};
private static final Map<String, NodeRole> BUILT_IN_LOOKUP =
Arrays.stream(BUILT_IN).collect(Collectors.toMap(NodeRole::getJsonName, Function.identity()));
/**
* For built-in roles, to preserve backwards compatibility when this was an enum, this provides compatibility for
* usages of the enum name as a string, (e.g. allcaps 'COORDINATOR'), which is used by system tables for displaying
* node role, and by curator discovery for the discovery path of a node role (the actual payload at the zk location
* uses {@link #jsonName})
*/
private final String name;
/**
* JSON serialized value for {@link NodeRole}
*/
private final String jsonName;
/**
* Create a custom node role. Known Druid node roles should ALWAYS use the built-in static node roles:
* ({@link #COORDINATOR}, {@link #OVERLORD}, {@link #ROUTER}, {@link #BROKER}{@link #INDEXER},
* {@link #MIDDLE_MANAGER}, {@link #HISTORICAL}) instead of constructing a new instance.
*/
public NodeRole(String jsonName)
{
this(jsonName, jsonName);
}
/**
* for built-in roles, to preserve backwards compatibility when this was an enum, allow built-in node roles to specify
* the 'name' which is used by 'toString' to be separate from the jsonName, which is the value which the node role
* will be serialized as and deserialized from
*/
private NodeRole(String name, String jsonName)
{
this.name = name;
this.jsonName = jsonName;
}
public Named getDruidServiceInjectName()
{
return Names.named(jsonName);
}
@JsonValue
public String getJsonName()
{
return jsonName;
}
@JsonCreator
public static NodeRole fromJsonName(String jsonName)
{
return BUILT_IN_LOOKUP.getOrDefault(jsonName, new NodeRole(jsonName));
}
@Override
public String toString()
{
// for built-in roles, to preserve backwards compatibility when this was an enum
return name;
}
/**
* built-in node roles
*/
public static NodeRole[] values()
{
return Arrays.copyOf(BUILT_IN, BUILT_IN.length);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NodeRole nodeRole = (NodeRole) o;
return name.equals(nodeRole.name) && jsonName.equals(nodeRole.jsonName);
}
@Override
public int hashCode()
{
return Objects.hash(name, jsonName);
}
} |
/*----------------------------------------------------------------------------
> Function Name: RtStatus_t ExtractPath(uint8_t *filepath,int32_t *index)
FunctionType: Reentrant
Inputs: 1) Pointer to filepath
2) Pointer to index
Outputs: Returns SUCCESS or an error if function fails.
Description: This function copies the string from first directory separator(\\)
to the end of string to the same string. It considers the
string as DBCS.
<
----------------------------------------------------------------------------*/
int32_t ExtractPath(uint8_t *filepath,int32_t *index)
{
int32_t Strlen,offset=*index;
int Char;
Strlen = Strlength(filepath);
while(1)
{
Char = GetChar(filepath,&offset);
if(Char =='/' || Char == '\0')
break;
}
*index = offset;
if(offset >= Strlen)
return END_OF_DIR_PATH;
return SUCCESS;
} |
// ==============================================================================================
// pidynbotsShutdownCB
//
// This callback is invoked whenever a game shutdown is detected, typically as a result of
// restart request, or operator terminating the server. This event is not a SISSM shutdown.
//
int pidynbotsShutdownCB( char *strIn )
{
return 0;
} |
/**
* The bullet data in an attacking, including its track, top point's coordinate
* @author wangqi
*
*/
public class BulletTrack {
public int roundNumber = 0;
public int startX = 0;
public int startY = 0;
public int wind = 0;
public int power = 0;
public int angle = 0;
//The bullet hit point's coordinate
public SimplePoint hitPoint;
//The top point
public SimplePoint topPoint;
//The bullet's flying seconds
public double flyingSeconds;
//The bullet's flying speed (pixels/second)
public double speed;
//The horizontal speed
public double speedX;
//The vertical speed
public double speedY;
//The sin value of hitting angle.
public double sinAttackAngle;
//The scale ratio for a bullet.
public int pngNum = 100;
//The check range of user
public int offx = 60;
public int offy = 60;
//For internal use only
public double ax, ay;
public int bx, by;
//1 爆炸 2 出界
public int result;
public String bullet;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BulletTrack [roundNumber=");
builder.append(roundNumber);
builder.append(", startX=");
builder.append(startX);
builder.append(", startY=");
builder.append(startY);
builder.append(", wind=");
builder.append(wind);
builder.append(", power=");
builder.append(power);
builder.append(", angle=");
builder.append(angle);
builder.append(", hitPoint=");
builder.append(hitPoint);
builder.append(", topPoint=");
builder.append(topPoint);
builder.append(", flyingSeconds=");
builder.append(flyingSeconds);
builder.append(", speed=");
builder.append(speed);
builder.append(", speedX=");
builder.append(speedX);
builder.append(", speedY=");
builder.append(speedY);
builder.append(", sinAttackAngle=");
builder.append(sinAttackAngle);
builder.append("]");
return builder.toString();
}
/**
* Convert this to BseBullet object
* @return
*/
public Bullet toBseBullet() {
Bullet.Builder builder = Bullet.newBuilder();
builder.setStartx(startX);
builder.setStarty(startY);
builder.setSpeedx((int)(speedX));
builder.setSpeedy((int)(speedY));
builder.setWind(wind);
builder.setPngNum(pngNum);
builder.setBullet(bullet);
builder.setOffx(offx);
builder.setOffy(offy);
return builder.build();
}
/**
* Construct these object from BceBulletTrack
* @param track
* @return
*/
public static BulletTrack fromBceBulletTrack(XinqiBceBulletTrack.BulletTrack track) {
BulletTrack bulletTrack = new BulletTrack();
bulletTrack.flyingSeconds = track.getFlyingSeconds()/10000.0;
Point p = track.getHitpoint();
if ( p != null ) {
SimplePoint hitPoint = new SimplePoint(p.getX(), p.getY());
bulletTrack.hitPoint = hitPoint;
}
p = track.getToppoint();
if ( p != null ) {
SimplePoint topPoint = new SimplePoint(p.getX(), p.getY());
bulletTrack.topPoint = topPoint;
}
bulletTrack.speedX = track.getSpeedx();
bulletTrack.speedY = track.getSpeedy();
bulletTrack.pngNum = track.getPngNum();
bulletTrack.result = track.getResult();
return bulletTrack;
}
} |
/**
* Created by zhoumy on 2017/2/6.
*/
@Service("trafficPolicyValidator")
public class DefaultTrafficPolicyValidator implements TrafficPolicyValidator {
@Resource
private SlbTrafficPolicyMapper slbTrafficPolicyMapper;
@Resource
private PathValidator pathValidator;
@Resource
private TrafficPolicyQuery trafficPolicyQuery;
@Resource
private GroupCriteriaQuery groupCriteriaQuery;
@Autowired
private GroupRepository groupRepository;
public static final String RELATED_GROUP_OPS_REMOVE_GVS = "REMOVE_GVS";
public static final String RELATED_GROUP_OPS_DEACTIVATE = "DEACTIVATE";
@Override
public void checkRestrictionForUpdate(TrafficPolicy target) throws Exception {
SlbTrafficPolicy e = slbTrafficPolicyMapper.selectByPrimaryKey(target.getId());
if (e == null) throw new ValidationException("Traffic policy that you try to update does not exist.");
if (e.getVersion() > target.getVersion()) {
throw new ValidationException("Newer offline version is detected.");
}
if (!e.getVersion().equals(target.getVersion())) {
throw new ValidationException("Mismatched offline version is detected.");
}
}
@Override
public void removable(Long targetId) throws Exception {
if (slbTrafficPolicyMapper.selectByPrimaryKey(targetId).getActiveVersion() > 0) {
throw new ValidationException("Traffic policy that you try to delete is still active.");
}
}
@Override
public void validateFields(TrafficPolicy policy, ValidationContext context) {
if (policy.getName() == null) {
context.error(policy.getId(), MetaType.TRAFFIC_POLICY, ErrorType.FIELD_VALIDATION, "Field `name` is empty.");
}
if (policy.getPolicyVirtualServers() == null || policy.getPolicyVirtualServers().size() == 0) {
context.error(policy.getId(), MetaType.TRAFFIC_POLICY, ErrorType.FIELD_VALIDATION, "Field `policy-virtual-servers` is empty.");
}
}
@Override
public Map<Long,String> validatedForDeactivate(TrafficPolicy policy) throws Exception {
Long savedGroupId = null;
List<Long> groups = new ArrayList<>();
Map<Long,String> relatedGroupOpsType= new HashMap<>();
// 1. weight check
for (TrafficControl c : policy.getControls()) {
if (c.getWeight() > 0) {
if (savedGroupId != null) {
throw new ValidationException("Policy has multi groups which have the weight large then 0.GroupId:" + savedGroupId);
} else {
savedGroupId = c.getGroup().getId();
}
}
groups.add(c.getGroup().getId());
}
// 2. multi policies check
for (Long gid : groups) {
Set<IdVersion> ids = trafficPolicyQuery.queryByGroupId(gid);
for (IdVersion idv : ids) {
if (!idv.getId().equals(policy.getId())) {
throw new ValidationException("Policy groups has multi policies. Policy:" + idv.getId());
}
}
}
// 3. path & priority check
groups.remove(savedGroupId);
Set<IdVersion> groupIdvs = groupCriteriaQuery.queryByIdsAndMode(groups.toArray(new Long[groups.size()]), SelectionMode.ONLINE_FIRST);
List<Group> groupList = groupRepository.list(groupIdvs.toArray(new IdVersion[groupIdvs.size()]));
Map<Long, PolicyVirtualServer> policyVses = new HashMap<>();
for (PolicyVirtualServer pvs : policy.getPolicyVirtualServers()) {
policyVses.put(pvs.getVirtualServer().getId(), pvs);
}
for (Group group : groupList) {
if (group.getId().equals(savedGroupId)) continue;
Map<Long, GroupVirtualServer> groupVirtualServerMap = new HashMap<>();
for (GroupVirtualServer gvs : group.getGroupVirtualServers()) {
groupVirtualServerMap.put(gvs.getVirtualServer().getId(), gvs);
}
if (policyVses.size() == groupVirtualServerMap.size() && policyVses.keySet().containsAll(groupVirtualServerMap.keySet())) {
for (Long vsId : policyVses.keySet()) {
String policyPath = policyVses.get(vsId).getPath();
String groupPath = groupVirtualServerMap.get(vsId).getPath();
if (!pathValidator.contains(policyPath, groupPath)) {
throw new ValidationException("Group's path contains policy's path.Policy:" + policy.getId() + ",path:" + policyPath
+ ";Group:" + group.getId() + ",path:" + groupPath);
}
}
relatedGroupOpsType.put(group.getId(), RELATED_GROUP_OPS_DEACTIVATE);
} else {
relatedGroupOpsType.put(group.getId(), RELATED_GROUP_OPS_REMOVE_GVS);
//throw new ValidationException("Group have more virtual servers than policy.Policy:" + policy.getId() + ";Group:" + group.getId());
}
}
return relatedGroupOpsType;
}
@Override
public Long[] validatePolicyControl(TrafficPolicy policy) throws ValidationException {
Long[] groupIds = new Long[policy.getControls().size()];
for (int i = 0; i < policy.getControls().size(); i++) {
groupIds[i] = policy.getControls().get(i).getGroup().getId();
}
if (groupIds.length < 1) {
throw new ValidationException("Traffic policy that you try to create/modify does not have enough traffic-controls.");
}
Arrays.sort(groupIds);
Long prev = groupIds[0];
for (int i = 1; i < groupIds.length; i++) {
if (prev.equals(groupIds[i])) {
throw new ValidationException("Traffic policy that you try to create/modify declares the same group " + prev + " more than once.");
}
prev = groupIds[i];
}
double totalWeight = 0.0;
for (TrafficControl c : policy.getControls()) {
if (c.getWeight() < 0) {
throw new ValidationException("Field `weight` only accepts positive value.");
}
totalWeight += c.getWeight();
}
if (totalWeight == 0) {
throw new ValidationException("Sum of field `weight` can not be zero.");
}
return groupIds;
}
@Override
public Map<Long, PolicyVirtualServer> validatePolicyOnVses(Long policyId, Long[] controlIds, Map<Long, List<LocationEntry>> groupEntries, List<PolicyVirtualServer> policyOnVses, Map<Long, List<LocationEntry>> groupRelatedPolicyEntries, ValidationContext context) throws ValidationException {
ValidationContext validationContext = context == null ? new ValidationContext() : context;
Map<Long, PolicyVirtualServer> result = new HashMap<>();
int i = 0;
int[] visited = new int[controlIds.length];
for (PolicyVirtualServer e : policyOnVses) {
Long vsId = e.getVirtualServer().getId();
List<LocationEntry> another = groupRelatedPolicyEntries.get(vsId);
if (another != null && another.size() > 0) {
for (LocationEntry ee : another) {
if (!ee.getEntryId().equals(policyId)) {
String error = "Some other traffic policies have occupied traffic-controls on vs " + vsId + ".";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
validationContext.error(ee.getEntryId(), MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
}
}
i++;
List<LocationEntry> entriesOnVs = groupEntries.get(vsId);
if (entriesOnVs == null || entriesOnVs.size() == 0) {
String error = "Traffic policy that you try to create/modify does not have enough traffic-controls.";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.FIELD_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
for (LocationEntry ee : entriesOnVs) {
int j = Arrays.binarySearch(controlIds, ee.getEntryId());
if (j < 0) continue;
visited[j] = i;
if (e.getPriority() <= ee.getPriority()) {
String error = "Traffic policy has lower `priority` than its control item " + controlIds[j] + " on vs " + vsId + ".";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
validationContext.error(controlIds[j], MetaType.GROUP, ErrorType.DEPENDENCY_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
if (!pathValidator.contains(ee.getPath(), e.getPath())) {
String error = "Traffic policy is neither sharing the same `path` with nor containing part of the `path` of its control item " + controlIds[j] + " on vs " + vsId + ".";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
validationContext.error(controlIds[j], MetaType.GROUP, ErrorType.DEPENDENCY_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
}
for (int k = 0; k < visited.length; k++) {
if (visited[k] != i) {
String error = "Group " + controlIds[k] + " is missing combination on vs " + vsId + ".";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
validationContext.error(controlIds[k], MetaType.GROUP, ErrorType.DEPENDENCY_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
}
PolicyVirtualServer prev = result.put(vsId, e);
if (prev != null) {
String error = "Traffic policy can have and only have one combination to the same virtual-server. \"vs-id\" : " + e.getVirtualServer().getId() + ".";
validationContext.error(policyId, MetaType.TRAFFIC_POLICY, ErrorType.DEPENDENCY_VALIDATION, error);
if (context == null) throw new ValidationException(error);
}
}
return result;
}
} |
One person has died and four were injured Tuesday after an explosion at an Army ammunition plant in Missouri, officials said.
The explosion took place in a mixing building at Lake City Army Ammunition Plant in Independence, Missouri at approximately 1 p.m.
One worker was killed and four were treated at the scene but refused further medical treatment, according to a spokesperson.
Scott Allen with the U.S. Department of Labor's Occupational Safety and Health Administration said federal workplace safety officials are headed to Independence to investigate the cause of the deadly explosion.
Lake City Commander Lt. Col. Eric Dennis said the explosion was in a primer mixing facility, where various chemical agents are mixed to create compounds used in ammunition.
The plant manufactures small-caliber ammunition and operates the North Atlantic Treaty Organization test center. It sits on 3,935 acres in Independence, just east of Kansas City.
An employee told Fox4KC that all workers are being sent home.
The property has more than 400 buildings and nine warehouses, and has a storage capacity of more than 700,000 square feet. Its workforce includes 29 Department of Army civilians and a soldier to provide contract oversight. It has a governmental staff payroll of $2.9 million.
A spokesperson says no further information about the accident was immediately available and the deceased victim's identity has not yet been released.
According to the Kansas City Star, previous explosions in December 1990 and March 1981 killed and injured workers at Lake City.
READ MORE FROM FOX 4 KANSAS CITY.
The Associated Press contributed to this report. |
/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable max-len */
import { expect } from "chai";
import { run_program, h, KEYWORD_TO_ATOM, OPERATOR_LOOKUP, SExp, t, CLVMObject, Tuple, Bytes } from "clvm";
import { bytes } from "../../../util/serializer/basic_types";
import { ConditionsDict, SExpUtil } from "../../../util/sexp";
import { ConditionOpcode } from "../../../util/sexp/condition_opcodes";
import { ConditionWithArgs } from "../../../util/sexp/condition_with_args";
const sexpUtil = new SExpUtil();
describe("SExpUtil", () => {
describe("fromHex()", () => {
it("Correctly converts a hex string to a SExp object", () => {
const plus = h(KEYWORD_TO_ATOM["+"]);
const q = h(KEYWORD_TO_ATOM["q"]);
const program1 = SExp.to([plus, 1, t(q, 175)]);
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(mod a (+ a 175))'
(+ 1 (q . 175))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(+ 1 (q . 175))'
ff10ff01ffff018200af80
*/
const program2 = sexpUtil.fromHex("ff10ff01ffff018200af80");
expect(
program1.equal_to(program2)
).to.be.true;
});
});
describe("toHex()", () => {
it("Correctly converts a SExp object to a hex string", () => {
const plus = h(KEYWORD_TO_ATOM["+"]);
const q = h(KEYWORD_TO_ATOM["q"]);
const program = SExp.to([plus, 1, t(q, 175)]);
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(mod a (+ a 175))'
(+ 1 (q . 175))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(+ 1 (q . 175))'
ff10ff01ffff018200af80
*/
expect(
sexpUtil.toHex(program)
).to.equal("ff10ff01ffff018200af80");
});
it("Works with 'null'", () => {
expect(
sexpUtil.toHex(null)
).to.equal("");
});
it("Works with 'undefined'", () => {
expect(
sexpUtil.toHex(undefined)
).to.equal("");
});
});
describe("run()", () => {
it("Correctly runs program without cost", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const result = sexpUtil.run(program, solution);
const expectedResult = SExp.to(25 + 175);
expect(
expectedResult.equal_to(result)
).to.be.true;
expect(result.as_int()).to.equal(200);
});
it("Correctly runs program with cost", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const expectedCost = run_program(
program,
solution,
OPERATOR_LOOKUP,
sexpUtil.MAX_BLOCK_COST_CLVM
)[0];
const result = sexpUtil.run(program, solution, expectedCost + 1);
const expectedResult = SExp.to(25 + 175);
expect(
expectedResult.equal_to(result)
).to.be.true;
expect(result.as_int()).to.equal(200);
});
it("Throws error if the cost is too low", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const expectedCost = run_program(
program,
solution,
OPERATOR_LOOKUP,
sexpUtil.MAX_BLOCK_COST_CLVM
)[0];
let failed: boolean = false;
let errOk: boolean = false;
try {
sexpUtil.run(program, solution, expectedCost - 1);
} catch(err: any) {
failed = true;
errOk = err.message === "cost exceeded";
}
expect(failed).to.be.true;
expect(errOk).to.be.true;
});
});
describe("runWithCost()", () => {
it("Correctly runs program without cost", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const expectedCost = run_program(
program,
solution,
OPERATOR_LOOKUP,
sexpUtil.MAX_BLOCK_COST_CLVM
)[0];
const [result, cost] = sexpUtil.runWithCost(program, solution);
const expectedResult = SExp.to(25 + 175);
expect(
expectedResult.equal_to(result)
).to.be.true;
expect(result.as_int()).to.equal(200);
expect(cost).to.equal(expectedCost);
});
it("Correctly runs program with cost", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const expectedCost = run_program(
program,
solution,
OPERATOR_LOOKUP,
sexpUtil.MAX_BLOCK_COST_CLVM
)[0];
const [result, cost] = sexpUtil.runWithCost(program, solution, expectedCost + 1);
const expectedResult = SExp.to(25 + 175);
expect(
expectedResult.equal_to(result)
).to.be.true;
expect(result.as_int()).to.equal(200);
expect(cost).to.equal(expectedCost);
});
it("Throws error if the cost is too low", () => {
const program = sexpUtil.fromHex("ff10ff01ffff018200af80");
const solution = SExp.to(25);
const expectedCost = run_program(
program,
solution,
OPERATOR_LOOKUP,
sexpUtil.MAX_BLOCK_COST_CLVM
)[0];
let failed: boolean = false;
let errOk: boolean = false;
try {
sexpUtil.run(program, solution, expectedCost - 1);
} catch(err: any) {
failed = true;
errOk = err.message === "cost exceeded";
}
expect(failed).to.be.true;
expect(errOk).to.be.true;
});
});
describe("sha256tree()", () => {
it("Works correctly for string", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run hash.clvm
(a (q 2 2 (c 2 (c 3 ()))) (c (q 2 (i (l 5) (q 11 (q . 2) (a 2 (c 2 (c 9 ()))) (a 2 (c 2 (c 13 ())))) (q 11 (q . 1) 5)) 1) 1))
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(mod () "yakuhito")'
(q . "yakuhito")
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(q . "yakuhito")'
ff018879616b756869746f
(venv) yakuhito@catstation:~/projects/clvm_tools$ brun '(a (q 2 2 (c 2 (c 3 ()))) (c (q 2 (i (l 5) (q 11 (q . 2) (a 2 (c 2 (c 9 ()))) (a 2 (c 2 (c 13 ())))) (q 11 (q . 1) 5)) 1) 1))' '(q . "yakuhito")'
0x88c3d66266c96a7125bc21ec44f386a358f9658559a3699cd2cf0846d57a5e76
(venv) yakuhito@catstation:~/projects/clvm_tools$
*/
const toHash = sexpUtil.fromHex("ff018879616b756869746f");
const res = sexpUtil.sha256tree(toHash);
expect(res).to.equal("88c3d66266c96a7125bc21ec44f386a358f9658559a3699cd2cf0846d57a5e76");
});
it("Works correctly for a program", () => {
/*
# Hashes itself!
(venv) yakuhito@catstation:~/projects/clvm_tools$ run hash.clvm
(a (q 2 2 (c 2 (c 3 ()))) (c (q 2 (i (l 5) (q 11 (q . 2) (a 2 (c 2 (c 9 ()))) (a 2 (c 2 (c 13 ())))) (q 11 (q . 1) 5)) 1) 1))
(venv) yakuhito@catstation:~/projects/clvm_tools$ brun '(a (q 2 2 (c 2 (c 3 ()))) (c (q 2 (i (l 5) (q 11 (q . 2) (a 2 (c 2 (c 9 ()))) (a 2 (c 2 (c 13 ())))) (q 11 (q . 1) 5)) 1) 1))' '(a (q 2 2 (c 2 (c 3 ()))) (c (q 2 (i (l 5) (q 11 (q . 2) (a 2 (c 2 (c 9 ()))) (a 2 (c 2 (c 13 ())))) (q 11 (q . 1) 5)) 1) 1))'
0x6dba5ecde970b43b7d9366ee1a065ee6aa4478c9b765dad95ab3dec4c3544975
(venv) yakuhito@catstation:~/projects/clvm_tools$
*/
const toHash = sexpUtil.fromHex(sexpUtil.SHA256TREE_PROGRAM);
const res = sexpUtil.sha256tree(toHash);
expect(res).to.equal("6dba5ecde970b43b7d9366ee1a065ee6aa4478c9b765dad95ab3dec4c3544975");
});
});
describe("conditionsDictForSolution()", () => {
it("Works", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ cat test.clvm
(mod (THROW_ERROR)
(defconstant AGG_SIG_ME 50)
(defconstant CREATE_COIN 51)
(if (= THROW_ERROR 1)
(x "ERROR")
(list
(list AGG_SIG_ME 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")
(list CREATE_COIN 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)
)
)
)
(venv) yakuhito@catstation:~/projects/clvm_tools$ run test.clvm
(a (q 2 (i (= 5 (q . 1)) (q 8 (q . "ERROR")) (q 4 (c 4 (q 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")) (c (c 6 (q 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)) ()))) 1) (c (q 50 . 51) 1))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(a (q 2 (i (= 5 (q . 1)) (q 8 (q . "ERROR")) (q 4 (c 4 (q 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")) (c (c 6 (q 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)) ()))) 1) (c (q 50 . 51) 1))'
ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080
*/
const program: SExp = sexpUtil.fromHex("ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080"); // ()
const solution: SExp = sexpUtil.fromHex("ff8080"); // (())
const res = sexpUtil.conditionsDictForSolution(program, solution, sexpUtil.MAX_BLOCK_COST_CLVM);
expect(res[0]).to.be.false;
expect(res[1]).to.not.be.null;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const dict: ConditionsDict = res[1]!;
expect(dict.size).to.equal(2);
const aggSigMes = dict.get(ConditionOpcode.AGG_SIG_ME);
expect(aggSigMes?.length).to.equal(1);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const aggSigMe = aggSigMes![0];
expect(aggSigMe.opcode).to.equal(ConditionOpcode.AGG_SIG_ME);
expect(aggSigMe.vars.toString()).to.equal("a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37,79616b756869746f");
const createCoins = dict.get(ConditionOpcode.CREATE_COIN);
expect(createCoins?.length).to.equal(1);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const createCoin = createCoins![0];
expect(createCoin.opcode).to.equal(ConditionOpcode.CREATE_COIN);
expect(createCoin.vars.toString()).to.equal("b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664,0a");
});
it("Works if puzzle throws an exception", () => {
const program: SExp = sexpUtil.fromHex("ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080"); // ()
const solution: SExp = sexpUtil.fromHex("ff0180"); // (1) => should throw exception
const res = sexpUtil.conditionsDictForSolution(program, solution, sexpUtil.MAX_BLOCK_COST_CLVM);
expect(res[0]).to.be.true;
expect(res[1]).to.be.null;
expect(res[2]).to.equal(0);
});
});
describe("conditionsForSolution()", () => {
it("Works", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ cat test.clvm
(mod (THROW_ERROR)
(defconstant AGG_SIG_ME 50)
(defconstant CREATE_COIN 51)
(if (= THROW_ERROR 1)
(x "ERROR")
(list
(list AGG_SIG_ME 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")
(list CREATE_COIN 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)
)
)
)
(venv) yakuhito@catstation:~/projects/clvm_tools$ run test.clvm
(a (q 2 (i (= 5 (q . 1)) (q 8 (q . "ERROR")) (q 4 (c 4 (q 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")) (c (c 6 (q 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)) ()))) 1) (c (q 50 . 51) 1))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(a (q 2 (i (= 5 (q . 1)) (q 8 (q . "ERROR")) (q 4 (c 4 (q 0xa37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37 "yakuhito")) (c (c 6 (q 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 10)) ()))) 1) (c (q 50 . 51) 1))'
ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080
*/
const program: SExp = sexpUtil.fromHex("ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080"); // ()
const solution: SExp = sexpUtil.fromHex("ff8080"); // (())
const res = sexpUtil.conditionsForSolution(program, solution, sexpUtil.MAX_BLOCK_COST_CLVM);
expect(res[0]).to.be.false;
expect(res[1]).to.not.be.null;
const arr: ConditionWithArgs[] = res[1] ?? [];
expect(arr.length).to.equal(2);
expect(arr[0].opcode).to.equal(ConditionOpcode.AGG_SIG_ME);
expect(arr[0].vars.toString()).to.equal("a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37,79616b756869746f");
expect(arr[1].opcode).to.equal(ConditionOpcode.CREATE_COIN);
expect(arr[1].vars.toString()).to.equal("b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664,0a");
});
it("Works if puzzle throws an exception", () => {
const program: SExp = sexpUtil.fromHex("ff02ffff01ff02ffff03ffff09ff05ffff010180ffff01ff08ffff01854552524f5280ffff01ff04ffff04ff04ffff01ffb0a37901780f3d6a13990bb17881d68673c64e36e5f0ae02922afe9b3743c1935765074d237507020c3177bd9476384a37ff8879616b756869746f8080ffff04ffff04ff06ffff01ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff0a8080ff80808080ff0180ffff04ffff01ff3233ff018080"); // ()
const solution: SExp = sexpUtil.fromHex("ff0180"); // (1) => should throw exception
const res = sexpUtil.conditionsForSolution(program, solution, sexpUtil.MAX_BLOCK_COST_CLVM);
expect(res[0]).to.be.true;
expect(res[1]).to.be.null;
expect(res[2]).to.equal(0);
});
});
describe("parseSExpToConditions()", () => {
it("Works with expected input", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(list (list 51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) (list 73 100000))'
((51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) (73 0x0186a0))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '((51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) (73 0x0186a0))'
ffff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980ffff49ff830186a08080
*/
const sexp: SExp = sexpUtil.fromHex("ffff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980ffff49ff830186a08080"); // ()
const res = sexpUtil.parseSExpToConditions(sexp);
expect(res[0]).to.be.false;
expect(res[1]).to.not.be.null;
const arr: ConditionWithArgs[] = res[1] ?? [];
expect(arr.length).to.equal(2);
expect(arr[0].opcode).to.equal(ConditionOpcode.CREATE_COIN);
expect(arr[0].vars.toString()).to.equal("b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664,0539");
expect(arr[1].opcode).to.equal(ConditionOpcode.ASSERT_MY_AMOUNT);
expect(arr[1].vars.toString()).to.equal("0186a0");
});
it("Works if given list contains an invalid condition", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(list (list 51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) () (list 73 100000))'
((51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) () (73 0x0186a0))
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '((51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337) () (73 0x0186a0))'
ffff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980ff80ffff49ff830186a08080
*/
const sexp: SExp = sexpUtil.fromHex("ffff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980ff80ffff49ff830186a08080"); // ()
const res = sexpUtil.parseSExpToConditions(sexp);
expect(res[0]).to.be.true;
expect(res[1]).to.be.null;
});
});
describe("parseSExpToCondition()", () => {
it("Works for a normal condition", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(list 51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337)'
(51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337)
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(51 0xb6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664 1337)'
ff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980
*/
const sexp: SExp = sexpUtil.fromHex("ff33ffa0b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664ff82053980");
const res = sexpUtil.parseSExpToCondition(sexp);
expect(res[0]).to.be.false;
expect(res[1]).to.not.be.null;
expect(res[1]?.opcode).to.equal(ConditionOpcode.CREATE_COIN);
expect(res[1]?.vars.length).to.equal(2);
expect(res[1]?.vars[0]).to.equal("b6b6c8e3b2f47b6705e440417907ab53f7c8f6d88a74668f14edf00b127ff664");
expect(res[1]?.vars[1]).to.equal("0539"); // 1337
});
it("Works if given () as input", () => {
const sexp: SExp = sexpUtil.fromHex("80"); // ()
const res = sexpUtil.parseSExpToCondition(sexp);
expect(res[0]).to.be.true;
expect(res[1]).to.be.null;
});
});
describe("asAtomList()", () => {
it("Works", () => {
/*
(venv) yakuhito@catstation:~/projects/clvm_tools$ run '(list 0x31 0x33 0x37)'
(49 51 55)
(venv) yakuhito@catstation:~/projects/clvm_tools$ opc '(49 51 55)'
ff31ff33ff3780
(venv) yakuhito@catstation:~/projects/clvm_tools$
*/
const sexp: SExp = sexpUtil.fromHex("ff31ff33ff3780");
const res: bytes[] = sexpUtil.asAtomList(sexp);
expect(res.length).to.equal(3);
expect(res.toString()).to.equal("31,33,37");
});
it("Works if list ends unexpectedly", () => {
const sexp: SExp = new SExp(
new CLVMObject(new Tuple(
new CLVMObject(
Bytes.from([0x31])
),
new CLVMObject(
new Tuple(
Bytes.from([0x33]),
Bytes.from([0x37])
)
)
))
);
const res: bytes[] = sexpUtil.asAtomList(sexp);
expect(res.length).to.equal(1);
expect(res[0]).to.equal("31");
});
});
describe("conditionsByOpcode()", () => {
it("Works", () => {
const c1 = new ConditionWithArgs();
c1.opcode = ConditionOpcode.AGG_SIG_ME;
c1.vars = ["11", "22"];
const c2 = new ConditionWithArgs();
c2.opcode = ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT;
c2.vars = ["33", "44"];
const c3 = new ConditionWithArgs();
c3.opcode = ConditionOpcode.AGG_SIG_ME;
c3.vars = ["55", "66"];
const conditions: ConditionWithArgs[] = [c1, c2, c3];
const res = sexpUtil.conditionsByOpcode(conditions);
expect(res.get(ConditionOpcode.AGG_SIG_ME)?.length).to.equal(2);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const aggSigMes = res.get(ConditionOpcode.AGG_SIG_ME)!;
expect(aggSigMes[0].opcode).to.equal(ConditionOpcode.AGG_SIG_ME);
expect(aggSigMes[0].vars.length).to.equal(2);
expect(aggSigMes[0].vars[0]).to.equal("11");
expect(aggSigMes[0].vars[1]).to.equal("22");
expect(aggSigMes[1].opcode).to.equal(ConditionOpcode.AGG_SIG_ME);
expect(aggSigMes[1].vars.length).to.equal(2);
expect(aggSigMes[1].vars[0]).to.equal("55");
expect(aggSigMes[1].vars[1]).to.equal("66");
expect(res.get(ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT)?.length).to.equal(1);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const ann = res.get(ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT)![0];
expect(ann.opcode).to.equal(ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT);
expect(ann.vars.length).to.equal(2);
expect(ann.vars[0]).to.equal("33");
expect(ann.vars[1]).to.equal("44");
});
});
describe("pkmPairsForConditionsDict()", () => {
it("Returns empty lists if there are no things to sign", () => {
const conditionsDict = new Map<ConditionOpcode, ConditionWithArgs[]>();
const cwa = new ConditionWithArgs();
cwa.opcode = ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT;
cwa.vars = [""];
conditionsDict.set(ConditionOpcode.AGG_SIG_UNSAFE, []);
conditionsDict.set(ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT, [cwa]);
const res = sexpUtil.pkmPairsForConditionsDict(
conditionsDict, "11", "22"
);
expect(res.length).to.equal(0);
});
it("Correctly handles AGG_SIG_UNSAFE conditions", () => {
const conditionsDict = new Map<ConditionOpcode, ConditionWithArgs[]>();
const cwa1 = new ConditionWithArgs();
cwa1.opcode = ConditionOpcode.AGG_SIG_UNSAFE;
cwa1.vars = ["deadbeef", "313337"];
const cwa2 = new ConditionWithArgs();
cwa2.opcode = ConditionOpcode.AGG_SIG_UNSAFE;
cwa2.vars = ["foodbabe", "909090"];
conditionsDict.set(ConditionOpcode.AGG_SIG_UNSAFE, [cwa1, cwa2]);
const res = sexpUtil.pkmPairsForConditionsDict(
conditionsDict, "11", "22"
);
expect(res.length).to.equal(2);
expect(res[0][0]).to.equal("deadbeef");
expect(res[0][1]).to.equal("313337");
expect(res[1][0]).to.equal("foodbabe");
expect(res[1][1]).to.equal("909090");
});
it("Correctly handles AGG_SIG_ME conditions", () => {
const conditionsDict = new Map<ConditionOpcode, ConditionWithArgs[]>();
const cwa1 = new ConditionWithArgs();
cwa1.opcode = ConditionOpcode.AGG_SIG_ME;
cwa1.vars = ["deadbeef", "313337"];
const cwa2 = new ConditionWithArgs();
cwa2.opcode = ConditionOpcode.AGG_SIG_ME;
cwa2.vars = ["foodbabe", "909090"];
conditionsDict.set(ConditionOpcode.AGG_SIG_ME, [cwa1, cwa2]);
const res = sexpUtil.pkmPairsForConditionsDict(
conditionsDict, "11", "22"
);
expect(res.length).to.equal(2);
expect(res[0][0]).to.equal("deadbeef");
expect(res[0][1]).to.equal("3133371122");
expect(res[1][0]).to.equal("foodbabe");
expect(res[1][1]).to.equal("9090901122");
});
});
});
|
/**
* @author Lee Rhodes
* @author Kevin Lang
*/
class HeapAuxHashMap implements AuxHashMap {
private final int lgConfigK; //required for #slot bits
private int lgAuxArrInts;
private int auxCount;
private int[] auxIntArr; //used by Hll4Array
/**
* Standard constructor
* @param lgAuxArrInts the log size of the aux integer array
* @param lgConfigK must be 7 to 21
*/
HeapAuxHashMap(final int lgAuxArrInts, final int lgConfigK) {
this.lgConfigK = lgConfigK;
this.lgAuxArrInts = lgAuxArrInts;
auxIntArr = new int[1 << lgAuxArrInts];
}
/**
* Copy constructor
* @param that another AuxHashMap
*/
HeapAuxHashMap(final HeapAuxHashMap that) {
lgConfigK = that.lgConfigK;
lgAuxArrInts = that.lgAuxArrInts;
auxCount = that.auxCount;
auxIntArr = that.auxIntArr.clone();
}
static final HeapAuxHashMap heapify(final Memory mem, final long offset, final int lgConfigK,
final int auxCount, final boolean srcCompact) {
final int lgAuxArrInts;
final HeapAuxHashMap auxMap;
if (srcCompact) { //early versions did not use LgArr byte field
lgAuxArrInts = PreambleUtil.computeLgArr(mem, auxCount, lgConfigK);
} else { //updatable
lgAuxArrInts = extractLgArr(mem);
}
auxMap = new HeapAuxHashMap(lgAuxArrInts, lgConfigK);
final int configKmask = (1 << lgConfigK) - 1;
if (srcCompact) {
for (int i = 0; i < auxCount; i++) {
final int pair = extractInt(mem, offset + (i << 2));
final int slotNo = HllUtil.getPairLow26(pair) & configKmask;
final int value = HllUtil.getPairValue(pair);
auxMap.mustAdd(slotNo, value); //increments count
}
} else { //updatable
final int auxArrInts = 1 << lgAuxArrInts;
for (int i = 0; i < auxArrInts; i++) {
final int pair = extractInt(mem, offset + (i << 2));
if (pair == EMPTY) { continue; }
final int slotNo = HllUtil.getPairLow26(pair) & configKmask;
final int value = HllUtil.getPairValue(pair);
auxMap.mustAdd(slotNo, value); //increments count
}
}
return auxMap;
}
@Override
public HeapAuxHashMap copy() {
return new HeapAuxHashMap(this);
}
@Override
public int getAuxCount() {
return auxCount;
}
@Override
public int[] getAuxIntArr() {
return auxIntArr;
}
@Override
public int getCompactSizeBytes() {
return auxCount << 2;
}
@Override
public PairIterator getIterator() {
return new IntArrayPairIterator(auxIntArr, lgConfigK);
}
@Override
public int getLgAuxArrInts() {
return lgAuxArrInts;
}
@Override
public int getUpdatableSizeBytes() {
return 4 << lgAuxArrInts;
}
@Override
public boolean isMemory() {
return false;
}
@Override
public boolean isOffHeap() {
return false;
}
//In C: two-registers.c Line 300.
@Override
public void mustAdd(final int slotNo, final int value) {
final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
final int pair = HllUtil.pair(slotNo, value);
if (index >= 0) {
final String pairStr = HllUtil.pairString(pair);
throw new SketchesStateException("Found a slotNo that should not be there: " + pairStr);
}
//Found empty entry
auxIntArr[~index] = pair;
auxCount++;
checkGrow();
}
//In C: two-registers.c Line 205
@Override
public int mustFindValueFor(final int slotNo) {
final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (index >= 0) {
return HllUtil.getPairValue(auxIntArr[index]);
}
throw new SketchesStateException("SlotNo not found: " + slotNo);
}
//In C: two-registers.c Line 321.
@Override
public void mustReplace(final int slotNo, final int value) {
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (idx >= 0) {
auxIntArr[idx] = HllUtil.pair(slotNo, value); //replace
return;
}
final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value));
throw new SketchesStateException("Pair not found: " + pairStr);
}
//Searches the Aux arr hash table for an empty or a matching slotNo depending on the context.
//If entire entry is empty, returns one's complement of index = found empty.
//If entry contains given slotNo, returns its index = found slotNo.
//Continues searching.
//If the probe comes back to original index, throws an exception.
private static final int find(final int[] auxArr, final int lgAuxArrInts, final int lgConfigK,
final int slotNo) {
assert lgAuxArrInts < lgConfigK;
final int auxArrMask = (1 << lgAuxArrInts) - 1;
final int configKmask = (1 << lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = auxArr[probe];
if (arrVal == EMPTY) { //Compares on entire entry
return ~probe; //empty
}
else if (slotNo == (arrVal & configKmask)) { //Compares only on slotNo
return probe; //found given slotNo, return probe = index into aux array
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
}
private void checkGrow() {
if ((RESIZE_DENOM * auxCount) > (RESIZE_NUMER * auxIntArr.length)) {
growAuxSpace();
//TODO if direct, ask for more memory
}
}
private void growAuxSpace() {
final int[] oldArray = auxIntArr;
final int configKmask = (1 << lgConfigK) - 1;
auxIntArr = new int[1 << ++lgAuxArrInts];
for (int i = 0; i < oldArray.length; i++) {
final int fetched = oldArray[i];
if (fetched != EMPTY) {
//find empty in new array
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, fetched & configKmask);
auxIntArr[~idx] = fetched;
}
}
}
} |
/**
\brief Writing info on original (node-based) nodes
*/
void extractor::WriteNodeMapping(const std::vector<QueryNode> &internal_to_external_node_map)
{
boost::filesystem::ofstream node_stream(config.node_output_path, std::ios::binary);
const unsigned size_of_mapping = internal_to_external_node_map.size();
node_stream.write((char *)&size_of_mapping, sizeof(unsigned));
if (size_of_mapping > 0)
{
node_stream.write((char *)internal_to_external_node_map.data(),
size_of_mapping * sizeof(QueryNode));
}
node_stream.close();
} |
package response
type WebLink struct {
Name string `json:"name"`
Url string `json:"url"`
OriginUrl string `json:"origin_url"`
Content string `json:"content"`
}
|
<gh_stars>0
use crate::app;
use ash::version::DeviceV1_0;
use ash::vk;
pub fn update_descriptor_set(
app_data: &app::AppData,
vulkan_data: &app::VulkanInitData,
resource_index: usize,
) {
let device = vulkan_data.get_device_ref();
let set = app_data.descriptor_sets[resource_index];
let buffer_info = vk::DescriptorBufferInfo {
buffer: app_data.vertex_mem_buffers[resource_index].buffer,
offset: 0,
range: vk::WHOLE_SIZE,
};
let image_info = vk::DescriptorImageInfo {
sampler: vk::Sampler::null(),
image_view: app_data.font_mem_image.view,
image_layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
};
let infos = [buffer_info];
let buffer_desc_write = vk::WriteDescriptorSet::builder()
.dst_set(set)
.dst_binding(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.buffer_info(&infos)
.build();
let infos = [image_info];
let texture_desc_write = vk::WriteDescriptorSet::builder()
.dst_set(set)
.dst_binding(1)
.descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
.image_info(&infos)
.build();
unsafe {
device.update_descriptor_sets(&[buffer_desc_write, texture_desc_write], &[]);
}
}
pub fn update_descriptor_sets(app_data: &app::AppData, vulkan_data: &app::VulkanInitData) {
for i in 0..app_data.descriptor_sets.len() {
update_descriptor_set(app_data, vulkan_data, i);
}
}
|
<reponame>Eric-Arellano/rust
// run-pass
macro_rules! make_foo {
() => (
struct Foo;
impl Foo {
fn bar(&self) {}
}
)
}
make_foo!();
pub fn main() {
Foo.bar()
}
|
import re
from . import base
class regex_search_ternary(base.Function):
"""
Ternary regex operator, it takes arguments in the following form
STR1, REGEX, STR2, STR3
If REGEX matches STR1 (re.search is used), STR2 is returned,
otherwise STR3 is returned
"""
def __init__(self):
# 4 arguments
super(regex_search_ternary, self).__init__("regex_search_ternary", 4, 4)
def execute(self, args):
if not super(regex_search_ternary, self).execute(args):
return None
if re.search(args[1], args[0]):
return args[2]
else:
return args[3]
|
/**
*
* Maintains a list of topics
*
* @author wyatt
*
*/
public class TopicListViewAdapter extends PostListViewAdapter<TopicModel> {
public TopicListViewAdapter(FragmentActivity theActivity,
PostModelList<TopicModel> arrayList) {
super(theActivity, arrayList);
}
/*
* (non-Javadoc)
*
* @see
* ca.ualberta.cs.adapters.PostListViewAdapter#populateCellTitle(android
* .view.View, ca.ualberta.cs.models.PostModel)
*/
@Override
protected void populateCellTitle(View theView, TopicModel thePost) {
// Fill title/comment text
TextView titleText = (TextView) theView
.findViewById(R.id.textViewTitle);
// List of topics, display the title
String theTitle = thePost.getTitle();
titleText.setText(theTitle);
}
/*
* (non-Javadoc)
*
* @see ca.ualberta.cs.adapters.PostListViewAdapter#getViewClass()
*/
@Override
protected Class<?> getViewClass() {
// TODO Auto-generated method stub
return TopicViewActivity.class;
}
/*
* (non-Javadoc)
*
* @see ca.ualberta.cs.adapters.PostListViewAdapter#setSelectedList()
*/
@Override
protected void setSelectedList() {
SelectedTopicModelList.setTopicList(theArrayList);
}
} |
Neil Kopit is a marketing director with the Ourisman car dealership. Its Tenleytown business is leaving the District for Bethesda. (Bonnie Jo Mount/The Washington Post)
One glance at the Ourisman Volkswagen’s showroom in Tenleytown helps explain why traditional car dealerships will soon be a thing of the past in the District.
Outside, new cars are backed side by side against the showroom, their hoods extending to the sidewalk. The small lot is crammed with a couple dozen used vehicles. Most of the dealership’s inventory is kept a couple miles away in an underground parking garage.
Clearly, space is an issue. And that is an expensive problem to have, given the spiraling cost of real estate in the District. That problem is only exacerbated by the shifting economics of car dealerships, which operate on narrow profit margins, making them increasingly reliant on high volumes to be viable.
So Ourisman is leaving Upper Northwest for Bethesda in March. And with its departure, the District will be without a traditional car dealership for the first time in nearly a century. The departure means that the Tesla store on K Street NW — a relatively small space featuring the cutting-edge electric vehicles customers frequently order online — will soon be the only place to buy a new car in the city. Less than a half-century ago, the city was home to 40 new car dealerships, according to the Washington Area New Auto Dealers Association.
“Land is at a premium in many urban environments,” said Steven Szakaly, chief economist for the National Automobile Dealers Association. “Dealer profit margins are pretty slim. Hotels, retail spaces, their margins are much higher. That makes it hard for car dealers to stay in places like D.C.”
The growing dominance of large dealership groups has only increased the pressure on urban car dealers. New, larger dealerships often require brightly lit mega lots that are a more natural fit in suburban settings.
Many of the big-city dealerships that remain, like several in Manhattan, are owned by deep-pocketed manufacturers. The size of new-car dealerships has expanded in recent years as their numbers have declined. The government-managed bankruptcies of General Motors and Chrysler contributed to a loss of more than 2,700 dealerships between 2007 and 2010, and last year there were fewer than 18,000 dealerships left in the country.
“There are huge incentives and really good economies of scale if you can consolidate and become a larger group,” Szakaly said.
Also, the very largest dealers are cornering a growing share of new-car sales. As recently as 2009, the nation’s top 125 auto dealership groups accounted for 16.4 percent of the nation’s new car sales. Last year, the top 125 groups were responsible for 19.3 percent of sales — a growth pattern that is expected to persist, said Alan Haig, president of Haig Partners, an auto dealer brokerage based in Fort Lauderdale, Fla.
“Operating a car dealership has grown more complex,” Haig said, noting that manufacturers are demanding that dealers offer plush showrooms with more amenities for customers. Big ownership groups are often the only ones that have the cash needed to meet those demands, he said.
Not only are dealerships bigger, but they are also more profitable than they have been in a long time. In the years before the 2007 recession, car dealerships cleared an average profit of about $600,000 a year, Haig said. That dipped by more than half during the downturn. But in recent years, the big profits are back and dealers now average nearly $1 million a year in profits.
Those big numbers are drawing new investors to the market, while pushing the value of many of the businesses into the tens of millions of dollars — well beyond the reach of all but the wealthiest buyers.
In October, Warren Buffett’s Berkshire Hathaway announced plans to buy the Van Tuyl group, then the nation’s largest privately held dealership group. The group, which was founded in 1955 as a single Chevrolet dealership, had 78 dealerships across the country and nearly $8 billion in revenue last year, according to news reports.
Buffett said the dealerships are a good investment because each one averages about $100 million a year in business, making their tiny profit margins of less than 2 percent attractive.
But those low margins and the need for a high sales volume all but rule out car dealers in places such as the District, analysts said.
“Low-margin businesses that require a lot of real estate are not what is going to do well in a city like Washington, D.C.,” Haig said. “Those things make it difficult to justify holding a car dealership in D.C.”
The land where Ourisman now stands in Tenleytown has been purchased by Georgetown Day School, part of a $40 million purchase intended to consolidate the school’s campuses.
“People don’t have the property that’s needed for dealers, and nobody wants the zoning in their neighborhood anyway,” said Neil Kopit, Ourisman’s strategic marketing director.
Meanwhile, the Internet has flipped the car-buying equation for many salespeople, making neighborhood connections and location less important. Ourisman still gets a fair amount of business from foreign embassy staffers and other customers who are nearby. But most car buyers do the bulk of their shopping online and only come to dealers to close the deal.
“That is just the way things go,” said Ron Sowell, who has sold cars at the Wisconsin Avenue Volkswagen dealership for nine years. “As long as my service department is in the same place, we will be all right.” |
from unittest import TestCase
from unittest.mock import patch
from nose.tools import istest
from convertfrom.main import convert, main
class EntryPointTest(TestCase):
@istest
@patch('convertfrom.main.sys')
@patch('convertfrom.main.print')
@patch('convertfrom.main.convert')
def prints_converted_result(self, mock_convert, mock_print, mock_sys):
mock_sys.argv = ['convertfrom', '2a', 'to', 'b']
mock_convert.return_value = '2b'
main()
mock_print.assert_called_once_with('2b')
mock_convert.assert_called_once_with(['2a', 'to', 'b'])
@istest
@patch('convertfrom.main.convert')
def exits_on_exceptions(self, mock_convert):
exception = RuntimeError('oops')
mock_convert.side_effect = exception
with self.assertRaises(SystemExit):
main()
class ConvertTest(TestCase):
@istest
def converts_10m_to_1000cm(self):
result = convert(['10m', 'to', 'cm'])
self.assertEqual(result, '1000.0cm')
@istest
def converts_1m_to_100cm(self):
result = convert(['1m', 'to', 'cm'])
self.assertEqual(result, '100.0cm')
@istest
def converts_1m_to_1000mm(self):
result = convert(['1m', 'to', 'mm'])
self.assertEqual(result, '1000.0mm')
@istest
def converts_200cm_to_2m(self):
result = convert(['200cm', 'to', 'm'])
self.assertEqual(result, '2.0m')
@istest
def converts_1meter_to_100cm(self):
result = convert(['1meter', 'to', 'cm'])
self.assertEqual(result, '100.0cm')
@istest
def converts_1_meter_to_100cm(self):
result = convert(['1', 'meter', 'to', 'cm'])
self.assertEqual(result, '100.0cm')
@istest
def converts_1_meter_to_1m(self):
result = convert(['1', 'meter', 'to', 'meters'])
self.assertEqual(result, '1.0meters')
|
//This class is used to make the sell order Priority Queue,which overwrite the compare method
public class Sellorder implements Comparable <Sellorder>{
public Integer Price;
public Integer Amount;
public String ID;
public Integer getPrice() {
return Price;
}
public void setPrice(Integer Price) {
this.Price = Price;
}
public Integer getAmount() {
return Amount;
}
public void setAmount(Integer Amount) {
this.Amount = Amount;
}
public void setID(String ID) {
this.ID = ID;
}
public String getID() {
return ID;
}
public void setAge(Integer Amount) {
this.Amount= Amount;
}
public Sellorder(){}
public Sellorder(Integer Price, Integer Amount, String ID){
this.Price=Price;
this.Amount=Amount;
this.ID=ID;
}
@Override
public String toString() {
return "Sellorder{" +
"Price=" + Price +
", Amount=" + Amount +
", ID=" + ID +
'}';
}
public boolean equals(Sellorder other){
return this.getID()==other.getID();
}
public int compareTo(Sellorder other) {
if(this.equals(other))
return 0;
else if((getPrice()==other.getPrice())&&(getAmount()>other.getAmount())) //We put the price with lower price first,then compare the amount
return 1;
else if(getPrice()>other.getPrice())
return 1;
else
return -1;
}
} |
<reponame>Epsilon-Infinity/QRE2020<filename>just_sort.py
import utils
from copy import deepcopy
from collections import defaultdict
# {'book_scores':book_scores, days:'days', 'libraries':libraries}
def solver(inputs):
books_so_far = set()
libraries = inputs["libraries"]
# sort libraries
libraries = sorted(libraries, key=lambda x: x.score(books_so_far))
return libraries
if __name__ == "__main__":
utils.solve_files('data', solver)
|
#include "Validation/MuonGEMDigis/interface/GEMStripDigiValidation.h"
#include "Validation/MuonGEMDigis/interface/GEMPadDigiValidation.h"
#include "Validation/MuonGEMDigis/interface/GEMCoPadDigiValidation.h"
#include "Validation/MuonGEMDigis/interface/GEMDigiTrackMatch.h"
#include "Validation/MuonGEMDigis/interface/GEMCheckGeometry.h"
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE (GEMStripDigiValidation) ;
DEFINE_FWK_MODULE (GEMPadDigiValidation) ;
DEFINE_FWK_MODULE (GEMCoPadDigiValidation) ;
DEFINE_FWK_MODULE (GEMDigiTrackMatch) ;
DEFINE_FWK_MODULE (GEMCheckGeometry) ;
|
// In the name of God
// Code by: mrMaster
#include <bits/stdc++.h>
using namespace std;
#define bpc __builtin_popcount
#define blz __builtin_clz
#define btz __builtin_ctz
#define boost ios_base :: sync_with_stdio(false) , cout.tie(0) , cin.tie(0)
#define endl '\n'
typedef long long ll;
typedef long double ld;
typedef pair<int,int>pii;
const int INF = 1e9 + 10;
const ll LINF = 1000ll * 1000 * 1000 * 1000 * 1000 * 1000 + 100;
const int MN = 1e5 + 10;
int big[2][MN];
int little[2][MN];
pii t[MN];
int arr[MN];
ll ans = 0;
int n;
ll k;
void upd(int id , int ind , int val)
{
int sv = ind;
for(;ind<=n;ind += ind&-ind) little[id][ind] += val;
ind = n-sv+1;
for(;ind<=n;ind += ind&-ind) big[id][ind] += val;
}
int get(bool flag , int id , int ind)
{
int ret = 0;
if(flag){ // yani bozorgtar az ind haro mikhaim
ind = n-ind+1;
for(;ind;ind-=ind&-ind) ret += big[id][ind];
}else{
for(;ind;ind-=ind&-ind) ret += little[id][ind];
}
return ret;
}
void input()
{
cin >> n >> k;
for(int i=0;i<n;++i){
cin >> arr[i];
t[i] = pii(arr[i] , i);
}
sort(t , t+n);
int cur = 1;
for(int i=0;i<n;++i){
arr[t[i].second] = cur;
if(i < n-1 && t[i].first < t[i+1].first) ++cur;
}
}
void solve()
{
int l,r; l = r = 0;
ll cur = 0;
for(int i=0;i<n;++i){
cur += get(1 , 1 , arr[i]+1);
upd(1 , arr[i] , +1);
}
upd(1 , arr[0] , -1);
r = 1;
upd(0 , arr[0] , +1);
while(l < n && r < n){
// cout << l << ' ' << r << ' ' << cur << endl;
if(r <= l || cur > k){
cur -= get(0 , 1 , arr[r]-1) + get(1 , 0 , arr[r]+1);
upd(1 , arr[r] , -1);
++r;
}else{
ans += n-r;
++l;
cur += get(1 , 0 , arr[l]+1) + get(0 , 1 , arr[l]-1);
upd(0 , arr[l] , +1);
}
}
cout << ans << endl;
}
int main()
{
// n = 10;
// upd(0 , 1 , +1);
// cout << get(0 , 0 , 2) << endl;
// return 0;
input();
solve();
return 0;
}
|
/*****************************************************************************/
/**
*
* This function gets the acknowledge flag
*
* @param InstancePtr is a pointer to the XV_HdmiTx core instance.
*
* @note None.
*
******************************************************************************/
int XV_HdmiTx_DdcGetAck(XV_HdmiTx *InstancePtr)
{
u32 Status;
Status = XV_HdmiTx_ReadReg(InstancePtr->Config.BaseAddress,
(XV_HDMITX_DDC_STA_OFFSET));
return (Status & XV_HDMITX_DDC_STA_ACK_MASK);
} |
n,i=raw_input().split();
n=int(n);
i=int(i);
if(i%2==0):
i=n+1-i;
print (i/2)+1;
|
Subsets and Splits