text stringlengths 1 1.05M |
|---|
package queue
import "testing"
func TestNewArrayQueue(t *testing.T) {
if NewArrayQueue(0) != nil {
t.Error(`TestNewArrayQueue failed`)
}
queue := NewArrayQueue(5)
if queue == nil || queue.length != 0 || cap(queue.data) != 5 {
t.Error(`TestNewArrayQueue failed`)
}
}
func TestArrayQueuePush(t *testing.T) {
queue := NewArrayQueue(2)
queue.Push(1)
queue.Push(2)
queue.Push(3)
if queue.length != 3 || queue.data[0] != 1 || queue.data[1] != 2 || queue.data[2] != 3 || cap(queue.data) != 4 {
t.Error(`TestArrayQueuePush failed`)
}
}
func TestArrayQueuePop(t *testing.T) {
queue := NewArrayQueue(2)
queue.Push(1)
queue.Push(2)
queue.Push(3)
queue.Push(4)
e1 := queue.Pop()
e2 := queue.Pop()
e3 := queue.Pop()
e4 := queue.Pop()
e5 := queue.Pop()
if e1 != 1 || e2 != 2 || e3 != 3 || e4 != 4 || e5 != nil {
t.Error(`TestArrayQueuePop failed`)
}
}
func TestArrayQueuePeek(t *testing.T) {
queue := NewArrayQueue(2)
queue.Push(1)
queue.Push(2)
e1 := queue.Peek()
if queue.length != 2 || e1 != 1 {
t.Error(`TestArrayQueuePeek failed`)
}
queue.Pop()
e2 := queue.Peek()
if queue.length != 1 || e2 != 2 {
t.Error(`TestArrayQueuePeek failed`)
}
queue.Pop()
e3 := queue.Peek()
if e3 != nil {
t.Error(`TestArrayQueuePeek failed`)
}
}
func TestArrayQueueEmpty(t *testing.T) {
queue := NewArrayQueue(2)
if !queue.Empty() {
t.Error(`TestArrayQueueEmpty failed`)
}
queue.Push(1)
queue.Push(2)
queue.Pop()
if queue.Empty() {
t.Error(`TestArrayQueueEmpty failed`)
}
queue.Pop()
if !queue.Empty() {
t.Error(`TestListQueueEmpty failed`)
}
}
func TestArrayQueueSearch(t *testing.T) {
queue := NewArrayQueue(2)
queue.Push(1)
queue.Push(2)
if queue.Search(2) != 2 || queue.Search(1) != 1 || queue.Search(3) != -1 {
t.Error(`TestArrayQueueSearch failed`)
}
queue.Pop()
queue.Pop()
if queue.Search(1) != -1 {
t.Error(`TestArrayQueueSearch failed`)
}
}
|
<filename>src/main/scala/pl/project13/scala/words/verbs/RetryVerb.scala
package pl.project13.scala.words.verbs
import scala.collection._
trait RetryVerb {
/**
* Try to execute a block (for a result) {@code times} times, and return the first successful result.
* Otherwise, collect thrown exceptions and return their list (with max length = {@code times})
*
* @param times how many times we should try to execute the function
* @param beforeEach will be called before every try to call {@code block}
* @param onException will be called on each failure (thrown exception), use it to log messages for example
*/
def retry[T](times: Long,
beforeEach: (Int) => Unit = {(n) =>},
onException: (Int, Boolean, Throwable) => Unit = {(n, willRetry, exception) =>})
(block: => T): Either[Seq[Exception], T] = {
val exceptions = new mutable.ListBuffer[Exception]
var n = 1
while (n <= times) {
try {
beforeEach(n)
return Right(block)
} catch {
case e: Exception =>
onException(n, n != times, e)
exceptions += e
}
n += 1
}
Left(exceptions.toSeq)
}
}
object RetryVerb extends RetryVerb |
package main
import (
"log"
"net/http"
"strings"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
)
// Thanks to otraore for the code example
// https://gist.github.com/otraore/4b3120aa70e1c1aa33ba78e886bb54f3
func main() {
r := gin.Default()
store := sessions.NewCookieStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))
r.POST("/login", login)
r.GET("/logout", logout)
private := r.Group("/private")
{
private.GET("/", private1)
private.GET("/two", private2)
}
private.Use(AuthRequired())
r.Run(":8080")
}
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
// You'd normally redirect to login page
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
} else {
// Continue down the chain to handler etc
c.Next()
}
}
}
func login(c *gin.Context) {
session := sessions.Default(c)
username := c.PostForm("username")
password := c.PostForm("password")
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Parameters can't be empty"})
return
}
if username == "hello" && password == "<PASSWORD>" {
session.Set("user", username) //In real world usage you'd set this to the users ID
err := session.Save()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate session token"})
} else {
c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}
} else {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication failed"})
}
}
func logout(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
} else {
log.Println(user)
session.Delete("user")
session.Save()
c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out"})
}
}
func private1(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
c.JSON(http.StatusOK, gin.H{"hello": user})
}
func private2(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"hello": "Logged in user"})
}
|
package net.microfalx.resource;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import static net.microfalx.resource.ResourceUtils.getInputStreamAsBytes;
import static net.microfalx.resource.ResourceUtils.requireNonNull;
/**
* A resource which is stored in memory.
*/
public final class MemoryResource extends AbstractResource {
static final long serialVersionUID = -2384762736253212324L;
private byte[] data;
private final String fileName;
private final long lastModified;
private boolean writable = true;
/**
* Creates a resource from another resource.
*
* @param resource the resource
* @return a non-null instance
* @throws IOException if an I/O occurs
*/
public static Resource create(Resource resource) throws IOException {
byte[] data = getInputStreamAsBytes(resource.getInputStream());
return create(data, resource.getName());
}
/**
* Creates a new resource from a text.
*
* @param text the text
* @return a non-null instance
*/
public static Resource create(String text) {
requireNonNull(text);
return create(text.getBytes());
}
/**
* Creates a new resource from a text.
*
* @param text the text
* @param fileName the file name associated with the memory stream
* @return a non-null instance
*/
public static Resource create(String text, String fileName) {
requireNonNull(text);
return create(text.getBytes(), fileName);
}
/**
* Creates a new resource from a text.
*
* @param text the text
* @param fileName the file name associated with the memory stream
* @param lastModified the timestamp when the resource was changed
* @return a non-null instance
*/
public static Resource create(String text, String fileName, long lastModified) {
requireNonNull(text);
return create(text.getBytes(), fileName, lastModified);
}
/**
* Creates a new resource from a byte array.
*
* @param data the array used as content for resource
* @return a non-null instance
*/
public static Resource create(byte[] data) {
String id = UUID.randomUUID().toString();
return create(data, id);
}
/**
* Creates a new resource from a byte array.
*
* @param data the array used as content for resource
* @param fileName the file name associated with the memory stream
* @return a non-null instance
*/
public static Resource create(byte[] data, String fileName) {
String id = UUID.randomUUID().toString();
return new MemoryResource(data, id, fileName, System.currentTimeMillis());
}
/**
* Creates a new resource from a byte array.
*
* @param data the array used as content for resource
* @param fileName the file name associated with the memory stream
* @param lastModified the timestamp when the resource was changed
* @return a non-null instance
*/
public static Resource create(byte[] data, String fileName, long lastModified) {
String id = UUID.randomUUID().toString();
return new MemoryResource(data, id, fileName, lastModified);
}
private MemoryResource(byte[] data, String id, String fileName, long lastModified) {
super(Type.FILE, id);
requireNonNull(data);
this.fileName = fileName;
this.data = Arrays.copyOf(data, data.length);
this.lastModified = lastModified;
}
@Override
public Resource getParent() {
return null;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public boolean exists() {
return true;
}
@Override
public long lastModified() {
return lastModified;
}
@Override
public long length() {
return data.length;
}
@Override
public InputStream doGetInputStream() {
return new ByteArrayInputStream(data);
}
@Override
public boolean isWritable() {
return writable;
}
@Override
public OutputStream doGetOutputStream() throws IOException {
return new MemoryOutputStream();
}
@Override
public Collection<Resource> list() {
return Collections.emptyList();
}
@Override
public Resource resolve(String path) {
return NullResource.createNull();
}
@Override
public URI toURI() {
try {
return new URI("memory://" + getId() + "/" + getFileName());
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
class MemoryOutputStream extends ByteArrayOutputStream {
@Override
public void close() throws IOException {
super.close();
data = toByteArray();
}
}
} |
package com.tdsata.ourapp.activity;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.tdsata.ourapp.R;
import com.tdsata.ourapp.entity.Member;
import com.tdsata.ourapp.util.FixedValue;
import com.tdsata.ourapp.util.Server;
import com.tdsata.ourapp.util.Tools;
import com.tdsata.ourapp.view.HeadPortraitView;
public class ActivityPersonalInformation extends AppCompatActivity {
private final AppCompatActivity activity = this;
private Member currentMember;
private Toolbar toolbar;
private MenuItem alterCount;
private HeadPortraitView headPhoto;
private View toSettingInfo;
private ImageView arrow;
private TextView name;
private TextView number;
private TextView count;
private TextView department;
private TextView flag;
private TextView subject;
private TextView phone;
private TextView qq;
private TextView teacher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_information);
currentMember = (Member) getIntent().getSerializableExtra(FixedValue.currentMember);
if (currentMember == null) {
Toast.makeText(activity, "未知部员信息", Toast.LENGTH_SHORT).show();
finish();
}
initView();
myListener();
if (Tools.my.hasPermission()) {
alterCount.setVisible(true);
}
if (currentMember.getNumber().equals(Tools.my.getAccount())) {
arrow.setVisibility(View.VISIBLE);
}
currentMember.settingHeadPhoto(activity, headPhoto);
name.setText(currentMember.getName());
number.setText(currentMember.getNumber());
count.setText(String.valueOf(currentMember.getCount()));
department.setText(Tools.my.getDepartment().getWholeName());
flag.setText(currentMember.getIdentity());
subject.setText(currentMember.getSubject());
phone.setText(currentMember.getPhone());
qq.setText(currentMember.getQQ());
teacher.setText(currentMember.getTeacher());
}
private void initView() {
toolbar = findViewById(R.id.toolbar);
alterCount = toolbar.getMenu().findItem(R.id.alterCount);
headPhoto = findViewById(R.id.headPhoto);
toSettingInfo = findViewById(R.id.toSettingInfo);
arrow = findViewById(R.id.arrow);
name = findViewById(R.id.name);
number = findViewById(R.id.number);
count = findViewById(R.id.count);
department = findViewById(R.id.department);
flag = findViewById(R.id.flag);
subject = findViewById(R.id.subject);
phone = findViewById(R.id.phone);
qq = findViewById(R.id.qq);
teacher = findViewById(R.id.teacher);
}
private void myListener() {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
private int changeValue = 0;
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.alterCount) {
changeValue = 0;
View changeView = View.inflate(activity, R.layout.dialog_change_integral, null);
final AlertDialog changeDialog = new AlertDialog.Builder(activity, R.style.AlertDialogCornerRadius)
.setView(changeView)
.create();
changeDialog.show();
changeDialog.setCanceledOnTouchOutside(false);
final View addCount = changeView.findViewById(R.id.addCount);
final View minusCount = changeView.findViewById(R.id.minusCount);
final TextView changeValueText = changeView.findViewById(R.id.changeValueText);
final EditText inputReason = changeView.findViewById(R.id.inputReason);
final View ok = changeView.findViewById(R.id.ok);
addCount.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
changeValue += 1;
if (changeValue > 0) {
changeValueText.setText("+" + changeValue);
} else {
changeValueText.setText(String.valueOf(changeValue));
}
}
});
minusCount.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
changeValue -= 1;
if (changeValue > 0) {
changeValueText.setText("+" + changeValue);
} else {
changeValueText.setText(String.valueOf(changeValue));
}
}
});
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String description = String.valueOf(inputReason.getText());
changeDialog.setCancelable(false);
ok.setEnabled(false);
Server.changeCount(currentMember.getNumber(), changeValue, description, activity, new Server.EndOfRequest() {
@Override
public void onSuccess(String result) {
switch (result) {
case "OK":
changeDialog.dismiss();
Toast.makeText(activity, "已修改", Toast.LENGTH_SHORT).show();
count.setText(String.valueOf(currentMember.getCount() + changeValue));
Server.refreshMembers(activity, new Server.EndOfRequest() {
@Override
public void onSuccess(String result) {
if (Tools.refreshMemberList(activity, Server.aesDecryptData(result))) {
new Server.RefreshLocalPhotoThread(activity, null).start();
}
}
@Override
public void onException() {}
@Override
public void onTimeout() {}
@Override
public void noNet() {}
});
break;
case "AES_KEY_ERROR":
Server.startInitConnectionThread();
case "ERROR":
onFail("修改失败,请重试");
break;
}
}
@Override
public void onException() {
onFail("修改失败");
}
@Override
public void onTimeout() {
onFail("连接超时");
}
@Override
public void noNet() {
onFail("网络连接不畅");
}
private void onFail(String message) {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
changeDialog.setCancelable(true);
ok.setEnabled(true);
}
});
}
});
return true;
}
return false;
}
});
toSettingInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentMember.getNumber().equals(Tools.my.getAccount())) {
startActivity(new Intent(activity, ActivityUploadPersonalInfo.class));
}
}
});
}
} |
#!/usr/bin/python
# rebeebus.py 1.0 - An rDNS lookup utility.
# Compatible with Python 2 and 3
# Copyright 2018 13Cubed. All rights reserved. Written by: <NAME>
import sys
import json
import re
import csv
import argparse
import socket
import operator
# Handle Python 2 and 3 compatibility for urllib
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
# Import dns.resolver module and handle error on failure
try:
import dns.resolver
except:
print('Rebeebus requires the dns.resolver module. Please install it and try again.\nHint: pip install dnspython')
sys.exit(1)
# Import dns.reversename module and handle error on failure
try:
import dns.reversename
except:
print('Rebeebus requires the dns.reversename module. Please install it and try again.\nHint: pip install dnspython')
sys.exit(1)
def getData(filenames, dnsServer, includePrivate, sortByCount):
"""
The given file is scraped for IPv4 addresses, and the addresses are used
to attempt rDNS queries to the specified server.
"""
addresses = []
filteredAddresses = []
results = []
for filename in filenames:
try:
f = open(filename, 'rU')
except IOError:
print ('Could not find the specified file:', filename)
sys.exit(1)
# Parse file for valid IPv4 addresses via RegEx
addresses += re.findall(r'(\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b)',f.read())
f.close()
# Count number of occurrences for each IP address
addressCounts = {i:addresses.count(i) for i in addresses}
# Remove duplicates from list
addresses = set(addresses)
for address in addresses:
if (includePrivate == 1):
# Filter list to eliminate bogon addresses, the loopback network, and link local addresses; add results to new list
if not (re.match(r'^0.\d{1,3}.\d{1,3}.\d{1,3}$|^127.\d{1,3}.\d{1,3}.\d{1,3}$|^169.254.\d{1,3}.\d{1,3}$', address)):
filteredAddresses.append(address)
else:
# Filter list to eliminate bogon addresses, the loopback network, link local addresses, and RFC 1918 ranges; add results to new list
if not (re.match(r'^0.\d{1,3}.\d{1,3}.\d{1,3}$|^127.\d{1,3}.\d{1,3}.\d{1,3}$|^169.254.\d{1,3}.\d{1,3}$|^10.\d{1,3}.\d{1,3}.\d{1,3}$|^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$|^192.168.\d{1,3}.\d{1,3}$', address)):
filteredAddresses.append(address)
# Configure the DNS resolver
resolver = dns.resolver.Resolver()
resolver.nameservers = [dnsServer]
resolver.timeout = 1
resolver.lifetime = 1
# Iterate through new list and perform rDNS lookups
for filteredAddress in filteredAddresses:
formattedData = ''
try:
addr = dns.reversename.from_address(filteredAddress)
formattedData = filteredAddress + ',' + str(resolver.query(addr,"PTR")[0]) + ','
except:
formattedData = filteredAddress + ',-,'
# Get number of occurrences for IP address and add to results
addressCount = addressCounts[filteredAddress]
formattedData += str(addressCount)
# Add final formatted data string to list
results.append(formattedData)
if (sortByCount == 1):
# Sort addresses by count (descending)
results = sorted(results, key=lambda x: int(x.split(',')[2]), reverse=True)
# Add column headers
results.insert(0,'IP Address,Hostname,Count')
return results
def printData(results):
rows = list(csv.reader(results))
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
for row in rows:
print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))
def writeData(results,outfile):
try:
f = open(outfile, 'w')
except IOError:
print ('Could not write the specified file:', outfile)
sys.exit(1)
for result in results:
f.write(result + '\n')
f.close()
def checkServer(dnsServer):
# Configure the DNS resolver
resolver = dns.resolver.Resolver()
resolver.nameservers = [dnsServer]
resolver.timeout = 1
resolver.lifetime = 1
try:
answer = resolver.query('google.com', 'A')
success = 1
except dns.resolver.Timeout:
success = 0
return success
def main():
parser = argparse.ArgumentParser(description='Rebeebus - An rDNS lookup utility.', usage='rebeebus.py filename(s) [-d x.x.x.x] [-p] [-w outfile] [-s]', add_help=False)
parser.add_argument('filenames', nargs="*")
requiredArguments = parser.add_argument_group('required arguments')
requiredArguments.add_argument('-d','--dns-server', help='Use the specified DNS server to resolve addresses', required=True)
parser.add_argument('-p', '--include-private', action='store_true', help='Attempt rDNS lookups for RFC 1918 (private) addresses', required=False)
parser.add_argument('-w', '--write', help='Write output to CSV file instead of stdout', required=False)
parser.add_argument('-s', '--sort-by-count', action='store_true', help='Sort addresses by count (descending)', required=False)
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='Show this help message and exit')
args = vars(parser.parse_args())
# Make sure at least one filename was provided
if not (args['filenames']):
parser.print_usage()
parser.exit()
filenames = args['filenames']
includePrivate = 0
writeToFile = 0
sortByCount = 0
if (args['dns_server']):
# Validate provided server IP address
try:
socket.inet_aton(args['dns_server'])
dnsServer = args['dns_server']
except socket.error:
parser.print_usage()
parser.exit()
if (args['include_private']):
includePrivate = 1
if (args['write']):
writeToFile = 1
outfile = args['write']
if (args['sort_by_count']):
sortByCount = 1
# Let's make sure the specified DNS server is working before we go any further ...
success = checkServer(dnsServer)
if (success == 0):
print(dnsServer + ' is not responding to DNS queries. Are you sure that\'s the correct IP address?')
sys.exit(1)
output = getData(filenames,dnsServer,includePrivate,sortByCount)
if (writeToFile == 1):
writeData(output,outfile)
else:
printData(output)
print ('\nCopyright (C) 2018 13Cubed. All rights reserved.')
if __name__ == '__main__':
main()
|
# Default bindings
bindgen --unstable-rust --opaque-type "std.*" --whitelist-type "gvr.*" --whitelist-function "gvr.*" --rustified-enum "gvr.*" -o src/bindings.rs gvr/wrapper.h -- -std=c99 -I/usr/include/clang/3.9/include
# Android bindings
ANDROID_INCLUDES="$ANDROID_NDK/platforms/android-18/arch-arm/usr/include"
bindgen --unstable-rust --opaque-type "std.*" --whitelist-type "gvr.*" --whitelist-function "gvr.*" --rustified-enum "gvr.*" -o src/bindings_android.rs gvr/wrapper.h -- -std=c99 -D__ANDROID__ -I$ANDROID_INCLUDES -I/usr/include/clang/3.9/include |
def search_word(word, dictionary):
if word in dictionary.keys():
return dictionary[word]
else:
return None
dictionary = {'hello': 'string', 'goodbye': 'bye'}
word = 'hello'
result = search_word(word, dictionary)
if result:
print('Word found in dictionary: ' + result)
else:
print('Word not found in dictionary.') |
export const PSEUDO_RETURN = Symbol('TO_BE_DECORATED')
function decorate(condition, newValue) {
return function (func) {
return function (...args) {
const result = func.apply(this, args)
if (condition(result)) {
return newValue
}
return result
}
}
}
function add(a, b) {
return a + b
}
const decoratedAdd = decorate(
(result) => result > 10,
PSEUDO_RETURN
)(add)
console.log(decoratedAdd(3, 5)) // Output: 8
console.log(decoratedAdd(7, 5)) // Output: Symbol(TO_BE_DECORATED) |
#include "SentryHook.h"
#include "fishhook.h"
#include <dispatch/dispatch.h>
#include <execinfo.h>
#include <mach/mach.h>
#include <pthread.h>
// NOTE on accessing thread-locals across threads:
// We save the async stacktrace as a thread local when dispatching async calls,
// but the various crash handlers need to access these thread-locals across threads
// sometimes, which we do here:
// While `pthread_t` is an opaque type, the offset of `thread specific data` (tsd)
// is fixed due to backwards compatibility.
// See:
// https://github.com/apple/darwin-libpthread/blob/c60d249cc84dfd6097a7e71c68a36b47cbe076d1/src/types_internal.h#L409-L432
#if __LP64__
# define TSD_OFFSET 224
#else
# define TSD_OFFSET 176
#endif
static pthread_key_t async_caller_key = 0;
sentrycrash_async_backtrace_t *
sentrycrash_get_async_caller_for_thread(SentryCrashThread thread)
{
const pthread_t pthread = pthread_from_mach_thread_np((thread_t)thread);
void **tsd_slots = (void *)((uint8_t *)pthread + TSD_OFFSET);
return (sentrycrash_async_backtrace_t *)__atomic_load_n(
&tsd_slots[async_caller_key], __ATOMIC_SEQ_CST);
}
void
sentrycrash__async_backtrace_incref(sentrycrash_async_backtrace_t *bt)
{
if (!bt) {
return;
}
__atomic_fetch_add(&bt->refcount, 1, __ATOMIC_SEQ_CST);
}
void
sentrycrash__async_backtrace_decref(sentrycrash_async_backtrace_t *bt)
{
if (!bt) {
return;
}
if (__atomic_fetch_add(&bt->refcount, -1, __ATOMIC_SEQ_CST) == 1) {
sentrycrash__async_backtrace_decref(bt->async_caller);
free(bt);
}
}
sentrycrash_async_backtrace_t *
sentrycrash__async_backtrace_capture(void)
{
sentrycrash_async_backtrace_t *bt = malloc(sizeof(sentrycrash_async_backtrace_t));
bt->refcount = 1;
bt->len = backtrace(bt->backtrace, MAX_BACKTRACE_FRAMES);
sentrycrash_async_backtrace_t *caller = pthread_getspecific(async_caller_key);
sentrycrash__async_backtrace_incref(caller);
bt->async_caller = caller;
return bt;
}
static void (*real_dispatch_async)(dispatch_queue_t queue, dispatch_block_t block);
void
sentrycrash__hook_dispatch_async(dispatch_queue_t queue, dispatch_block_t block)
{
// create a backtrace, capturing the async callsite
sentrycrash_async_backtrace_t *bt = sentrycrash__async_backtrace_capture();
return real_dispatch_async(queue, ^{
// inside the async context, save the backtrace in a thread local for later consumption
pthread_setspecific(async_caller_key, bt);
// call through to the original block
block();
// and decref our current backtrace
pthread_setspecific(async_caller_key, NULL);
sentrycrash__async_backtrace_decref(bt);
});
}
static void (*real_dispatch_async_f)(
dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work);
void
sentrycrash__hook_dispatch_async_f(
dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work)
{
sentrycrash__hook_dispatch_async(queue, ^{ work(context); });
}
static void (*real_dispatch_after)(
dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);
void
sentrycrash__hook_dispatch_after(
dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block)
{
// create a backtrace, capturing the async callsite
sentrycrash_async_backtrace_t *bt = sentrycrash__async_backtrace_capture();
return real_dispatch_after(when, queue, ^{
// inside the async context, save the backtrace in a thread local for later consumption
pthread_setspecific(async_caller_key, bt);
// call through to the original block
block();
// and decref our current backtrace
pthread_setspecific(async_caller_key, NULL);
sentrycrash__async_backtrace_decref(bt);
});
}
static void (*real_dispatch_after_f)(dispatch_time_t when, dispatch_queue_t queue,
void *_Nullable context, dispatch_function_t work);
void
sentrycrash__hook_dispatch_after_f(
dispatch_time_t when, dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work)
{
sentrycrash__hook_dispatch_after(when, queue, ^{ work(context); });
}
static void (*real_dispatch_barrier_async)(dispatch_queue_t queue, dispatch_block_t block);
void
sentrycrash__hook_dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block)
{
// create a backtrace, capturing the async callsite
sentrycrash_async_backtrace_t *bt = sentrycrash__async_backtrace_capture();
return real_dispatch_barrier_async(queue, ^{
// inside the async context, save the backtrace in a thread local for later consumption
pthread_setspecific(async_caller_key, bt);
// call through to the original block
block();
// and decref our current backtrace
pthread_setspecific(async_caller_key, NULL);
sentrycrash__async_backtrace_decref(bt);
});
}
static void (*real_dispatch_barrier_async_f)(
dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work);
void
sentrycrash__hook_dispatch_barrier_async_f(
dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work)
{
sentrycrash__hook_dispatch_barrier_async(queue, ^{ work(context); });
}
static bool hooks_installed = false;
void
sentrycrash_install_async_hooks(void)
{
if (__atomic_exchange_n(&hooks_installed, true, __ATOMIC_SEQ_CST)) {
return;
}
if (pthread_key_create(&async_caller_key, NULL) != 0) {
return;
}
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_async", sentrycrash__hook_dispatch_async, (void *)&real_dispatch_async },
},
1);
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_async_f", sentrycrash__hook_dispatch_async_f,
(void *)&real_dispatch_async_f },
},
1);
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_after", sentrycrash__hook_dispatch_after, (void *)&real_dispatch_after },
},
1);
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_after_f", sentrycrash__hook_dispatch_after_f,
(void *)&real_dispatch_after_f },
},
1);
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_barrier_async", sentrycrash__hook_dispatch_barrier_async,
(void *)&real_dispatch_barrier_async },
},
1);
sentrycrash__hook_rebind_symbols(
(struct rebinding[1]) {
{ "dispatch_barrier_async_f", sentrycrash__hook_dispatch_barrier_async_f,
(void *)&real_dispatch_barrier_async_f },
},
1);
// NOTE: We will *not* hook the following functions:
//
// - dispatch_async_and_wait
// - dispatch_async_and_wait_f
// - dispatch_barrier_async_and_wait
// - dispatch_barrier_async_and_wait_f
//
// Because these functions `will use the stack of the submitting thread` in some cases
// and our thread tracking logic would do the wrong thing in that case.
//
// See:
// https://github.com/apple/swift-corelibs-libdispatch/blob/f13ea5dcc055e5d2d7c02e90d8c9907ca9dc72e1/private/workloop_private.h#L321-L326
}
// TODO: uninstall hooks
|
var searchData=
[
['l',['l',['../unionDFSR__Type.html#a583e3138696be655c46f297e083ece52',1,'DFSR_Type::l()'],['../unionIFSR__Type.html#a8f4e4fe46a9cb9b6c8a6355f9b0938e3',1,'IFSR_Type::l()']]],
['l1pctl',['L1PCTL',['../unionACTLR__Type.html#a5464ac7b26943d2cb868c154b0b1375c',1,'ACTLR_Type']]],
['l1pe',['L1PE',['../unionACTLR__Type.html#aacb87aa6bf093e1ee956342e0cb5903e',1,'ACTLR_Type']]],
['l1radis',['L1RADIS',['../unionACTLR__Type.html#a3800bdd7abfab1a51dcfa7069e245d65',1,'ACTLR_Type']]],
['l2radis',['L2RADIS',['../unionACTLR__Type.html#a947f73d64ebde186b9416fd6dc66bc26',1,'ACTLR_Type']]],
['load',['LOAD',['../structTimer__Type.html#a073457d2d18c2eff93fd12aec81ef20b',1,'Timer_Type']]],
['lock_5fline_5fen',['LOCK_LINE_EN',['../structL2C__310__TypeDef.html#a58357795f3cda2b0063411abc5165804',1,'L2C_310_TypeDef']]],
['lpae',['LPAE',['../unionDFSR__Type.html#add7c7800b87cabdb4a9ecdf41e4469a7',1,'DFSR_Type::LPAE()'],['../unionIFSR__Type.html#a40c5236caf0549cc1cc78945b0b0f131',1,'IFSR_Type::LPAE()']]]
];
|
<gh_stars>0
#from distutils.core import setup
from setuptools import setup
try:
desc = open('README.md').read()
except (IOError, FileNotFoundError) as e:
desc = ''
setup(name='peri',
url='http://github.com/peri-source/peri/',
license='MIT License',
author='<NAME>, <NAME>',
version='0.1.2',
packages=[
'peri', 'peri.mc', 'peri.comp', 'peri.viz',
'peri.priors', 'peri.test', 'peri.opt', 'peri.gui'
],
scripts=['bin/peri'],
install_requires=[
"future>=0.15.0",
"numpy>=1.8.1",
"scipy>=0.14.0",
"matplotlib>=1.0.0",
"pillow>=1.1.7"
],
package_data={
'peri': ['../README.md', 'gui/*.ui']
},
platforms='any',
classifiers = [
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Development Status :: 2 - Pre-Alpha',
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering :: Image Recognition',
'Topic :: Scientific/Engineering :: Physics',
],
description='Parameter Extraction from the Reconstruction of Images',
long_description=desc,
)
|
#!/bin/sh
set -e
if [ "$#" -ne 1 ]; then
echo "ERROR: Illegal number of parameters"
echo "Usage: $0 <inventory-path>"
exit 1
fi
INVENTORY_PATH=$1
#Deploy keycloak
echo "@@@@@@@@@ Keycloak "
ansible-playbook -i $INVENTORY_PATH ../ansible/keycloak.yml --tags deploy --extra-vars=@config.yml
|
<gh_stars>0
/*
EXAMPLE TASK:
- Write an Airplane class whose constructor initializes `name` from an argument.
- All airplanes built with Airplane should initialize with an `isFlying` property of false.
- Give airplanes the ability to `.takeOff()` and `.land()`:
+ If a plane takes off, its `isFlying` property gets set to true.
+ If a plane lands, its `isFlying` property gets set to false.
*/
// EXAMPLE SOLUTION CODE:
class Airplane {
constructor(name) {
this.name = name;
this.isFlying = false;
}
takeOff() {
this.isFlying = true;
}
land() {
this.isFlying = false;
}
}
/*
// 👇 COMPLETE YOUR WORK BELOW 👇
// 👇 COMPLETE YOUR WORK BELOW 👇
// 👇 COMPLETE YOUR WORK BELOW 👇
*/
/*
TASK 1
- Write a Person class whose constructor initializes `name` and `age` from arguments.
- All instances of Person should also initialize with an empty `stomach` array.
- Give instances of Person the ability to `.eat("someFood")`:
+ When eating an edible, it should be pushed into the `stomach`.
+ The `eat` method should have no effect if there are 10 items in the `stomach`.
- Give instances of Person the ability to `.poop()`:
+ When an instance poops, its `stomach` should empty.
- Give instances of Person a method `.toString()`:
+ It should return a string with `name` and `age`. Example: "Mary, 50"
*/
class Person {
}
/*
TASK 2
- Write a Car class whose constructor initializes `model` and `milesPerGallon` from arguments.
- All instances built with Car:
+ should initialize with a `tank` at 0
+ should initialize with an `odometer` at 0
- Give cars the ability to get fueled with a `.fill(gallons)` method. Add the gallons to `tank`.
- Give cars ability to `.drive(distance)`. The distance driven:
+ Should cause the `odometer` to go up.
+ Should cause the the `tank` to go down taking `milesPerGallon` into account.
- A car which runs out of `fuel` while driving can't drive any more distance:
+ The `drive` method should return a string "I ran out of fuel at x miles!" x being `odometer`.
*/
class Car {
}
/*
TASK 3
- Write a Lambdasian class.
- Its constructor takes a single argument - an object with the following keys:
+ name
+ age
+ location
- Its constructor should initialize `name`, `age` and `location` properties on the instance.
- Instances of Lambdasian should be able to `.speak()`:
+ Speaking should return a phrase `Hello my name is {name}, I am from {location}`.
+ {name} and {location} of course come from the instance's own properties.
*/
class Lambdasian {
}
/*
TASK 4
- Write an Instructor class extending Lambdasian.
- Its constructor takes a single argument - an object with the following keys:
+ All the keys used to initialize instances of Lambdasian.
+ `specialty`: what the instance of Instructor is good at, i.e. 'redux'
+ `favLanguage`: i.e. 'JavaScript, Python, Elm etc.'
+ `catchPhrase`: i.e. `Don't forget the homies`.
- The constructor calls the parent constructor passing it what it needs.
- The constructor should also initialize `specialty`, `favLanguage` and `catchPhrase` properties on the instance.
- Instructor instances have the following methods:
+ `demo` receives a `subject` string as an argument and returns the phrase 'Today we are learning about {subject}' where subject is the param passed in.
+ `grade` receives a `student` object and a `subject` string as arguments and returns '{student.name} receives a perfect score on {subject}'
*/
class Instructor {
}
/*
TASK 5
- Write a Student class extending Lambdasian.
- Its constructor takes a single argument - an object with the following keys:
+ All the keys used to initialize instances of Lambdasian.
+ `previousBackground` i.e. what the Student used to do before Lambda School
+ `className` i.e. CS132
+ `favSubjects`. i.e. an array of the student's favorite subjects ['HTML', 'CSS', 'JS']
- The constructor calls the parent constructor passing to it what it needs.
- The constructor should also initialize `previousBackground`, `className` and `favSubjects` properties on the instance.
- Student instances have the following methods:
+ `listSubjects` a method that returns all of the student's favSubjects in a single string: `Loving HTML, CSS, JS!`.
+ `PRAssignment` a method that receives a subject as an argument and returns `student.name has submitted a PR for {subject}`
+ `sprintChallenge` similar to PRAssignment but returns `student.name has begun sprint challenge on {subject}`
*/
class Student {
}
/*
TASK 6
- Write a ProjectManager class extending Instructor.
- Its constructor takes a single argument - an object with the following keys:
+ All the keys used to initialize instances of Instructor.
+ `gradClassName`: i.e. CS1
+ `favInstructor`: i.e. Sean
- Its constructor calls the parent constructor passing to it what it needs.
- The constructor should also initialize `gradClassName` and `favInstructor` properties on the instance.
- ProjectManager instances have the following methods:
+ `standUp` a method that takes in a slack channel and returns `{name} announces to {channel}, @channel standy times!`
+ `debugsCode` a method that takes in a student object and a subject and returns `{name} debugs {student.name}'s code on {subject}`
*/
class ProjectManager {
}
/*
STRETCH PROBLEM (no tests!)
- Extend the functionality of the Student by adding a prop called grade and setting it equal to a number between 1-100.
- Now that our students have a grade build out a method on the Instructor (this will be used by _BOTH_ instructors and PM's) that will randomly add or subtract points to a student's grade. _Math.random_ will help.
- Add a graduate method to a student.
+ This method, when called, will check the grade of the student and see if they're ready to graduate from Lambda School
+ If the student's grade is above a 70% let them graduate! Otherwise go back to grading their assignments to increase their score.
*/
///////// END OF CHALLENGE /////////
///////// END OF CHALLENGE /////////
///////// END OF CHALLENGE /////////
if (typeof exports !== 'undefined') {
module.exports = module.exports || {}
if (Airplane) { module.exports.Airplane = Airplane }
if (Person) { module.exports.Person = Person }
if (Car) { module.exports.Car = Car }
if (Lambdasian) { module.exports.Lambdasian = Lambdasian }
if (Instructor) { module.exports.Instructor = Instructor }
if (Student) { module.exports.Student = Student }
if (ProjectManager) { module.exports.ProjectManager = ProjectManager }
}
|
#!/bin/bash
# Credits: Adapted from https://github.com/choderalab/pymbar/blob/master/devtools/travis-ci/install.sh
# with some modifications
pushd .
cd $HOME
# Install Miniconda
MINICONDA=Miniconda2-latest-Linux-x86_64.sh
if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then MINICONDA=Miniconda2-latest-MacOSX-x86_64.sh; fi
MINICONDA_HOME=$HOME/miniconda
MINICONDA_MD5=$(curl -s https://repo.continuum.io/miniconda/ | grep -A3 $MINICONDA | sed -n '4p' | sed -n 's/ *<td>\(.*\)<\/td> */\1/p')
wget -q http://repo.continuum.io/miniconda/$MINICONDA
if [[ $MINICONDA_MD5 != $(md5sum $MINICONDA | cut -d ' ' -f 1) ]]; then
echo "Miniconda MD5 mismatch"
exit 1
fi
bash $MINICONDA -b -p $MINICONDA_HOME
# Configure miniconda
export PIP_ARGS="-U"
export PATH=$MINICONDA_HOME/bin:$PATH
conda update --yes conda
conda install --yes conda-build jinja2 anaconda-client
popd
|
#!/bin/bash
set -e
# Ask node for headers
HEADERS_URL=$(node -p 'process.release.headersUrl')
# Work out the filename from the URL, as well as the directory without the ".tar.gz" file extension:
rm -rf ./build
mkdir build
HEADERS_TARBALL=./build/`basename "$HEADERS_URL"`
# Download, making sure we download to the same output document, without wget adding "-1" etc. if the file was previously partially downloaded:
echo "Downloading $HEADERS_URL..."
if command -v wget &> /dev/null; then
wget --quiet --show-progress --output-document=$HEADERS_TARBALL $HEADERS_URL
else
curl --silent --progress-bar --output $HEADERS_TARBALL $HEADERS_URL
fi
# Extract and then remove the downloaded tarball:
echo "Extracting $HEADERS_TARBALL..."
tar -xf $HEADERS_TARBALL -C ./build
rm $HEADERS_TARBALL
|
'use strict';
const Sequelize = require('sequelize');
const path = require('path');
const config = require(path.resolve('server/middleware/config/config'));
const sequelize = new Sequelize(config.db.database, config.db.username, config.db.password, config.db.option);
sequelize
.authenticate()
.then(() => {
console.log('Connect to database has been established successfully.');
require(path.resolve('server/middleware/model/model'))(sequelize).forEach((model) => {
sequelize[model.name] = model;
});
return sequelize;
})
.then(() => {
return sequelize.sync();
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = sequelize; |
/*
Build the table with the platform, compiler and core names.
*/
/*
select NB,CATEGORY.category,NAME,CYCLES,PLATFORM.platform,CORE.core,COMPILERKIND.compiler,COMPILER.version,DATE
from BasicBenchmarks
INNER JOIN CATEGORY USING(categoryid)
INNER JOIN PLATFORM USING(platformid)
INNER JOIN CORE USING(coreid)
INNER JOIN COMPILER USING(compilerid)
INNER JOIN COMPILERKIND USING(compilerkindid)
;
*/
/*
Compute the max cycles for a test configuration (category + name)
*/
/*
select NAME,max(CYCLES),PLATFORM.platform,CORE.core,COMPILERKIND.compiler,COMPILER.version
from BasicBenchmarks
INNER JOIN CATEGORY USING(categoryid)
INNER JOIN PLATFORM USING(platformid)
INNER JOIN CORE USING(coreid)
INNER JOIN COMPILER USING(compilerid)
INNER JOIN COMPILERKIND USING(compilerkindid)
GROUP BY NAME,category
;
*/
/*
Get last values
*/
/*
Better to use the ON syntax than the USING syntax.
See diff.sql for example
*/
select NB,CATEGORY.category,NAME,CYCLES,PLATFORM.platform,CORE.core,COMPILERKIND.compiler,COMPILER.version,DATE
from BasicBenchmarks
INNER JOIN CATEGORY USING(categoryid)
INNER JOIN PLATFORM USING(platformid)
INNER JOIN CORE USING(coreid)
INNER JOIN COMPILER USING(compilerid)
INNER JOIN COMPILERKIND USING(compilerkindid)
WHERE DATE BETWEEN datetime('now','localtime','-10 minutes') AND datetime('now', 'localtime');
|
#!/bin/bash
# usage: sbatch job/bridges.sh
#SBATCH -J box-dm
#SBATCH -p RM-small
#SBATCH -N 2
#SBATCH --ntasks-per-node=28
#SBATCH -t 8:00:00
#SBATCH -o gizmo.log
#SBATCH -D .
set -e
module list
spack env activate gizmo
set -x
pwd
date
export I_MPI_JOB_RESPECT_PROCESS_PLACEMENT=0
export MPIRUN="mpirun -n $SLURM_NTASKS -ppn $SLURM_NTASKS_PER_NODE"
if [[ -d output/restartfiles ]]; then
RESTART_FLAG=1
else
RESTART_FLAG=
fi
export RESTART_FLAG
make run-gizmo
date
|
import { Functional } from '../../../../../Class/Functional'
import { Done } from '../../../../../Class/Functional/Done'
import { Config } from '../../../../../Class/Unit/Config'
import { CA } from '../../../../../interface/CA'
export interface I {
canvas: CA
step: any[]
}
export interface O {
i: number
}
export default class Draw extends Functional<I, O> {
constructor(config?: Config) {
super(
{
i: ['canvas', 'step'],
o: [],
},
config,
{
input: {
canvas: {
ref: true,
},
},
}
)
}
f({ canvas, step }: I, done: Done<O>): void {
canvas.draw(step)
done({})
}
}
|
export class WelcomeMessage {
type: string;
content: string;
} |
def process_data_and_call_script(file_name, lower_threshold, upper_threshold):
with open(file_name, 'r') as file:
data = file.read().strip().split()
measurements = [float(val) for val in data]
count_within_range = sum(1 for measurement in measurements if lower_threshold <= measurement <= upper_threshold)
command = f'../../check.rb {file_name} {lower_threshold} {upper_threshold} {count_within_range}'
return command
# Example usage
file_name = 'accept-annulus-coarse-status.txt'
lower_threshold = 0.3
upper_threshold = 3.0
result_command = process_data_and_call_script(file_name, lower_threshold, upper_threshold)
print(result_command) |
<reponame>jessehu/app-autoscaler
'use strict';
var expect = require("chai").expect;
var logger = require('../../../lib/log/logger');
var schemaValidator = require('../../../lib/validation/schemaValidator');
var rewire = require('rewire');
var schemaValidatorPrivate = rewire('../../../lib/validation/schemaValidator');
describe('Validating Policy JSON schema construction',function(){
it('Should validate the getSpecificDateSchema successfully',function(){
var schema = schemaValidatorPrivate.__get__('getSpecificDateSchema')();
expect(schema.id).to.equal('/specific_date');
expect(schema.properties.start_date_time).to.deep.equal({'type':'string','format':'dateTimeFormat'});
expect(schema.properties.end_date_time).to.deep.equal({ 'type':'string','format':'dateTimeFormat' });
expect(schema.properties.instance_min_count).to.deep.equal({ 'type':'integer','minimum':1 });
expect(schema.properties.instance_max_count).to.deep.equal({ 'type':'integer' ,'minimum':1});
expect(schema.properties.initial_min_instance_count).to.deep.equal({ 'type':'integer','minimum':1 });
expect(schema.required).to.deep.equal( ['start_date_time','end_date_time','instance_min_count','instance_max_count']);
});
it('Should validate the getRecurringSchema successfully',function(){
var schema = schemaValidatorPrivate.__get__('getRecurringSchema')();
var weekEnum = schemaValidatorPrivate.__get__('getDaysInWeeksInISOFormat')();
var monthEnum = schemaValidatorPrivate.__get__('getDaysInMonthInISOFormat')();
expect(schema.id).to.equal('/recurring_schedule');
expect(schema.properties.start_time).to.deep.equal({ 'type':'string','format':'timeFormat' });
expect(schema.properties.end_time).to.deep.equal({ 'type':'string','format':'timeFormat' });
expect(schema.properties.instance_min_count).to.deep.equal({ 'type':'integer','minimum':1});
expect(schema.properties.instance_max_count).to.deep.equal({ 'type':'integer','minimum':1});
expect(schema.properties.initial_min_instance_count).to.deep.equal({ 'type':'integer','minimum':1 });
expect(schema.properties.days_of_week).to.deep.equal({ 'type':'array','uniqueItems': true,
'items':{ 'type':'number','enum':weekEnum } });
expect(schema.properties.days_of_month).to.deep.equal({ 'type':'array','uniqueItems': true,
'items':{ 'type':'number','enum':monthEnum } });
expect(schema.properties.start_date).to.deep.equal({'anyOf': [{ 'type':'string', 'format':'dateFormat' },{ 'type':'string', 'enum':[''] } ]});
expect(schema.properties.end_date).to.deep.equal({'anyOf': [ { 'type':'string', 'format':'dateFormat' },{ 'type':'string', 'enum':[''] }]});
expect(schema.required).to.deep.equal(['start_time','end_time','instance_min_count','instance_max_count']);
expect(schema.oneOf).to.deep.equal([ {'required':['days_of_week']}, {'required':['days_of_month']} ]);;
});
it('should validate the getScheduleSchema successfully',function(){
var schema = schemaValidatorPrivate.__get__('getScheduleSchema')();
var timezoneEnum = schemaValidatorPrivate.__get__('getTimeZones')();
expect(schema.id).to.equal('/schedules');
expect(schema.properties.timezone).to.deep.equal({ 'type':'string','format': 'timeZoneFormat' });
expect(schema.properties.recurring_schedule.type).to.equal('array');
expect(schema.properties.recurring_schedule.items).to.deep.equal({ '$ref': '/recurring_schedule' });
expect(schema.properties.recurring_schedule.minItems).to.equal(1);
expect(schema.properties.specific_date.type).to.equal('array');
expect(schema.properties.specific_date.items).to.deep.equal({ '$ref':'/specific_date' });
expect(schema.properties.specific_date.minItems).to.equal(1);
expect(schema.required).to.deep.equal(['timezone']);
expect(schema.anyOf).to.deep.equal([ {'required':["recurring_schedule"]}, {'required':["specific_date"]} ]);
});
it('should validate the getScalingRuleSchema successfully',function(){
var schema = schemaValidatorPrivate.__get__('getScalingRuleSchema')();
var validOperator = schemaValidatorPrivate.__get__('getValidOperators')();
var adjustmentPattern = schemaValidatorPrivate.__get__('getAdjustmentPattern')();
var metricTypeEnum = schemaValidatorPrivate.__get__('getMetricTypes')();
expect(schema.id).to.equal('/scaling_rules');
expect(schema.properties.metric_type).to.deep.equal({ 'type':'string','enum':metricTypeEnum});
expect(schema.properties.stat_window_secs).to.deep.equal({ 'type':'number','minimum': 60,'maximum': 3600 });
expect(schema.properties.breach_duration_secs).to.deep.equal({ 'type':'number','minimum': 60,'maximum': 3600 });
expect(schema.properties.threshold).to.deep.equal({ 'type':'number','minimum': 1,'maximum': 100 });
expect(schema.properties.operator).to.deep.equal({ 'type':'string','enum':validOperator });
expect(schema.properties.cool_down_secs).to.deep.equal({ 'type':'number','minimum': 60,'maximum': 3600 });
expect(schema.properties.adjustment).to.deep.equal({ 'type':'string','pattern':adjustmentPattern });
expect(schema.required).to.deep.equal(['metric_type','threshold','operator','adjustment']);
});
it('should validate the getPolicySchema successfully',function(){
var schema = schemaValidatorPrivate.__get__('getPolicySchema')();
expect(schema.id).to.equal('/policySchema');
expect(schema.properties.instance_min_count).to.deep.equal( { 'type':'integer','minimum':1});
expect(schema.properties.instance_min_count).to.deep.equal( { 'type':'integer','minimum':1 });
expect(schema.properties.scaling_rules.type).to.equal('array');
expect(schema.properties.scaling_rules.items).to.deep.equal({ '$ref': '/scaling_rules' });
expect(schema.properties.schedules).to.deep.equal({ '$ref':'/schedules' });
expect(schema.required).to.deep.equal(['instance_min_count','instance_max_count']);
expect(schema.anyOf).to.deep.equal([{'required':['scaling_rules']},{'required':['schedules']}]);
});
it('should validate the getValidOperators successfully',function(){
var validOperators = schemaValidatorPrivate.__get__('getValidOperators')();
expect(validOperators).to.not.be.null;
expect(validOperators).to.have.members(['<','>','<=','>=']);
});
it('should validate the getAdjustmentPattern successfully',function(){
var adjustmentPattern = schemaValidatorPrivate.__get__('getAdjustmentPattern')();
expect(adjustmentPattern).to.not.be.null;
expect(adjustmentPattern).to.equal('^[-|+][1-9]+[0-9]*$');
});
it('should validate the getDaysInWeeksInISOFormat successfully',function(){
var daysInWeekInISO = schemaValidatorPrivate.__get__('getDaysInWeeksInISOFormat')();
expect(daysInWeekInISO).to.not.be.null;
expect(daysInWeekInISO).to.have.members([1,2,3,4,5,6,7]);
});
it('should validate the getDaysInMonthInISOFormat successfully',function(){
var daysInMonthInISO = schemaValidatorPrivate.__get__('getDaysInMonthInISOFormat')();
expect(daysInMonthInISO).to.not.be.null;
expect(daysInMonthInISO).to.have.members([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23,24,25,26,27,28,29,30,31]);
});
}); |
class ServerManager {
private $endStartDate;
private $queryParameters = [];
public function setEndStartDate($endStartDate) {
$this->endStartDate = $endStartDate;
$this->queryParameters["EndStartDate"] = $endStartDate;
}
public function getServerLockStatus() {
// Implement logic to retrieve server lock status
// For example:
// return $this->serverLockStatus;
}
} |
// Copyright (c) 2015-2016, ETH Zurich, <NAME>, Zurich Eye
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <ze/pangolin/pangolin.hpp>
namespace ze {
//! A change event callback triggered, whenever the value of the wrapped scalar
//! is changed.
template<typename Scalar>
using ChangeEventCallback = std::function<void(Scalar)>;
//! A wrapper for primitive typically numeric types that calls a callback and
//! notifies a pangolin plotter about changes.
//! A pangolin context watching the primitive is only created if the watch
//! is createad with a name or from a value.
template<class T>
class PrimitiveTypeWrapperImpl {
public:
using value_type = T;
PrimitiveTypeWrapperImpl()
: member_name_("Default")
{
}
PrimitiveTypeWrapperImpl(T v)
: value_(v)
, member_name_("Default")
{
initialize();
}
PrimitiveTypeWrapperImpl(T v, bool watch)
: PrimitiveTypeWrapperImpl(v)
{
if (watch)
{
initialize();
}
}
PrimitiveTypeWrapperImpl(const PrimitiveTypeWrapperImpl<T>& rhs)
: PrimitiveTypeWrapperImpl(rhs.value_)
{
}
//! A string constructor to name the context / window of pangolin.
PrimitiveTypeWrapperImpl(const std::string& member_name)
: member_name_(member_name)
{
initialize();
}
operator T() const {return value_;}
void change_callback(T value)
{
ze::PangolinPlotter::instance().log(member_name_, value);
}
// Modifiers
PrimitiveTypeWrapperImpl& operator=(T v) { value_=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator+=(T v) { value_+=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator-=(T v) { value_-=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator*=(T v) { value_*=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator/=(T v) { value_/=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator%=(T v) { value_%=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator++() { ++value_; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator--() { --value_; notify(); return *this; }
PrimitiveTypeWrapperImpl operator++(int) { notify(); return PrimitiveTypeWrapperImpl(value_++, false); }
PrimitiveTypeWrapperImpl operator--(int) { notify(); return PrimitiveTypeWrapperImpl(value_--, false); }
PrimitiveTypeWrapperImpl& operator&=(T v) { value_&=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator|=(T v) { value_|=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator^=(T v) { value_^=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator<<=(T v) { value_<<=v; notify(); return *this; }
PrimitiveTypeWrapperImpl& operator>>=(T v) { value_>>=v; notify(); return *this; }
//accessors
PrimitiveTypeWrapperImpl operator+() const { return PrimitiveTypeWrapperImpl(+value_, false); }
PrimitiveTypeWrapperImpl operator-() const { return PrimitiveTypeWrapperImpl(-value_, false); }
PrimitiveTypeWrapperImpl operator!() const { return PrimitiveTypeWrapperImpl(!value_, false); }
PrimitiveTypeWrapperImpl operator~() const { return PrimitiveTypeWrapperImpl(~value_, false); }
//friends
friend PrimitiveTypeWrapperImpl operator+(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw+=v; }
friend PrimitiveTypeWrapperImpl operator+(PrimitiveTypeWrapperImpl iw, T v) { return iw+=v; }
friend PrimitiveTypeWrapperImpl operator+(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)+=iw; }
friend PrimitiveTypeWrapperImpl operator-(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw-=v; }
friend PrimitiveTypeWrapperImpl operator-(PrimitiveTypeWrapperImpl iw, T v) { return iw-=v; }
friend PrimitiveTypeWrapperImpl operator-(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)-=iw; }
friend PrimitiveTypeWrapperImpl operator*(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw*=v; }
friend PrimitiveTypeWrapperImpl operator*(PrimitiveTypeWrapperImpl iw, T v) { return iw*=v; }
friend PrimitiveTypeWrapperImpl operator*(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)*=iw; }
friend PrimitiveTypeWrapperImpl operator/(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw/=v; }
friend PrimitiveTypeWrapperImpl operator/(PrimitiveTypeWrapperImpl iw, T v) { return iw/=v; }
friend PrimitiveTypeWrapperImpl operator/(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)/=iw; }
friend PrimitiveTypeWrapperImpl operator%(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw%=v; }
friend PrimitiveTypeWrapperImpl operator%(PrimitiveTypeWrapperImpl iw, T v) { return iw%=v; }
friend PrimitiveTypeWrapperImpl operator%(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)%=iw; }
friend PrimitiveTypeWrapperImpl operator&(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw&=v; }
friend PrimitiveTypeWrapperImpl operator&(PrimitiveTypeWrapperImpl iw, T v) { return iw&=v; }
friend PrimitiveTypeWrapperImpl operator&(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)&=iw; }
friend PrimitiveTypeWrapperImpl operator|(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw|=v; }
friend PrimitiveTypeWrapperImpl operator|(PrimitiveTypeWrapperImpl iw, T v) { return iw|=v; }
friend PrimitiveTypeWrapperImpl operator|(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)|=iw; }
friend PrimitiveTypeWrapperImpl operator^(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw^=v; }
friend PrimitiveTypeWrapperImpl operator^(PrimitiveTypeWrapperImpl iw, T v) { return iw^=v; }
friend PrimitiveTypeWrapperImpl operator^(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)^=iw; }
friend PrimitiveTypeWrapperImpl operator<<(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw<<=v; }
friend PrimitiveTypeWrapperImpl operator<<(PrimitiveTypeWrapperImpl iw, T v) { return iw<<=v; }
friend PrimitiveTypeWrapperImpl operator<<(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)<<=iw;}
friend PrimitiveTypeWrapperImpl operator>>(PrimitiveTypeWrapperImpl iw, PrimitiveTypeWrapperImpl v) { return iw>>=v; }
friend PrimitiveTypeWrapperImpl operator>>(PrimitiveTypeWrapperImpl iw, T v) { return iw>>=v; }
friend PrimitiveTypeWrapperImpl operator>>(T v, PrimitiveTypeWrapperImpl iw) { return PrimitiveTypeWrapperImpl(v, false)>>=iw; }
//! Set the callback to trigger on change.
void setChangeCallback(ChangeEventCallback<T> change_cb)
{
change_cb_ = change_cb;
}
private:
//! The value wrapped by the object.
T value_;
//! The identifier / variable name wrapped in the object and also used for
//! identification of the plot wrt. to pangolin.
const std::string member_name_;
//! A callback triggered when the primitive changes.
ChangeEventCallback<T> change_cb_;
//! Notifiy helper function that calls the callback if defined.
void notify()
{
if (change_cb_)
{
change_cb_(value_);
}
}
//! Initialize the pangolin logging callbacks on change.
void initialize()
{
this->setChangeCallback(std::bind(&PrimitiveTypeWrapperImpl<T>::change_callback,
this,
std::placeholders::_1));
}
};
typedef PrimitiveTypeWrapperImpl<int> intWrapper;
typedef PrimitiveTypeWrapperImpl<unsigned> uintWrapper;
typedef PrimitiveTypeWrapperImpl<short> shortWrapper;
typedef PrimitiveTypeWrapperImpl<char> charWrapper;
typedef PrimitiveTypeWrapperImpl<unsigned long long> ullWrapper;
typedef PrimitiveTypeWrapperImpl<float> floatWrapper;
typedef PrimitiveTypeWrapperImpl<double> doubleWrapper;
typedef PrimitiveTypeWrapperImpl<long double> longDoubleWrapper;
} // namespace ze
|
def print_fibonacci(n):
# Negative numbers are not allowed
if n < 0:
print("Incorrect input")
# Initial two numbers of the series
a = 0
b = 1
# Print the series up to the given number
print("Fibonacci series up to", n, ":")
while a < n:
print(a, end=" ")
c = a + b
a = b
b = c
# Driver Code
n = int(input("Enter a number: "))
print_fibonacci(n) |
#!/bin/sh
nohup python run.py --config=testing_config.py --mode=train > output.txt 2>&1 &
|
#!/bin/bash
set -e
NAME=simple_link
INSTALL_DIR=/usr/local/code/faasm/wasm/rust/$NAME
mkdir -p $INSTALL_DIR
# Depending on whether we are in the Rust-Faasm workspace or not
if [[ -d target ]]; then
cp target/wasm32-unknown-unknown/debug/faasm-sys.wasm $INSTALL_DIR/function.wasm
else
cp ../target/wasm32-unknown-unknown/debug/faasm-sys.wasm $INSTALL_DIR/function.wasm
fi
# Faasm toolchain as usual, could use inv too
codegen_func rust $NAME
simple_runner rust $NAME
|
<gh_stars>0
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package Notification;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Property;
import android.view.Gravity;
import android.view.View;
import com.demo.remind.R;
/**
* A {@link View} that draws primitive circles.
*/
public class CircleView extends View {
/**
* A Property wrapper around the fillColor functionality handled by the
* {@link #setFillColor(int)} and {@link #getFillColor()} methods.
*/
public final static Property<CircleView, Integer> FILL_COLOR =
new Property<CircleView, Integer>(Integer.class, "fillColor") {
@Override
public Integer get(CircleView view) {
return view.getFillColor();
}
@Override
public void set(CircleView view, Integer value) {
view.setFillColor(value);
}
};
/**
* A Property wrapper around the radius functionality handled by the
* {@link #setRadius(float)} and {@link #getRadius()} methods.
*/
public final static Property<CircleView, Float> RADIUS =
new Property<CircleView, Float>(Float.class, "radius") {
@Override
public Float get(CircleView view) {
return view.getRadius();
}
@Override
public void set(CircleView view, Float value) {
view.setRadius(value);
}
};
/**
* The {@link Paint} used to draw the circle.
*/
private final Paint mCirclePaint = new Paint();
private int mGravity;
private float mCenterX;
private float mCenterY;
private float mRadius;
public CircleView(Context context) {
this(context, null /* attrs */);
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0 /* defStyleAttr */);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.CircleView, defStyleAttr, 0 /* defStyleRes */);
mGravity = a.getInt(R.styleable.CircleView_android_gravity, Gravity.NO_GRAVITY);
mCenterX = a.getDimension(R.styleable.CircleView_centerX, 0.0f);
mCenterY = a.getDimension(R.styleable.CircleView_centerY, 0.0f);
mRadius = a.getDimension(R.styleable.CircleView_radius, 0.0f);
mCirclePaint.setColor(a.getColor(R.styleable.CircleView_fillColor, Color.WHITE));
a.recycle();
}
@Override
public void onRtlPropertiesChanged(int layoutDirection) {
super.onRtlPropertiesChanged(layoutDirection);
if (mGravity != Gravity.NO_GRAVITY) {
applyGravity(mGravity, layoutDirection);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mGravity != Gravity.NO_GRAVITY) {
applyGravity(mGravity, getLayoutDirection());
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw the circle, duh
canvas.drawCircle(mCenterX, mCenterY, mRadius, mCirclePaint);
}
@Override
public boolean hasOverlappingRendering() {
// only if we have a background, which we shouldn't...
return getBackground() != null;
}
/**
* @return the current {@link Gravity} used to align/size the circle
*/
public final int getGravity() {
return mGravity;
}
/**
* Describes how to align/size the circle relative to the view's bounds. Defaults to
* {@link Gravity#NO_GRAVITY}.
* <p/>
* Note: using {@link #setCenterX(float)}, {@link #setCenterY(float)}, or
* {@link #setRadius(float)} will automatically clear any conflicting gravity bits.
*
* @param gravity the {@link Gravity} flags to use
* @return this object, allowing calls to methods in this class to be chained
* @see
*/
public CircleView setGravity(int gravity) {
if (mGravity != gravity) {
mGravity = gravity;
if (gravity != Gravity.NO_GRAVITY && isLayoutDirectionResolved()) {
applyGravity(gravity, getLayoutDirection());
}
}
return this;
}
/**
* @return the ARGB color used to fill the circle
*/
public final int getFillColor() {
return mCirclePaint.getColor();
}
/**
* Sets the ARGB color used to fill the circle and invalidates only the affected area.
*
* @param color the ARGB color to use
* @return this object, allowing calls to methods in this class to be chained
* @see
*/
public CircleView setFillColor(int color) {
if (mCirclePaint.getColor() != color) {
mCirclePaint.setColor(color);
// invalidate the current area
invalidate(mCenterX, mCenterY, mRadius);
}
return this;
}
/**
* Sets the x-coordinate for the center of the circle and invalidates only the affected area.
*
* @param centerX the x-coordinate to use, relative to the view's bounds
* @return this object, allowing calls to methods in this class to be chained
* @see
*/
public CircleView setCenterX(float centerX) {
final float oldCenterX = mCenterX;
if (oldCenterX != centerX) {
mCenterX = centerX;
// invalidate the old/new areas
invalidate(oldCenterX, mCenterY, mRadius);
invalidate(centerX, mCenterY, mRadius);
}
// clear the horizontal gravity flags
mGravity &= ~Gravity.HORIZONTAL_GRAVITY_MASK;
return this;
}
/**
* Sets the y-coordinate for the center of the circle and invalidates only the affected area.
*
* @param centerY the y-coordinate to use, relative to the view's bounds
* @return this object, allowing calls to methods in this class to be chained
* @see
*/
public CircleView setCenterY(float centerY) {
final float oldCenterY = mCenterY;
if (oldCenterY != centerY) {
mCenterY = centerY;
// invalidate the old/new areas
invalidate(mCenterX, oldCenterY, mRadius);
invalidate(mCenterX, centerY, mRadius);
}
// clear the vertical gravity flags
mGravity &= ~Gravity.VERTICAL_GRAVITY_MASK;
return this;
}
/**
* @return the radius of the circle
*/
public final float getRadius() {
return mRadius;
}
/**
* Sets the radius of the circle and invalidates only the affected area.
*
* @param radius the radius to use
* @return this object, allowing calls to methods in this class to be chained
* @see
*/
public CircleView setRadius(float radius) {
final float oldRadius = mRadius;
if (oldRadius != radius) {
mRadius = radius;
// invalidate the old/new areas
invalidate(mCenterX, mCenterY, oldRadius);
if (radius > oldRadius) {
invalidate(mCenterX, mCenterY, radius);
}
}
// clear the fill gravity flags
if ((mGravity & Gravity.FILL_HORIZONTAL) == Gravity.FILL_HORIZONTAL) {
mGravity &= ~Gravity.FILL_HORIZONTAL;
}
if ((mGravity & Gravity.FILL_VERTICAL) == Gravity.FILL_VERTICAL) {
mGravity &= ~Gravity.FILL_VERTICAL;
}
return this;
}
/**
* Invalidates the rectangular area that circumscribes the circle defined by {@code centerX},
* {@code centerY}, and {@code radius}.
*/
private void invalidate(float centerX, float centerY, float radius) {
invalidate((int) (centerX - radius - 0.5f), (int) (centerY - radius - 0.5f),
(int) (centerX + radius + 0.5f), (int) (centerY + radius + 0.5f));
}
/**
* Applies the specified {@code gravity} and {@code layoutDirection}, adjusting the alignment
* and size of the circle depending on the resolved {@link Gravity} flags. Also invalidates the
* affected area if necessary.
*
* @param gravity the {@link Gravity} the {@link Gravity} flags to use
* @param layoutDirection the layout direction used to resolve the absolute gravity
*/
@SuppressLint("RtlHardcoded")
private void applyGravity(int gravity, int layoutDirection) {
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final float oldRadius = mRadius;
final float oldCenterX = mCenterX;
final float oldCenterY = mCenterY;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
mCenterX = 0.0f;
break;
case Gravity.CENTER_HORIZONTAL:
case Gravity.FILL_HORIZONTAL:
mCenterX = getWidth() / 2.0f;
break;
case Gravity.RIGHT:
mCenterX = getWidth();
break;
}
switch (absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.TOP:
mCenterY = 0.0f;
break;
case Gravity.CENTER_VERTICAL:
case Gravity.FILL_VERTICAL:
mCenterY = getHeight() / 2.0f;
break;
case Gravity.BOTTOM:
mCenterY = getHeight();
break;
}
switch (absoluteGravity & Gravity.FILL) {
case Gravity.FILL:
mRadius = Math.min(getWidth(), getHeight()) / 2.0f;
break;
case Gravity.FILL_HORIZONTAL:
mRadius = getWidth() / 2.0f;
break;
case Gravity.FILL_VERTICAL:
mRadius = getHeight() / 2.0f;
break;
}
if (oldCenterX != mCenterX || oldCenterY != mCenterY || oldRadius != mRadius) {
invalidate(oldCenterX, oldCenterY, oldRadius);
invalidate(mCenterX, mCenterY, mRadius);
}
}
}
|
<gh_stars>0
package pulse.problem.schemes.rte;
import static pulse.math.MathUtils.fastPowLoop;
import org.apache.commons.math3.analysis.UnivariateFunction;
import pulse.problem.statements.NonlinearProblem;
import pulse.problem.statements.Pulse2D;
/**
* Contains methods for calculating the integral spectral characteristics of a
* black body with a specific spatial temperature profile. The latter is managed
* using a {@code UnivariateFunction} previously generated with a
* {@code SplineInterpolator}.
*
*/
public class BlackbodySpectrum {
private double reductionFactor;
private UnivariateFunction interpolation;
/**
* Creates a {@code BlackbodySpectrum}. Calculates the reduction factor
* <math>δ<i>T</i><sub>m</sub>/<i>T</i><sub>0</sub></math>, which is
* needed for calculations of the maximum heating. Note the interpolation
* needs to be set
*
* @param p a problem statement
*/
public BlackbodySpectrum(NonlinearProblem p) {
final double maxHeating = p.getProperties().maximumHeating((Pulse2D) p.getPulse());
reductionFactor = maxHeating / ((double) p.getProperties().getTestTemperature().getValue());
}
/**
* Calculates the spectral radiance, which is equal to the spectral power
* divided by π, at the given coordinate.
*
* @param x the geometric coordinate at which calculation should be
* performed
* @return the spectral radiance at {@code x}
*/
public double radianceAt(double x) {
return radiance(interpolation.value(x));
}
/**
* Calculates the emissive power at the given coordinate. This is equal to
* <math>0.25 <i>T</i><sub>0</sub>/δ<i>T</i><sub>m</sub> [1
* +δ<i>T</i><sub>m</sub> /<i>T</i><sub>0</sub> θ (<i>x</i>)
* ]<sup>4</sup></math>, where θ is the reduced temperature.
*
* @param x the geometric coordinate inside the sample
* @return the local emissive power value
*/
public double powerAt(double x) {
return emissivePower(interpolation.value(x));
}
/**
* Sets a new function for the spatial temperature profile. The function is
* generally constructed using a {@code SplineInterpolator}
*
* @param interpolation
*/
public void setInterpolation(UnivariateFunction interpolation) {
this.interpolation = interpolation;
}
public UnivariateFunction getInterpolation() {
return interpolation;
}
@Override
public String toString() {
return "[" + getClass().getSimpleName() + ": Rel. heating = " + reductionFactor + "]";
}
private double emissivePower(double reducedTemperature) {
return 0.25 / reductionFactor * fastPowLoop(1.0 + reducedTemperature * reductionFactor, 4);
}
private double radiance(double reducedTemperature) {
return emissivePower(reducedTemperature) / Math.PI;
}
}
|
<reponame>zhaoyb/LinkAgent<filename>instrument-modules/user-modules/module-rabbitmq/src/main/java/com/pamirs/attach/plugin/rabbitmq/common/ChannelHolder.java
/**
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: <EMAIL>
* 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,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pamirs.attach.plugin.rabbitmq.common;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.ChannelN;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeoutException;
/**
* 负责与业务 Channel 一对一进行映射,防止直接操作业务 Channel 导致 Channel 关闭的问题
*
* @author xiaobin.zfb|<EMAIL>
* @since 2020/11/25 2:34 下午
*/
public class ChannelHolder {
private final static Logger LOGGER = LoggerFactory.getLogger(ChannelHolder.class);
public static final Object NULL_OBJECT = new Object();
private static ConcurrentHashMap<Integer, ConcurrentMap<String, Object>> consumerTags = new ConcurrentHashMap<Integer, ConcurrentMap<String, Object>>();
private static ConcurrentHashMap<String, String> queueTags = new ConcurrentHashMap<String, String>();
private static ConcurrentHashMap<Integer, Channel> channelCache = new ConcurrentHashMap<Integer, Channel>();
/**
* 业务 consumerTag -> 影子 consumerTag
*/
private static ConcurrentHashMap<String, String> shadowTags = new ConcurrentHashMap<String, String>();
public static void release() {
consumerTags.clear();
queueTags.clear();
for (Map.Entry<Integer, Channel> entry : channelCache.entrySet()) {
if (entry.getValue() != null && entry.getValue().isOpen()) {
try {
entry.getValue().close();
} catch (Throwable e) {
LOGGER.error("rabbitmq close shadow channel error.", e);
}
}
}
channelCache.clear();
}
public static String getQueueByTag(String consumerTag) {
return queueTags.get(consumerTag);
}
/**
* 向当前连接绑定一个 consumerTag
*
* @param target
* @param businessConsumerTag 业务的 consumerTag
* @param shadowConsumerTag 影子 consumerTag
* @param queue 业务 queue 名称
*/
public static void addConsumerTag(Channel target, String businessConsumerTag, String shadowConsumerTag, String queue) {
int identityCode = System.identityHashCode(target);
Channel shadowChannel = channelCache.get(identityCode);
if (shadowChannel == null) {
return;
}
int key = System.identityHashCode(shadowChannel);
ConcurrentMap<String, Object> tags = consumerTags.get(key);
if (tags == null) {
tags = new ConcurrentHashMap<String, Object>();
ConcurrentMap<String, Object> oldTags = consumerTags.putIfAbsent(key, tags);
if (oldTags != null) {
tags = oldTags;
}
}
tags.put(shadowConsumerTag, NULL_OBJECT);
/**
* 防止并发情况,有其他的 在移除 ConsumerTag 可能导致该 Set 从 consumerTags 里面被移除
*/
consumerTags.put(key, tags);
queueTags.put(shadowConsumerTag, queue);
shadowTags.put(businessConsumerTag, shadowConsumerTag);
}
/**
* 增加影子消费者的订阅
*
* @param target
* @param ptQueue
* @param autoAck
* @param consumerTag
* @param noLocal
* @param exclusive
* @param arguments
* @param callback
* @return 返回 consumerTag
*/
public static String consumeShadowQueue(Channel target, String ptQueue, boolean autoAck, String consumerTag, boolean noLocal, boolean exclusive, Map<String, Object> arguments, Consumer callback) throws IOException {
Channel shadowChannel = getShadowChannel(target);
if (shadowChannel == null || !shadowChannel.isOpen()) {
LOGGER.warn("rabbitmq basicConsume failed. cause by shadow channel is not found or closed. queue={}, consumerTag={}", ptQueue, consumerTag);
return null;
}
String result = shadowChannel.basicConsume(ptQueue, autoAck, consumerTag, noLocal, exclusive, arguments, callback);
final int key = System.identityHashCode(shadowChannel);
ConfigCache.putQueue(key, ptQueue);
return result;
}
/**
* 取消影子 consumer 的订阅,取消后会移除 consumerTag 的缓存
*
* @param target 业务 channel
* @param consumerTag consumerTag
*/
public static void cancelShadowConsumerTag(Channel target, String consumerTag) {
Channel shadowChannel = getShadowChannel(target);
if (shadowChannel == null || !shadowChannel.isOpen()) {
LOGGER.warn("rabbitmq basicCancel failed. cause by shadow channel is not found or closed. consumerTag={}", consumerTag);
return;
}
try {
shadowChannel.basicCancel(consumerTag);
} catch (IOException e) {
LOGGER.error("rabbitmq basicCancel shadow consumer error. consumerTag={}", consumerTag, e);
}
removeConsumerTag(target, consumerTag);
}
/**
* 移除 ChannelN对应的 ConsumerTag
*
* @param target
* @param consumerTag
*/
public static void removeConsumerTag(Channel target, String consumerTag) {
int identityCode = System.identityHashCode(target);
Channel shadowChannel = channelCache.get(identityCode);
if (shadowChannel == null) {
return;
}
int key = System.identityHashCode(shadowChannel);
ConcurrentMap<String, Object> tags = consumerTags.get(key);
if (tags == null) {
return;
}
tags.remove(consumerTag);
if (tags.isEmpty()) {
consumerTags.remove(key);
}
}
/**
* 判断当前连接有没有此 consumerTag
*
* @param target
* @param consumerTag
* @return
*/
public static boolean isExistsConsumerTag(ChannelN target, String consumerTag) {
int identityCode = System.identityHashCode(target);
Channel shadowChannel = channelCache.get(identityCode);
if (shadowChannel == null) {
return false;
}
int key = System.identityHashCode(shadowChannel);
ConcurrentMap<String, Object> tags = consumerTags.get(key);
if (tags == null) {
return false;
}
return tags.containsKey(consumerTag);
}
/**
* 检测 queue 是否存在,与业务 Channel 隔离开来
* 如果获取Channel 失败,则直接返回 false
*
* @param target 业务 Channel
* @param queue 检测的 Queue
* @return 返回 queue 是否存在
*/
public static boolean isQueueExists(Channel target, String queue) {
Channel channel = getShadowChannel(target);
if (channel == null) {
return false;
}
try {
channel.queueDeclarePassive(queue);
return true;
} catch (Throwable e) {
return false;
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
} catch (TimeoutException e) {
} catch (Throwable e) {
}
}
}
}
/**
* 根据业务的 consumerTag 判断该 consumer 是否已经存在影子消费者
*
* @param consumerTag 业务 consumerTag
* @return 返回是否已经存在影子 Consumer
*/
public static boolean existsConsumer(String consumerTag) {
return shadowTags.containsKey(consumerTag);
}
/**
* 获取影子 Channel
*
* @param target
* @return
*/
public static Channel getShadowChannel(Channel target) {
if (target == null || !target.isOpen()) {
return null;
}
int key = System.identityHashCode(target);
Channel shadowChannel = channelCache.get(key);
if (shadowChannel == null || !shadowChannel.isOpen()) {
Channel channel = null;
try {
channel = target.getConnection().createChannel();
} catch (IOException e) {
return null;
}
Channel old = channelCache.putIfAbsent(key, channel);
if (old != null) {
if (!old.isOpen()) {
channelCache.put(key, channel);
} else {
try {
channel.close();
} catch (Throwable e) {
}
channel = old;
}
}
return channel;
}
return shadowChannel;
}
}
|
source $stdenv/setup
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
|
#ifndef LLVM_TRANSFORMS_MY_NEW_PASS_H
#define LLVM_TRANSFORMS_MY_NEW_PASS_H
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/PassPlugin.h"
namespace llvm {
class MyNewPass : public PassInfoMixin<MyNewPass> {
public:
static char ID;
PreservedAnalyses run(
Function &F,
FunctionAnalysisManager &FAM
);
static bool isRequired() { return true; }
};
}
#endif
|
module Arbre
module HTML
AUTO_BUILD_ELEMENTS = [ :a, :abbr, :address, :area, :article, :aside, :audio, :b, :base,
:bdo, :blockquote, :body, :br, :button, :canvas, :caption, :cite,
:code, :col, :colgroup, :command, :datalist, :dd, :del, :details,
:dfn, :div, :dl, :dt, :em, :embed, :fieldset, :figcaption, :figure,
:footer, :form, :h1, :h2, :h3, :h4, :h5, :h6, :head, :header, :hgroup,
:hr, :html, :i, :iframe, :img, :input, :ins, :keygen, :kbd, :label,
:legend, :li, :link, :map, :mark, :menu, :meta, :meter, :nav, :noscript,
:object, :ol, :optgroup, :option, :output, :pre, :progress, :q,
:s, :samp, :script, :section, :select, :small, :source, :span,
:strong, :style, :sub, :summary, :sup, :table, :tbody, :td,
:textarea, :tfoot, :th, :thead, :time, :title, :tr, :ul, :var, :video ]
HTML5_ELEMENTS = [ :p ] + AUTO_BUILD_ELEMENTS
AUTO_BUILD_ELEMENTS.each do |name|
class_eval <<-EOF
class #{name.to_s.capitalize} < Tag
builder_method :#{name}
end
EOF
end
class P < Tag
builder_method :para
end
class Table < Tag
def initialize(*)
super
set_table_tag_defaults
end
protected
# Set some good defaults for tables
def set_table_tag_defaults
set_attribute :border, 0
set_attribute :cellspacing, 0
set_attribute :cellpadding, 0
end
end
end
end
|
using UnityEngine;
public class MyClass : MonoBehaviour
{
public GameObject cubePrefab;
// Start is called before the first frame update
void Start()
{
// Instantiate the cube
GameObject cube = Instantiate(cubePrefab);
// Rotate the cube
cube.transform.Rotate(0f, 45f, 0f);
}
} |
<reponame>eden-lab/eden-archetype<gh_stars>1-10
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.dao.repository.mybatis;
// 关系数据库
|
#!/usr/bin/env bash
#
# The entrypoint script is what docker will use
# to set the environment before it is used. In this case,
# we:
#
# 1. Ensure that all required environments are present
# 2. That the project contains a configuration folder and configuration file
# 3. Optionally invite the user to create an environment folder
# if it does not exist
# 4. Set up additional environment variables and create some configuration
# files dynamically
# 5. Run the requested command, or open a shell if no command were given
#
set -e
# The project name is mostly used for informational purposes,
# but users may want to use this value to determine how
# their tools (Ansible, Terraform, etc) should run.
if
[ "${PROJECT_NAME}" == "" ]
then
echo "The PROJECT_NAME environment variable is not set; quitting."
exit 1
fi
# We need to know which environment files to use;
# If the PROJECT_ENVIRONMENT shell environment variable
# is not set, there is nothing else we can do.
if
[ "${PROJECT_ENVIRONMENT}" == "" ]
then
echo "The PROJECT_ENVIRONMENT environment variable is not set; quitting."
exit 1
fi
# Go to the scripts folder
pushd ./scripts/ > /dev/null
# Store the command we have received, and create
# a variable holding the path to the environment files
# in the project
export COMMAND="${@}"
export PROJECT_ENVIRONMENT_FILES_PATH="${PROJECT_FILES_PATH}/${PROJECT_ENVIRONMENT}"
# We make sure that the base directory structure is present,
# and that a configuration file is indeed present.
if
[ ! -f "${PROJECT_CONFIG_FILE_PATH}" ]
then
echo "Your project does not appear to have been initialized;"
echo "There should be a ./${CONFIG_FOLDER} folder at the top-level of your project,"
echo "and a ./${CONFIG_FOLDER}/${CONFIG_FILENAME} file needs to be present."
exit 1
fi
# If the environment folder does not exist,
# we invite the user to create it
if
[ ! -d "${PROJECT_ENVIRONMENT_FILES_PATH}" ]
then
source ./create_environment.sh
fi
popd > /dev/null
# We finally downgrade the user and run the
# command. The reason for this is twofold:
#
# 1. Avoid unintentional changes to files put on the container.
# 2. (Windows) file permissions for ALL mounted files
# is 0755; this means that running as root in the container
# and trying to ssh to a remote server using an ssh key on the
# mounted file system will result in "bad permission" error.
#
# Note that create.sh and run.sh do run as root; only the user's
# shell is downgraded to the shell user.
#
# Ref: https://github.com/docker/docker/issues/27685#issuecomment-256648694
#
pushd ${PROJECT_ENVIRONMENT_FILES_PATH} > /dev/null
# We install the latest bash profile in the user home so that each user gets the
# same behaviour
cp "${ROOT_FOLDER}/scripts/user_bash_profile.sh" "/home/${SHELL_USER}/.bash_profile"
# Some scripts might pass complex arguments that need to be safely escaped before
# being passed to bash -c, example is gitlab passing 'sh -c "if true; then foo; fi"'
# that will fail when passed directly, thankfully printf on bash supports the %q format
# sequence that allows converting an argument to a safe string to be used as shell
# input
#
# Ref: https://stackoverflow.com/questions/34271519/passing-arguments-to-bash-c-with-spaces
#
printf -v SAFE_COMMAND '%q ' "${@}"
sudo -H -E -u ${SHELL_USER} bash --login -c "$SAFE_COMMAND"
popd > /dev/null
|
module.exports = async function (message, tokens, command, client) {
require("dotenv").config();
const cc = require('../bot');
const Discord = require('discord.js');
const channel = "845386774327197726";
const config = require('../config.json');
if (message.author.id == process.env.OWNER) {
const HOTSRole = message.guild.roles.cache.find(role => role.name === "HOTS");
const LOLRole = message.guild.roles.cache.find(role => role.name === "LOL");
const HuntRole = message.guild.roles.cache.find(role => role.name === "Hunt");
const OverwatchRole = message.guild.roles.cache.find(role => role.name === "Overwatch");
const StarCraft2Role = message.guild.roles.cache.find(role => role.name === "StarCraft2");
const NorthgardRole = message.guild.roles.cache.find(role => role.name === "Northgard");
const RocketLeagueRole = message.guild.roles.cache.find(role => role.name === "Rocket League");
const TarkovRole = message.guild.roles.cache.find(role => role.name === "Tarkov");
const RemmantRole = message.guild.roles.cache.find(role => role.name === "Remnant");
const MemberEmoji = '';
const HOTSEmoji = `${config.emoji.one}`;
const LOLEmoji = `${config.emoji.two}`;
const HuntEmoji = `${config.emoji.three}`;
const OverwatchEmoji = `${config.emoji.four}`;
const StarCraft2Emoji = `${config.emoji.five}`;
const NorthgardEmoji = `${config.emoji.six}`;
const RocketLeagueEmoji = `${config.emoji.seven}`;
const TarkovEmoji = `${config.emoji.eight}`;
const RemmantEmoji = `${config.emoji.nine}`;
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`After reading the #rules click ${MemberEmoji}`)
.setDescription(`
${HOTSEmoji} Heroes of the Storm\n
${LOLEmoji} League of Legends\n
${HuntEmoji} Hunt Showdown\n
${OverwatchEmoji} Overwatch\n
${StarCraft2Emoji} StarCraft 2\n
${NorthgardEmoji} Northgard\n
${RocketLeagueEmoji} Rocket League\n
${TarkovEmoji} Escape from Tarkov\n
${RemmantEmoji} Remmant\n`);
let messageEmbed = await message.channel.send(embed);
messageEmbed.react(HOTSEmoji);
messageEmbed.react(LOLEmoji);
messageEmbed.react(HuntEmoji);
messageEmbed.react(OverwatchEmoji);
messageEmbed.react(StarCraft2Emoji);
messageEmbed.react(NorthgardEmoji);
messageEmbed.react(RocketLeagueEmoji);
messageEmbed.react(TarkovEmoji);
messageEmbed.react(RemmantEmoji);
cc.client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === HOTSEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(HOTSRole);
};
if (reaction.emoji.name === LOLEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(LOLRole);
};
if (reaction.emoji.name === HuntEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(HuntRole);
};
if (reaction.emoji.name === OverwatchEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(OverwatchRole);
};
if (reaction.emoji.name === StarCraft2Emoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(StarCraft2Role);
};
if (reaction.emoji.name === NorthgardEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(NorthgardRole);
};
if (reaction.emoji.name === RocketLeagueEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(RocketLeagueRole);
};
if (reaction.emoji.name === TarkovEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(TarkovRole);
};
if (reaction.emoji.name === RemmantEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(RemmantRole);
};
} else {
return;
};
});
cc.client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === MemberEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(MemberRole);
};
if (reaction.emoji.name === HOTSEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(HOTSRole);
};
if (reaction.emoji.name === LOLEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(LOLRole);
};
if (reaction.emoji.name === HuntEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(HuntRole);
};
if (reaction.emoji.name === OverwatchEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(OverwatchRole);
};
if (reaction.emoji.name === StarCraft2Emoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(StarCraft2Role);
};
if (reaction.emoji.name === NorthgardEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(NorthgardRole);
};
if (reaction.emoji.name === RocketLeagueEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(RocketLeagueRole);
};
if (reaction.emoji.name === TarkovEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(TarkovRole);
};
if (reaction.emoji.name === RemmantEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(RemmantRole);
};
} else {
return;
};
});
};
}; |
/*
应用通用功能
*/
// 判断地址栏是否有lang参数,没有则跳转到带lang参数的地址
if(MET['url']['basepath']){
var str=window.parent.document.URL,
s=str.indexOf("lang="+M['lang']),
z=str.indexOf("lang");
if (s=='-1' && z!='-1') {
var s1=str.indexOf('#');
if (s1=='-1') {
str=str.replace(/(lang=[^#]*)/g, "lang="+M['lang']+"#");
}
str=str.replace(/(lang=[^#]*#)/g, "lang="+lang+"#");
parent.location.href=str;
}
}
// 获取地址栏参数
function getQueryString(name) {
var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)", "i");
var r=window.location.search.substr(1).match(reg);
if (r!=null) return unescape(decodeURIComponent(r[2]));
return null;
}
// 修改、添加、删除地址栏参数
function replaceParamVal(paramName,replaceWith) {
var newUrl=oldUrl=window.location.href,
paramNames='&' + paramName + '=';
re = eval('/('+paramNames+')([^&]*)/gi');
if(replaceWith){
if(oldUrl.indexOf(paramNames)>=0){
newUrl = oldUrl.replace(re, paramNames + replaceWith);
}else{
newUrl = oldUrl+ paramNames + replaceWith;
}
}else if(oldUrl.indexOf(paramNames)>=0){
newUrl = oldUrl.replace(re, '');
}
history.pushState('','',newUrl);
}
// 可视化弹框中页面隐藏头部
if (parent.window.location.search.indexOf('pageset=1') >= 0) $('.metadmin-head').hide();
// 操作成功、失败提示信息
if(top.location!=location) $("html",parent.document).find('.turnovertext').remove();
// 弹出提示信息
function metAlert(text,delay,bg_ok,type){
delay=typeof delay != 'undefined'?delay:2000;
bg_ok=bg_ok?'bgshow':'';
if(text!=' '){
text=text||METLANG.jsok;
text='<div>'+text+'</div>';
if(parseInt(type)==0) text+='<button type="button" class="close white" data-dismiss="alert"><span aria-hidden="true">×</span></button>';
if(!$('.metalert-text').length){
var html='<div class="metalert-text p-x-40 p-y-10 bg-purple-600 white font-size-16">'+text+'</div>';
if(parseInt(type)==0) html='<div class="metalert-wrapper w-full alert '+bg_ok+'">'+html+'</div>';
$('body').append(html);
}
var $met_alert=$('.metalert-text');
$met_alert.html(text);
$('.metalert-wrapper').show();
if($met_alert.height()%2) $met_alert.height($met_alert.height()+1);
}
if(delay){
setTimeout(function(){
var $obj=parseInt(type)==0?$('.metalert-wrapper'):$('.metalert-text');
$obj.fadeOut();
},delay);
}
}
// 弹出页面返回的提示信息
var turnover=[];
turnover['text']=getQueryString('turnovertext');
turnover['type']=parseInt(getQueryString('turnovertype'));
turnover['delay']=turnover['type']?undefined:0;
if(turnover['text']) metAlert(turnover['text'],turnover['delay'],!turnover['type'],turnover['type']);
// 系统参数
var lang=M['lang'],
siteurl=M['weburl'],
basepath=MET['url']['basepath']?MET['url']['basepath']:'';
if(typeof MET != 'undefined'){
for(var name in MET){
if(!M[name]) M[name]=MET[name];
}
}
M['n']=getQueryString('n'),
M['c']=getQueryString('c'),
M['a']=getQueryString('a');
if(!M['url']) M['url']=[];
M['url']['system']=M['weburl']+'app/system/';
M['url']['static']=M['url']['system']+'include/static/';
M['url']['static_vendor']=M['url']['static']+'vendor/';
M['url']['static2']=M['url']['system']+'include/static2/';
M['url']['static2_vendor']=M['url']['static2']+'vendor/';
M['url']['static2_plugin']=M['url']['static2']+'js/Plugin/';
M['url']['uiv2']=M['weburl']+'public/ui/v2/';
M['url']['uiv2_css']=M['url']['uiv2']+'static/css/';
M['url']['uiv2_js']=M['url']['uiv2']+'static/js/';
M['url']['uiv2_plugin']=M['url']['uiv2']+'static/plugin/';
M['url']['app']=M['weburl']+'app/app/';
M['url']['pub']=M['weburl']+'app/system/include/public/';
M['url']['epl']=M['url']['pub']+'js/examples/';
M['url']['editor']=M['url']['app']+MET['met_editor']+'/';
// 插件路径
M['plugin']=[];
M['plugin']['formvalidation']=[
M['url']['static2_vendor']+'formvalidation/formValidation.min.css',
M['url']['static2_vendor']+'formvalidation/formValidation.min.js',
M['url']['static2_vendor']+'formvalidation/language/zh_CN.js',
M['url']['static2_vendor']+'formvalidation/framework/bootstrap4.min.js',
M['url']['static2_vendor']+'jquery-enplaceholder/jquery.enplaceholder.min.js',
M['url']['uiv2_js']+'form.js'
];
M['plugin']['datatables']=[
M['url']['static2_vendor']+'datatables-bootstrap/dataTables.bootstrap.min.css',
M['url']['static2_vendor']+'datatables-responsive/dataTables.responsive.min.css',
M['url']['static2_vendor']+'datatables/jquery.dataTables.min.js',
M['url']['static2_vendor']+'datatables-bootstrap/dataTables.bootstrap.min.js',
M['url']['static2_vendor']+'datatables-responsive/dataTables.responsive.min.js',
M['url']['uiv2_js']+'datatable.js'
];
M['plugin']['ueditor']=[
M['weburl']+'app/app/ueditor/ueditor.config.js',
M['weburl']+'app/app/ueditor/ueditor.all.min.js'
];
M['plugin']['minicolors']=[
M['url']['epl']+'color/jquery.minicolors.css',
M['url']['epl']+'color/jquery.minicolors.min.js'
];
M['plugin']['tokenfield']=[
M['url']['static2_vendor']+'bootstrap-tokenfield/bootstrap-tokenfield.min.css',
M['url']['static2_vendor']+'bootstrap-tokenfield/bootstrap-tokenfield.min.js',
M['url']['static2_plugin']+'bootstrap-tokenfield.min.js'
];
M['plugin']['ionrangeslider']=[
M['url']['static2_vendor']+'ionrangeslider/ionrangeslider.min.css',
M['url']['static2_vendor']+'ionrangeslider/ion.rangeSlider.min.js'
];
M['plugin']['datetimepicker']=[
M['url']['epl']+'time/jquery.datetimepicker.css',
M['url']['epl']+'time/jquery.datetimepicker.js'
];
M['plugin']['select-linkage']=M['url']['static_vendor']+'select-linkage/jquery.cityselect.js';
M['plugin']['alertify']=[
M['url']['static2_vendor']+'alertify/alertify.min.css',
M['url']['static2_vendor']+'alertify/alertify.js',
M['url']['static2_plugin']+'alertify.min.js'
];
M['plugin']['selectable']=[
M['url']['static2_plugin']+'asselectable.min.js',
M['url']['static2_plugin']+'selectable.min.js'
];
M['plugin']['fileinput']=M['url']['static2_vendor']+'fileinput/fileinput.min.js';
M['plugin']['lazyload']=M['weburl']+'public/ui/v2/static/plugin/jquery.lazyload.min.js';
M['plugin']['hover-dropdown']=M['url']['static_vendor']+'bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js';
M['plugin']['asscrollable']=[
M['url']['static2_vendor']+'asscrollable/asScrollable.min.css',
M['url']['static2_vendor']+'asscrollbar/jquery-asScrollbar.min.js',
M['url']['static2_vendor']+'asscrollable/jquery-asScrollable.min.js',
M['url']['static2_plugin']+'asscrollable.min.js'
]
M['plugin']['touchspin']=[
M['url']['static2_vendor']+'bootstrap-touchspin/bootstrap-touchspin.min.css',
M['url']['static2_vendor']+'bootstrap-touchspin/bootstrap-touchspin.min.js'
]
M['plugin']['masonry']=M['url']['static2_vendor']+'masonry/masonry.pkgd.min.js';
M['plugin']['appear']=[
M['url']['static2_vendor']+'jquery-appear/jquery.appear.min.js',
M['url']['static2_plugin']+'jquery-appear.min.js'
];
M['plugin']['ladda']=[
M['url']['static2_vendor']+'ladda/ladda.min.css',
M['url']['static2_vendor']+'ladda/spin.min.js',
M['url']['static2_vendor']+'ladda/ladda.min.js',
M['url']['static2_plugin']+'ladda.min.js'
];
M['plugin']['webui-popover']=[
M['url']['static2_vendor']+'webui-popover/webui-popover.min.css',
M['url']['static2_vendor']+'webui-popover/jquery.webui-popover.min.js'
];
// 表单验证
if($('form').length && typeof validate =='undefined') $.include(M['plugin']['formvalidation']);
// ajax表格
if($('.dataTable').length && typeof datatableOption =='undefined') $.include(M['plugin']['datatables']);
// 系统功能
$.fn.extend({
// 编辑器
metEditor:function(){
if(!$(this).length) return;
if(M['met_editor']=='ueditor'){// 百度编辑器
if(typeof textarea_editor_val =='undefined') window.textarea_editor_val=[];
var $self=$(this);
$.include(M['plugin']['ueditor'],function(){
$self.each(function(index, val) {
var index1=$(this).index('textarea[data-plugin="editor"]');
if(!$(this).attr('id')) $(this).attr({id:'textarea-editor'+index1});
textarea_editor_val[index1]=UE.getEditor(val.id,{
scaleEnabled:true, // 是否可以拉伸长高,默认false(当开启时,自动长高失效)
autoFloatEnabled:false, // 是否保持toolbar的位置不动,默认true
initialFrameWidth : $(this).data('editor-x')||'100%',
initialFrameHeight : $(this).data('editor-y')||400,
});
});
});
}else if(M['met_editor']=='editormd'){// markdown编辑器
}
},
// 颜色选择器
metDatetimepicker:function(){
if(!$(this).length) return;
$(this).each(function(index, el) {
var $self=$(this);
$(this).datetimepicker({
lang:M['lang']=='cn'?'ch':'en',
timepicker:$self.attr("data-day-type")==2?true:false,
format:$self.attr("data-day-type")==2?'Y-m-d H:i:s':'Y-m-d'
});
});
},
// 联动菜单
metCitySelect:function(){
if(!$(this).length) return;
if(typeof citySelect =='undefined') window.citySelect=[];
$(this).each(function(index){
var country=$(this).find(".country").attr("data-checked"),
p=$(this).find(".prov").attr("data-checked"),
c=$(this).find(".city").attr("data-checked"),
s=$(this).find(".dist").attr("data-checked"),
url=$(this).attr('data-select-url')?$(this).attr('data-select-url'):M['url']['static2_vendor']+'select-linkage/citydata.min.json',
option={url:url,prov:p, city:c, dist:s, nodata:'none'};
if($(this).hasClass('shop-address-select')){
option={
url:url,country:country, prov:p, city:c, dist:s, nodata:'none',
required:false,
country_name_key:'name',
p_name_key:'name',
n_name_key:'name',
s_name_key:'name',
p_children_key:'children',
n_children_key:'children',
value_key:'id',
getCityjson:function(json,key){
key=key||0;
return json[key]['children'];
}
};
}
citySelect[index]=$(this).citySelect(option);
});
},
// 上传文件
metFileInput:function(){
if(!$(this).length) return;
$(this).each(function(index, el) {
var url=$(this).data('url')||M['url']['system']+'entrance.php?lang='+M['lang']+'&c=uploadify&m=include&a=doupfile&type=1',
multiple=$(this).attr('multiple'),
$form_group=$(this).parents('.form-group');
$(this).removeAttr('hidden').fileinput({// fileinput插件
language:'zh', // 语言文字
showCaption:false, // 输入框
showRemove:false, // 删除按钮
browseLabel:'', // 按钮文字
showUpload:false, // 上传按钮
uploadUrl: url, // 处理上传
uploadAsync:multiple // 异步批量上传
}).on("filebatchselected", function(event, files) {
$(this).fileinput("upload");
}).on('fileuploaded', function(event, data, previewId, index) {
var $text=$(this).parents('.input-group-file').find('input[type="text"]'),
path='';
if(multiple){
path=$text.val()?$text.val()+','+data.response.path:data.response.path;
}else{
path=data.response.path;
}
$text.val(path);// 输入框文件路径更新
// 显示上传成功文字
$form_group.removeClass('has-danger').addClass('has-success');
if(!$form_group.find('small.form-control-label').length) $form_group.append('<small class="form-control-label"></small>');
var tips=M['langtxt'].jsx17||M['langtxt'].fileOK;
$form_group.find('small.form-control-label').text(tips);
}).on('filebatchuploaderror', function(event, data, previewId, index) {
// 显示报错文字
$form_group.removeClass('has-success').addClass('has-danger');
if(!$form_group.find('small.form-control-label').length) $form_group.append('<small class="form-control-label"></small>');
$form_group.find('small.form-control-label').text(data.response.error);
});
$(this).siblings('i').attr({class:'icon wb-upload'}).parents('.btn-file').insertAfter($(this).parents('.file-input'));
});
},
// 单选、多选默认选中
metRadioCheckboxChecked:function(){
if(!$(this).length) return;
$(this).each(function(index, el) {
var checked=String($(this).data('checked'));
if(checked!=''){
checked=checked.indexOf('#@met@#')>=0?checked.split('#@met@#'):[checked];
var name=$(this).attr('name');
for (var i=0; i < checked.length; i++) {
$('input[name="'+name+'"][value="'+checked[i]+'"]').attr('checked', true);
}
}
});
},
// 下拉菜单默认选中
metSelectChecked:function(){
if(!$(this).length) return;
$(this).each(function(index, el) {
$('option[value="'+$(this).data('checked')+'"]',this).attr({selected:true});
});
},
// 图片延迟加载
metlazyLoad:function(){
if(!$(this).length) return;
var $self=$(this);
if(typeof $.fn.lazyload == 'undefined'){
$.include(M['plugin']['lazyload'],function(){
$self.lazyload({placeholder:M['lazyloadbg']});
})
}else if($('script[src*="js/basic_admin.js"]').length){
$self.lazyload({placeholder:M['lazyloadbg']});
}else{
if(typeof M['lazyload_load_num'] =='undefined') M['lazyload_load_num']=0;
var delay=M['lazyload_load_num']?0:500;
if(delay){
setTimeout(function(){
var is_lazyload=true;
$self.each(function(index, el) {
if($(this).attr('data-lazyload')=='true'){
is_lazyload=false;
return false;
}
});
if(is_lazyload) $self.lazyload({placeholder:M['lazyloadbg']});
M['lazyload_load_num']++;
},delay);
}else{
$self.lazyload({placeholder:M['lazyloadbg']});
}
}
},
// 通用功能开启
metCommon:function(){
var dom=this;
// 编辑器
if($('textarea[data-plugin="editor"]',dom).length) $('textarea[data-plugin="editor"]',dom).metEditor();
// 颜色选择器
if($('input[data-plugin="minicolors"]',dom).length) $.include(M['plugin']['minicolors'],function(){
$('input[data-plugin="minicolors"]',dom).minicolors();
});
// 标签
if($('input[data-plugin="tokenfield"]',dom).length) $.include(M['plugin']['tokenfield'],'','siterun');
// 滑块
if($('input[type="text"][data-plugin="ionRangeSlider"]',dom).length) $.include(M['plugin']['ionrangeslider']);
// 日期选择器
if($('input[data-plugin="datetimepicker"]',dom).length) $.include(M['plugin']['datetimepicker'],function(){
$('input[data-plugin="datetimepicker"]',dom).metDatetimepicker();
});
// 联动菜单
if($('[data-plugin="select-linkage"]',dom).length) $.include(M['plugin']['select-linkage'],function(){
$('[data-plugin="select-linkage"]',dom).metCitySelect();
});
// 模态对话框
if($('[data-plugin="alertify"]',dom).length) $.include(M['plugin']['alertify'],'','siterun');
// 全选、全不选
if($('[data-plugin="selectable"]',dom).length) $.include(M['plugin']['selectable'],'','siterun');
// 上传文件
if($('input[type="file"][data-plugin="fileinput"]',dom).length) $.include(M['plugin']['fileinput'],function(){
$('input[type="file"][data-plugin="fileinput"]',dom).metFileInput();
})
// 滚动条
if($('[data-plugin="scrollable"]',dom).length) $.include(M['plugin']['asscrollable'],'','siterun');
// 单选、多选默认选中
if($('input[data-checked]',dom).length) $('input[data-checked]',dom).metRadioCheckboxChecked();
// 下拉菜单默认选中
if($('select[data-checked]',dom).length) $('select[data-checked]',dom).metSelectChecked();
// 数量改变
if($('[data-plugin="touchSpin"]',dom).length && typeof $.fn.TouchSpin =='undefined') $.include(M['plugin']['touchspin'],function(){
$('[data-plugin="touchSpin"]',dom).TouchSpin();
});
// 图片延迟加载
if($('[data-original]',dom).length) $('[data-original]',dom).metlazyLoad();
}
});
// 通用功能开启
$(document).metCommon();
if($('.met-sidebar-nav-active-name').length) $('.met-sidebar-nav-active-name').html($('.met-sidebar-nav-mobile .dropdown-menu .dropdown-item.active').text());
// 勾选开关
$(document).on('change', 'input[type="checkbox"][data-plugin="switchery"]', function(event) {
var val=$(this).is(':checked')?1:0;
$(this).val(val);
});
// 非前台模板页面-兼容老模板
if(M['url']['basepath'] || $('script[src*="js/basic_web.js"]').length){
// 返回顶部
$(".met-scroll-top").click(function(){
$('html,body').animate({scrollTop:0},300);
});
// 返回顶部按钮显示/隐藏
var wh=$(window).height();
$(window).scroll(function(){
if($(this).scrollTop()>wh){
$(".met-scroll-top").removeAttr('hidden').addClass("animation-slide-bottom");
}else{
$(".met-scroll-top").attr({hidden:''}).removeClass('animation-slide-bottom');
}
});
}
$(function(){
// 表单功能
// 添加项
$(document).on('click', '[table-addlist]', function(event) {
var $table=$(this).parents('table').length?$(this).parents('table'):$($(this).data('table-id')),
html=$table.find('[table-addlist-data]').val();
$table.find('tbody').append(html);
var $new_tr=$table.find('tbody tr:last-child');
if(!$new_tr.find('[table-cancel]').length && $table.find('[table-del-url]').length) $new_tr.find('td:last-child').append('<button type="button" class="btn btn-default btn-outline m-l-5" table-cancel>撤销</button>');
});
// 撤销项
$(document).on('click', '[table-cancel]', function(event) {
$(this).parents('tr').remove();
})
// 删除项
$(document).on('click', '[table-del]', function(event) {
var $self=$(this),
remove=function(){
alertify.theme('bootstrap').okBtn(METLANG.confirm).cancelBtn(METLANG.jslang2).confirm(METLANG.delete_information, function (ev) {
$self.parents('tr').remove();
})
};
if(typeof alertify =='undefined'){
$.include(M['plugin']['alertify'],function(){
remove();
});
}else{
remove();
}
})
// 删除多项
$(document).on('click', '[table-del-url]', function(event) {
var $checkbox=$(this).parents('table').find('tbody input[type="checkbox"][id*="row-id-"]:checked'),
del_data={id:[]};
$checkbox.each(function(index, el) {
del_data['id'].push($(this).parents('tr').find('[name="id"]').val());
})
$.ajax({
url: $(this).data('table-del-url'),
type: "POST",
dataType:'json',
data:{del_data:del_data},
success: function(result){
console.log(result);
}
});
})
}); |
#https://github.com/hatem-mahmoud/scripts/blob/master/hugepage_usage_ins.sh
total_shmsize=0
total_hugepagesize=0
for pid in `ps -ef | grep ora_pmon_|egrep -v "grep|+ASM"| awk '{print $2}'`
do
echo
echo "-----------------------------------------------------------"
echo
ps -ef | grep $pid | grep -v grep
shmsize=`grep -A 1 'SYSV00000000' /proc/$pid/smaps | grep "^Size:" | awk 'BEGIN{sum=0}{sum+=$2}END{print sum/1024}' | awk -F"." '{print $1}'`
hugepagesize=`grep -B 11 'KernelPageSize: 2048 kB' /proc/$pid/smaps | grep "^Size:" | awk 'BEGIN{sum=0}{sum+=$2}END{print sum/1024}' | awk -F"." '{prin
t $1}'`
echo "INSTANCE SGA (SMALL/HUGE page)" : $shmsize "MB"
echo "INSTANCE SGA (HUGE PAGE)" $hugepagesize "MB"
echo "Percent Huge page :" $(( $hugepagesize *100 / $shmsize )) "%"
total_shmsize=$(( $shmsize + $total_shmsize ))
total_hugepagesize=$(( $total_hugepagesize + $hugepagesize ))
done
echo
echo "-----------------------------------------------------------"
echo "-----------------------------------------------------------"
echo
echo "SGA TOTAL (SMALL/HUGE page)" : $total_shmsize "MB"
echo "SGA TOTAL (HUGE PAGE)" $total_hugepagesize "MB"
echo "Percent Huge page :" $(( $total_hugepagesize *100 / $total_shmsize )) "%" |
import { RefObject } from 'react';
export const createUseObserverVisible = (observerOptions: IntersectionObserverInit) => (
containerRef: RefObject<HTMLDivElement>
) => {
return true;
};
|
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import mock
import pytest
import requests
from requests.exceptions import ConnectTimeout, ProxyError
from datadog_checks.checks import AgentCheck
PROXY_SETTINGS = {
'http': 'http(s)://user:password@proxy_for_http:port',
'https': 'http(s)://user:password@proxy_for_https:port',
'no': None
}
SKIP_PROXY_SETTINGS = {
'http': '',
'https': '',
'no': None
}
NO_PROXY_DD_CONFIG_SETTINGS = {
'http': 'http://1.2.3.4:567',
'https': 'https://1.2.3.4:567',
'no': 'localhost'
}
BAD_PROXY_SETTINGS = {
'http': 'http://1.2.3.4:567',
'https': 'https://1.2.3.4:567',
}
def test_use_proxy():
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value=PROXY_SETTINGS):
check = AgentCheck()
assert check.get_instance_proxy({}, 'uri/health') == PROXY_SETTINGS
def test_skip_proxy():
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value=PROXY_SETTINGS):
check = AgentCheck()
assert check.get_instance_proxy({'skip_proxy': True}, 'uri/health') == SKIP_PROXY_SETTINGS
def test_deprecated_no_proxy():
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value=PROXY_SETTINGS):
check = AgentCheck()
assert check.get_instance_proxy({'no_proxy': True}, 'uri/health') == SKIP_PROXY_SETTINGS
def test_http_proxy():
old_env = dict(os.environ)
os.environ['HTTP_PROXY'] = BAD_PROXY_SETTINGS['http']
try:
check = AgentCheck()
proxies = check.get_instance_proxy({'skip_proxy': True}, 'uri/health')
response = requests.get('http://google.com', proxies=proxies)
response.raise_for_status()
finally:
os.environ.clear()
os.environ.update(old_env)
def test_http_proxy_fail():
old_env = dict(os.environ)
os.environ['HTTP_PROXY'] = BAD_PROXY_SETTINGS['http']
try:
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value={}):
check = AgentCheck()
proxies = check.get_instance_proxy({}, 'uri/health')
with pytest.raises((ConnectTimeout, ProxyError)):
requests.get('http://google.com', timeout=1, proxies=proxies)
finally:
os.environ.clear()
os.environ.update(old_env)
def test_https_proxy():
old_env = dict(os.environ)
os.environ['HTTPS_PROXY'] = BAD_PROXY_SETTINGS['https']
try:
check = AgentCheck()
proxies = check.get_instance_proxy({'skip_proxy': True}, 'uri/health')
response = requests.get('https://google.com', proxies=proxies)
response.raise_for_status()
finally:
os.environ.clear()
os.environ.update(old_env)
def test_https_proxy_fail():
old_env = dict(os.environ)
os.environ['HTTPS_PROXY'] = BAD_PROXY_SETTINGS['https']
try:
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value={}):
check = AgentCheck()
proxies = check.get_instance_proxy({}, 'uri/health')
with pytest.raises((ConnectTimeout, ProxyError)):
requests.get('https://google.com', timeout=1, proxies=proxies)
finally:
os.environ.clear()
os.environ.update(old_env)
def test_config_no_proxy():
with mock.patch('datadog_checks.checks.AgentCheck._get_requests_proxy', return_value=NO_PROXY_DD_CONFIG_SETTINGS):
check = AgentCheck()
proxy_results = check.get_instance_proxy({}, 'uri/health')
assert 'localhost' in proxy_results['no']
|
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {SimulationEditorComponent} from './simulation-editor.component';
import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service';
import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec';
import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service';
import {storageNodeEditorContentServiceSpy} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.spec';
import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor';
import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec';
describe('SimulationEditorComponent', () => {
let component: SimulationEditorComponent;
let fixture: ComponentFixture<SimulationEditorComponent>;
beforeEach(async(() => {
const contentService = storageNodeEditorContentServiceSpy();
TestBed.configureTestingModule({
declarations: [SimulationEditorComponent],
providers: [
{provide: StorageNodeEditorContentService, useValue: contentService},
{provide: SimulationService, useValue: simulationServiceSpy()},
{provide: STORAGE_NODE, useValue: testStorageFileNode()},
]
})
.overrideTemplate(SimulationEditorComponent, '')
.overrideProvider(StorageNodeEditorContentService, {useValue: contentService})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimulationEditorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
public class User
{
public string Username { get; set; }
public string Email { get; set; }
public int Age { get; set; }
public DateTime CreatedAt { get; set; }
} |
/*
* (c) Copyright 2015 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.frontend.find.hod.export;
import com.hp.autonomy.frontend.find.core.export.ExportControllerTest;
import com.hp.autonomy.hod.client.error.HodErrorException;
import com.hp.autonomy.searchcomponents.hod.search.HodDocumentsService;
import com.hp.autonomy.searchcomponents.hod.search.HodQueryRequest;
import com.hp.autonomy.searchcomponents.hod.search.HodQueryRequestBuilder;
import com.hp.autonomy.types.requests.Documents;
import org.mockito.Mock;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.io.IOException;
import java.util.Collections;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;
abstract class HodExportControllerTest extends ExportControllerTest<HodQueryRequest, HodErrorException> {
@MockBean
private HodDocumentsService documentsService;
@Mock
private HodQueryRequest queryRequest;
@Mock
private HodQueryRequestBuilder queryRequestBuilder;
@Override
protected void mockRequestObjects() throws IOException {
when(requestMapper.parseQueryRequest(any())).thenReturn(queryRequest);
when(queryRequest.toBuilder()).thenReturn(queryRequestBuilder);
when(queryRequestBuilder.start(anyInt())).thenReturn(queryRequestBuilder);
when(queryRequestBuilder.maxResults(anyInt())).thenReturn(queryRequestBuilder);
when(queryRequestBuilder.print(anyString())).thenReturn(queryRequestBuilder);
when(queryRequestBuilder.build()).thenReturn(queryRequest);
when(queryRequest.getMaxResults()).thenReturn(Integer.MAX_VALUE);
}
@Override
protected void mockNumberOfResults(final int numberOfResults) throws HodErrorException {
when(documentsService.queryTextIndex(any())).thenReturn(new Documents<>(Collections.emptyList(), numberOfResults, null, null, null, null));
}
}
|
<reponame>achouman/IKVM.NET<gh_stars>10-100
/*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineMetrics;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.peer.FontPeer;
import java.io.*;
import java.lang.ref.SoftReference;
import java.nio.file.Files;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import sun.font.StandardGlyphVector;
import cli.System.IntPtr;
import cli.System.Drawing.GraphicsUnit;
import cli.System.Drawing.Text.PrivateFontCollection;
import cli.System.Runtime.InteropServices.GCHandle;
import cli.System.Runtime.InteropServices.GCHandleType;
import sun.font.AttributeMap;
import sun.font.AttributeValues;
import sun.font.CompositeFont;
import sun.font.CreatedFontTracker;
import sun.font.Font2D;
import sun.font.Font2DHandle;
import sun.font.FontAccess;
import sun.font.FontManager;
import sun.font.FontManagerFactory;
import sun.font.FontUtilities;
import sun.font.GlyphLayout;
import sun.font.FontLineMetrics;
import sun.font.CoreMetrics;
import sun.font.SunFontManager;
import static sun.font.EAttribute.*;
/**
* The <code>Font</code> class represents fonts, which are used to
* render text in a visible way.
* A font provides the information needed to map sequences of
* <em>characters</em> to sequences of <em>glyphs</em>
* and to render sequences of glyphs on <code>Graphics</code> and
* <code>Component</code> objects.
*
* <h4>Characters and Glyphs</h4>
*
* A <em>character</em> is a symbol that represents an item such as a letter,
* a digit, or punctuation in an abstract way. For example, <code>'g'</code>,
* <font size=-1>LATIN SMALL LETTER G</font>, is a character.
* <p>
* A <em>glyph</em> is a shape used to render a character or a sequence of
* characters. In simple writing systems, such as Latin, typically one glyph
* represents one character. In general, however, characters and glyphs do not
* have one-to-one correspondence. For example, the character 'á'
* <font size=-1>LATIN SMALL LETTER A WITH ACUTE</font>, can be represented by
* two glyphs: one for 'a' and one for '´'. On the other hand, the
* two-character string "fi" can be represented by a single glyph, an
* "fi" ligature. In complex writing systems, such as Arabic or the South
* and South-East Asian writing systems, the relationship between characters
* and glyphs can be more complicated and involve context-dependent selection
* of glyphs as well as glyph reordering.
*
* A font encapsulates the collection of glyphs needed to render a selected set
* of characters as well as the tables needed to map sequences of characters to
* corresponding sequences of glyphs.
*
* <h4>Physical and Logical Fonts</h4>
*
* The Java Platform distinguishes between two kinds of fonts:
* <em>physical</em> fonts and <em>logical</em> fonts.
* <p>
* <em>Physical</em> fonts are the actual font libraries containing glyph data
* and tables to map from character sequences to glyph sequences, using a font
* technology such as TrueType or PostScript Type 1.
* All implementations of the Java Platform must support TrueType fonts;
* support for other font technologies is implementation dependent.
* Physical fonts may use names such as Helvetica, Palatino, HonMincho, or
* any number of other font names.
* Typically, each physical font supports only a limited set of writing
* systems, for example, only Latin characters or only Japanese and Basic
* Latin.
* The set of available physical fonts varies between configurations.
* Applications that require specific fonts can bundle them and instantiate
* them using the {@link #createFont createFont} method.
* <p>
* <em>Logical</em> fonts are the five font families defined by the Java
* platform which must be supported by any Java runtime environment:
* Serif, SansSerif, Monospaced, Dialog, and DialogInput.
* These logical fonts are not actual font libraries. Instead, the logical
* font names are mapped to physical fonts by the Java runtime environment.
* The mapping is implementation and usually locale dependent, so the look
* and the metrics provided by them vary.
* Typically, each logical font name maps to several physical fonts in order to
* cover a large range of characters.
* <p>
* Peered AWT components, such as {@link Label Label} and
* {@link TextField TextField}, can only use logical fonts.
* <p>
* For a discussion of the relative advantages and disadvantages of using
* physical or logical fonts, see the
* <a href="http://java.sun.com/j2se/corejava/intl/reference/faqs/index.html#desktop-rendering">Internationalization FAQ</a>
* document.
*
* <h4>Font Faces and Names</h4>
*
* A <code>Font</code>
* can have many faces, such as heavy, medium, oblique, gothic and
* regular. All of these faces have similar typographic design.
* <p>
* There are three different names that you can get from a
* <code>Font</code> object. The <em>logical font name</em> is simply the
* name that was used to construct the font.
* The <em>font face name</em>, or just <em>font name</em> for
* short, is the name of a particular font face, like Helvetica Bold. The
* <em>family name</em> is the name of the font family that determines the
* typographic design across several faces, like Helvetica.
* <p>
* The <code>Font</code> class represents an instance of a font face from
* a collection of font faces that are present in the system resources
* of the host system. As examples, Arial Bold and Courier Bold Italic
* are font faces. There can be several <code>Font</code> objects
* associated with a font face, each differing in size, style, transform
* and font features.
* <p>
* The {@link GraphicsEnvironment#getAllFonts() getAllFonts} method
* of the <code>GraphicsEnvironment</code> class returns an
* array of all font faces available in the system. These font faces are
* returned as <code>Font</code> objects with a size of 1, identity
* transform and default font features. These
* base fonts can then be used to derive new <code>Font</code> objects
* with varying sizes, styles, transforms and font features via the
* <code>deriveFont</code> methods in this class.
*
* <h4>Font and TextAttribute</h4>
*
* <p><code>Font</code> supports most
* <code>TextAttribute</code>s. This makes some operations, such as
* rendering underlined text, convenient since it is not
* necessary to explicitly construct a <code>TextLayout</code> object.
* Attributes can be set on a Font by constructing or deriving it
* using a <code>Map</code> of <code>TextAttribute</code> values.
*
* <p>The values of some <code>TextAttributes</code> are not
* serializable, and therefore attempting to serialize an instance of
* <code>Font</code> that has such values will not serialize them.
* This means a Font deserialized from such a stream will not compare
* equal to the original Font that contained the non-serializable
* attributes. This should very rarely pose a problem
* since these attributes are typically used only in special
* circumstances and are unlikely to be serialized.
*
* <ul>
* <li><code>FOREGROUND</code> and <code>BACKGROUND</code> use
* <code>Paint</code> values. The subclass <code>Color</code> is
* serializable, while <code>GradientPaint</code> and
* <code>TexturePaint</code> are not.</li>
* <li><code>CHAR_REPLACEMENT</code> uses
* <code>GraphicAttribute</code> values. The subclasses
* <code>ShapeGraphicAttribute</code> and
* <code>ImageGraphicAttribute</code> are not serializable.</li>
* <li><code>INPUT_METHOD_HIGHLIGHT</code> uses
* <code>InputMethodHighlight</code> values, which are
* not serializable. See {@link java.awt.im.InputMethodHighlight}.</li>
* </ul>
*
* Clients who create custom subclasses of <code>Paint</code> and
* <code>GraphicAttribute</code> can make them serializable and
* avoid this problem. Clients who use input method highlights can
* convert these to the platform-specific attributes for that
* highlight on the current platform and set them on the Font as
* a workaround.</p>
*
* <p>The <code>Map</code>-based constructor and
* <code>deriveFont</code> APIs ignore the FONT attribute, and it is
* not retained by the Font; the static {@link #getFont} method should
* be used if the FONT attribute might be present. See {@link
* java.awt.font.TextAttribute#FONT} for more information.</p>
*
* <p>Several attributes will cause additional rendering overhead
* and potentially invoke layout. If a <code>Font</code> has such
* attributes, the <code>{@link #hasLayoutAttributes()}</code> method
* will return true.</p>
*
* <p>Note: Font rotations can cause text baselines to be rotated. In
* order to account for this (rare) possibility, font APIs are
* specified to return metrics and take parameters 'in
* baseline-relative coordinates'. This maps the 'x' coordinate to
* the advance along the baseline, (positive x is forward along the
* baseline), and the 'y' coordinate to a distance along the
* perpendicular to the baseline at 'x' (positive y is 90 degrees
* clockwise from the baseline vector). APIs for which this is
* especially important are called out as having 'baseline-relative
* coordinates.'
*/
public class Font implements java.io.Serializable
{
private static class FontAccessImpl extends FontAccess {
public Font2D getFont2D(Font font) {
return font.getFont2D();
}
public void setFont2D(Font font, Font2DHandle handle) {
font.font2DHandle = handle;
}
public void setCreatedFont(Font font) {
font.createdFont = true;
}
public boolean isCreatedFont(Font font) {
return font.createdFont;
}
}
static {
FontAccess.setFontAccess(new FontAccessImpl());
}
/**
* This is now only used during serialization. Typically
* it is null.
*
* @serial
* @see #getAttributes()
*/
private Hashtable fRequestedAttributes;
/*
* Constants to be used for logical font family names.
*/
/**
* A String constant for the canonical family name of the
* logical font "Dialog". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String DIALOG = "Dialog";
/**
* A String constant for the canonical family name of the
* logical font "DialogInput". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String DIALOG_INPUT = "DialogInput";
/**
* A String constant for the canonical family name of the
* logical font "SansSerif". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String SANS_SERIF = "SansSerif";
/**
* A String constant for the canonical family name of the
* logical font "Serif". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String SERIF = "Serif";
/**
* A String constant for the canonical family name of the
* logical font "Monospaced". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String MONOSPACED = "Monospaced";
/*
* Constants to be used for styles. Can be combined to mix
* styles.
*/
/**
* The plain style constant.
*/
public static final int PLAIN = 0;
/**
* The bold style constant. This can be combined with the other style
* constants (except PLAIN) for mixed styles.
*/
public static final int BOLD = 1;
/**
* The italicized style constant. This can be combined with the other
* style constants (except PLAIN) for mixed styles.
*/
public static final int ITALIC = 2;
/**
* The baseline used in most Roman scripts when laying out text.
*/
public static final int ROMAN_BASELINE = 0;
/**
* The baseline used in ideographic scripts like Chinese, Japanese,
* and Korean when laying out text.
*/
public static final int CENTER_BASELINE = 1;
/**
* The baseline used in Devanigiri and similar scripts when laying
* out text.
*/
public static final int HANGING_BASELINE = 2;
/**
* Identify a font resource of type TRUETYPE.
* Used to specify a TrueType font resource to the
* {@link #createFont} method.
* The TrueType format was extended to become the OpenType
* format, which adds support for fonts with Postscript outlines,
* this tag therefore references these fonts, as well as those
* with TrueType outlines.
* @since 1.3
*/
public static final int TRUETYPE_FONT = 0;
/**
* Identify a font resource of type TYPE1.
* Used to specify a Type1 font resource to the
* {@link #createFont} method.
* @since 1.5
*/
public static final int TYPE1_FONT = 1;
/**
* The logical name of this <code>Font</code>, as passed to the
* constructor.
* @since JDK1.0
*
* @serial
* @see #getName
*/
protected String name;
/**
* The style of this <code>Font</code>, as passed to the constructor.
* This style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
* @since JDK1.0
*
* @serial
* @see #getStyle()
*/
protected int style;
/**
* The point size of this <code>Font</code>, rounded to integer.
* @since JDK1.0
*
* @serial
* @see #getSize()
*/
protected int size;
/**
* The point size of this <code>Font</code> in <code>float</code>.
*
* @serial
* @see #getSize()
* @see #getSize2D()
*/
protected float pointSize;
/**
* The platform specific font information.
*/
private transient FontPeer peer;
private transient cli.System.Drawing.Font netFont;
private transient Font2DHandle font2DHandle;
private transient AttributeValues values;
private transient boolean hasLayoutAttributes;
/*
* If the origin of a Font is a created font then this attribute
* must be set on all derived fonts too.
*/
private transient boolean createdFont = false;
/*
* This is true if the font transform is not identity. It
* is used to avoid unnecessary instantiation of an AffineTransform.
*/
private transient boolean nonIdentityTx;
/*
* A cached value used when a transform is required for internal
* use. This must not be exposed to callers since AffineTransform
* is mutable.
*/
private static final AffineTransform identityTx = new AffineTransform();
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -4206021311591459213L;
/**
* Gets the peer of this <code>Font</code>.
* @return the peer of the <code>Font</code>.
* @since JDK1.1
* @deprecated Font rendering is now platform independent.
*/
@Deprecated
public FontPeer getPeer(){
return getPeer_NoClientCode();
}
// NOTE: This method is called by privileged threads.
// We implement this functionality in a package-private method
// to insure that it cannot be overridden by client subclasses.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
final FontPeer getPeer_NoClientCode() {
if(peer == null) {
Toolkit tk = Toolkit.getDefaultToolkit();
this.peer = tk.getFontPeer(name, style);
}
return peer;
}
/**
* Return the AttributeValues object associated with this
* font. Most of the time, the internal object is null.
* If required, it will be created from the 'standard'
* state on the font. Only non-default values will be
* set in the AttributeValues object.
*
* <p>Since the AttributeValues object is mutable, and it
* is cached in the font, care must be taken to ensure that
* it is not mutated.
*/
private AttributeValues getAttributeValues() {
if (values == null) {
AttributeValues valuesTmp = new AttributeValues();
valuesTmp.setFamily(name);
valuesTmp.setSize(pointSize); // expects the float value.
if ((style & BOLD) != 0) {
valuesTmp.setWeight(2); // WEIGHT_BOLD
}
if ((style & ITALIC) != 0) {
valuesTmp.setPosture(.2f); // POSTURE_OBLIQUE
}
valuesTmp.defineAll(PRIMARY_MASK); // for streaming compatibility
values = valuesTmp;
}
return values;
}
private Font2D getFont2D() {
FontManager fm = FontManagerFactory.getInstance();
if (fm.usingPerAppContextComposites() &&
font2DHandle != null &&
font2DHandle.font2D instanceof CompositeFont &&
((CompositeFont)(font2DHandle.font2D)).isStdComposite()) {
return fm.findFont2D(name, style,
FontManager.LOGICAL_FALLBACK);
} else if (font2DHandle == null) {
font2DHandle =
fm.findFont2D(name, style,
FontManager.LOGICAL_FALLBACK).handle;
}
/* Do not cache the de-referenced font2D. It must be explicitly
* de-referenced to pick up a valid font in the event that the
* original one is marked invalid
*/
return font2DHandle.font2D;
}
@cli.IKVM.Attributes.HideFromJavaAttribute.Annotation
public cli.System.Drawing.Font getNetFont(){
if(netFont == null){
netFont = getFont2D().createNetFont(this);
}
return netFont;
}
/**
* Creates a new <code>Font</code> from the specified name, style and
* point size.
* <p>
* The font name can be a font face name or a font family name.
* It is used together with the style to find an appropriate font face.
* When a font family name is specified, the style argument is used to
* select the most appropriate face from the family. When a font face
* name is specified, the face's style and the style argument are
* merged to locate the best matching font from the same family.
* For example if face name "Arial Bold" is specified with style
* <code>Font.ITALIC</code>, the font system looks for a face in the
* "Arial" family that is bold and italic, and may associate the font
* instance with the physical font face "Arial Bold Italic".
* The style argument is merged with the specified face's style, not
* added or subtracted.
* This means, specifying a bold face and a bold style does not
* double-embolden the font, and specifying a bold face and a plain
* style does not lighten the font.
* <p>
* If no face for the requested style can be found, the font system
* may apply algorithmic styling to achieve the desired style.
* For example, if <code>ITALIC</code> is requested, but no italic
* face is available, glyphs from the plain face may be algorithmically
* obliqued (slanted).
* <p>
* Font name lookup is case insensitive, using the case folding
* rules of the US locale.
* <p>
* If the <code>name</code> parameter represents something other than a
* logical font, i.e. is interpreted as a physical font face or family, and
* this cannot be mapped by the implementation to a physical font or a
* compatible alternative, then the font system will map the Font
* instance to "Dialog", such that for example, the family as reported
* by {@link #getFamily() getFamily} will be "Dialog".
* <p>
*
* @param name the font name. This can be a font face name or a font
* family name, and may represent either a logical font or a physical
* font found in this {@code GraphicsEnvironment}.
* The family names for logical fonts are: Dialog, DialogInput,
* Monospaced, Serif, or SansSerif. Pre-defined String constants exist
* for all of these names, for example, {@code DIALOG}. If {@code name} is
* {@code null}, the <em>logical font name</em> of the new
* {@code Font} as returned by {@code getName()} is set to
* the name "Default".
* @param style the style constant for the {@code Font}
* The style argument is an integer bitmask that may
* be {@code PLAIN}, or a bitwise union of {@code BOLD} and/or
* {@code ITALIC} (for example, {@code ITALIC} or {@code BOLD|ITALIC}).
* If the style argument does not conform to one of the expected
* integer bitmasks then the style is set to {@code PLAIN}.
* @param size the point size of the {@code Font}
* @see GraphicsEnvironment#getAllFonts
* @see GraphicsEnvironment#getAvailableFontFamilyNames
* @since JDK1.0
*/
public Font(String name, int style, int size) {
this.name = (name != null) ? name : "Default";
this.style = (style & ~0x03) == 0 ? style : 0;
this.size = size;
this.pointSize = size;
}
private Font(String name, int style, float sizePts) {
this.name = (name != null) ? name : "Default";
this.style = (style & ~0x03) == 0 ? style : 0;
this.size = (int)(sizePts + 0.5);
this.pointSize = sizePts;
}
/* This constructor is used by deriveFont when attributes is null */
private Font(String name, int style, float sizePts,
boolean created, Font2DHandle handle) {
this(name, style, sizePts);
this.createdFont = created;
/* Fonts created from a stream will use the same font2D instance
* as the parent.
* One exception is that if the derived font is requested to be
* in a different style, then also check if its a CompositeFont
* and if so build a new CompositeFont from components of that style.
* CompositeFonts can only be marked as "created" if they are used
* to add fall backs to a physical font. And non-composites are
* always from "Font.createFont()" and shouldn't get this treatment.
*/
if (created) {
if (handle.font2D instanceof CompositeFont &&
handle.font2D.getStyle() != style) {
FontManager fm = FontManagerFactory.getInstance();
this.font2DHandle = fm.getNewComposite(null, style, handle);
} else {
this.font2DHandle = handle;
}
}
}
/* This constructor is used when one font is derived from another.
* Fonts created from a stream will use the same font2D instance as the
* parent. They can be distinguished because the "created" argument
* will be "true". Since there is no way to recreate these fonts they
* need to have the handle to the underlying font2D passed in.
* "created" is also true when a special composite is referenced by the
* handle for essentially the same reasons.
* But when deriving a font in these cases two particular attributes
* need special attention: family/face and style.
* The "composites" in these cases need to be recreated with optimal
* fonts for the new values of family and style.
* For fonts created with createFont() these are treated differently.
* JDK can often synthesise a different style (bold from plain
* for example). For fonts created with "createFont" this is a reasonable
* solution but its also possible (although rare) to derive a font with a
* different family attribute. In this case JDK needs
* to break the tie with the original Font2D and find a new Font.
* The oldName and oldStyle are supplied so they can be compared with
* what the Font2D and the values. To speed things along :
* oldName == null will be interpreted as the name is unchanged.
* oldStyle = -1 will be interpreted as the style is unchanged.
* In these cases there is no need to interrogate "values".
*/
private Font(AttributeValues values, String oldName, int oldStyle,
boolean created, Font2DHandle handle) {
this.createdFont = created;
if (created) {
this.font2DHandle = handle;
String newName = null;
if (oldName != null) {
newName = values.getFamily();
if (oldName.equals(newName)) newName = null;
}
int newStyle = 0;
if (oldStyle == -1) {
newStyle = -1;
} else {
if (values.getWeight() >= 2f) newStyle = BOLD;
if (values.getPosture() >= .2f) newStyle |= ITALIC;
if (oldStyle == newStyle) newStyle = -1;
}
if (handle.font2D instanceof CompositeFont) {
if (newStyle != -1 || newName != null) {
FontManager fm = FontManagerFactory.getInstance();
this.font2DHandle =
fm.getNewComposite(newName, newStyle, handle);
}
} else if (newName != null) {
this.createdFont = false;
this.font2DHandle = null;
}
}
initFromValues(values);
}
/**
* Creates a new <code>Font</code> with the specified attributes.
* Only keys defined in {@link java.awt.font.TextAttribute TextAttribute}
* are recognized. In addition the FONT attribute is
* not recognized by this constructor
* (see {@link #getAvailableAttributes}). Only attributes that have
* values of valid types will affect the new <code>Font</code>.
* <p>
* If <code>attributes</code> is <code>null</code>, a new
* <code>Font</code> is initialized with default values.
* @see java.awt.font.TextAttribute
* @param attributes the attributes to assign to the new
* <code>Font</code>, or <code>null</code>
*/
public Font(Map<? extends Attribute, ?> attributes) {
initFromValues(AttributeValues.fromMap(attributes, RECOGNIZED_MASK));
}
/**
* Creates a new <code>Font</code> from the specified <code>font</code>.
* This constructor is intended for use by subclasses.
* @param font from which to create this <code>Font</code>.
* @throws NullPointerException if <code>font</code> is null
* @since 1.6
*/
protected Font(Font font) {
if (font.values != null) {
initFromValues(font.getAttributeValues().clone());
} else {
this.name = font.name;
this.style = font.style;
this.size = font.size;
this.pointSize = font.pointSize;
}
this.font2DHandle = font.font2DHandle;
this.createdFont = font.createdFont;
}
/**
* Font recognizes all attributes except FONT.
*/
private static final int RECOGNIZED_MASK = AttributeValues.MASK_ALL
& ~AttributeValues.getMask(EFONT);
/**
* These attributes are considered primary by the FONT attribute.
*/
private static final int PRIMARY_MASK =
AttributeValues.getMask(EFAMILY, EWEIGHT, EWIDTH, EPOSTURE, ESIZE,
ETRANSFORM, ESUPERSCRIPT, ETRACKING);
/**
* These attributes are considered secondary by the FONT attribute.
*/
private static final int SECONDARY_MASK =
RECOGNIZED_MASK & ~PRIMARY_MASK;
/**
* These attributes are handled by layout.
*/
private static final int LAYOUT_MASK =
AttributeValues.getMask(ECHAR_REPLACEMENT, EFOREGROUND, EBACKGROUND,
EUNDERLINE, ESTRIKETHROUGH, ERUN_DIRECTION,
EBIDI_EMBEDDING, EJUSTIFICATION,
EINPUT_METHOD_HIGHLIGHT, EINPUT_METHOD_UNDERLINE,
ESWAP_COLORS, ENUMERIC_SHAPING, EKERNING,
ELIGATURES, ETRACKING, ESUPERSCRIPT);
private static final int EXTRA_MASK =
AttributeValues.getMask(ETRANSFORM, ESUPERSCRIPT, EWIDTH);
/**
* Initialize the standard Font fields from the values object.
*/
private void initFromValues(AttributeValues values) {
this.values = values;
values.defineAll(PRIMARY_MASK); // for 1.5 streaming compatibility
this.name = values.getFamily();
this.pointSize = values.getSize();
this.size = (int)(values.getSize() + 0.5);
if (values.getWeight() >= 2f) this.style |= BOLD; // not == 2f
if (values.getPosture() >= .2f) this.style |= ITALIC; // not == .2f
this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);
this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);
}
/**
* Returns a <code>Font</code> appropriate to the attributes.
* If <code>attributes</code>contains a <code>FONT</code> attribute
* with a valid <code>Font</code> as its value, it will be
* merged with any remaining attributes. See
* {@link java.awt.font.TextAttribute#FONT} for more
* information.
*
* @param attributes the attributes to assign to the new
* <code>Font</code>
* @return a new <code>Font</code> created with the specified
* attributes
* @throws NullPointerException if <code>attributes</code> is null.
* @since 1.2
* @see java.awt.font.TextAttribute
*/
public static Font getFont(Map<? extends Attribute, ?> attributes) {
// optimize for two cases:
// 1) FONT attribute, and nothing else
// 2) attributes, but no FONT
// avoid turning the attributemap into a regular map for no reason
if (attributes instanceof AttributeMap &&
((AttributeMap)attributes).getValues() != null) {
AttributeValues values = ((AttributeMap)attributes).getValues();
if (values.isNonDefault(EFONT)) {
Font font = values.getFont();
if (!values.anyDefined(SECONDARY_MASK)) {
return font;
}
// merge
values = font.getAttributeValues().clone();
values.merge(attributes, SECONDARY_MASK);
return new Font(values, font.name, font.style,
font.createdFont, font.font2DHandle);
}
return new Font(attributes);
}
Font font = (Font)attributes.get(TextAttribute.FONT);
if (font != null) {
if (attributes.size() > 1) { // oh well, check for anything else
AttributeValues values = font.getAttributeValues().clone();
values.merge(attributes, SECONDARY_MASK);
return new Font(values, font.name, font.style,
font.createdFont, font.font2DHandle);
}
return font;
}
return new Font(attributes);
}
/**
* Returns a new <code>Font</code> using the specified font type
* and input data. The new <code>Font</code> is
* created with a point size of 1 and style {@link #PLAIN PLAIN}.
* This base font can then be used with the <code>deriveFont</code>
* methods in this class to derive new <code>Font</code> objects with
* varying sizes, styles, transforms and font features. This
* method does not close the {@link InputStream}.
* <p>
* To make the <code>Font</code> available to Font constructors the
* returned <code>Font</code> must be registered in the
* <code>GraphicsEnviroment</code> by calling
* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.
* @param fontFormat the type of the <code>Font</code>, which is
* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is specified.
* or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is specified.
* @param fontStream an <code>InputStream</code> object representing the
* input data for the font.
* @return a new <code>Font</code> created with the specified font type.
* @throws IllegalArgumentException if <code>fontFormat</code> is not
* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.
* @throws FontFormatException if the <code>fontStream</code> data does
* not contain the required font tables for the specified format.
* @throws IOException if the <code>fontStream</code>
* cannot be completely read.
* @see GraphicsEnvironment#registerFont(Font)
* @since 1.3
*/
public static Font createFont(int fontFormat, InputStream fontStream)
throws java.awt.FontFormatException, java.io.IOException {
if (fontFormat != Font.TRUETYPE_FONT &&
fontFormat != Font.TYPE1_FONT) {
throw new IllegalArgumentException ("font format not recognized");
}
// read the stream in a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream( fontStream.available() );
byte[] buffer = new byte[1024];
int count;
while( (count = fontStream.read( buffer, 0, buffer.length )) != -1 ) {
baos.write( buffer, 0, count );
}
byte[] fontData = baos.toByteArray();
// create a private Font Collection and add the font data
PrivateFontCollection pfc;
try {
pfc = createPrivateFontCollection(fontData);
} catch( cli.System.IO.FileNotFoundException x ) {
FontFormatException ffe = new FontFormatException(x.getMessage());
ffe.initCause(x);
throw ffe;
}
// create the font object
Font2D font2D = SunFontManager.createFont2D( pfc.get_Families()[0], 0 );
Font2DHandle font2DHandle = font2D.handle;
Font font = new Font( font2D.getFontName( Locale.getDefault() ), PLAIN, 1, true, font2DHandle );
return font;
}
// create a private Font Collection and add the font data
@cli.System.Security.SecuritySafeCriticalAttribute.Annotation
private static PrivateFontCollection createPrivateFontCollection(byte[] fontData) throws cli.System.IO.FileNotFoundException {
GCHandle handle = GCHandle.Alloc(fontData, GCHandleType.wrap(GCHandleType.Pinned));
try {
PrivateFontCollection pfc = new PrivateFontCollection();
// AddMemoryFont throws a cli.System.IO.FileNotFoundException if the data are corrupt
pfc.AddMemoryFont( handle.AddrOfPinnedObject(), fontData.length );
return pfc;
} finally {
handle.Free();
}
}
/**
* Returns a new <code>Font</code> using the specified font type
* and the specified font file. The new <code>Font</code> is
* created with a point size of 1 and style {@link #PLAIN PLAIN}.
* This base font can then be used with the <code>deriveFont</code>
* methods in this class to derive new <code>Font</code> objects with
* varying sizes, styles, transforms and font features.
* @param fontFormat the type of the <code>Font</code>, which is
* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is
* specified or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is
* specified.
* So long as the returned font, or its derived fonts are referenced
* the implementation may continue to access <code>fontFile</code>
* to retrieve font data. Thus the results are undefined if the file
* is changed, or becomes inaccessible.
* <p>
* To make the <code>Font</code> available to Font constructors the
* returned <code>Font</code> must be registered in the
* <code>GraphicsEnviroment</code> by calling
* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.
* @param fontFile a <code>File</code> object representing the
* input data for the font.
* @return a new <code>Font</code> created with the specified font type.
* @throws IllegalArgumentException if <code>fontFormat</code> is not
* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.
* @throws NullPointerException if <code>fontFile</code> is null.
* @throws IOException if the <code>fontFile</code> cannot be read.
* @throws FontFormatException if <code>fontFile</code> does
* not contain the required font tables for the specified format.
* @throws SecurityException if the executing code does not have
* permission to read from the file.
* @see GraphicsEnvironment#registerFont(Font)
* @since 1.5
*/
public static Font createFont(int fontFormat, File fontFile)
throws java.awt.FontFormatException, java.io.IOException {
fontFile = new File(fontFile.getPath());
if (fontFormat != Font.TRUETYPE_FONT &&
fontFormat != Font.TYPE1_FONT) {
throw new IllegalArgumentException ("font format not recognized");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
FilePermission filePermission =
new FilePermission(fontFile.getPath(), "read");
sm.checkPermission(filePermission);
}
if (!fontFile.canRead()) {
throw new IOException("Can't read " + fontFile);
}
// create a private Font Collection and add the font data
PrivateFontCollection pfc = new PrivateFontCollection();
try {
pfc.AddFontFile( fontFile.getPath() );
if (false) throw new cli.System.IO.FileNotFoundException();
} catch( cli.System.IO.FileNotFoundException fnfe ) {
FileNotFoundException ex = new FileNotFoundException(fnfe.getMessage());
ex.initCause( fnfe );
throw ex;
}
// create the font object
Font2D font2D = SunFontManager.createFont2D( pfc.get_Families()[0], 0 );
Font2DHandle font2DHandle = font2D.handle;
Font font = new Font( font2D.getFontName( Locale.getDefault() ), PLAIN, 1, true, font2DHandle );
return font;
}
/**
* Returns a copy of the transform associated with this
* <code>Font</code>. This transform is not necessarily the one
* used to construct the font. If the font has algorithmic
* superscripting or width adjustment, this will be incorporated
* into the returned <code>AffineTransform</code>.
* <p>
* Typically, fonts will not be transformed. Clients generally
* should call {@link #isTransformed} first, and only call this
* method if <code>isTransformed</code> returns true.
*
* @return an {@link AffineTransform} object representing the
* transform attribute of this <code>Font</code> object.
*/
public AffineTransform getTransform() {
/* The most common case is the identity transform. Most callers
* should call isTransformed() first, to decide if they need to
* get the transform, but some may not. Here we check to see
* if we have a nonidentity transform, and only do the work to
* fetch and/or compute it if so, otherwise we return a new
* identity transform.
*
* Note that the transform is _not_ necessarily the same as
* the transform passed in as an Attribute in a Map, as the
* transform returned will also reflect the effects of WIDTH and
* SUPERSCRIPT attributes. Clients who want the actual transform
* need to call getRequestedAttributes.
*/
if (nonIdentityTx) {
AttributeValues values = getAttributeValues();
AffineTransform at = values.isNonDefault(ETRANSFORM)
? new AffineTransform(values.getTransform())
: new AffineTransform();
if (values.getSuperscript() != 0) {
// can't get ascent and descent here, recursive call to this fn,
// so use pointsize
// let users combine super- and sub-scripting
int superscript = values.getSuperscript();
double trans = 0;
int n = 0;
boolean up = superscript > 0;
int sign = up ? -1 : 1;
int ss = up ? superscript : -superscript;
while ((ss & 7) > n) {
int newn = ss & 7;
trans += sign * (ssinfo[newn] - ssinfo[n]);
ss >>= 3;
sign = -sign;
n = newn;
}
trans *= pointSize;
double scale = Math.pow(2./3., n);
at.preConcatenate(AffineTransform.getTranslateInstance(0, trans));
at.scale(scale, scale);
// note on placement and italics
// We preconcatenate the transform because we don't want to translate along
// the italic angle, but purely perpendicular to the baseline. While this
// looks ok for superscripts, it can lead subscripts to stack on each other
// and bring the following text too close. The way we deal with potential
// collisions that can occur in the case of italics is by adjusting the
// horizontal spacing of the adjacent glyphvectors. Examine the italic
// angle of both vectors, if one is non-zero, compute the minimum ascent
// and descent, and then the x position at each for each vector along its
// italic angle starting from its (offset) baseline. Compute the difference
// between the x positions and use the maximum difference to adjust the
// position of the right gv.
}
if (values.isNonDefault(EWIDTH)) {
at.scale(values.getWidth(), 1f);
}
return at;
}
return new AffineTransform();
}
// x = r^0 + r^1 + r^2... r^n
// rx = r^1 + r^2 + r^3... r^(n+1)
// x - rx = r^0 - r^(n+1)
// x (1 - r) = r^0 - r^(n+1)
// x = (r^0 - r^(n+1)) / (1 - r)
// x = (1 - r^(n+1)) / (1 - r)
// scale ratio is 2/3
// trans = 1/2 of ascent * x
// assume ascent is 3/4 of point size
private static final float[] ssinfo = {
0.0f,
0.375f,
0.625f,
0.7916667f,
0.9027778f,
0.9768519f,
1.0262346f,
1.0591564f,
};
/**
* Returns the family name of this <code>Font</code>.
*
* <p>The family name of a font is font specific. Two fonts such as
* Helvetica Italic and Helvetica Bold have the same family name,
* <i>Helvetica</i>, whereas their font face names are
* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of
* available family names may be obtained by using the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
*
* <p>Use <code>getName</code> to get the logical name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> that is the family name of this
* <code>Font</code>.
*
* @see #getName
* @see #getFontName
* @since JDK1.1
*/
public String getFamily() {
return getFamily_NoClientCode();
}
// NOTE: This method is called by privileged threads.
// We implement this functionality in a package-private
// method to insure that it cannot be overridden by client
// subclasses.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
final String getFamily_NoClientCode() {
return getFamily(Locale.getDefault());
}
/**
* Returns the family name of this <code>Font</code>, localized for
* the specified locale.
*
* <p>The family name of a font is font specific. Two fonts such as
* Helvetica Italic and Helvetica Bold have the same family name,
* <i>Helvetica</i>, whereas their font face names are
* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of
* available family names may be obtained by using the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
*
* <p>Use <code>getFontName</code> to get the font face name of the font.
* @param l locale for which to get the family name
* @return a <code>String</code> representing the family name of the
* font, localized for the specified locale.
* @see #getFontName
* @see java.util.Locale
* @since 1.2
*/
public String getFamily(Locale l) {
if (l == null) {
throw new NullPointerException("null locale doesn't mean default");
}
return getFont2D().getFamilyName(l);
}
/**
* Returns the postscript name of this <code>Font</code>.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> representing the postscript name of
* this <code>Font</code>.
* @since 1.2
*/
public String getPSName() {
return getFont2D().getPostscriptName();
}
/**
* Returns the logical name of this <code>Font</code>.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> representing the logical name of
* this <code>Font</code>.
* @see #getFamily
* @see #getFontName
* @since JDK1.0
*/
public String getName() {
return name;
}
/**
* Returns the font face name of this <code>Font</code>. For example,
* Helvetica Bold could be returned as a font face name.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getName</code> to get the logical name of the font.
* @return a <code>String</code> representing the font face name of
* this <code>Font</code>.
* @see #getFamily
* @see #getName
* @since 1.2
*/
public String getFontName() {
return getFontName(Locale.getDefault());
}
/**
* Returns the font face name of the <code>Font</code>, localized
* for the specified locale. For example, Helvetica Fett could be
* returned as the font face name.
* Use <code>getFamily</code> to get the family name of the font.
* @param l a locale for which to get the font face name
* @return a <code>String</code> representing the font face name,
* localized for the specified locale.
* @see #getFamily
* @see java.util.Locale
*/
public String getFontName(Locale l) {
if (l == null) {
throw new NullPointerException("null locale doesn't mean default");
}
return getFont2D().getFontName(l);
}
/**
* Returns the style of this <code>Font</code>. The style can be
* PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
* @return the style of this <code>Font</code>
* @see #isPlain
* @see #isBold
* @see #isItalic
* @since JDK1.0
*/
public int getStyle() {
return style;
}
/**
* Returns the point size of this <code>Font</code>, rounded to
* an integer.
* Most users are familiar with the idea of using <i>point size</i> to
* specify the size of glyphs in a font. This point size defines a
* measurement between the baseline of one line to the baseline of the
* following line in a single spaced text document. The point size is
* based on <i>typographic points</i>, approximately 1/72 of an inch.
* <p>
* The Java(tm)2D API adopts the convention that one point is
* equivalent to one unit in user coordinates. When using a
* normalized transform for converting user space coordinates to
* device space coordinates 72 user
* space units equal 1 inch in device space. In this case one point
* is 1/72 of an inch.
* @return the point size of this <code>Font</code> in 1/72 of an
* inch units.
* @see #getSize2D
* @see GraphicsConfiguration#getDefaultTransform
* @see GraphicsConfiguration#getNormalizingTransform
* @since JDK1.0
*/
public int getSize() {
return size;
}
/**
* Returns the point size of this <code>Font</code> in
* <code>float</code> value.
* @return the point size of this <code>Font</code> as a
* <code>float</code> value.
* @see #getSize
* @since 1.2
*/
public float getSize2D() {
return pointSize;
}
/**
* Indicates whether or not this <code>Font</code> object's style is
* PLAIN.
* @return <code>true</code> if this <code>Font</code> has a
* PLAIN sytle;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isPlain() {
return style == 0;
}
/**
* Indicates whether or not this <code>Font</code> object's style is
* BOLD.
* @return <code>true</code> if this <code>Font</code> object's
* style is BOLD;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isBold() {
return (style & BOLD) != 0;
}
/**
* Indicates whether or not this <code>Font</code> object's style is
* ITALIC.
* @return <code>true</code> if this <code>Font</code> object's
* style is ITALIC;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isItalic() {
return (style & ITALIC) != 0;
}
/**
* Indicates whether or not this <code>Font</code> object has a
* transform that affects its size in addition to the Size
* attribute.
* @return <code>true</code> if this <code>Font</code> object
* has a non-identity AffineTransform attribute.
* <code>false</code> otherwise.
* @see java.awt.Font#getTransform
* @since 1.4
*/
public boolean isTransformed() {
return nonIdentityTx;
}
/**
* Return true if this Font contains attributes that require extra
* layout processing.
* @return true if the font has layout attributes
* @since 1.6
*/
public boolean hasLayoutAttributes() {
return hasLayoutAttributes;
}
/**
* Returns a <code>Font</code> object from the system properties list.
* <code>nm</code> is treated as the name of a system property to be
* obtained. The <code>String</code> value of this property is then
* interpreted as a <code>Font</code> object according to the
* specification of <code>Font.decode(String)</code>
* If the specified property is not found, or the executing code does
* not have permission to read the property, null is returned instead.
*
* @param nm the property name
* @return a <code>Font</code> object that the property name
* describes, or null if no such property exists.
* @throws NullPointerException if nm is null.
* @since 1.2
* @see #decode(String)
*/
public static Font getFont(String nm) {
return getFont(nm, null);
}
/**
* Returns the <code>Font</code> that the <code>str</code>
* argument describes.
* To ensure that this method returns the desired Font,
* format the <code>str</code> parameter in
* one of these ways
* <p>
* <ul>
* <li><em>fontname-style-pointsize</em>
* <li><em>fontname-pointsize</em>
* <li><em>fontname-style</em>
* <li><em>fontname</em>
* <li><em>fontname style pointsize</em>
* <li><em>fontname pointsize</em>
* <li><em>fontname style</em>
* <li><em>fontname</em>
* </ul>
* in which <i>style</i> is one of the four
* case-insensitive strings:
* <code>"PLAIN"</code>, <code>"BOLD"</code>, <code>"BOLDITALIC"</code>, or
* <code>"ITALIC"</code>, and pointsize is a positive decimal integer
* representation of the point size.
* For example, if you want a font that is Arial, bold, with
* a point size of 18, you would call this method with:
* "Arial-BOLD-18".
* This is equivalent to calling the Font constructor :
* <code>new Font("Arial", Font.BOLD, 18);</code>
* and the values are interpreted as specified by that constructor.
* <p>
* A valid trailing decimal field is always interpreted as the pointsize.
* Therefore a fontname containing a trailing decimal value should not
* be used in the fontname only form.
* <p>
* If a style name field is not one of the valid style strings, it is
* interpreted as part of the font name, and the default style is used.
* <p>
* Only one of ' ' or '-' may be used to separate fields in the input.
* The identified separator is the one closest to the end of the string
* which separates a valid pointsize, or a valid style name from
* the rest of the string.
* Null (empty) pointsize and style fields are treated
* as valid fields with the default value for that field.
*<p>
* Some font names may include the separator characters ' ' or '-'.
* If <code>str</code> is not formed with 3 components, e.g. such that
* <code>style</code> or <code>pointsize</code> fields are not present in
* <code>str</code>, and <code>fontname</code> also contains a
* character determined to be the separator character
* then these characters where they appear as intended to be part of
* <code>fontname</code> may instead be interpreted as separators
* so the font name may not be properly recognised.
*
* <p>
* The default size is 12 and the default style is PLAIN.
* If <code>str</code> does not specify a valid size, the returned
* <code>Font</code> has a size of 12. If <code>str</code> does not
* specify a valid style, the returned Font has a style of PLAIN.
* If you do not specify a valid font name in
* the <code>str</code> argument, this method will return
* a font with the family name "Dialog".
* To determine what font family names are available on
* your system, use the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
* If <code>str</code> is <code>null</code>, a new <code>Font</code>
* is returned with the family name "Dialog", a size of 12 and a
* PLAIN style.
* @param str the name of the font, or <code>null</code>
* @return the <code>Font</code> object that <code>str</code>
* describes, or a new default <code>Font</code> if
* <code>str</code> is <code>null</code>.
* @see #getFamily
* @since JDK1.1
*/
public static Font decode(String str) {
String fontName = str;
String styleName = "";
int fontSize = 12;
int fontStyle = Font.PLAIN;
if (str == null) {
return new Font(DIALOG, fontStyle, fontSize);
}
int lastHyphen = str.lastIndexOf('-');
int lastSpace = str.lastIndexOf(' ');
char sepChar = (lastHyphen > lastSpace) ? '-' : ' ';
int sizeIndex = str.lastIndexOf(sepChar);
int styleIndex = str.lastIndexOf(sepChar, sizeIndex-1);
int strlen = str.length();
if (sizeIndex > 0 && sizeIndex+1 < strlen) {
try {
fontSize =
Integer.valueOf(str.substring(sizeIndex+1)).intValue();
if (fontSize <= 0) {
fontSize = 12;
}
} catch (NumberFormatException e) {
/* It wasn't a valid size, if we didn't also find the
* start of the style string perhaps this is the style */
styleIndex = sizeIndex;
sizeIndex = strlen;
if (str.charAt(sizeIndex-1) == sepChar) {
sizeIndex--;
}
}
}
if (styleIndex >= 0 && styleIndex+1 < strlen) {
styleName = str.substring(styleIndex+1, sizeIndex);
styleName = styleName.toLowerCase(Locale.ENGLISH);
if (styleName.equals("bolditalic")) {
fontStyle = Font.BOLD | Font.ITALIC;
} else if (styleName.equals("italic")) {
fontStyle = Font.ITALIC;
} else if (styleName.equals("bold")) {
fontStyle = Font.BOLD;
} else if (styleName.equals("plain")) {
fontStyle = Font.PLAIN;
} else {
/* this string isn't any of the expected styles, so
* assume its part of the font name
*/
styleIndex = sizeIndex;
if (str.charAt(styleIndex-1) == sepChar) {
styleIndex--;
}
}
fontName = str.substring(0, styleIndex);
} else {
int fontEnd = strlen;
if (styleIndex > 0) {
fontEnd = styleIndex;
} else if (sizeIndex > 0) {
fontEnd = sizeIndex;
}
if (fontEnd > 0 && str.charAt(fontEnd-1) == sepChar) {
fontEnd--;
}
fontName = str.substring(0, fontEnd);
}
return new Font(fontName, fontStyle, fontSize);
}
/**
* Gets the specified <code>Font</code> from the system properties
* list. As in the <code>getProperty</code> method of
* <code>System</code>, the first
* argument is treated as the name of a system property to be
* obtained. The <code>String</code> value of this property is then
* interpreted as a <code>Font</code> object.
* <p>
* The property value should be one of the forms accepted by
* <code>Font.decode(String)</code>
* If the specified property is not found, or the executing code does not
* have permission to read the property, the <code>font</code>
* argument is returned instead.
* @param nm the case-insensitive property name
* @param font a default <code>Font</code> to return if property
* <code>nm</code> is not defined
* @return the <code>Font</code> value of the property.
* @throws NullPointerException if nm is null.
* @see #decode(String)
*/
public static Font getFont(String nm, Font font) {
String str = null;
try {
str =System.getProperty(nm);
} catch(SecurityException e) {
}
if (str == null) {
return font;
}
return decode ( str );
}
transient int hash;
/**
* Returns a hashcode for this <code>Font</code>.
* @return a hashcode value for this <code>Font</code>.
* @since JDK1.0
*/
public int hashCode() {
if (hash == 0) {
hash = name.hashCode() ^ style ^ size;
/* It is possible many fonts differ only in transform.
* So include the transform in the hash calculation.
* nonIdentityTx is set whenever there is a transform in
* 'values'. The tests for null are required because it can
* also be set for other reasons.
*/
if (nonIdentityTx &&
values != null && values.getTransform() != null) {
hash ^= values.getTransform().hashCode();
}
}
return hash;
}
/**
* Compares this <code>Font</code> object to the specified
* <code>Object</code>.
* @param obj the <code>Object</code> to compare
* @return <code>true</code> if the objects are the same
* or if the argument is a <code>Font</code> object
* describing the same font as this object;
* <code>false</code> otherwise.
* @since JDK1.0
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null) {
try {
Font font = (Font)obj;
if (size == font.size &&
style == font.style &&
nonIdentityTx == font.nonIdentityTx &&
hasLayoutAttributes == font.hasLayoutAttributes &&
pointSize == font.pointSize &&
name.equals(font.name)) {
/* 'values' is usually initialized lazily, except when
* the font is constructed from a Map, or derived using
* a Map or other values. So if only one font has
* the field initialized we need to initialize it in
* the other instance and compare.
*/
if (values == null) {
if (font.values == null) {
return true;
} else {
return getAttributeValues().equals(font.values);
}
} else {
return values.equals(font.getAttributeValues());
}
}
}
catch (ClassCastException e) {
}
}
return false;
}
/**
* Converts this <code>Font</code> object to a <code>String</code>
* representation.
* @return a <code>String</code> representation of this
* <code>Font</code> object.
* @since JDK1.0
*/
// NOTE: This method may be called by privileged threads.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
public String toString() {
String strStyle;
if (isBold()) {
strStyle = isItalic() ? "bolditalic" : "bold";
} else {
strStyle = isItalic() ? "italic" : "plain";
}
return getClass().getName() + "[family=" + getFamily() + ",name=" + name + ",style=" +
strStyle + ",size=" + size + "]";
} // toString()
/** Serialization support. A <code>readObject</code>
* method is neccessary because the constructor creates
* the font's peer, and we can't serialize the peer.
* Similarly the computed font "family" may be different
* at <code>readObject</code> time than at
* <code>writeObject</code> time. An integer version is
* written so that future versions of this class will be
* able to recognize serialized output from this one.
*/
/**
* The <code>Font</code> Serializable Data Form.
*
* @serial
*/
private int fontSerializedDataVersion = 1;
/**
* Writes default serializable fields to a stream.
*
* @param s the <code>ObjectOutputStream</code> to write
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see #readObject(java.io.ObjectInputStream)
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.lang.ClassNotFoundException,
java.io.IOException
{
if (values != null) {
synchronized(values) {
// transient
fRequestedAttributes = values.toSerializableHashtable();
s.defaultWriteObject();
fRequestedAttributes = null;
}
} else {
s.defaultWriteObject();
}
}
/**
* Reads the <code>ObjectInputStream</code>.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @serial
* @see #writeObject(java.io.ObjectOutputStream)
*/
private void readObject(java.io.ObjectInputStream s)
throws java.lang.ClassNotFoundException,
java.io.IOException
{
s.defaultReadObject();
if (pointSize == 0) {
pointSize = (float)size;
}
// Handle fRequestedAttributes.
// in 1.5, we always streamed out the font values plus
// TRANSFORM, SUPERSCRIPT, and WIDTH, regardless of whether the
// values were default or not. In 1.6 we only stream out
// defined values. So, 1.6 streams in from a 1.5 stream,
// it check each of these values and 'undefines' it if the
// value is the default.
if (fRequestedAttributes != null) {
values = getAttributeValues(); // init
AttributeValues extras =
AttributeValues.fromSerializableHashtable(fRequestedAttributes);
if (!AttributeValues.is16Hashtable(fRequestedAttributes)) {
extras.unsetDefault(); // if legacy stream, undefine these
}
values = getAttributeValues().merge(extras);
this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);
this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);
fRequestedAttributes = null; // don't need it any more
}
}
/**
* Returns the number of glyphs in this <code>Font</code>. Glyph codes
* for this <code>Font</code> range from 0 to
* <code>getNumGlyphs()</code> - 1.
* @return the number of glyphs in this <code>Font</code>.
* @since 1.2
*/
public int getNumGlyphs() {
return getFont2D().getNumGlyphs();
}
/**
* Returns the glyphCode which is used when this <code>Font</code>
* does not have a glyph for a specified unicode code point.
* @return the glyphCode of this <code>Font</code>.
* @since 1.2
*/
public int getMissingGlyphCode() {
return getFont2D().getMissingGlyphCode();
}
/**
* Returns the baseline appropriate for displaying this character.
* <p>
* Large fonts can support different writing systems, and each system can
* use a different baseline.
* The character argument determines the writing system to use. Clients
* should not assume all characters use the same baseline.
*
* @param c a character used to identify the writing system
* @return the baseline appropriate for the specified character.
* @see LineMetrics#getBaselineOffsets
* @see #ROMAN_BASELINE
* @see #CENTER_BASELINE
* @see #HANGING_BASELINE
* @since 1.2
*/
public byte getBaselineFor(char c) {
return getFont2D().getBaselineFor(c);
}
/**
* Returns a map of font attributes available in this
* <code>Font</code>. Attributes include things like ligatures and
* glyph substitution.
* @return the attributes map of this <code>Font</code>.
*/
public Map<TextAttribute,?> getAttributes(){
return new AttributeMap(getAttributeValues());
}
/**
* Returns the keys of all the attributes supported by this
* <code>Font</code>. These attributes can be used to derive other
* fonts.
* @return an array containing the keys of all the attributes
* supported by this <code>Font</code>.
* @since 1.2
*/
public Attribute[] getAvailableAttributes() {
// FONT is not supported by Font
Attribute attributes[] = {
TextAttribute.FAMILY,
TextAttribute.WEIGHT,
TextAttribute.WIDTH,
TextAttribute.POSTURE,
TextAttribute.SIZE,
TextAttribute.TRANSFORM,
TextAttribute.SUPERSCRIPT,
TextAttribute.CHAR_REPLACEMENT,
TextAttribute.FOREGROUND,
TextAttribute.BACKGROUND,
TextAttribute.UNDERLINE,
TextAttribute.STRIKETHROUGH,
TextAttribute.RUN_DIRECTION,
TextAttribute.BIDI_EMBEDDING,
TextAttribute.JUSTIFICATION,
TextAttribute.INPUT_METHOD_HIGHLIGHT,
TextAttribute.INPUT_METHOD_UNDERLINE,
TextAttribute.SWAP_COLORS,
TextAttribute.NUMERIC_SHAPING,
TextAttribute.KERNING,
TextAttribute.LIGATURES,
TextAttribute.TRACKING,
};
return attributes;
}
/**
* Creates a new <code>Font</code> object by replicating this
* <code>Font</code> object and applying a new style and size.
* @param style the style for the new <code>Font</code>
* @param size the size for the new <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(int style, float size){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
newValues.setSize(size);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/**
* Creates a new <code>Font</code> object by replicating this
* <code>Font</code> object and applying a new style and transform.
* @param style the style for the new <code>Font</code>
* @param trans the <code>AffineTransform</code> associated with the
* new <code>Font</code>
* @return a new <code>Font</code> object.
* @throws IllegalArgumentException if <code>trans</code> is
* <code>null</code>
* @since 1.2
*/
public Font deriveFont(int style, AffineTransform trans){
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
applyTransform(trans, newValues);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/**
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new size to it.
* @param size the size for the new <code>Font</code>.
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(float size){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
newValues.setSize(size);
return new Font(newValues, null, -1, createdFont, font2DHandle);
}
/**
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new transform to it.
* @param trans the <code>AffineTransform</code> associated with the
* new <code>Font</code>
* @return a new <code>Font</code> object.
* @throws IllegalArgumentException if <code>trans</code> is
* <code>null</code>
* @since 1.2
*/
public Font deriveFont(AffineTransform trans){
AttributeValues newValues = getAttributeValues().clone();
applyTransform(trans, newValues);
return new Font(newValues, null, -1, createdFont, font2DHandle);
}
/**
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new style to it.
* @param style the style for the new <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(int style){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/**
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new set of font attributes
* to it.
*
* @param attributes a map of attributes enabled for the new
* <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(Map<? extends Attribute, ?> attributes) {
if (attributes == null) {
return this;
}
AttributeValues newValues = getAttributeValues().clone();
newValues.merge(attributes, RECOGNIZED_MASK);
return new Font(newValues, name, style, createdFont, font2DHandle);
}
/**
* Checks if this <code>Font</code> has a glyph for the specified
* character.
*
* <p> <b>Note:</b> This method cannot handle <a
* href="../../java/lang/Character.html#supplementary"> supplementary
* characters</a>. To support all Unicode characters, including
* supplementary characters, use the {@link #canDisplay(int)}
* method or <code>canDisplayUpTo</code> methods.
*
* @param c the character for which a glyph is needed
* @return <code>true</code> if this <code>Font</code> has a glyph for this
* character; <code>false</code> otherwise.
* @since 1.2
*/
public boolean canDisplay(char c){
return getFont2D().canDisplay(c);
}
/**
* Checks if this <code>Font</code> has a glyph for the specified
* character.
*
* @param codePoint the character (Unicode code point) for which a glyph
* is needed.
* @return <code>true</code> if this <code>Font</code> has a glyph for the
* character; <code>false</code> otherwise.
* @throws IllegalArgumentException if the code point is not a valid Unicode
* code point.
* @see Character#isValidCodePoint(int)
* @since 1.5
*/
public boolean canDisplay(int codePoint) {
if (!Character.isValidCodePoint(codePoint)) {
throw new IllegalArgumentException("invalid code point: " +
Integer.toHexString(codePoint));
}
return getFont2D().canDisplay(codePoint);
}
/**
* Indicates whether or not this <code>Font</code> can display a
* specified <code>String</code>. For strings with Unicode encoding,
* it is important to know if a particular font can display the
* string. This method returns an offset into the <code>String</code>
* <code>str</code> which is the first character this
* <code>Font</code> cannot display without using the missing glyph
* code. If the <code>Font</code> can display all characters, -1 is
* returned.
* @param str a <code>String</code> object
* @return an offset into <code>str</code> that points
* to the first character in <code>str</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>str</code>.
* @since 1.2
*/
public int canDisplayUpTo(String str) {
Font2D font2d = getFont2D();
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (font2d.canDisplay(c)) {
continue;
}
if (!Character.isHighSurrogate(c)) {
return i;
}
if (!font2d.canDisplay(str.codePointAt(i))) {
return i;
}
i++;
}
return -1;
}
/**
* Indicates whether or not this <code>Font</code> can display
* the characters in the specified <code>text</code>
* starting at <code>start</code> and ending at
* <code>limit</code>. This method is a convenience overload.
* @param text the specified array of <code>char</code> values
* @param start the specified starting offset (in
* <code>char</code>s) into the specified array of
* <code>char</code> values
* @param limit the specified ending offset (in
* <code>char</code>s) into the specified array of
* <code>char</code> values
* @return an offset into <code>text</code> that points
* to the first character in <code>text</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>text</code>.
* @since 1.2
*/
public int canDisplayUpTo(char[] text, int start, int limit) {
Font2D font2d = getFont2D();
for (int i = start; i < limit; i++) {
char c = text[i];
if (font2d.canDisplay(c)) {
continue;
}
if (!Character.isHighSurrogate(c)) {
return i;
}
if (!font2d.canDisplay(Character.codePointAt(text, i, limit))) {
return i;
}
i++;
}
return -1;
}
/**
* Indicates whether or not this <code>Font</code> can display the
* text specified by the <code>iter</code> starting at
* <code>start</code> and ending at <code>limit</code>.
*
* @param iter a {@link CharacterIterator} object
* @param start the specified starting offset into the specified
* <code>CharacterIterator</code>.
* @param limit the specified ending offset into the specified
* <code>CharacterIterator</code>.
* @return an offset into <code>iter</code> that points
* to the first character in <code>iter</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>iter</code>.
* @since 1.2
*/
public int canDisplayUpTo(CharacterIterator iter, int start, int limit) {
Font2D font2d = getFont2D();
char c = iter.setIndex(start);
for (int i = start; i < limit; i++, c = iter.next()) {
if (font2d.canDisplay(c)) {
continue;
}
if (!Character.isHighSurrogate(c)) {
return i;
}
char c2 = iter.next();
// c2 could be CharacterIterator.DONE which is not a low surrogate.
if (!Character.isLowSurrogate(c2)) {
return i;
}
if (!font2d.canDisplay(Character.toCodePoint(c, c2))) {
return i;
}
i++;
}
return -1;
}
/**
* Returns the italic angle of this <code>Font</code>. The italic angle
* is the inverse slope of the caret which best matches the posture of this
* <code>Font</code>.
* @see TextAttribute#POSTURE
* @return the angle of the ITALIC style of this <code>Font</code>.
*/
public float getItalicAngle() {
return getItalicAngle(null);
}
/* The FRC hints don't affect the value of the italic angle but
* we need to pass them in to look up a strike.
* If we can pass in ones already being used it can prevent an extra
* strike from being allocated. Note that since italic angle is
* a property of the font, the font transform is needed not the
* device transform. Finally, this is private but the only caller of this
* in the JDK - and the only likely caller - is in this same class.
*/
private float getItalicAngle(FontRenderContext frc) {
Object aa, fm;
if (frc == null) {
aa = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
fm = RenderingHints.VALUE_FRACTIONALMETRICS_OFF;
} else {
aa = frc.getAntiAliasingHint();
fm = frc.getFractionalMetricsHint();
}
return getFont2D().getItalicAngle(this, identityTx, aa, fm);
}
/**
* Checks whether or not this <code>Font</code> has uniform
* line metrics. A logical <code>Font</code> might be a
* composite font, which means that it is composed of different
* physical fonts to cover different code ranges. Each of these
* fonts might have different <code>LineMetrics</code>. If the
* logical <code>Font</code> is a single
* font then the metrics would be uniform.
* @return <code>true</code> if this <code>Font</code> has
* uniform line metrics; <code>false</code> otherwise.
*/
public boolean hasUniformLineMetrics() {
return false; // REMIND always safe, but prevents caller optimize
}
private transient SoftReference flmref;
private FontLineMetrics defaultLineMetrics(FontRenderContext frc) {
FontLineMetrics flm = null;
if (flmref == null
|| (flm = (FontLineMetrics)flmref.get()) == null
|| !flm.frc.equals(frc)) {
/* The device transform in the frc is not used in obtaining line
* metrics, although it probably should be: REMIND find why not?
* The font transform is used but its applied in getFontMetrics, so
* just pass identity here
*/
float [] metrics = new float[8];
getFont2D().getFontMetrics(this, identityTx,
frc.getAntiAliasingHint(),
frc.getFractionalMetricsHint(),
metrics);
float ascent = metrics[0];
float descent = metrics[1];
float leading = metrics[2];
float ssOffset = 0;
if (values != null && values.getSuperscript() != 0) {
ssOffset = (float)getTransform().getTranslateY();
ascent -= ssOffset;
descent += ssOffset;
}
float height = ascent + descent + leading;
int baselineIndex = 0; // need real index, assumes roman for everything
// need real baselines eventually
float[] baselineOffsets = { 0, (descent/2f - ascent) / 2f, -ascent };
float strikethroughOffset = metrics[4];
float strikethroughThickness = metrics[5];
float underlineOffset = metrics[6];
float underlineThickness = metrics[7];
float italicAngle = getItalicAngle(frc);
if (isTransformed()) {
AffineTransform ctx = values.getCharTransform(); // extract rotation
if (ctx != null) {
Point2D.Float pt = new Point2D.Float();
pt.setLocation(0, strikethroughOffset);
ctx.deltaTransform(pt, pt);
strikethroughOffset = pt.y;
pt.setLocation(0, strikethroughThickness);
ctx.deltaTransform(pt, pt);
strikethroughThickness = pt.y;
pt.setLocation(0, underlineOffset);
ctx.deltaTransform(pt, pt);
underlineOffset = pt.y;
pt.setLocation(0, underlineThickness);
ctx.deltaTransform(pt, pt);
underlineThickness = pt.y;
}
}
strikethroughOffset += ssOffset;
underlineOffset += ssOffset;
CoreMetrics cm = new CoreMetrics(ascent, descent, leading, height,
baselineIndex, baselineOffsets,
strikethroughOffset, strikethroughThickness,
underlineOffset, underlineThickness,
ssOffset, italicAngle);
flm = new FontLineMetrics(0, cm, frc);
flmref = new SoftReference(flm);
}
return (FontLineMetrics)flm.clone();
}
/**
* Returns a {@link LineMetrics} object created with the specified
* <code>String</code> and {@link FontRenderContext}.
* @param str the specified <code>String</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified <code>String</code> and {@link FontRenderContext}.
*/
public LineMetrics getLineMetrics( String str, FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
flm.numchars = str.length();
return flm;
}
/**
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param str the specified <code>String</code>
* @param beginIndex the initial offset of <code>str</code>
* @param limit the end offset of <code>str</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics( String str,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/**
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param chars an array of characters
* @param beginIndex the initial offset of <code>chars</code>
* @param limit the end offset of <code>chars</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics(char [] chars,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/**
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param ci the specified <code>CharacterIterator</code>
* @param beginIndex the initial offset in <code>ci</code>
* @param limit the end offset of <code>ci</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics(CharacterIterator ci,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/**
* Returns the logical bounds of the specified <code>String</code> in
* the specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param str the specified <code>String</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a {@link Rectangle2D} that is the bounding box of the
* specified <code>String</code> in the specified
* <code>FontRenderContext</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds( String str, FontRenderContext frc) {
char[] array = str.toCharArray();
return getStringBounds(array, 0, array.length, frc);
}
/**
* Returns the logical bounds of the specified <code>String</code> in
* the specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param str the specified <code>String</code>
* @param beginIndex the initial offset of <code>str</code>
* @param limit the end offset of <code>str</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* specified <code>String</code> in the specified
* <code>FontRenderContext</code>.
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than zero, or <code>limit</code> is greater than the
* length of <code>str</code>, or <code>beginIndex</code>
* is greater than <code>limit</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds( String str,
int beginIndex, int limit,
FontRenderContext frc) {
String substr = str.substring(beginIndex, limit);
return getStringBounds(substr, frc);
}
/**
* Returns the logical bounds of the specified array of characters
* in the specified <code>FontRenderContext</code>. The logical
* bounds contains the origin, ascent, advance, and height, which
* includes the leading. The logical bounds does not always enclose
* all the text. For example, in some languages and in some fonts,
* accent marks can be positioned above the ascent or below the
* descent. To obtain a visual bounding box, which encloses all the
* text, use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param chars an array of characters
* @param beginIndex the initial offset in the array of
* characters
* @param limit the end offset in the array of characters
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* specified array of characters in the specified
* <code>FontRenderContext</code>.
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than zero, or <code>limit</code> is greater than the
* length of <code>chars</code>, or <code>beginIndex</code>
* is greater than <code>limit</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds(char [] chars,
int beginIndex, int limit,
FontRenderContext frc) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
}
if (limit > chars.length) {
throw new IndexOutOfBoundsException("limit: " + limit);
}
if (beginIndex > limit) {
throw new IndexOutOfBoundsException("range length: " +
(limit - beginIndex));
}
// this code should be in textlayout
// quick check for simple text, assume GV ok to use if simple
boolean simple = values == null ||
(values.getKerning() == 0 && values.getLigatures() == 0 &&
values.getBaselineTransform() == null);
if (simple) {
simple = ! FontUtilities.isComplexText(chars, beginIndex, limit);
}
if (simple) {
GlyphVector gv = new StandardGlyphVector(this, chars, beginIndex,
limit - beginIndex, frc);
return gv.getLogicalBounds();
} else {
// need char array constructor on textlayout
String str = new String(chars, beginIndex, limit - beginIndex);
TextLayout tl = new TextLayout(str, this, frc);
return new Rectangle2D.Float(0, -tl.getAscent(), tl.getAdvance(),
tl.getAscent() + tl.getDescent() +
tl.getLeading());
}
}
/**
* Returns the logical bounds of the characters indexed in the
* specified {@link CharacterIterator} in the
* specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param ci the specified <code>CharacterIterator</code>
* @param beginIndex the initial offset in <code>ci</code>
* @param limit the end offset in <code>ci</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* characters indexed in the specified <code>CharacterIterator</code>
* in the specified <code>FontRenderContext</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than the start index of <code>ci</code>, or
* <code>limit</code> is greater than the end index of
* <code>ci</code>, or <code>beginIndex</code> is greater
* than <code>limit</code>
*/
public Rectangle2D getStringBounds(CharacterIterator ci,
int beginIndex, int limit,
FontRenderContext frc) {
int start = ci.getBeginIndex();
int end = ci.getEndIndex();
if (beginIndex < start) {
throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
}
if (limit > end) {
throw new IndexOutOfBoundsException("limit: " + limit);
}
if (beginIndex > limit) {
throw new IndexOutOfBoundsException("range length: " +
(limit - beginIndex));
}
char[] arr = new char[limit - beginIndex];
ci.setIndex(beginIndex);
for(int idx = 0; idx < arr.length; idx++) {
arr[idx] = ci.current();
ci.next();
}
return getStringBounds(arr,0,arr.length,frc);
}
/**
* Returns the bounds for the character with the maximum
* bounds as defined in the specified <code>FontRenderContext</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box
* for the character with the maximum bounds.
*/
public Rectangle2D getMaxCharBounds(FontRenderContext frc) {
float [] metrics = new float[4];
getFont2D().getFontMetrics(this, frc, metrics);
return new Rectangle2D.Float(0, -metrics[0],
metrics[3],
metrics[0] + metrics[1] + metrics[2]);
}
/**
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param str the specified <code>String</code>
* @return a new <code>GlyphVector</code> created with the
* specified <code>String</code> and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector(FontRenderContext frc, String str)
{
return (GlyphVector)new StandardGlyphVector(this, str, frc);
}
/**
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param chars the specified array of characters
* @return a new <code>GlyphVector</code> created with the
* specified array of characters and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)
{
return (GlyphVector)new StandardGlyphVector(this, chars, frc);
}
/**
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping the specified characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param ci the specified <code>CharacterIterator</code>
* @return a new <code>GlyphVector</code> created with the
* specified <code>CharacterIterator</code> and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector( FontRenderContext frc,
CharacterIterator ci)
{
return (GlyphVector)new StandardGlyphVector(this, ci, frc);
}
/**
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param glyphCodes the specified integer array
* @return a new <code>GlyphVector</code> created with the
* specified integer array and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector( FontRenderContext frc,
int [] glyphCodes)
{
return (GlyphVector)new StandardGlyphVector(this, glyphCodes, frc);
}
/**
* Returns a new <code>GlyphVector</code> object, performing full
* layout of the text if possible. Full layout is required for
* complex text, such as Arabic or Hindi. Support for different
* scripts depends on the font and implementation.
* <p>
* Layout requires bidi analysis, as performed by
* <code>Bidi</code>, and should only be performed on text that
* has a uniform direction. The direction is indicated in the
* flags parameter,by using LAYOUT_RIGHT_TO_LEFT to indicate a
* right-to-left (Arabic and Hebrew) run direction, or
* LAYOUT_LEFT_TO_RIGHT to indicate a left-to-right (English)
* run direction.
* <p>
* In addition, some operations, such as Arabic shaping, require
* context, so that the characters at the start and limit can have
* the proper shapes. Sometimes the data in the buffer outside
* the provided range does not have valid data. The values
* LAYOUT_NO_START_CONTEXT and LAYOUT_NO_LIMIT_CONTEXT can be
* added to the flags parameter to indicate that the text before
* start, or after limit, respectively, should not be examined
* for context.
* <p>
* All other values for the flags parameter are reserved.
*
* @param frc the specified <code>FontRenderContext</code>
* @param text the text to layout
* @param start the start of the text to use for the <code>GlyphVector</code>
* @param limit the limit of the text to use for the <code>GlyphVector</code>
* @param flags control flags as described above
* @return a new <code>GlyphVector</code> representing the text between
* start and limit, with glyphs chosen and positioned so as to best represent
* the text
* @throws ArrayIndexOutOfBoundsException if start or limit is
* out of bounds
* @see java.text.Bidi
* @see #LAYOUT_LEFT_TO_RIGHT
* @see #LAYOUT_RIGHT_TO_LEFT
* @see #LAYOUT_NO_START_CONTEXT
* @see #LAYOUT_NO_LIMIT_CONTEXT
* @since 1.4
*/
public GlyphVector layoutGlyphVector(FontRenderContext frc,
char[] text,
int start,
int limit,
int flags) {
return new StandardGlyphVector(this,text,start, limit-start, frc);
}
/**
* A flag to layoutGlyphVector indicating that text is left-to-right as
* determined by Bidi analysis.
*/
public static final int LAYOUT_LEFT_TO_RIGHT = 0;
/**
* A flag to layoutGlyphVector indicating that text is right-to-left as
* determined by Bidi analysis.
*/
public static final int LAYOUT_RIGHT_TO_LEFT = 1;
/**
* A flag to layoutGlyphVector indicating that text in the char array
* before the indicated start should not be examined.
*/
public static final int LAYOUT_NO_START_CONTEXT = 2;
/**
* A flag to layoutGlyphVector indicating that text in the char array
* after the indicated limit should not be examined.
*/
public static final int LAYOUT_NO_LIMIT_CONTEXT = 4;
private static void applyTransform(AffineTransform trans, AttributeValues values) {
if (trans == null) {
throw new IllegalArgumentException("transform must not be null");
}
values.setTransform(trans);
}
private static void applyStyle(int style, AttributeValues values) {
// WEIGHT_BOLD, WEIGHT_REGULAR
values.setWeight((style & BOLD) != 0 ? 2f : 1f);
// POSTURE_OBLIQUE, POSTURE_REGULAR
values.setPosture((style & ITALIC) != 0 ? .2f : 0f);
}
}
|
<gh_stars>1-10
// TextStream.cpp: implementation of the CTextStream class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <no5tl\utils.h>
#include <no5tl\mystring.h>
#include <no5tl\colorfader.h>
#include <yahoo\myutf8.h>
#include "TextStream.h"
using namespace NO5YAHOO;
using namespace NO5TL;
static int ParseFadeTag(LPCTSTR tag,CSimpleArray<CYahooColor> &lst);
static int MakeColorList(const CSimpleArray<CString> &in,
CSimpleArray<CYahooColor> &out);
static void ParseKeyValuePairs(LPCTSTR text,CNo5SimpleMap<CString,CString> &pairs,
CSimpleArray<CString> &props);
static int MaxStringLen(LPCTSTR a[],int count);
/****************** CTextAtom ************************/
void CTextAtom::Destroy(void)
{
switch(m_type){
case ATOM_FONT:
case ATOM_TATTOO:
if(m_bSet && m_pFont){
delete m_pFont;
}
break;
case ATOM_FADE:
case ATOM_ALT:
if(m_bSet && m_pColors){
delete m_pColors;
}
break;
case ATOM_TEXT:
case ATOM_SMILEY:
case ATOM_HTML:
if(m_pText)
delete m_pText;
break;
case ATOM_LINK:
if(m_bSet && m_pText)
delete m_pText;
else if(!m_bSet)
ATLASSERT(!m_pText);
break;
default:
break;
}
Zero();
}
CTextAtom & CTextAtom::CopyFrom(const CTextAtom &from)
{
if(this != &from){
Destroy();
m_type = from.m_type;
m_bSet = from.m_bSet;
switch(from.m_type){
case ATOM_FONT:
case ATOM_TATTOO:
if(from.m_bSet){
m_pFont = new FontInfo;
if(from.m_pFont){
*m_pFont = *from.m_pFont;
}
}
break;
case ATOM_ALT:
case ATOM_FADE:
if(from.m_bSet){
m_pColors = new CSimpleArray<CYahooColor>;
if(from.m_pColors){
NO5TL::CopySimpleArray<CYahooColor>(*m_pColors,*(from.m_pColors));
}
}
break;
case ATOM_SMILEY:
case ATOM_TEXT:
case ATOM_HTML:
m_pText = new CString();
if(from.m_pText){
*m_pText = *from.m_pText;
}
break;
case ATOM_LINK:
if(from.m_bSet){
m_pText = new CString();
if(from.m_pText){
*m_pText = *from.m_pText;
}
}
else{
ATLASSERT(!from.m_pText); // debug;
}
break;
default:
m_nothing = from.m_nothing;
break;
}
}
return *this;
}
const CTextAtom & CTextAtom::AtomText(LPCTSTR p)
{
if(m_type != ATOM_TEXT){
Destroy();
m_type = ATOM_TEXT;
}
if(!m_pText)
m_pText = new CString;
if(p){
*m_pText = p;
}
return *this;
}
CString CTextAtom::GetYahooCode(void) const
{
CYahooColor color;
switch(m_type){
case ATOM_BOLD:
if(m_bSet)
return CString("\x1b[1m");
else
return CString("\x1b[x1m");
case ATOM_ITALIC:
if(m_bSet)
return CString("\x1b[2m");
else
return CString("\x1b[x2m");
case ATOM_UNDER:
if(m_bSet)
return CString("\x1b[4m");
else
return CString("\x1b[x4m");
case ATOM_COLOR:
color = m_color;
return color.GetString(CYahooColor::YCSF_4);
case ATOM_FONT:
case ATOM_TATTOO:
return MakeFontTag();
case ATOM_FADE:
return MakeFadeAltTag();
case ATOM_ALT:
return MakeFadeAltTag();
case ATOM_CHAR:
return CString(1,m_ch);
case ATOM_TEXT:
if(m_pText)
return *m_pText;
else
return CString();
case ATOM_BREAK:
return CString("\r\n");
case ATOM_SMILEY:
if(m_pText)
return *m_pText;
else
return CString();
case ATOM_LINK:
if(m_bSet && m_pText)
return *m_pText;
else
return CString();
default:
return CString();
}
}
CString CTextAtom::GetInlineCode(void) const
{
CYahooColor color;
switch(m_type){
case ATOM_BOLD:
if(m_bSet)
return CString("<b>");
else
return CString("</b>");
case ATOM_ITALIC:
if(m_bSet)
return CString("<i>");
else
return CString("</i>");
case ATOM_UNDER:
if(m_bSet)
return CString("<u>");
else
return CString("</u>");
case ATOM_COLOR:
color = m_color;
return color.GetString(CYahooColor::YCSF_1);
case ATOM_FONT:
case ATOM_TATTOO:
return MakeFontTag();
case ATOM_FADE:
return MakeFadeAltTag();
case ATOM_ALT:
return MakeFadeAltTag();
case ATOM_CHAR:
return CString(1,m_ch);
case ATOM_TEXT:
if(m_pText)
return *m_pText;
else
return CString();
case ATOM_BREAK:
return CString("\r\n");
case ATOM_SMILEY:
if(m_pText)
return *m_pText;
else
return CString();
case ATOM_LINK:
if(m_bSet && m_pText)
return *m_pText;
else
return CString();
default:
return CString();
}
}
CString CTextAtom::MakeFontTag(void) const
{
CString res;
char tmp[3] = {0};
if(m_bSet){
res += "<font";
if(!m_pFont){
res += '>';
return res;
}
if(m_pFont->HasInfo()){
res += ' ';
res += m_pFont->m_inf.GetCode2();
}
if(!m_pFont->m_face.IsEmpty()){
res += " face=\"";
res += m_pFont->m_face;
res += '\"';
}
if(m_pFont->m_size > 0){
int size = m_pFont->m_size;
res += " size=\"";
if(size > 99){
// we dont need size that long, and this will
// prevent overflowing the buffer tmp[3]
size = 99;
}
wsprintf(tmp,"%d\"",size);
res += tmp;
}
if(m_type == ATOM_TATTOO)
res += " tattoo ";
// TODO: color in font tags
res += '>';
}
else
res = "</font>";
return res;
}
CString CTextAtom::MakeFadeAltTag(void) const
{
CString res;
if(!m_bSet){
if(m_type == ATOM_FADE)
return CString("</fade>");
else if(m_type == ATOM_ALT)
return CString("</alt>");
else{
ATLASSERT(0);
}
}
else{
ATLASSERT(m_pFont != NULL);
res += "<";
}
if(m_type == ATOM_FADE)
res += "fade ";
else
res += "alt ";
CSimpleArray<CYahooColor> &colors = *m_pColors;
for(int i=0;i<colors.GetSize();i++){
res += colors[i].GetString(CYahooColor::YCSF_2);
if(i < colors.GetSize() - 1){
res += ',';
}
else
break;
}
res += '>';
return res;
}
bool CTextAtom::ParseYahooTag(LPCTSTR p)
{
BOOL bSet = TRUE;
CYahooColor color;
LPCTSTR tag = p;
bool res = false;
Destroy();
if(*p != '\x1b')
return false;
if(*++p != '[')
return false;
if(*++p == 'x'){
bSet = FALSE;
p++;
}
if(*p == 'm'){
return true;
}
if(*p == '#'){
if(color.SetFromString(tag)){
res = true;
AtomColor(color);
}
else{
AtomBadtag(ATOM_COLOR);
res = true;
}
return res;
}
else if(*p == 'f'){
if(!bSet){
// i dont know if there are xf tags
AtomFontOff();
return true;
}
else{
LPCTSTR q;
// it has to be between double quotes
p++;
if(*p != '\"')
return false;
q = ++p;
while(*q && *q != '\"' )
q++;
if(*q != '\"')
return false;
if(q > p){
CString tmp;
StringCopyN(tmp,p,0,q - p);
AtomFont(tmp,0);
return true;
}
}
}
else if(*p == 'l'){
AtomLink(bSet);
return true;
}
else if(isdigit(*p)){
int i = atoi(p);
if( i < 0)
return false;
res = true;
switch(i){
case 1:
AtomBold(bSet);
break;
case 2:
AtomItalic(bSet);
break;
case 3:
//m_edit.SetStrike(bSet);
break;
case 4:
AtomUnder(bSet);
break;
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
if(color.SetFromString(tag))
AtomColor(color);
else
res = false;
break;
default:
res = false;
break;
}
}
return res;
}
bool CTextAtom::ParseInlineTag(LPCTSTR tag)
{
LPCTSTR p,q;
CString tmp;
bool res = false;
BOOL bSet = TRUE;
CYahooColor color;
Destroy();
p = q = tag;
if(*q != '<')
return false;
q++;
// skips eventual whitespaces ex: < font
while(::isspace(*q))
q++;
if(!*q) // there was only opening and white spaces <\t\t\t
return false;
if(*q == '>')
return false; // < >
if(*q == '/'){
bSet = FALSE;
q++;
}
// check for a <#abcdef>
else if(*q == '#'){
if(color.SetFromString(tag)){
AtomColor(color);
return true;
}
else{
AtomBadtag(ATOM_COLOR);
return true;
}
}
// check for color names like <red>
else if(::isalpha(*q)){
if(color.SetFromString(tag)){
AtomColor(color);
return true;
}
}
p = q;
// find next white space, signaling the end of the word
while(*q && *q != '>' && !::isspace(*q))
q++;
// in < font size = "10" face="blah">
// q would be after font and p in f
if(!*q)
return false;
StringCopyN(tmp,p,0,q - p);
if(!tmp.CompareNoCase("font")){
if(!bSet){
AtomFontOff();
res = true;
}
else{
CNo5SimpleMap<CString,CString> pairs(false);
CSimpleArray<CString> props;
CString font;
CString size;
CString color;
int nSize = -1;
CYahooColor clr(CLR_INVALID);
CInfoTag inf;
CString tmp = q;
tmp.Remove('>');
ParseKeyValuePairs((LPCSTR)tmp,pairs,props);
font = pairs.Lookup(CString("face"));
size = pairs.Lookup(CString("size"));
color = pairs.Lookup(CString("color"));
if(!font.IsEmpty())
res = true;
if(!size.IsEmpty()){
nSize = atoi(size);
nSize = max(6,min(nSize,36));
res = true;
}
if(!color.IsEmpty()){
if(clr.SetFromString(color)){
res = true;
}
else
clr = CLR_INVALID;
}
// handle "properties" , that is, strings in the font
// tag that are not key=value pairs
if(props.GetSize()){
if(!props[0].CompareNoCase("INF")){
res = inf.Parse(props);
}
else if(!props[0].CompareNoCase("tattoo")){
AtomTattoo(font,nSize,clr);
return true;
}
else{
// we will not add anything to the stream for
// tags like <font blah>
AtomBadtag(ATOM_FONT);
return true;
}
}
// finally set the font atom
if(res){
CInfoTag *pinf = NULL;
if(inf.GetMap().GetSize()){
pinf = &inf;
}
AtomFont(font,nSize,pinf,clr);
}
} // else
} // font
// we will eliminate errors like adding fade-on and alt-on
// without closing the fade-on in the AddAtom method
// or is better to handle it here ?
else if(!tmp.CompareNoCase("fade")){
res = true;
if(bSet){
CSimpleArray<CYahooColor> colors;
if(ParseFadeTag(tag,colors)){
m_bSet = true;
AtomFade(colors);
}
}
else{
m_bSet = false;
AtomFadeOff();
}
}
else if(!tmp.CompareNoCase("alt")){
res = true;
if(bSet){
CSimpleArray<CYahooColor> colors;
if(ParseFadeTag(tag,colors)){
m_bSet = true;
AtomAlt(colors);
}
}
else{
m_bSet = false;
AtomAltOff();
}
}
else if(!tmp.CompareNoCase("b")){
res = true;
AtomBold(bSet);
}
else if(!tmp.CompareNoCase("i")){
res = true;
AtomItalic(bSet);
}
else if(!tmp.CompareNoCase("u")){
res = true;
AtomUnder(bSet);
}
/*
else if(!tmp.CompareNoCase("n")){
res = true;
AtomBreak();
}
*/
return res;
}
/********************* CTextStream ****************/
CTextStream::CTextStream()
{
Reset();
}
CTextStream::~CTextStream()
{
}
void CTextStream::AddYahooText(LPCTSTR text)
{
EnumTags3(text,"<\x1b",">m",*this,TagParser(this));
}
void CTextStream::AddInlineText(LPCTSTR text)
{
EnumTags3(text,"<",">",*this,TagParser(this));
}
void CTextStream::AddPlainText(LPCTSTR text)
{
LPCTSTR p,q;
CTextAtom atom;
CString tmp;
CString smiley;
CString s;
p = q = text;
while( * q ){
// we add a break only if we find "\r\n"
if( (*q == '\r') && (*(q + 1) == '\n') ){
if(q > p){
StringCopyN(tmp,p,0,q - p);
AddAtom(atom.AtomText(tmp));
}
AddAtom(atom.AtomBreak());
q += 2;
p = q;
}
else if(*q == '\r' || *q == '\n'){
if(q > p){
StringCopyN(tmp,p,0,q - p);
AddAtom(atom.AtomText(tmp));
}
p = ++q;
}
else if(IsSmiley(q,smiley)){
if(q > p){
StringCopyN(tmp,p,0,q - p);
AddAtom(atom.AtomText(tmp));
}
AddAtom(atom.AtomSmiley(smiley));
q += smiley.GetLength();
p = q;
}
else if(IsLink(q,smiley)){
if(q > p){
StringCopyN(tmp,p,0,q - p);
AddAtom(atom.AtomText(tmp));
}
p = q;
AddAtom(atom.AtomLink(smiley));
AddAtom(atom.AtomLink(FALSE));
q += smiley.GetLength();
p = q;
}
else
q++;
}
if(q > p){
StringCopyN(tmp,p,0,q - p);
AddAtom(atom.AtomText(tmp));
}
}
CTextStream & CTextStream::AddAtom(const CTextAtom &atom)
{
bool bAdd = true;
const int atom_type = atom.GetType();
if(atom_type == ATOM_FADE){
if(atom.m_bSet){
if(m_fade || m_alt){
// cant open without closing
bAdd = false;
}
else
m_fade = true;
}
else{
// and closing without open
if(!m_fade)
bAdd = false;
else
m_fade = false;
}
if(bAdd && atom.m_bSet){
// lets also save it in the stream
if(atom.m_pColors){
NO5TL::CopySimpleArray(m_colors,*(atom.m_pColors));
}
}
}
else if(atom_type == ATOM_ALT){
if(atom.m_bSet){
if(m_fade || m_alt){
// cant open without closing
bAdd = false;
}
else
m_alt = true;
}
else{
if(!m_fade)
bAdd = false;
else
m_alt = false;
}
if(bAdd && atom.m_bSet){
// lets also save it in the stream
if(atom.m_pColors){
NO5TL::CopySimpleArray(m_colors,*atom.m_pColors);
}
}
}
else if(atom_type == ATOM_FONT){
if(atom.m_bSet){
// save the info tag
if(atom.m_pFont && atom.m_pFont->HasInfo()){
m_inf = atom.m_pFont->m_inf;
}
}
// TODO:
// store font face and font size in the stream
// in case we want to know it
}
else if(atom_type == ATOM_BREAK){
m_breaks++;
}
else if(atom_type == ATOM_SMILEY){
m_smileys++;
}
else if(atom_type == ATOM_LINK){
if(atom.m_bSet)
m_links++;
}
else if(atom_type == ATOM_BADTAG){
m_badtags++;
}
if(bAdd){
m_atoms.Add((CTextAtom &)atom);
// we will add charset atoms here if needed
if(atom.m_type == ATOM_FONT || atom.m_type == ATOM_TATTOO){
if(atom.m_pFont && atom.m_pFont->HasFace()){
CTextAtom atom2;
if(CGetCharSet::IsSymbolCharSet(atom.m_pFont->m_face)){
AddAtom(atom2.AtomCharset(SYMBOL_CHARSET));
}
else{
AddAtom(atom2.AtomCharset(DEFAULT_CHARSET));
}
}
}
//m_atoms.Add((CTextAtom &)atom);
}
return *this;
}
CString CTextStream::GetPlainText(int AtomBegin,int AtomEnd) const
{
int i;
CString s;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomBegin <= AtomEnd);
for(i = AtomBegin;i<AtomEnd;i++){
switch(m_atoms[i].m_type){
case ATOM_CHAR:
s += m_atoms[i].m_ch;
break;
case ATOM_TEXT:
if(m_atoms[i].m_pText){
s += *(m_atoms[i].m_pText);
}
break;
case ATOM_BREAK:
s += "\r\n";
break;
default:
break;
}
}
return s;
}
CString CTextStream::GetPlainText2(int AtomBegin,int AtomEnd) const
{
int i;
CString s;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomBegin <= AtomEnd);
for(i = AtomBegin;i<AtomEnd;i++){
switch(m_atoms[i].m_type){
case ATOM_CHAR:
s += m_atoms[i].m_ch;
break;
case ATOM_TEXT:
if(m_atoms[i].m_pText){
s += *(m_atoms[i].m_pText);
}
break;
case ATOM_BREAK:
s += "\r\n";
break;
case ATOM_SMILEY:
if(m_atoms[i].m_pText){
s += *(m_atoms[i].m_pText);
}
break;
case ATOM_LINK:
if(m_atoms[i].m_bSet && m_atoms[i].m_pText){
s += *(m_atoms[i].m_pText);
}
break;
default:
break;
}
}
return s;
}
CString CTextStream::GetYahooText(int AtomBegin,int AtomEnd) const
{
CString s;
int i;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomBegin < AtomEnd);
// add the info tag string, if we have one
if(!m_inf.IsEmpty()){
s += m_inf.GetCode();
}
for(i = AtomBegin;i<AtomEnd;i++){
s += m_atoms[i].GetYahooCode();
}
return s;
}
CString CTextStream::GetInlineText(int AtomBegin,int AtomEnd) const
{
CString s;
int i;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomBegin < AtomEnd);
for(i = AtomBegin;i<AtomEnd;i++){
s += m_atoms[i].GetInlineCode();
}
return s;
}
int CTextStream::GetPlainTextLength(int AtomStart,int AtomEnd) const
{
int i;
int res = 0;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomStart < AtomEnd);
for(i = AtomStart;i < AtomEnd;i++){
switch(m_atoms[i].GetType()){
case ATOM_TEXT:
if(m_atoms[i].m_pText){
res += m_atoms[i].m_pText->GetLength();
}
break;
case ATOM_CHAR:
res += 1;
break;
}
}
return res;
}
// used to get the length of the text between a begin-fade and
// an end-fade
// atom start must be an ATOM_FADE with m_fade == true
int CTextStream::GetFadeLen(int AtomStart) const
{
int AtomEnd;
ATLASSERT(m_atoms[AtomStart].GetType() == ATOM_FADE);
ATLASSERT(m_atoms[AtomStart].m_bSet == true);
// find the end of the fade
AtomEnd = FindAtom(ATOM_FADE,AtomStart + 1);
if(AtomEnd >= 0){
ATLASSERT(m_atoms[AtomEnd].GetType() == ATOM_FADE);
ATLASSERT(m_atoms[AtomEnd].m_bSet == false);
}
else
AtomEnd = -1;
return GetPlainTextLength(AtomStart,AtomEnd);
}
// returns the index of the first occurent of atom.m_type == m_type
// searchs the range [AtomStart,AtomEnd[
int CTextStream::FindAtom(int type,int AtomStart,int AtomEnd) const
{
int i;
if(AtomEnd < 0 || AtomEnd > m_atoms.GetSize()){
AtomEnd = m_atoms.GetSize();
}
ATLASSERT(AtomStart < AtomEnd);
for(i=AtomStart;i<AtomEnd;i++){
if(m_atoms[i].GetType() == type)
return i;
}
return -1;
}
// default implentation of IsLink
bool CTextStream::IsLink(LPCTSTR p,CString &link)
{
LPCTSTR a[] = { _T("http://"),_T("www."),_T("mailto://")};
const int count = sizeof(a)/sizeof(a[0]);
int i;
CString s;
bool res = false;
int max_len = MaxStringLen(a,count);
StringCopyN(s,p,0,max_len);
for(i=0; i < count && res == false ;i++){
if(s.Find(a[i]) == 0)
res = true;
}
if(res){
LPCTSTR q = p;
while(*q && !isspace(*q))
q++;
StringCopyN(link,p,0,(int)(q - p));
}
return res;
}
CTextStream & CTextStream::Append(CTextStream &ts)
{
const int count = ts.m_atoms.GetSize();
for(int i=0; i<count; i++){
AddAtom(ts.m_atoms[i]);
}
return *this;
}
/************** local functions ***********************/
// return the number of colors added
int ParseFadeTag(LPCTSTR tag,CSimpleArray<CYahooColor> &lst)
{
CStringToken st;
CSimpleArray<CString> tmp;
st.Init(tag,"<> ,");
st.GetNext();
st.GetAll(tmp);
return MakeColorList(tmp,lst);
}
// return number of colors successfully converted and added to out
int MakeColorList(const CSimpleArray<CString> &in,CSimpleArray<CYahooColor> &out)
{
const int count = in.GetSize();
int i;
CYahooColor color;
int res = 0;
for(i = 0;i<count;i++){
if(color.SetFromString(in[i])){
if(out.Add(color))
res++;
}
}
return res;
}
// parses [pStart,pEnd[
// example key1="value 1" key2="blah bleh" key3="value 3"
// we always begin at a key or space
// there may not be spaces between equal sign
// there has to be quotes around the value to be considered
// props (properties ) will return the strings that doenst contain a '='
// we need it because people use the font tag to other things
void ParseKeyValuePairs(LPCSTR text,CNo5SimpleMap<CString,CString> &pairs,CSimpleArray<CString> &props)
{
LPCTSTR p,q;
CString key,val;
p = q = text;
while(*q){
while(::isspace(*q))
q++;
p = q; // begining of key
while(*q && *q != '=' && !(::isspace(*q)))
q++;
if(!(*q) || ::isspace(*q)){
// we found a something that is not a key=value pair
StringCopyN(key,p,0,(int)(q - p));
props.Add(key);
}
else if(*q == '='){ // we found a key
// copy the key
StringCopyN(key,p,0,(int)(q - p));
p = ++q; // first quote of value
if(*q && *q == '\"'){ // value has to start with quote
p = ++q; // beginning of value
while(*q && *q != '\"')
q++;
if(*q){
StringCopyN(val,p,0,(int)(q - p));
pairs.Add(key,val);
q++;
}
else{
if(*q)
q++;
}
}
}
else {
//
}
}
}
int MaxStringLen(LPCTSTR a[],int count)
{
int res = 0;
for(int i=0;i<count;i++){
if(lstrlen(a[i]) > res)
res = lstrlen(a[i]);
}
return res;
}
|
<gh_stars>0
SELECT p.page_id, p.page_title, p.slug, p.keywords, p.description
FROM page p
WHERE slug = '{$url}'; |
#!/bin/sh
set -e
prefix="$HOME/.local/bin"
mkdir -p "$prefix"
this_script=$(basename "$0")
for script in *; do
if test -x "$script" && test -f "$script" && ! [ "$script" = "$this_script" ]; then
abs_script="$PWD/$script"
dest="$prefix/${script%.*}"
ln -s "$abs_script" "$dest"
echo "$abs_script -> $dest"
fi
done
|
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { createWriteStream, existsSync, mkdirSync, unlinkSync } from 'fs';
import { FileUpload } from 'graphql-upload';
import { join } from 'path';
import * as moment from 'moment';
@Injectable()
export class UploadService {
public async uploadFile({
createReadStream,
filename,
}: FileUpload): Promise<string> {
return new Promise(async (resolve, reject) => {
const file_name = moment().valueOf() + filename;
const url = `/client/${file_name}`;
mkdirSync(join(__dirname, '../../client'), {
recursive: true,
});
return createReadStream()
.pipe(createWriteStream(join(__dirname, '../../client', file_name)))
.on('finish', () => resolve(url))
.on('error', () => {
reject(new InternalServerErrorException());
});
});
}
public async removeFile(url: string) {
if (existsSync(join(__dirname, '../..', url))) {
unlinkSync(join(__dirname, '../..', url));
return true;
} else {
return false;
}
}
}
|
#! /usr/bin/env bash
set -e
cd /generator-output
CMDNAME=${0##*/}
usage() {
exitcode="$1"
cat <<USAGE >&2
Postprocess the output of openapi-generator
Usage:
$CMDNAME -p PACKAGE_NAME
Options:
-p, --package-name The name to use for the generated package
-h, --help Show this message
USAGE
exit "$exitcode"
}
main() {
validate_inputs
merge_generated_models
delete_unused
fix_any_of
fix_docs_path
apply_formatters
}
validate_inputs() {
if [ -z "$PACKAGE_NAME" ]; then
echo "Error: you need to provide --package-name argument"
usage 2
fi
}
merge_generated_models() {
# Need to merge the generated models into a single file to prevent circular imports
# shellcheck disable=SC2046
# shellcheck disable=SC2010
cat $(ls "${PACKAGE_NAME}"/models/*.py | grep -v __init__) >"${PACKAGE_NAME}"/models.py
rm -r "${PACKAGE_NAME}"/models >/dev/null 2>&1 || true
echo "
import inspect
import sys
import io
import pydantic
IO = io.IOBase
current_module = sys.modules[__name__]
for model in inspect.getmembers(current_module, inspect.isclass):
model_class = model[1]
if isinstance(model_class, pydantic.BaseModel) or hasattr(model_class, \"update_forward_refs\"):
model_class.update_forward_refs()
" >> "${PACKAGE_NAME}"/models.py
}
delete_unused() {
# Delete empty folder
rm -r "${PACKAGE_NAME}"/test >/dev/null 2>&1 || true
rm "${PACKAGE_NAME}"/rest.py >/dev/null 2>&1 || true
rm "${PACKAGE_NAME}"/configuration.py >/dev/null 2>&1 || true
}
fix_any_of() {
find . -name "*.py" -exec sed -i.bak "s/AnyOf[a-zA-Z0-9]*/Any/" {} \;
find . -name "*.md" -exec sed -i.bak "s/AnyOf[a-zA-Z0-9]*/Any/" {} \;
find . -name "*.bak" -exec rm {} \;
}
fix_docs_path() {
sed -i -e "s="${PACKAGE_NAME}"/docs=docs=" "${PACKAGE_NAME}"_README.md
}
apply_formatters() {
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place "${PACKAGE_NAME}" --exclude=__init__.py
isort --float-to-top -w 120 -m 3 --trailing-comma --force-grid-wrap 0 --combine-as -p "${PACKAGE_NAME}" "${PACKAGE_NAME}"
black --fast -l 120 --target-version py36 "${PACKAGE_NAME}"
}
while [ $# -gt 0 ]; do
case "$1" in
-p | --package-name)
PACKAGE_NAME=$2
shift 2
;;
-h | --help)
usage 0
;;
*)
echo "Unknown argument: $1"
usage 1
;;
esac
done
main
|
<reponame>kkoogqw/OpenItem
package models
import (
"context"
"fmt"
"github.com/qiniu/qmgo/field"
"github.com/qiniu/qmgo/options"
"go.mongodb.org/mongo-driver/bson"
"proj-review/database"
"proj-review/log"
"proj-review/request"
"proj-review/response"
"proj-review/utils"
)
type Assignment struct {
field.DefaultField `bson:",inline"`
Uuid string `bson:"uuid"`
UserId string `bson:"user_id"`
ProjectId string `bson:"project_id"`
Role int `bson:"role"`
Operator string `bson:"operator"`
IsConfirmed bool `bson:"is_confirmed"`
Status int `bson:"status"`
}
// role: 0-admin, 1-expert, 2-assistant, 3-teachers, 4-outer
// Operator "system" or uuid of user
func init() {
// create index
err := database.MgoAssignments.CreateIndexes(
context.Background(),
[]options.IndexModel{
{Key: []string{"uuid"}, Unique: true},
{Key: []string{"user_id"}, Unique: false},
{Key: []string{"project_id"}, Unique: false},
{Key: []string{"user_id", "project_id"}, Unique: true},
},
)
if err != nil {
log.Logger.Error("[Mongo Assignment] " + err.Error())
return
}
log.Logger.Info("[Mongo] Create the index in assignments collection successfully")
return
}
// DoMakeAssignment
func DoMakeAssignment(makeAssignReq *request.MakeAssignment) (*response.AssignmentDefault, bool) {
// check user and project status
user, ok := getUserById(makeAssignReq.UserId)
if !ok || user.Name == "" {
return &response.AssignmentDefault{
Description: "User ID error",
}, false
}
proj, err := getProjectById(makeAssignReq.ProjectId)
if err != nil {
return &response.AssignmentDefault{
Description: "check project",
}, false
}
if proj.Status == 3 {
return &response.AssignmentDefault{
Description: "project has been terminated",
}, false
}
// check whether user has been assigned -> set unique index
newAssignment := Assignment{
Uuid: utils.GenUuidV4(),
UserId: makeAssignReq.UserId,
ProjectId: makeAssignReq.ProjectId,
Role: makeAssignReq.Role,
Operator: makeAssignReq.Operator,
IsConfirmed: false,
}
result, err := database.MgoAssignments.InsertOne(context.Background(), &newAssignment)
if err != nil {
log.Logger.Error("[Mongo Assignment] " + err.Error())
return &response.AssignmentDefault{
Description: "create failed",
}, false
}
log.Logger.Info(fmt.Sprintf("Created new assignment: %s", result.InsertedID))
return &response.AssignmentDefault{
AssignmentId: newAssignment.Uuid,
Description: "ok",
}, true
}
// DoChangeAssignment
func DoChangeAssignment(changeReq *request.ChangeAssignment) (*response.AssignmentDefault, bool) {
var orgAssign Assignment
err := database.MgoAssignments.Find(context.Background(), bson.M{
"uuid": changeReq.AssignmentId,
}).One(&orgAssign)
if err != nil || orgAssign.Status < 0 { // < 0: assignment has been set as invalid.
return &response.AssignmentDefault{
Description: "assignment status error",
}, false
}
err = database.MgoAssignments.UpdateOne(context.Background(), bson.M{"uuid": orgAssign.Uuid}, bson.M{
"$set": bson.M{
"role": changeReq.NewRole,
"operator": changeReq.Operator,
"is_confirmed": false, // reset, need to be confirmed again.
},
})
if err != nil {
log.Logger.Warn("[Assignment change]" + err.Error())
return &response.AssignmentDefault{
Description: "Change assignment error",
}, false
}
return &response.AssignmentDefault{
AssignmentId: orgAssign.Uuid,
Description: "ok",
}, true
}
// DoRemoveAssigment
func DoRemoveAssignment(aid string) (*response.AssignmentDefault, bool) {
err := database.MgoAssignments.Remove(context.Background(), bson.M{
"uuid": aid,
})
if err != nil {
log.Logger.Error("[Mongo Remove] " + err.Error())
return &response.AssignmentDefault{
AssignmentId: aid,
Description: "fail",
}, false
}
return &response.AssignmentDefault{
AssignmentId: aid,
Description: "success",
}, false
}
// DoGetUserAssignments
func DoGetUserAssignments(userId string) (*response.GetAssignments, bool) {
var assignments []Assignment
database.MgoAssignments.Find(context.Background(), bson.M{
"user_id": userId,
}).Sort("createAt").All(&assignments)
if len(assignments) == 0 {
return &response.GetAssignments{
Count: 0,
Description: "no record...",
}, false
}
var assignItems []response.AssignmentItem
for _, a := range assignments {
assignItems = append(assignItems, convertAssignmentToResponse(a))
}
return &response.GetAssignments{
Count: len(assignments),
Description: "ok",
Assignments: assignItems,
}, true
}
// DoGetProjectAssignments
func DoGetProjectAssignments(projId string) (*response.GetAssignments, bool) {
var assignments []Assignment
database.MgoAssignments.Find(context.Background(), bson.M{
"project_id": projId,
}).Sort("createAt").All(&assignments)
if len(assignments) == 0 {
return &response.GetAssignments{
Count: 0,
Description: "no record...",
}, false
}
var assignItems []response.AssignmentItem
for _, a := range assignments {
assignItems = append(assignItems, convertAssignmentToResponse(a))
}
return &response.GetAssignments{
Count: len(assignments),
Description: "ok",
Assignments: assignItems,
}, true
}
// convertAssignmentToResponse
func convertAssignmentToResponse(a Assignment) response.AssignmentItem {
var u User
var p Project
database.MgoUsers.Find(context.Background(), bson.M{
"uuid": a.UserId,
}).One(&u)
database.MgoProjects.Find(context.Background(), bson.M{
"uuid": a.ProjectId,
}).One(&p)
return response.AssignmentItem{
Uuid: a.Uuid,
UserId: a.UserId,
UserName: u.Name,
ProjectId: a.ProjectId,
ProjectName: p.BasicInfo.Name,
Role: a.Role,
IsConfirmed: a.IsConfirmed,
Status: a.Status,
CreatedAt: a.CreateAt,
}
}
// createOneAssignment
func createOneAssignment(user string, project string, role int, opr string, confirm bool) error {
newAssign := Assignment{
Uuid: utils.GenUuidV4(),
UserId: user,
ProjectId: project,
Role: role,
Operator: opr,
Status: 0,
IsConfirmed: confirm,
}
_, err := database.MgoAssignments.InsertOne(context.Background(), &newAssign)
if err != nil {
return err
}
return nil
}
|
# Define the positive and negative words
positive_words = ["good", "great", "excellent", "awesome", "amazing"]
negative_words = ["bad", "terrible", "horrible", "awful", "poor"]
# Prompt the user for their opinion
opinion = input("What do you think of this topic? ")
# Initialize counters for positive and negative words
positive_count = 0
negative_count = 0
# Convert the user's input to lowercase for case-insensitive comparison
opinion_lower = opinion.lower()
# Count the occurrences of positive and negative words in the user's input
for word in positive_words:
if word in opinion_lower:
positive_count += 1
for word in negative_words:
if word in opinion_lower:
negative_count += 1
# Determine the sentiment based on the counts of positive and negative words
if positive_count > negative_count:
sentiment = "positive"
elif positive_count < negative_count:
sentiment = "negative"
else:
sentiment = "neutral"
# Display the sentiment based on the user's input
print("Your sentiment on this topic is:", sentiment) |
package com.twitter.calculator
import com.twitter.finatra.thrift.ThriftServer
import com.twitter.finatra.thrift.routing.ThriftRouter
import com.twitter.finatra.thrift.filters._
import com.twitter.finatra.thrift.modules.ClientIdWhitelistModule
object CalculatorServerMain extends CalculatorServer
class CalculatorServer extends ThriftServer {
override val name = "calculator-server"
override def modules = Seq(
ClientIdWhitelistModule)
override def configureThrift(router: ThriftRouter) {
router
.filter[LoggingMDCFilter]
.filter[TraceIdMDCFilter]
.filter[ThriftMDCFilter]
.filter[AccessLoggingFilter]
.filter[StatsFilter]
.filter[ExceptionTranslationFilter]
.filter[ClientIdWhitelistFilter]
.add[CalculatorController]
}
}
|
public class ReverseString {
public static void main(String[] args) {
String str = "hello world";
System.out.println(reverseString(str));
}
public static String reverseString(String str) {
char[] arr = str.toCharArray();
int n = arr.length;
for (int i = 0; i < n/2; i++) {
char temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
return new String(arr);
}
} |
import { checkNpmVersions } from 'meteor/tmeasday:check-npm-versions';
checkNpmVersions({
"eval": "^0.1.2"
}, 'steedos:instance-record-queue');
|
/**
*
*/
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @author dzh
* @date Oct 9, 2013 8:13:15 PM
* @since 1.0
*/
public class OutputHandler implements InvocationHandler {
private Object obj;
public OutputHandler(Object obj) {
this.obj = obj;
}
/*
* (non-Javadoc)
*
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
* java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = obj.getClass().getMethods()[0].invoke(obj, args);
return result;
}
}
|
<filename>app/models/EvaluationResult.scala
package models
import play.api.libs.json._
case class EvaluationResult(mostSpeeches: String, mostSecurity: String, leastWordy: String)
object EvaluationResult {
implicit val writes = Json.writes[EvaluationResult]
}
|
def compute_bmi(height, weight):
bmi = weight / (height * height)
return bmi
bmi = compute_bmi(172, 85)
print("Your BMI is {:.2f}".format(bmi)) |
package ro.msg.learning.shop.dto;
import lombok.*;
import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@Builder
public class CustomerOrderDto extends BaseDto {
private int locationId;
private String locationName;
private int customerId;
private String customerName;
private LocalDateTime createdAt;
private String country;
private String city;
private String county;
private String streetAddress;
@Override
public String toString() {
return "CustomerOrderDto{" +
"shippedFrom=" + locationName +
", customer=" + locationId +
", createdAt=" + createdAt +
", country='" + country + '\'' +
", city='" + city + '\'' +
", county='" + county + '\'' +
", streetAddress='" + streetAddress + '\'' +
'}';
}
}
|
S=`seq 3`
echo "real,user,sys" > ubuntu_classifier_time1.csv && \
(for i in $S; do TIMEFORMAT=%R','%U','%S && \
time ./demos/classifier.py infer ./models/openface/celeb-classifier.nn4.small2.v1.pkl images/examples/{carell,adams,lennon}* 2>/dev/null ;done)>ubuntu_classifier_output1.txt 2>> ubuntu_classifier_time1.csv
|
#!/bin/bash
for filename in src/*.js; do
name=${filename##*/}
base=${name%.js}
./node_modules/.bin/jsdoc2md "$filename" > "docs/$base.md"
done
chmod 777 -R docs; |
#!/usr/bin/env bash
set -e
set -x
SRC=${1:-"src/zenml tests"}
# mypy src/zenml
flake8 $SRC
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place $SRC --exclude=__init__.py,legacy/* --check
isort $SRC scripts --check-only
black $SRC --check
interrogate $SRC -c pyproject.toml |
module SagePay
module Server
class RefundResponse < Response
attr_accessor_if_ok :vps_tx_id, :tx_auth_no
self.key_converter = key_converter.merge({
"VPSTxId" => :vps_tx_id,
"TxAuthNo" => :tx_auth_no
})
self.value_converter[:status]["NOTAUTHED"] = :not_authed
def vps_tx_id
if ok?
@vps_tx_id
else
raise RuntimeError, "Unable to retrieve the transaction id as the status was not OK."
end
end
def tx_auth_no
if ok?
@tx_auth_no
else
raise RuntimeError, "Unable to retrieve the authorisation number as the status was not OK."
end
end
end
end
end
|
#!/usr/bin/env bash
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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.txt
#
# 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.
#
#==========================================================================*/
# Run this script to set up the git repository to push to the Gerrit code review
# system.
die() {
echo 'Failure during Gerrit setup.' 1>&2
echo '----------------------------' 1>&2
echo '' 1>&2
echo "$@" 1>&2
exit 1
}
gerrit_user() {
read -ep "Enter your gerrit user (set in Gerrit Settings/Profile) [$USER]: " gu
if [ "$gu" == "" ]; then
# Use current user name.
gu=$USER
fi
echo -e "\nConfiguring 'gerrit' remote with user '$gu'..."
if git config remote.gerrit.url >/dev/null; then
# Correct the remote url
git remote set-url gerrit $gu@review.source.kitware.com:SimpleITK || \
die "Could not amend gerrit remote."
else
# Add a new one
git remote add gerrit $gu@review.source.kitware.com:SimpleITK || \
die "Could not add gerrit remote."
fi
cat << EOF
For more information on Gerrit usage, see the ITK development process
https://www.itk.org/Wiki/ITK/Develop
EOF
}
# Make sure we are inside the repository.
cd "$(echo "$0"|sed 's/[^/]*$//')"
if git config remote.gerrit.url >/dev/null; then
echo "Gerrit was already configured. The configured remote URL is:"
echo
git config remote.gerrit.url
echo
read -ep "Is the username correct? [Y/n]: " correct
if [ "$correct" == "n" ] || [ "$correct" == "N" ]; then
gerrit_user
fi
else
cat << EOF
Gerrit is a code review system that works with Git.
In order to use Gerrit, an account must be registered at the review site:
http://review.source.kitware.com/p/SimpleITK
If you already have an account for ITK, VTK, etc. it should work for
SimpleITK. To create a new account you will need an OpenID:
http://openid.net/get-an-openid/
EOF
gerrit_user
fi
read -ep "Would you like to verify authentication to Gerrit? [y/N]: " ans
if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
echo
echo "Fetching from gerrit to test SSH key configuration (Settings/SSH Public Keys)"
git fetch gerrit ||
die "Could not fetch gerrit remote. You need to upload your public SSH key to Gerrit."
echo "Done."
fi
echo -e "\nConfiguring GerritId hook..."
if git config hooks.GerritId >/dev/null; then
echo "GerritId hook already configured."
else
cat << EOF
This hook automatically add a "Change-Id" footer to commit messages
to make interaction with Gerrit easier.
EOF
read -ep "Would you like to enable it? [Y/n]: " ans
if [ "$ans" != "n" ] && [ "$ans" != "N" ]; then
git config hooks.GerritId true
cat << EOF
To disable this feature, run
git config hooks.GerritId false
EOF
fi
echo "Done."
fi
|
IMG=${1}
PSF=${2}
OVERSAMPLE=${3}
ERROR=${4}
XSHIFT=${5}
YSHIFT=${6}
RAC=${7}
DECC=${8}
LARGE_SCALE_FILTER=${9}
MASK_MORE=${10}
GET_SHIFT=${11}
SHIFT_ANCHOR=${12}
SHIFT_MASK=${13}
SHIFT_STEP=${14}
SHIFT_MAX=${15}
echo ${IMG}
DIR=`dirname ${IMG}`
# Change here the directory where the software is located (default: current directory)
BIN_DIR=.
if [ ${LARGE_SCALE_FILTER} -gt 0 ]; then
# Backup the original image so we don't apply twice
if [ -f ${IMG}-orig.fits ]; then
cp ${IMG}-orig.fits ${IMG}.fits
else
cp ${IMG}.fits ${IMG}-orig.fits
fi
${BIN_DIR}/make_mask ${IMG}.fits ${DIR}/mask_all.reg ${IMG}-mask-all.fits
if [ -f ${IMG}-bad.reg ]; then
${BIN_DIR}/add_mask ${IMG}-mask-all.fits ${IMG}-bad.reg
fi
${BIN_DIR}/large_scale_filter image=${IMG}.fits size=${LARGE_SCALE_FILTER} mask=${IMG}-mask-all.fits
fi
if [ -f ${IMG}-mask-border.reg ]; then
${BIN_DIR}/make_mask ${IMG}.fits ${IMG}-mask-border.reg ${IMG}-mask-border.fits
else
if [ ${MASK_MORE} -eq 0 ]; then
${BIN_DIR}/make_mask ${IMG}.fits ${DIR}/mask_border.reg ${IMG}-mask-border.fits
fi
if [ ${MASK_MORE} -eq 1 ]; then
${BIN_DIR}/make_mask ${IMG}.fits ${DIR}/mask_border_more.reg ${IMG}-mask-border.fits
fi
fi
if [ -f ${IMG}-bad.reg ]; then
${BIN_DIR}/add_mask ${IMG}-mask-border.fits ${IMG}-bad.reg
fi
if [ ${GET_SHIFT} -eq 0 ]; then
${BIN_DIR}/multi_subtract image=${IMG}.fits psf=${DIR}/${PSF} oversample=${OVERSAMPLE} \
mask=${IMG}-mask-border.fits out=${IMG}-allsub.fits error=${ERROR} \
model_dir=${DIR}/imfit/models xshift=${XSHIFT} yshift=${YSHIFT} reuse_models=0 \
ra_center=${RAC} dec_center=${DECC}
else
${BIN_DIR}/multi_subtract image=${IMG}.fits psf=${DIR}/${PSF} oversample=${OVERSAMPLE} \
mask=${IMG}-mask-border.fits out=${IMG}-allsub.fits error=${ERROR} \
model_dir=${DIR}/imfit/models shift_anchors=${SHIFT_ANCHOR} \
shift_fit_radius=${SHIFT_MASK} max_shift=${SHIFT_MAX} shift_dp=${SHIFT_STEP} \
ra_center=${RAC} dec_center=${DECC}
fi
|
<gh_stars>0
import {Component, Input, OnInit} from '@angular/core';
import {SubAssembly} from '../../../../../typescript-generator/configurator';
@Component({
selector: 'app-sub-assembly-tree',
templateUrl: './sub-assembly-tree.component.html',
styleUrls: ['./sub-assembly-tree.component.scss']
})
export class SubAssemblyTreeComponent implements OnInit {
@Input() subassembly: SubAssembly;
@Input() depth: number;
isCollapsed = true;
constructor() {
}
ngOnInit() {
}
trackElement(index: number, element: any) {
return element ? element.instanceId : null;
}
}
|
#!/bin/bash
pipenv run python -m unittest tests/test.py |
<filename>TOJ/toj 144.cpp
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
struct V{
int a;
int b;
bool x;
};
int main(){
int n,m;
scanf("%d%d",&n,&m);
V v1[m],v2[m];
for(int q=0;q<m;q++){
scanf("%d%d",&v1[q].a,&v1[q].b);
v1[q].x=0;
v2[q].a=v1[q].a;
v2[q].b=v1[q].b;
v2[q].x=0;
}
int tree[n];
memset(tree,-1,sizeof tree);
tree[v1[0].a]=0;
tree[v1[0].b]=1;
v1[0].x=1;
bool empty=1;
while(empty){
empty=0;
for(int q=0;q<m;q++){
if(v1[q].x==0&&tree[v1[q].a]!=-1){
tree[v1[q].b]=tree[v1[q].a]+1;
v1[q].x=1;
empty=1;
}
else if(v1[q].x==0&&tree[v1[q].b]!=-1){
tree[v1[q].a]=tree[v1[q].b]+1;
v1[q].x=1;
empty=1;
}
}
}
int maxd=-1,maxn=-1;
for(int q=0;q<n;q++){
if(tree[q]>maxd){
maxd=tree[q];
maxn=q;
}
}
memset(tree,-1,sizeof tree);
tree[maxn]=0;
empty=1;
while(empty){
empty=0;
for(int q=0;q<m;q++){
if(v2[q].x==0&&tree[v2[q].a]!=-1){
tree[v2[q].b]=tree[v2[q].a]+1;
v2[q].x=1;
empty=1;
}
else if(v2[q].x==0&&tree[v2[q].b]!=-1){
tree[v2[q].a]=tree[v2[q].b]+1;
v2[q].x=1;
empty=1;
}
}
}
maxd=-1,maxn=-1;
for(int q=0;q<n;q++){
if(tree[q]>maxd){
maxd=tree[q];
maxn=q;
}
}
printf("%d\n",maxd);
} |
export MIDI_DEV=`amidi -l | grep ZOOM | awk '{print $2}'`
outFile=Check${1}.txt
for midiString in `grep "^SEND" ChangeTo${1}.txt | awk -F\: '{print $2}'`
do
echo "Sending next command"
echo "SEND: ${midiString}" >> ${outFile}
amidi -p ${MIDI_DEV} -S ${midiString} -r tm.bin -t 1 ; hexdump -C tm.bin > tm.txt
cat tm.txt >> ${outFile}
rm tm.bin tm.txt
done
|
<reponame>Gr-UML-SIR/TaxSejour<gh_stars>0
package com.prefecture.gestionlocale.model.service.facade;
import com.prefecture.gestionlocale.bean.Categorie;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
public interface CategorieService {
ResponseEntity<?> findAll(String search, Pageable pageable);
ResponseEntity<?> create(Categorie categorie);
ResponseEntity<?> update(Categorie categorie);
ResponseEntity<?> delete(Long id);
ResponseEntity<?> read(Long id);
ResponseEntity<?> dataForSelect();
}
|
package model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import model.Constants.WOWCharacterClass;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class WOWCharacter implements Serializable {
private static final long serialVersionUID = -2216740042870567547L;
@XmlElement(name="name")
private String name_;
@XmlElement(name="realm")
private String realm_;
@XmlElement(name="class")
private WOWCharacterClass class_;
@XmlElementWrapper(name="DKPEvent")
@XmlElement(name="Event")
private List<DKPEvent> log_;
public WOWCharacter(String name, String realm,
WOWCharacterClass characterClass) {
name_ = name;
realm_ = realm;
class_ = characterClass;
log_ = new LinkedList<DKPEvent>();
}
// JAXB uses this method as well
public String getName() {
return this.name_;
}
// JAXB uses this method as well
public String getRealm() {
return this.realm_;
}
// JAXB uses this method as well
public WOWCharacterClass getWOWCharacterClass() {
return this.class_;
}
public List<DKPEvent> getEventList() {
return log_;
}
public void addDKPEvent(DKPEvent event) throws NotEnoughDKPException {
if (canAddEvent(event)) {
log_.add(event);
} else {
throw new NotEnoughDKPException();
}
}
private boolean canAddEvent(DKPEvent event) {
if (event.getType().equals(Constants.DKPEventType.MODIFIED_BY_OFFICER)) {
return true;
} else {
return getTotalDKP() + event.getScore() > Constants.UNDERLIMIT_DKP;
}
}
public int getTotalDKP() {
int score = 0;
Iterator<DKPEvent> it = log_.iterator();
DKPEvent tmpEvent;
while (it.hasNext()) {
tmpEvent = it.next();
score += tmpEvent.getScore();
}
return score;
}
/*
* The following code shouldn't be used by model. Only JAXB should use it.
*/
public WOWCharacter() {
}
public void setName(String name) {
name_ = name;
}
public void setRealm(String realm) {
realm_ = realm;
}
public void setWOWCharacterClass(WOWCharacterClass c) {
class_ = c;
}
}
|
#!/bin/bash
h=false
b=false
dt="$(date "+%Y-%m-%d_%H_%M_%S")"
while getopts ":h :b" o; do
case "${o}" in
h)
h=true;;
b)
b=true;;
esac
done
echo "============================"
echo "Scraping HKN: $h"
echo "Scraping Berkeleytime: $b"
echo "Date/Time: $dt"
echo "============================"
echo "Script starting in 3 seconds. Press CTRL+C to quit now."
sleep 1
sleep 1
sleep 1
echo "Created directory: scrape_$dt"
FILEDIR="../../../data/current"
echo "Checking for previous run"
if [ -d "$FILEDIR" ]; then
NEWFILEDIRNAME="archived_run_$dt"
NEWFILEDIR="../../../data/$NEWFILEDIRNAME"
echo "Previous run found. Renaming to: $NEWFILEDIRNAME"
mv $FILEDIR $NEWFILEDIR
else
echo "No previous run found."
fi
mkdir $FILEDIR
if $h; then
echo "Starting HKN scrape"
HKNFILE="hkn_data.json"
HKNFILE1="hkn_courses.json"
scrapy crawl hkn -o $HKNFILE
echo "Moving HKN files"
mv $HKNFILE $FILEDIR
mv $HKNFILE1 $FILEDIR
echo
fi
if $b; then
echo "Starting Berkeleytime scrape"
BTFILE="bt_data.json"
BTFILE1="bt_catalog.json"
BTFILE2="bt_filter.json"
scrapy crawl berkeleytime -o $BTFILE
echo "Moving Berkeleytime files"
mv $BTFILE $FILEDIR
mv $BTFILE1 $FILEDIR
mv $BTFILE2 $FILEDIR
echo
fi
echo "============================"
echo "SUMMARY"
echo "============================"
cd $FILEDIR
if $h; then
echo "HKN Files:"
ls hkn_*
echo
fi
if $b; then
echo "Berkeleytime Files:"
ls bt_*
echo
fi
echo "Scraping done" |
var $isOk = "";
$(function () {
$("#userName").blur(findUser);
$("#password").blur(password11);
$("#password22").blur(password22);
})
function check11() {
const a1 = $isOk;
const a2 = password11();
const a3 = password22();
const isTrue = a1 && a2 && a3;
if (!isTrue) {
alert("请填写详细信息");
return false;
} else {
return isTrue;
}
}
function password11() {
const password = $("#password").val();
if (password===""){
$("#msg2").html("请输入您的密码").css("color","red");
return false;
}else {
$("#msg2").html("√").css("color","green");
return true;
}
}
function password22() {
const password22 = $("#password22").val();
const password11 = $("#password").val();
if (password22==="" || password22!==<PASSWORD> ){
$("#msg3").html("两次密码输入不一致,请重新输入").css("color","red");
return false;
}else {
$("#msg3").html("√").css("color","green");
return true;
}
}
function findUser() {
const name = $("#userName").val();
if (name===""){
$("#msg1").html("请填写用户名").css("color","red");
$isOk = false;
}
if (name!=="") {
$.get("/voteUser/selectOne", {"name": name}, function (data) {
if (data=="用户名可以使用"){
$("#msg1").html(data).css("color","green");
$isOk = true;
}
if (data == "用户名已被使用"){
$("#msg1").html(data).css("color","red");
$isOk = false;
}
}, "text");
}
}
|
<gh_stars>10-100
#ifndef SLEEP_H
#define SLEEP_H
#include <stdint.h>
#include <stdbool.h>
#ifdef __MINGW32__
#include <windows.h>
#include <unistd.h>
#endif // __MINGW32__
#ifdef __linux
#include <unistd.h>
#endif // __linux
void msleep(uint32_t usec);
#endif
|
<reponame>elko-dev/spawn<filename>firebase/firebase_test.go
package firebase
import (
"testing"
)
func TestPlatformReturnsErrorOnProjectError(t *testing.T) {
// ctrl := gomock.NewController(t)
// defer ctrl.Finish()
// mockProject := NewMockFirebaseProject(ctrl)
// mockProject.EXPECT().Create("projectId").Return(gcp.Project{}, errors.New("error"))
}
|
<reponame>JakeKaad/minesweeper-js
mineSweeper.factory('CellsFactory', function CellsFactory() {
var factory = {};
factory.Cell = {};
factory.createCell = function(id) {
var cell = Object.create(factory.Cell);
cell.id = id;
cell.bomb = false;
cell.revealed = false;
cell.flag = false;
return cell;
};
factory.Cell.setNeighborBomb = function() {
var neighborBomb = 0
this.neighbors.forEach(function(neighbor) {
if (neighbor.bomb === true) {
neighborBomb += 1;
};
});
this.neighborBomb = neighborBomb
};
factory.Cell.setDisplay = function() {
if (this.bomb === true) {
this.display = '\u2297';
} else if (this.neighborBomb === 0) {
this.display = ""
} else {
this.display = this.neighborBomb.toString();
}
};
factory.Cell.plantFlag = function() {
this.flag = !this.flag;
}
return factory;
});
|
<filename>opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecutor.java
/*
* Copyright 2015 OpenCB
*
* 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.opencb.opencga.analysis;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.opencb.datastore.core.ObjectMap;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.CatalogManager;
import org.opencb.opencga.catalog.models.File;
import org.opencb.opencga.catalog.models.Job;
import org.opencb.opencga.core.SgeManager;
import org.opencb.opencga.core.common.Config;
import org.opencb.opencga.analysis.beans.Analysis;
import org.opencb.opencga.analysis.beans.Execution;
import org.opencb.opencga.analysis.beans.Option;
import org.opencb.opencga.core.common.StringUtils;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.core.exec.Command;
import org.opencb.opencga.core.exec.SingleProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class AnalysisJobExecutor {
public static final String EXECUTE = "execute";
public static final String SIMULATE = "simulate";
public static final String OPENCGA_ANALYSIS_JOB_EXECUTOR = "OPENCGA.ANALYSIS.JOB.EXECUTOR";
protected static Logger logger = LoggerFactory.getLogger(AnalysisJobExecutor.class);
protected final Properties analysisProperties;
protected final String home;
protected String analysisName;
protected String executionName;
protected Path analysisRootPath;
protected Path analysisPath;
protected Path manifestFile;
protected Path resultsFile;
protected String sessionId;
protected Analysis analysis;
protected Execution execution;
protected static ObjectMapper jsonObjectMapper = new ObjectMapper();
private AnalysisJobExecutor() throws IOException, AnalysisExecutionException {
home = Config.getOpenCGAHome();
analysisProperties = Config.getAnalysisProperties();
executionName = null;
}
public AnalysisJobExecutor(String analysisStr, String execution) throws IOException, AnalysisExecutionException {
this(analysisStr, execution, "system");
}
@Deprecated
public AnalysisJobExecutor(String analysisStr, String execution, String analysisOwner) throws IOException, AnalysisExecutionException {
this();
if (analysisOwner.equals("system")) {
this.analysisRootPath = Paths.get(analysisProperties.getProperty("OPENCGA.ANALYSIS.BINARIES.PATH"));
} else {
this.analysisRootPath = Paths.get(home, "accounts", analysisOwner);
}
this.analysisName = analysisStr;
if (analysisName.contains(".")) {
executionName = analysisName.split("\\.")[1];
analysisName = analysisName.split("\\.")[0];
} else {
executionName = execution;
}
load();
}
public AnalysisJobExecutor(Path analysisRootPath, String analysisName, String executionName) throws IOException, AnalysisExecutionException {
this();
this.analysisRootPath = analysisRootPath;
this.analysisName = analysisName;
this.executionName = executionName;
load();
}
private void load() throws IOException, AnalysisExecutionException {
analysisPath = Paths.get(home).resolve(analysisRootPath).resolve(analysisName);
manifestFile = analysisPath.resolve(Paths.get("manifest.json"));
resultsFile = analysisPath.resolve(Paths.get("results.js"));
analysis = getAnalysis();
execution = getExecution();
}
public void execute(String jobName, int jobId, String jobFolder, String commandLine) throws AnalysisExecutionException, IOException {
logger.debug("AnalysisJobExecuter: execute, 'jobName': " + jobName + ", 'jobFolder': " + jobFolder);
logger.debug("AnalysisJobExecuter: execute, command line: " + commandLine);
executeCommandLine(commandLine, jobName, jobId, jobFolder, analysisName);
}
public static void execute(CatalogManager catalogManager, Job job, String sessionId)
throws AnalysisExecutionException, IOException, CatalogException {
logger.debug("AnalysisJobExecuter: execute, job: {}", job);
// read execution param
String jobExecutor = Config.getAnalysisProperties().getProperty(OPENCGA_ANALYSIS_JOB_EXECUTOR);
// local execution
if (jobExecutor == null || jobExecutor.trim().equalsIgnoreCase("LOCAL")) {
logger.debug("AnalysisJobExecuter: execute, running by SingleProcess");
executeLocal(catalogManager, job, sessionId);
} else {
logger.debug("AnalysisJobExecuter: execute, running by SgeManager");
try {
SgeManager.queueJob(job.getToolName(), job.getResourceManagerAttributes().get(Job.JOB_SCHEDULER_NAME).toString(),
-1, job.getTmpOutDirUri().getPath(), job.getCommandLine(), null, "job." + job.getId());
catalogManager.modifyJob(job.getId(), new ObjectMap("status", Job.Status.QUEUED), sessionId);
} catch (Exception e) {
logger.error(e.toString());
throw new AnalysisExecutionException("ERROR: sge execution failed.");
}
}
}
private boolean checkRequiredParams(Map<String, List<String>> params, List<Option> validParams) {
for (Option param : validParams) {
if (param.isRequired() && !params.containsKey(param.getName())) {
System.out.println("Missing param: " + param);
return false;
}
}
return true;
}
private Map<String, List<String>> removeUnknownParams(Map<String, List<String>> params, List<Option> validOptions) {
Set<String> validKeyParams = new HashSet<String>();
for (Option param : validOptions) {
validKeyParams.add(param.getName());
}
Map<String, List<String>> paramsCopy = new HashMap<String, List<String>>(params);
for (String param : params.keySet()) {
if (!validKeyParams.contains(param)) {
paramsCopy.remove(param);
}
}
return paramsCopy;
}
public String createCommandLine(Map<String, List<String>> params)
throws AnalysisExecutionException {
return createCommandLine(execution.getExecutable(), params);
}
public String createCommandLine(String executable, Map<String, List<String>> params)
throws AnalysisExecutionException {
logger.debug("params received in createCommandLine: " + params);
String binaryPath = analysisPath.resolve(executable).toString();
// Check required params
List<Option> validParams = execution.getValidParams();
validParams.addAll(analysis.getGlobalParams());
validParams.add(new Option(execution.getOutputParam(), "Outdir", false));
if (checkRequiredParams(params, validParams)) {
params = new HashMap<String, List<String>>(removeUnknownParams(params, validParams));
} else {
throw new AnalysisExecutionException("ERROR: missing some required params.");
}
StringBuilder cmdLine = new StringBuilder();
cmdLine.append(binaryPath);
if (params.containsKey("tool")) {
String tool = params.get("tool").get(0);
cmdLine.append(" --tool ").append(tool);
params.remove("tool");
}
for (String key : params.keySet()) {
// Removing renato param
if (!key.equals("renato")) {
if (key.length() == 1) {
cmdLine.append(" -").append(key);
} else {
cmdLine.append(" --").append(key);
}
if (params.get(key) != null) {
String paramsArray = params.get(key).toString();
String paramValue = paramsArray.substring(1, paramsArray.length() - 1).replaceAll("\\s", "");
cmdLine.append(" ").append(paramValue);
}
}
}
return cmdLine.toString();
}
public QueryResult<Job> createJob(Map<String, List<String>> params,
CatalogManager catalogManager, int studyId, String jobName, String description, File outDir, List<Integer> inputFiles, String sessionId)
throws AnalysisExecutionException, CatalogException {
return createJob(execution.getExecutable(), params, catalogManager, studyId, jobName, description, outDir, inputFiles, sessionId);
}
public QueryResult<Job> createJob(String executable, Map<String, List<String>> params,
CatalogManager catalogManager, int studyId, String jobName, String description, File outDir,
List<Integer> inputFiles, String sessionId)
throws AnalysisExecutionException, CatalogException {
// Create temporal Outdir
String randomString = "J_" + StringUtils.randomString(10);
URI temporalOutDirUri = catalogManager.createJobOutDir(studyId, randomString, sessionId);
params.put(getExecution().getOutputParam(), Arrays.asList(temporalOutDirUri.getPath()));
// Create commandLine
String commandLine = createCommandLine(executable, params);
System.out.println(commandLine);
return createJob(catalogManager, studyId, jobName, analysisName, description, outDir, inputFiles, sessionId,
randomString, temporalOutDirUri, commandLine, false, false, new HashMap<String, Object>(), new HashMap<String, Object>());
}
public static QueryResult<Job> createJob(CatalogManager catalogManager, int studyId, String jobName, String toolName, String description,
File outDir, List<Integer> inputFiles, String sessionId,
String randomString, URI temporalOutDirUri, String commandLine,
boolean execute, boolean simulate, Map<String, Object> attributes,
Map<String, Object> resourceManagerAttributes)
throws AnalysisExecutionException, CatalogException {
logger.debug("Creating job {}: simulate {}, execute {}", jobName, simulate, execute);
long start = System.currentTimeMillis();
QueryResult<Job> jobQueryResult;
if (resourceManagerAttributes == null) {
resourceManagerAttributes = new HashMap<>();
}
if (simulate) { //Simulate a job. Do not create it.
resourceManagerAttributes.put(Job.JOB_SCHEDULER_NAME, randomString);
jobQueryResult = new QueryResult<>("simulatedJob", (int) (System.currentTimeMillis() - start), 1, 1, "", "", Collections.singletonList(
new Job(-10, jobName, catalogManager.getUserIdBySessionId(sessionId), toolName,
TimeUtils.getTime(), description, start, System.currentTimeMillis(), "", commandLine, -1,
Job.Status.PREPARED, -1, outDir.getId(), temporalOutDirUri, inputFiles, Collections.<Integer>emptyList(),
null, attributes, resourceManagerAttributes)));
} else {
if (execute) {
/** Create a RUNNING job in CatalogManager **/
jobQueryResult = catalogManager.createJob(studyId, jobName, toolName, description, commandLine, temporalOutDirUri,
outDir.getId(), inputFiles, attributes, resourceManagerAttributes, Job.Status.RUNNING, null, sessionId);
Job job = jobQueryResult.first();
jobQueryResult = executeLocal(catalogManager, job, sessionId);
} else {
/** Create a PREPARED job in CatalogManager **/
resourceManagerAttributes.put(Job.JOB_SCHEDULER_NAME, randomString);
jobQueryResult = catalogManager.createJob(studyId, jobName, toolName, description, commandLine, temporalOutDirUri,
outDir.getId(), inputFiles, attributes, resourceManagerAttributes, Job.Status.PREPARED, null, sessionId);
}
}
return jobQueryResult;
}
private static QueryResult<Job> executeLocal(CatalogManager catalogManager, Job job, String sessionId) throws CatalogException {
logger.info("==========================================");
logger.info("Executing job {}({})", job.getName(), job.getId());
logger.debug("Executing commandLine {}", job.getCommandLine());
logger.info("==========================================");
System.err.println();
Command com = new Command(job.getCommandLine());
com.run();
System.err.println();
logger.info("==========================================");
logger.info("Finished job {}({})", job.getName(), job.getId());
logger.info("==========================================");
/** Change status to DONE - Add the execution information to the job entry **/
// new AnalysisJobManager().jobFinish(jobQueryResult.first(), com.getExitValue(), com);
ObjectMap parameters = new ObjectMap();
parameters.put("resourceManagerAttributes", new ObjectMap("executionInfo", com));
parameters.put("status", Job.Status.DONE);
catalogManager.modifyJob(job.getId(), parameters, sessionId);
/** Record output **/
AnalysisOutputRecorder outputRecorder = new AnalysisOutputRecorder(catalogManager, sessionId);
outputRecorder.recordJobOutput(job, com.getExitValue() != 0);
/** Change status to READY or ERROR **/
if (com.getExitValue() == 0) {
catalogManager.modifyJob(job.getId(), new ObjectMap("status", Job.Status.READY), sessionId);
} else {
parameters = new ObjectMap();
parameters.put("status", Job.Status.ERROR);
parameters.put("error", Job.ERRNO_FINISH_ERROR);
parameters.put("errorDescription", Job.errorDescriptions.get(Job.ERRNO_FINISH_ERROR));
catalogManager.modifyJob(job.getId(), parameters, sessionId);
}
return catalogManager.getJob(job.getId(), new QueryOptions(), sessionId);
}
private static void executeCommandLine(String commandLine, String jobName, int jobId, String jobFolder, String analysisName)
throws AnalysisExecutionException, IOException {
// read execution param
String jobExecutor = Config.getAnalysisProperties().getProperty("OPENCGA.ANALYSIS.JOB.EXECUTOR");
// local execution
if (jobExecutor == null || jobExecutor.trim().equalsIgnoreCase("LOCAL")) {
logger.debug("AnalysisJobExecuter: execute, running by SingleProcess");
Command com = new Command(commandLine);
SingleProcess sp = new SingleProcess(com);
sp.getRunnableProcess().run();
}
// sge execution
else {
logger.debug("AnalysisJobExecuter: execute, running by SgeManager");
try {
SgeManager.queueJob(analysisName, jobName, -1, jobFolder, commandLine, null, "job." + jobId);
} catch (Exception e) {
logger.error(e.toString());
throw new AnalysisExecutionException("ERROR: sge execution failed.");
}
}
}
public Analysis getAnalysis() throws IOException, AnalysisExecutionException {
if (analysis == null) {
analysis = jsonObjectMapper.readValue(manifestFile.toFile(), Analysis.class);
// analysis = gson.fromJson(IOUtils.toString(manifestFile.toFile()), Analysis.class);
}
return analysis;
}
public Execution getExecution() throws AnalysisExecutionException {
if (execution == null) {
if (executionName == null || executionName.isEmpty()) {
execution = analysis.getExecutions().get(0);
} else {
for (Execution exe : analysis.getExecutions()) {
if (exe.getId().equalsIgnoreCase(executionName)) {
execution = exe;
break;
}
}
}
}
return execution;
}
public String getExamplePath(String fileName) {
return analysisPath.resolve("examples").resolve(fileName).toString();
}
public String help(String baseUrl) {
if (!Files.exists(manifestFile)) {
return "Manifest for " + analysisName + " not found.";
}
String execName = "";
if (executionName != null)
execName = "." + executionName;
StringBuilder sb = new StringBuilder();
sb.append("Analysis: " + analysis.getName() + "\n");
sb.append("Description: " + analysis.getDescription() + "\n");
sb.append("Version: " + analysis.getVersion() + "\n\n");
sb.append("Author: " + analysis.getAuthor().getName() + "\n");
sb.append("Email: " + analysis.getAuthor().getEmail() + "\n");
if (!analysis.getWebsite().equals(""))
sb.append("Website: " + analysis.getWebsite() + "\n");
if (!analysis.getPublication().equals(""))
sb.append("Publication: " + analysis.getPublication() + "\n");
sb.append("\nUsage: \n");
sb.append(baseUrl + "analysis/" + analysisName + execName + "/{action}?{params}\n\n");
sb.append("\twhere: \n");
sb.append("\t\t{action} = [run, help, params, test, status]\n");
sb.append("\t\t{params} = " + baseUrl + "analysis/" + analysisName + execName + "/params\n");
return sb.toString();
}
public String params() {
if (!Files.exists(manifestFile)) {
return "Manifest for " + analysisName + " not found.";
}
if (execution == null) {
return "ERROR: Executable not found.";
}
StringBuilder sb = new StringBuilder();
sb.append("Valid params for " + analysis.getName() + ":\n\n");
for (Option param : execution.getValidParams()) {
String required = "";
if (param.isRequired())
required = "*";
sb.append("\t" + param.getName() + ": " + param.getDescription() + " " + required + "\n");
}
sb.append("\n\t*: required parameters.\n");
return sb.toString();
}
public String test(String jobName, int jobId, String jobFolder) throws AnalysisExecutionException, IOException {
// TODO test
if (!Files.exists(manifestFile)) {
return "Manifest for " + analysisName + " not found.";
}
if (execution == null) {
return "ERROR: Executable not found.";
}
executeCommandLine(execution.getTestCmd(), jobName, jobId, jobFolder, analysisName);
return String.valueOf(jobName);
}
public String getResult() throws AnalysisExecutionException {
return execution.getResult();
}
public InputStream getResultInputStream() throws AnalysisExecutionException, IOException {
System.out.println(resultsFile.toAbsolutePath().toString());
if (!Files.exists(resultsFile)) {
resultsFile = analysisPath.resolve(Paths.get("results.js"));
}
if (Files.exists(resultsFile)) {
return Files.newInputStream(resultsFile);
}
throw new AnalysisExecutionException("result.js not found.");
}
}
|
<filename>scripts/telaInicial.js
let minimo = 0
let minimoPesq = 0
var imagens = 5
var liTamanho
var scrollTamanho
let operacaoCarrosselLivro = null
let operacaoCarrosseislLivro = null
function frente(valor){
$(`#Carrosseis #carrossel${valor}`).animate({scrollLeft: $(`#Carrosseis #carrossel${valor}`).scrollLeft() + scrollTamanho}, 300)
}
function back(valor){
$(`#Carrosseis #carrossel${valor}`).animate({scrollLeft: $(`#Carrosseis #carrossel${valor}`).scrollLeft() - scrollTamanho - liTamanho}, 300)
}
function carregaLivros(Elemento){
if(operacaoCarrosselLivro != null){
operacaoCarrosselLivro.abort();
operacaoCarrosselLivro = null;
}
operacaoCarrosselLivro = $.ajax({
method: "POST",
url: "carregaLivrosInicial.php",
data: {min:minimo}
})
.done(function(res){
if(res.length > 0){
window.document.getElementById('Carrosseis').innerHTML += res
Elemento.innerText = "Carregar Mais"
Elemento.classList.remove('loading')
Elemento.classList.add('CarregarMais')
}else{
Elemento.style.display = "none"
}
})
.fail(function(){
if(operacaoCarrosselLivro == null){
alert("Ocorreu um erro ao tentar carregar mais livros")
}
Elemento.innerText = "Carregar Mais"
Elemento.classList.remove('loading')
Elemento.classList.add('CarregarMais')
})
}
function carregaLivrosCarro(obj){
obj.innerText = ""
obj.classList.add('loading')
obj.classList.remove('CarregarMais')
minimo += 5
carregaLivros(obj)
}
//Função que carrega mais livros no carrossel
function carregaMaisLivrosCarro(codigo, pos, obj){
let ulCarrossel = window.document.getElementById(`carro${pos}`)
let mini = ulCarrossel.childNodes.length - 1
let dados = {
cod: codigo,
min: mini,
posi: pos
}
if(operacaoCarrosseislLivro != null){
operacaoCarrosseislLivro.abort();
operacaoCarrosseislLivro = null;
}
operacaoCarrosseislLivro = $.ajax({
method: "POST",
url: "carregaLivrosCarro.php",
data: dados,
beforeSend: function(){
obj.innerHTML = ""
obj.classList.add('CPlusLoading')
obj.classList.remove('CPlus')
obj.classList.remove('CarregarMais')
}
})
.done(function(res){
window.document.getElementById(`liEsp${pos}`).remove()
if(res.length > 0){
ulCarrossel.innerHTML += res
ulCarrossel.style.gridTemplateColumns = `repeat(${ulCarrossel.childNodes.length}, 1fr)`
}
})
.fail(function(){
if(operacaoCarrosseislLivro == null){
alert("Ocorreu um erro ao tentar carregar os dados do carrossel")
}
obj.innerHTML = "+"
obj.classList.remove('CPlusLoading')
obj.classList.add('CPlus')
obj.classList.add('CarregarMais')
})
}
window.addEventListener("load", function(){
liTamanho = (parseInt($(`.carrosselLivros li`).outerWidth() + parseInt($(`.carrosselLivros li`).css('margin'))) + 50)
scrollTamanho = liTamanho * 5
defineTipoPesquisa()
carregaLivros(window.document.getElementById('carregarMaisCarro'))
}) |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <Windows.h>
#include <WinCrypt.h>
#if defined(__STDC__) && __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#else
typedef unsigned char bool;
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#define GENERATING 0
|
#!/bin/bash
set -ev
go get github.com/Peanuttown/gopacket
go get github.com/Peanuttown/gopacket/layers
go get github.com/Peanuttown/gopacket/tcpassembly
go get github.com/Peanuttown/gopacket/reassembly
go get github.com/Peanuttown/gopacket/pcapgo
|
package com.myprojects.marco.firechat.main;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.myprojects.marco.firechat.BaseActivity;
import com.myprojects.marco.firechat.Dependencies;
import com.myprojects.marco.firechat.R;
import com.myprojects.marco.firechat.UserLocation;
import com.myprojects.marco.firechat.main.presenter.MainPresenter;
import com.myprojects.marco.firechat.main.view.MainDisplayer;
import com.myprojects.marco.firechat.navigation.AndroidMainNavigator;
/**
* Created by marco on 14/08/16.
*/
public class MainActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener {
private MainPresenter presenter;
private AndroidMainNavigator navigator;
FusedLocationProviderClient mFusedLocationClient;
UserLocation userLocation;
Location msLocation;
private static final int REQUEST_LOCATION_CODE_PERMISSION = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainDisplayer mainDisplayer = (MainDisplayer) findViewById(R.id.mainView);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
userLocation = new UserLocation();
getLocation();
navigator = new AndroidMainNavigator(this, googleApiClient);
presenter = new MainPresenter(
Dependencies.INSTANCE.getLoginService(),
Dependencies.INSTANCE.getUserService(),
mainDisplayer,
Dependencies.INSTANCE.getMainService(),
Dependencies.INSTANCE.getMessagingService(),
navigator,
Dependencies.INSTANCE.getFirebaseToken(),
this
);
}
private UserLocation getLocation() {
//Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(this, "The Location Permission is needed to show the weather ", Toast.LENGTH_SHORT).show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_CODE_PERMISSION);
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
}
}
} else {
// Log.d(TAG, "getLocation: Permission Granted");
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
msLocation = location;
userLocation.setLat(location.getLatitude());
userLocation.setLon(location.getLongitude());
Toast.makeText(MainActivity.this, "3", Toast.LENGTH_SHORT).show();
// mLocationText.setText("http://www.google.com/maps/place/"+msLocation.getLatitude()+","+msLocation.getLongitude());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
// mLocationText.setGravity(Gravity.CENTER_HORIZONTAL);
// mLocationText.setLayoutParams(params);
// mLocationText.setTextSize(20);
Toast.makeText(MainActivity.this, "http://www.google.com/maps/place/"+msLocation.getLatitude()+","+msLocation.getLongitude(), Toast.LENGTH_SHORT).show();
} else {
// mLocationText.setText(R.string.no_location);
Toast.makeText(MainActivity.this, "4", Toast.LENGTH_SHORT).show();
}
}
});
}
return userLocation;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!navigator.onActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onBackPressed() {
if (!presenter.onBackPressed())
if (!navigator.onBackPressed()) {
super.onBackPressed();
}
}
@Override
protected void onStart() {
super.onStart();
presenter.startPresenting();
}
@Override
protected void onStop() {
super.onStop();
presenter.stopPresenting();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// DO SOMETHING
}
}
|
function make_crc_table(nbits, poly, mask) {
var crcTable = [];
var remainder;
var topbit = 0;
/*
* Count topbit
*/
topbit = 1<<(nbits-1);
poly &= mask;
/*
* Compute the remainder of each possible dividend.
*/
for (var dividend = 0; dividend < 256; ++dividend)
{
/*
* Start with the dividend followed by zeros.
*/
remainder = dividend << (nbits - 8);
/*
* Perform modulo-2 division, a bit at a time.
*/
for (var bit = 8; bit > 0; --bit)
{
/*
* Try to divide the current data bit.
*/
if (remainder & topbit)
{
remainder = (remainder<<1) ^ poly;
}
else
{
remainder = (remainder<<1);
}
/*
* Mask, unsigned
*/
remainder &= mask;
remainder >>>= 0;
}
/*
* Store the result into the table.
*/
crcTable[dividend] = remainder;
}
return crcTable;
}
function make_crc_table_reversed(nbits, revpoly, mask) {
var crcTable = [];
var remainder;
revpoly &= mask;
/*
* Compute the remainder of each possible dividend.
*/
for (var dividend = 0; dividend < 256; ++dividend)
{
/*
* Start with the dividend followed by zeros.
*/
remainder = dividend;
/*
* Perform modulo-2 division, a bit at a time.
*/
for (var bit = 8; bit > 0; --bit)
{
/*
* Try to divide the current data bit.
*/
if (remainder & 1)
{
remainder = (remainder >>> 1) ^ revpoly;
}
else
{
remainder = (remainder >>> 1);
}
/*
* Mask, unsigned
*/
remainder &= mask;
remainder >>>= 0;
}
/*
* Store the result into the table.
*/
crcTable[dividend] = remainder;
}
return crcTable;
}
function get_sliced(val, curslice) {
return "0x"+("00000000"+val.toString(16)).slice(curslice);
}
function gen_code_crc(nbits, poly, isrev, isswap, init, final) {
if(isNaN(nbits) || isNaN(poly) || isNaN(init) || isNaN(final) || nbits<8)
return "";
var text = "";
var ln = "\n";
var tab = "\t";
var type = "unsigned " + (nbits <= 8 ? "char" : (nbits <= 16 ? "short" : "long") );
var curslice = (nbits <= 8 ? -2 : (nbits <= 16 ? -4 : -8) );
var mask = 0;
var poly_txt = get_sliced(poly, curslice);
//count mask
for(var i=0; i<nbits; i++) {
mask |= 1<<i;
}
//reverse poly if need, count mask
if(isrev) {
var temp = 0;
for(var i=0; i<(nbits-1); i++) {
if(poly & (1<<i)) {
temp |= (1<<(nbits-1-i));
}
}
poly = temp>>>0;
}
//append header with license
text += "/**"+ln
+" * This code is generated with sour-crc"+ln
+" * Provided under the MIT License"+ln
+" * "+ln
+" * Copyright (c) "+(new Date().getFullYear())+" <NAME>"+ln
+" * "+ln
+" * Permission is hereby granted, free of charge, to any person obtaining a copy"+ln
+" * of this software and associated documentation files (the \"Software\"), to deal"+ln
+" * in the Software without restriction, including without limitation the rights"+ln
+" * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell"+ln
+" * copies of the Software, and to permit persons to whom the Software is"+ln
+" * furnished to do so, subject to the following conditions:"+ln
+" * "+ln
+" * The above copyright notice and this permission notice shall be included in"+ln
+" * all copies or substantial portions of the Software."+ln
+" * "+ln
+" * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR"+ln
+" * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,"+ln
+" * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE"+ln
+" * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER"+ln
+" * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,"+ln
+" * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN"+ln
+" * THE SOFTWARE."+ln
+" **/"+ln
+""+ln
+type+" crcTable [ ] = {"+ln;
//append crc lookup table
var crc_table = [];
if(isrev)
crc_table = make_crc_table_reversed(nbits, poly, mask);
else
crc_table = make_crc_table(nbits, poly, mask);
for(var i=0; i<crc_table.length; i++) {
text += (i%8==0 ? tab : "")
+get_sliced(crc_table[i], curslice)
+(i<crc_table.length-1 ? ", " : "")
+(i%8==7 ? ln : "")
;
}
text += "};"+ln+ln;
//append footer with crc() function
text += "/**"+ln
+" * Calculate CRC"+nbits+" with configuration:"+ln
+" * polynom: "+poly_txt+ln
+" * reverse :"+(isrev ? "yes" : "no")+ln
+" * init value: "+get_sliced(init, curslice)+ln
+" * xourout value: "+get_sliced(final, curslice)+ln
+(nbits==16 ? " * swap: "+(isswap ? "yes" : "no")+ln : "")
+" **/"+ln
;
text += type+" crc (const unsigned char *data, const unsigned int len)"+ln
+"{"+ln
+tab+"unsigned char ind;"+ln
+tab+"int byte = 0;"+ln
+tab+type+" remainder = "+get_sliced(init, curslice)+";"+ln
+tab+"for (byte = 0; byte < len; ++byte)"+ln
+tab+"{"+ln;
if(isrev) {
//reversed
text += tab+tab+"ind = data[byte] ^ (remainder & 0xff);"+ln
+tab+tab+"remainder = crcTable[ind] ^ (remainder >> 8);"+ln;
} else {
//not inversed
text += tab+tab+"data = data[byte] ^ ((remainder >> "+(nbits-8)+") & 0xFF);"+ln
+tab+tab+"remainder = crcTable[ind] ^ (remainder << 8);"+ln;
}
text += tab+"}"+ln;
if(isswap && nbits == 16) {
//swap result bytes, exists for crc16 only
if(final!=0)
text += tab + "remainder = (remainder"+" ^ "+get_sliced(final, curslice)+");"+ln;
text += tab+"return ((remainder&0x00FF)<<8) | ((remainder&0xFF00)>>8);"+ln;
} else {
text += tab+"return (remainder"+(final==0 ? "" : " ^ "+get_sliced(final, curslice))+");"+ln;
}
text += "}"+ln;
return text;
}
|
def contains_duplicates(list):
seen = set()
for item in list:
if item in seen:
return True
seen.add(item)
return False
list = [1, 3, 2, 4, 5, 3]
print(contains_duplicates(list)) |
#ifndef _INCLUDE_PRINT_H
#define _INCLUDE_PRINT_H
// Prints string
// String has to be terminated with '$'.
void printString(const char* str);
#endif |
const algorithmia = require("algorithmia")
const augorithmiaApiKey = require('../credentials/algorithmia.json').apiKey
const sentenceBoundaryDetection = require('sbd')
const watsonApiKey = require('../credentials/watson-nlu.json').apikey
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const nlu = new NaturalLanguageUnderstandingV1({
authenticator: new IamAuthenticator({ apikey: watsonApiKey }),
version: '2018-04-05',
url: 'https://gateway.watsonplatform.net/natural-language-understanding/api/'
});
const state = require('./state.js')
async function robot() {
const content = state.load()
await fetchContentFromWikipedia(content)
sanitizeContent(content)
breakContentIntoSentences(content)
limitMaximumSentences(content)
await fetchKeywordsOfAllSentences(content)
state.save(content)
async function fetchContentFromWikipedia(content) {
const term = {
"articleName": content.searchTerm,
"lang": "pt"
}
// modo feito pelo deschamps
const algorithmiaAuthenticated = algorithmia(augorithmiaApiKey)
const wikipediaAlgorithm = algorithmiaAuthenticated.algo('web/WikipediaParser/0.1.2')
const wikipediaResponse = await wikipediaAlgorithm.pipe(term)
const wikipediaContent = wikipediaResponse.get()
content.sourceContentOriginal = wikipediaContent.content
// meu modo copiado do site
// não funcionou o async await
/*
algorithmia.client(augorithmiaApiKey)
.algo("web/WikipediaParser/0.1.2") // timeout is optional
.pipe(await content.searchTerm)
.then((response) => {
console.log(response.get());
}); */
}
function sanitizeContent(content) {
const withoutBlankLinesAndMarkdown = removeBlankLinesAndMarkdown(content.sourceContentOriginal)
const withoutDatesInParenteses = removeDatesInParentheses(withoutBlankLinesAndMarkdown)
content.sourceContentSanitized = withoutDatesInParenteses
function removeBlankLinesAndMarkdown(text) {
const allLines = text.split('\n')
const formatedText = allLines.filter((line) => {
if (line.trim().length === 0 || line.trim().startsWith('=')) {
return false
} else {
return true
}
})
return formatedText.join(' ')
}
function removeDatesInParentheses(text) {
return text.replace(/\((?:\([^()]*\)|[^()])*\)/gm, '').replace(/ /g, ' ')
}
}
function breakContentIntoSentences(content) {
content.sentences = []
const sentences = sentenceBoundaryDetection.sentences(content.sourceContentSanitized)
sentences.forEach((sentence) => {
content.sentences.push({
text: sentence,
keywords: [],
images: []
})
})
}
function limitMaximumSentences(content) {
content.sentences = content.sentences.slice(0, content.maximumSentences)
}
async function fetchWatsonAndReturnKeywords(sentence) {
await nlu.analyze(
{
html: sentence.text,
features: {
keywords: {}
}
})
.then(response => {
const keywords = response.result.keywords.map(keyword => {
return keyword.text;
});
sentence.keywords = keywords;
})
.catch(err => {
console.log('error: ', err);
});
}
async function fetchKeywordsOfAllSentences(content) {
const listOfKeywordsToFetch = []
for (const sentence of content.sentences) {
listOfKeywordsToFetch.push(
fetchWatsonAndReturnKeywords(sentence)
)
}
await Promise.all(listOfKeywordsToFetch)
}
}
module.exports = robot |
#! /bin/bash
dumpdir=${1-'/var/lib/p-rout/'}
filename=dump$(date +%Y%m%d-%H%M).sql.gz
find $dumpdir/ -name dump*-*.sql.gz -mtime +14 -delete
pg_dump -Z 9 -U p-rout -f $dumpdir/$filename -w p_rout
|
#include <iostream>
using namespace std;
int findMax(int arr[], int n) {
int max = arr[0];
for (int i=1; i<n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {-1, 3, 5, 8, 10, 15};
int n = sizeof(arr)/sizeof(arr[0]);
int max = findMax(arr, n);
cout << "The maximum value is: " << max << endl;
return 0;
} |
try:
from django.urls import url, include
except:
from django.conf.urls import url, include
from . import views as malice_views
app_name = 'malice'
urlpatterns = [
url(
r'^200/$',
malice_views.OK.as_view(),
name="ok"
),
url(
r'^403/$',
malice_views.PermissionDenied.as_view(),
name="permission-denied"
),
url(
r'^404/$',
malice_views.NotFound.as_view(),
name="not-found"
),
url(
r'^500/$',
malice_views.InternalServerError.as_view(),
name="internal-server-error"
),
]
|
#!/bin/bash
#set -x
RATIO_LIST="1/128 1/8 1/4 1/2 2/1 4/1 8/1 128/1"
VALUE_SIZE_POWER_RANGE="8 14"
CONN_CLI_COUNT_POWER_RANGE="5 11"
REPEAT_COUNT=5
RUN_COUNT=200000
KEY_SIZE=256
KEY_SPACE_SIZE=$((1024 * 64))
BACKEND_SIZE="$((20 * 1024 * 1024 * 1024))"
RANGE_RESULT_LIMIT=100
CLIENT_PORT="23790"
COMMIT=
ETCD_ROOT_DIR="$(cd $(dirname $0) && pwd)/../.."
ETCD_BIN_DIR="${ETCD_ROOT_DIR}/bin"
ETCD_BIN="${ETCD_BIN_DIR}/etcd"
ETCD_BM_BIN="${ETCD_BIN_DIR}/tools/benchmark"
WORKING_DIR="$(mktemp -d)"
CURRENT_DIR="$(pwd -P)"
OUTPUT_FILE="${CURRENT_DIR}/result-$(date '+%Y%m%d%H%M').csv"
trap ctrl_c INT
CURRENT_ETCD_PID=
function ctrl_c() {
# capture ctrl-c and kill server
echo "terminating..."
kill_etcd_server ${CURRENT_ETCD_PID}
exit 0
}
function quit() {
if [ ! -z ${CURRENT_ETCD_PID} ]; then
kill_etcd_server ${CURRENT_ETCD_PID}
fi
exit $1
}
function check_prerequisite() {
# check initial parameters
if [ -f "${OUTPUT_FILE}" ]; then
echo "file ${OUTPUT_FILE} already exists."
exit 1
fi
pushd ${ETCD_ROOT_DIR} > /dev/null
COMMIT=$(git log --pretty=format:'%h' -n 1)
if [ $? -ne 0 ]; then
COMMIT=N/A
fi
popd > /dev/null
cat >"${OUTPUT_FILE}" <<EOF
type,ratio,conn_size,value_size$(for i in $(seq 1 ${REPEAT_COUNT});do echo -n ",iter$i"; done),comment
PARAM,,,$(for i in $(seq 1 ${REPEAT_COUNT});do echo -n ","; done),"key_size=${KEY_SIZE},key_space_size=${KEY_SPACE_SIZE},backend_size=${BACKEND_SIZE},range_limit=${RANGE_RESULT_LIMIT},commit=${COMMIT}"
EOF
}
function run_etcd_server() {
if [ ! -x ${ETCD_BIN} ]; then
echo "no etcd binary found at: ${ETCD_BIN}"
exit 1
fi
# delete existing data directories
[ -d "db" ] && rm -rf db
[ -d "default.etcd" ] && rm -rf default.etcd/
echo "start etcd server in the background"
${ETCD_BIN} --quota-backend-bytes=${BACKEND_SIZE} \
--log-level 'error' \
--listen-client-urls http://0.0.0.0:${CLIENT_PORT} \
--advertise-client-urls http://127.0.0.1:${CLIENT_PORT} \
&>/dev/null &
return $!
}
function init_etcd_db() {
#initialize etcd database
if [ ! -x ${ETCD_BM_BIN} ]; then
echo "no etcd benchmark binary found at: ${ETCD_BM_BIN}"
quit -1
fi
echo "initialize etcd database..."
${ETCD_BM_BIN} put --sequential-keys \
--key-space-size=${KEY_SPACE_SIZE} \
--val-size=${VALUE_SIZE} --key-size=${KEY_SIZE} \
--endpoints http://127.0.0.1:${CLIENT_PORT} \
--total=${KEY_SPACE_SIZE} \
&>/dev/null
}
function kill_etcd_server() {
# kill etcd server
ETCD_PID=$1
if [ -z "$(ps aux | grep etcd | awk "{print \$2}")" ]; then
echo "failed to find the etcd instance to kill: ${ETCD_PID}"
return
fi
echo "kill etcd server instance"
kill -9 ${ETCD_PID}
wait ${ETCD_PID} 2>/dev/null
sleep 5
}
while getopts ":w:c:p:l:vh" OPTION; do
case $OPTION in
h)
echo "usage: $(basename $0) [-h] [-w WORKING_DIR] [-c RUN_COUNT] [-p PORT] [-l RANGE_QUERY_LIMIT] [-v]" >&2
exit 1
;;
w)
WORKING_DIR="${OPTARG}"
;;
c)
RUN_COUNT="${OPTARG}"
;;
p)
CLIENT_PORT="${OPTARG}"
;;
v)
set -x
;;
l)
RANGE_RESULT_LIMIT="${OPTARG}"
;;
\?)
echo "usage: $(basename $0) [-h] [-w WORKING_DIR] [-c RUN_COUNT] [-p PORT] [-l RANGE_QUERY_LIMIT] [-v]" >&2
exit 1
;;
esac
done
shift "$((${OPTIND} - 1))"
check_prerequisite
pushd "${WORKING_DIR}" > /dev/null
# progress stats management
ITER_TOTAL=$(($(echo ${RATIO_LIST} | wc | awk "{print \$2}") * \
$(seq ${VALUE_SIZE_POWER_RANGE} | wc | awk "{print \$2}") * \
$(seq ${CONN_CLI_COUNT_POWER_RANGE} | wc | awk "{print \$2}")))
ITER_CURRENT=0
PERCENTAGE_LAST_PRINT=0
PERCENTAGE_PRINT_THRESHOLD=5
for RATIO_STR in ${RATIO_LIST}; do
RATIO=$(echo "scale=4; ${RATIO_STR}" | bc -l)
for VALUE_SIZE_POWER in $(seq ${VALUE_SIZE_POWER_RANGE}); do
VALUE_SIZE=$((2 ** ${VALUE_SIZE_POWER}))
for CONN_CLI_COUNT_POWER in $(seq ${CONN_CLI_COUNT_POWER_RANGE}); do
# progress stats management
ITER_CURRENT=$((${ITER_CURRENT} + 1))
PERCENTAGE_CURRENT=$(echo "scale=3; ${ITER_CURRENT}/${ITER_TOTAL}*100" | bc -l)
if [ "$(echo "${PERCENTAGE_CURRENT} - ${PERCENTAGE_LAST_PRINT} > ${PERCENTAGE_PRINT_THRESHOLD}" |
bc -l)" -eq 1 ]; then
PERCENTAGE_LAST_PRINT=${PERCENTAGE_CURRENT}
echo "${PERCENTAGE_CURRENT}% completed"
fi
CONN_CLI_COUNT=$((2 ** ${CONN_CLI_COUNT_POWER}))
run_etcd_server
CURRENT_ETCD_PID=$!
sleep 5
init_etcd_db
START=$(date +%s)
LINE="DATA,${RATIO},${CONN_CLI_COUNT},${VALUE_SIZE}"
echo -n "run with setting [${LINE}]"
for i in $(seq ${REPEAT_COUNT}); do
echo -n "."
QPS=$(${ETCD_BM_BIN} txn-mixed "" \
--conns=${CONN_CLI_COUNT} --clients=${CONN_CLI_COUNT} \
--total=${RUN_COUNT} \
--endpoints "http://127.0.0.1:${CLIENT_PORT}" \
--rw-ratio ${RATIO} --limit ${RANGE_RESULT_LIMIT} \
--val-size ${VALUE_SIZE} \
2>/dev/null | grep "Requests/sec" | awk "{print \$2}")
if [ $? -ne 0 ]; then
echo "benchmark command failed: $?"
quit -1
fi
RD_QPS=$(echo -e "${QPS}" | sed -n '1 p')
WR_QPS=$(echo -e "${QPS}" | sed -n '2 p')
if [ -z "${RD_QPS}" ]; then
RD_QPS=0
fi
if [ -z "${WR_QPS}" ]; then
WR_QPS=0
fi
LINE="${LINE},${RD_QPS}:${WR_QPS}"
done
END=$(date +%s)
DIFF=$((${END} - ${START}))
echo "took ${DIFF} seconds"
cat >>"${OUTPUT_FILE}" <<EOF
${LINE}
EOF
kill_etcd_server ${CURRENT_ETCD_PID}
done
done
done
popd > /dev/null
|
<filename>infinibox_hosts_workload_graphite.py
'''
!/usr/bin/env python
Examples:
Overall Performance Statistics:
python infinibox_hosts_workload_graphite.py
-u "http://<infinimetrics_fqdn>/api/rest/"
-F <host fqdn>
-C "systems/<serialnumber>/monitored_entities"
-f "format=json&page=last&sort=-timestamp"
-U "username"
-P "password"
Add -v to the end to view output
'''
from pprint import pformat
import time
import socket
import yaml
import functions
import global_vars
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Disabled SSL certificate warnings for http api requests
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# define and gather command line options
parser = functions.ArgumentParserEx(
prog="check_infinidat",
description="Utilizes the Infinibox API to check status of monitored hardware and services.",
)
parser.add_argument(
"-u",
"--url",
dest="url",
default=None,
help="Specify the location of the Infinibox API. (default: %(default)s)"
)
parser.add_argument(
"-F",
"--fqdn",
dest="fqdn",
default=None,
help="Specify the fqdn of the Infinibox"
)
parser.add_argument(
"-U",
"--username",
dest="username",
default=None,
help="Username to use when connecting to API. (default: %(default)s)"
)
parser.add_argument(
"-P",
"--password",
dest="password",
default=None,
help="Password to use when connecting to API. (default: %(default)s)"
)
parser.add_argument(
"-C",
"--components",
dest="components",
default=None,
required=True,
help="Name of component to appent to url."
)
parser.add_argument(
"-f",
"--filters",
dest="filters",
default=None,
required=True,
help="Result filters to appent to url."
)
parser.add_argument(
"-t",
"--timeout",
dest="timeout",
default=10,
type=int,
help="Time in seconds plugin is allowed to run. (default: %(default)s)"
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
dest="verbose",
default=False,
help="Turn on verbosity."
)
# parse arguments
options = parser.parse_args()
# show command line options
if options.verbose:
# store password temporarily
password = options.password
# hide password from output
options.password = "<PASSWORD>"
# show command line options
print "command line options:\n%s\n" % (pformat(vars(options)))
# restore password
options.password = password
username = options.username
password = <PASSWORD>
timeout = options.timeout
url_args = ["https://{}/api/rest/hosts?fields=name,id&page_size=1000".format(
options.fqdn
)]
url_args.append("{}{}?{}".format(str(options.url), str(options.components), str(options.filters)))
functions.process_url(
url_args,
options.username,
options.password,
options.timeout,
options.verbose
)
i = 0
url_entity_id = []
host_names = []
# Associate host with entitiy id
for host in global_vars.outcome[0]:
shortname = host["name"].split(".")
host_names.append(shortname[0])
for entity_id in global_vars.outcome[1]:
if entity_id["group"] == "Hosts":
if host["id"] == entity_id["id_in_system"]:
monitor_entity_id = "{}{}/{}/data/?format=json&page_size=1&sort=timestamp&page=last".format(
options.url,
options.components,
entity_id["id"]
)
url_entity_id.append(monitor_entity_id)
'''
functions.process_url(
url_args,
options.username,
options.password,
options.timeout,
options.verbose
)
'''
# clear the list
del url_args[:]
del global_vars.outcome[:]
# append infinimetrics api urls
for url in url_entity_id:
r = requests.get(
"%s" % (url),
verify=False,
auth=(username, password),
timeout=timeout
)
try:
print r.json()
url_args.append(url)
except ValueError:
print "Failed to decode JSON. Exluding URL."
functions.process_url(
url_args,
options.username,
options.password,
options.timeout,
options.verbose
)
# Define Graphite information
with open("settings.yaml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
for section in cfg:
if options.fqdn.split(".")[1].find(section) != -1:
graphite_address = str(cfg[options.fqdn.split(".")[1]]["graphite_address"])
graphite_port = cfg[options.fqdn.split(".")[1]]["graphite_port"]
graphite_prefix = cfg[options.fqdn.split(".")[1]]["graphite_prefix"]
graphite_timeout = cfg[options.fqdn.split(".")[1]]["graphite_timeout"]
'''
print "graphite_address={}".format(graphite_address)
print "graphite_port={}".format(graphite_port)
print "graphite_prefix={}".format(graphite_prefix)
print "graphite_timeout={}".format(graphite_timeout)
print ""
'''
servername = options.fqdn.split(".")[0]
# Get data to send to Graphite
timestamp = str(time.time())[0:10]
i = 0
messages = []
while i < len(global_vars.outcome):
read_iops = str(int(global_vars.result[i]["result"][0]["read_ops"]))
read_bytes = str(int(global_vars.result[i]["result"][0]["read_bytes"]))
read_latency = str(int(global_vars.result[i]["result"][0]["read_latency"]))
write_iops = str(int(global_vars.result[i]["result"][0]["write_ops"]))
write_bytes = str(int(global_vars.result[i]["result"][0]["write_bytes"]))
write_latency = str(int(global_vars.result[i]["result"][0]["write_latency"]))
# Put Graphite data into list
messages.append([
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "read_iops", read_iops, timestamp)],
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "read_bytes", read_bytes, timestamp)],
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "read_latency", read_latency, timestamp)],
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "write_iops", write_iops, timestamp)],
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "write_bytes", write_bytes, timestamp)],
["{}.{}.{}.{}.{} {} {}".format(graphite_prefix, servername, "Host", host_names[i], "write_latency", write_latency, timestamp)]
])
i += 1
# Make connection to Graphite
conn = socket.socket()
conn.connect((graphite_address, graphite_port))
# Cycle through list items and send data to Graphit
for message in messages:
i = 0
while i < len(message):
msgOutput = message[i]
msgOutput = str(message[i]).strip("['']")
msgOutput = "{}\n".format(msgOutput)
print "msgOutput = {}".format(msgOutput)
conn.sendall(msgOutput)
i += 1
# Close connection to Graphite
conn.close()
|
package it.madlabs.patternrec.web.rest.model;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Abstract a Line based on implicit formula: ax + by + c = 0
*
* Note:
* the explicit form for representing lines is y = m*x + q, but we can't use it to all lines
* because the equation of parallel lines to x axe are x = c
* but we can use another equivalent equations, the implicit form, a*x + b*y + c = 0
* in which we can represent parallel line to x as 1*x + 0*y - c = 0
* with little maths we can pass from the implicit form to explicit one as y = m*x + q => -m*x + 1 * y - q
* in this way we can represent all possible lines
*/
public class Line{
public static final Line IDENTITY = new Line(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
private final BigDecimal a;
private final BigDecimal b;
private final BigDecimal c;
public Line(BigDecimal a, BigDecimal b, BigDecimal c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
if (a != null ? !a.equals(line.a) : line.a != null) return false;
if (b != null ? !b.equals(line.b) : line.b != null) return false;
return c != null ? c.equals(line.c) : line.c == null;
}
@Override
public int hashCode() {
int result = a != null ? a.hashCode() : 0;
result = 31 * result + (b != null ? b.hashCode() : 0);
result = 31 * result + (c != null ? c.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Line{" +
"a=" + a +
", b=" + b +
", c=" + c +
'}';
}
public boolean containsPoint(Point point) {
BigDecimal xBD = new BigDecimal(point.getX());
BigDecimal yBD = new BigDecimal(point.getY());
return a.multiply(xBD).add(b.multiply(yBD)).add(c).stripTrailingZeros().equals(BigDecimal.ZERO);
}
public Double calculateYgivenX(double x) {
BigDecimal xBD = new BigDecimal(x);
//ax + by + c = 0 => y = - (ax + c) / ba.multiply(xBD).add(b.multiply(yBD)).add(c)
return a.multiply(xBD).add(c).negate().divide(b).doubleValue();
}
} |
#!/bin/sh
#uname -r
# 4.19.97-v7+
# remove -v7+ from above output
# -----------------------------
kernel=$(uname -r | awk -F\- '{print $1}')
#echo $kernel
# drivers for kernel
iio=https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/iio
# open in browser
chromium-browser $iio/?h=v$kernel
|
import subprocess
def install_dependencies(system_deps, python_deps):
# Install system dependencies using apt-get
apt_command = ["sudo", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "--no-install-recommends", "--yes"] + system_deps
try:
subprocess.run(apt_command, check=True)
print("System dependencies installed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error installing system dependencies: {e}")
# Install Python dependencies using pip
pip_command = ["python3", "-m", "pip", "install"] + python_deps
try:
subprocess.run(pip_command, check=True)
print("Python dependencies installed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error installing Python dependencies: {e}")
# Example usage
system_deps = ["graphviz"]
python_deps = ["bs4", "jinja2"]
install_dependencies(system_deps, python_deps) |
'use strict';
const fs = require('fs');
const { registerAndLogin } = require('../../../test/helpers/auth');
const { createAuthRequest } = require('../../../test/helpers/request');
let rq;
const defaultProviderConfig = {
provider: 'local',
name: 'Local server',
enabled: true,
sizeLimit: 1000000,
};
const resetProviderConfigToDefault = () => {
return setConfigOptions(defaultProviderConfig);
};
const setConfigOptions = assign => {
return rq.put('/upload/settings/development', {
body: {
...defaultProviderConfig,
...assign,
},
});
};
const data = {};
describe('Upload plugin end to end tests', () => {
beforeAll(async () => {
const token = await registerAndLogin();
rq = createAuthRequest(token);
}, 60000);
afterEach(async () => {
await resetProviderConfigToDefault();
});
test('Upload a single file', async () => {
const req = rq.post('/graphql');
const form = req.form();
form.append(
'operations',
JSON.stringify({
query: /* GraphQL */ `
mutation uploadFiles($file: Upload!) {
upload(file: $file) {
id
name
mime
url
}
}
`,
variables: {
file: null,
},
})
);
form.append(
'map',
JSON.stringify({
0: ['variables.file'],
})
);
form.append('0', fs.createReadStream(__dirname + '/rec.jpg'));
const res = await req;
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
data: {
upload: {
id: expect.anything(),
name: 'rec.jpg',
},
},
});
data.file = res.body.data.upload;
});
test('Upload multiple files', async () => {
const req = rq.post('/graphql');
const form = req.form();
form.append(
'operations',
JSON.stringify({
query: /* GraphQL */ `
mutation uploadFiles($files: [Upload]!) {
multipleUpload(files: $files) {
id
name
mime
url
}
}
`,
variables: {
files: [null, null],
},
})
);
form.append(
'map',
JSON.stringify({
0: ['variables.files.0'],
1: ['variables.files.1'],
})
);
form.append('0', fs.createReadStream(__dirname + '/rec.jpg'));
form.append('1', fs.createReadStream(__dirname + '/rec.jpg'));
const res = await req;
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({
data: {
multipleUpload: expect.arrayContaining([
expect.objectContaining({
id: expect.anything(),
name: 'rec.jpg',
}),
]),
},
});
});
test('Update file information', async () => {
const res = await rq({
url: '/graphql',
method: 'POST',
body: {
query: /* GraphQL */ `
mutation updateFileInfo($id: ID!, $info: FileInfoInput!) {
updateFileInfo(id: $id, info: $info) {
id
name
alternativeText
caption
}
}
`,
variables: {
id: data.file.id,
info: {
name: '<NAME>',
alternativeText: 'alternative text test',
caption: 'caption test',
},
},
},
});
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
data: {
updateFileInfo: {
id: data.file.id,
name: '<NAME>',
alternativeText: 'alternative text test',
caption: 'caption test',
},
},
});
});
});
|
#!/bin/sh
set -euo pipefail
if [ "$#" != "1" ]; then
exit 1
fi
echo $(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")
|
#!/bin/bash
# Test clang-format formating
########################
# BEGIN CONFIG SECTION #
########################
CLANG_FORMAT_VERSIONS=( "7.0.0" "7.0.1" )
CALNG_FORMAT_DEFAULT_CMD="clang-format"
EXTENSIONS=( cpp hpp )
SOURCE_DIRS=( src lib )
CHECK_SUM=md5sum
########################
# END CONFIG SECTION #
########################
VERBOSE=0
GIT_MODE=0
ONLY_CHECK=0
for I in "$@"; do
case "$I" in
-v|--verbose) VERBOSE=1 ;;
-g|--git) GIT_MODE=1 ;;
-c|--only-check) ONLY_CHECK=1 ;;
esac
done
error() {
echo -e ' \x1b[1;31m______ ______________ ___ ___ _____ _________________ ___________ \x1b[0m'
echo -e ' \x1b[1;31m| ___| _ | ___ \ \/ | / _ \_ _| | ___| ___ \ ___ \ _ | ___ \ \x1b[0m'
echo -e ' \x1b[1;31m| |_ | | | | |_/ / . . |/ /_\ \| | | |__ | |_/ / |_/ / | | | |_/ / \x1b[0m'
echo -e ' \x1b[1;31m| _| | | | | /| |\/| || _ || | | __|| /| /| | | | / \x1b[0m'
echo -e ' \x1b[1;31m| | \ \_/ / |\ \| | | || | | || | | |___| |\ \| |\ \\\\ \_/ / |\ \ \x1b[0m'
echo -e ' \x1b[1;31m\_| \___/\_| \_\_| |_/\_| |_/\_/ \____/\_| \_\_| \_|\___/\_| \_| \x1b[0m'
echo -e ' \x1b[1;31m \x1b[0m'
echo -e " \x1b[1;31m==> \x1b[0;31m$*\x1b[0m"
}
verbose() {
(( VERBOSE == 0 )) && return
echo -e "$*"
}
cd "$(dirname "$0")"
[ -z "$CLANG_FORMAT_CMD" ] && CLANG_FORMAT_CMD="$CALNG_FORMAT_DEFAULT_CMD"
# Check if the command exists
CLANG_FORMAT_EXEC=$(which "$CLANG_FORMAT_CMD" 2> /dev/null)
if (( $? != 0 )); then
error "clang-format ($CLANG_FORMAT_CMD) not found. Try setting the CLANG_FORMAT_CMD environment variable"
exit 1
fi
verbose "clang-format command: $CLANG_FORMAT_EXEC"
# Check the version
CURRENT_VERSION="$($CLANG_FORMAT_EXEC --version | sed 's/^[^0-9]*//g')"
CURRENT_VERSION="$(echo "$CURRENT_VERSION" | sed 's/^\([0-9.]*\).*/\1/g')"
FOUND_VERSION=0
for I in "${CLANG_FORMAT_VERSIONS[@]}"; do
[[ "$I" == "$CURRENT_VERSION" ]] && (( FOUND_VERSION++ ))
done
if (( FOUND_VERSION == 0 )); then
error "Invalid clang-format version! ${CLANG_FORMAT_VERSIONS[@]} versions required but $CURRENT_VERSION provided"
exit 2
fi
verbose "clang-format version: $CURRENT_VERSION\n"
#########################
# Checking source files #
#########################
ERROR=0
NUM_FILES=0
TO_GIT_ADD=()
checkFormat() {
local I J
NUM_FILES=0
ERROR=0
verbose " ==> Checking files"
if (( GIT_MODE == 1 )); then
SOURCE_LIST=()
for I in $(git diff --cached --name-only); do
for J in "${SOURCE_DIRS[@]}"; do
echo "$I" | grep -E "^$J" &> /dev/null
if (( $? == 0 )); then
SOURCE_LIST+=( "$I" )
break
fi
done
done
else
SOURCE_LIST=( $(find "${SOURCE_DIRS[@]}" -type f) )
fi
for I in "${SOURCE_LIST[@]}"; do
for J in "${EXTENSIONS[@]}"; do
echo "$I" | grep -E "\.$J$" &> /dev/null
(( $? != 0 )) && continue
(( NUM_FILES++ ))
if [[ "$1" == "format" ]]; then
verbose " --> Fixing $I"
$CLANG_FORMAT_EXEC -i "$I"
TO_GIT_ADD+=( "$I" )
fi
verbose " --> Checking $I"
SUM_O="$($CHECK_SUM "$I")"
SUM_F="$($CLANG_FORMAT_EXEC "$I" | $CHECK_SUM)"
SUM_O="${SUM_O%% *}"
SUM_F="${SUM_F%% *}"
if [[ "$SUM_O" != "$SUM_F" ]]; then
echo -e " \x1b[1;31mFormat check error: $I"
(( ERROR++ ))
fi
break
done
done
}
checkFormat check
if (( ERROR != 0 )); then
error "$ERROR out of $NUM_FILES files are not formated"
(( ONLY_CHECK == 1 )) && exit $ERROR
read -p " ==> Try formatting source files [Y/n]? " -n 1 INPUT
[ -z "$INPUT" ] && INPUT=y || echo ""
if [[ "$INPUT" == "Y" || "$INPUT" == "y" ]]; then
checkFormat format
if (( ERROR != 0 )); then
error "$ERROR out of $NUM_FILES files are not formatted -- CLANG FORMAT FAIL"
exit $ERROR
fi
if (( GIT_MODE == 1 )); then
read -p " ==> Show formate updates diff [y/N]? " -n 1 INPUT
[ -z "$INPUT" ] && INPUT=n || echo ""
[[ "$INPUT" == "Y" || "$INPUT" == "y" ]] && git diff
fi
else
exit $ERROR
fi
fi
if (( GIT_MODE == 0 )); then
echo -e ' \x1b[1;32m______ ______________ ___ ___ _____ _____ _ __ \x1b[0m'
echo -e ' \x1b[1;32m| ___| _ | ___ \ \/ | / _ \_ _| | _ | | / / \x1b[0m'
echo -e ' \x1b[1;32m| |_ | | | | |_/ / . . |/ /_\ \| | | | | | |/ / \x1b[0m'
echo -e ' \x1b[1;32m| _| | | | | /| |\/| || _ || | | | | | \ \x1b[0m'
echo -e ' \x1b[1;32m| | \ \_/ / |\ \| | | || | | || | \ \_/ / |\ \ \x1b[0m'
echo -e ' \x1b[1;32m\_| \___/\_| \_\_| |_/\_| |_/\_/ \___/\_| \_/ \x1b[0m'
echo -e ' \x1b[1;32m \x1b[0m'
else
echo -e ' \x1b[1;32m _____ ________ ______ ________ _____ _____ _ __ \x1b[0m'
echo -e ' \x1b[1;32m/ __ \ _ | \/ || \/ |_ _|_ _| | _ | | / / \x1b[0m'
echo -e ' \x1b[1;32m| / \/ | | | . . || . . | | | | | | | | | |/ / \x1b[0m'
echo -e ' \x1b[1;32m| | | | | | |\/| || |\/| | | | | | | | | | \ \x1b[0m'
echo -e ' \x1b[1;32m| \__/\ \_/ / | | || | | |_| |_ | | \ \_/ / |\ \ \x1b[0m'
echo -e ' \x1b[1;32m \____/\___/\_| |_/\_| |_/\___/ \_/ \___/\_| \_/ \x1b[0m'
echo -e ' \x1b[1;32m \x1b[0m'
fi
echo -e " \x1b[1;32m==>\x1b[0m All $NUM_FILES files are OK"
# Add changes
if (( GIT_MODE == 1 )); then
for I in "${TO_GIT_ADD[@]}"; do
echo "$I"
git add "$I"
done
fi
exit $ERROR
|
<filename>old-katas/minimum-spanning-trees-kata/minimum-spanning-trees-kata-day-6/src/main/java/kata/java/LazySpanningTree.java
package kata.java;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LazySpanningTree {
private final Iterable<WeightedEdge> tree;
public LazySpanningTree(Iterable<WeightedEdge> tree) {
this.tree = tree;
}
public static LazySpanningTree create(EdgeWeightedGraph graph) {
if (graph.numberOfEdges() < 1) {
throw new RuntimeException();
}
return new LazySpanningTree(new SpanningTreeBuilder(graph).createTree());
}
public Iterable<WeightedEdge> tree() {
return tree;
}
private static class SpanningTreeBuilder {
private final Set<Integer> marked = new HashSet<>();
private final Queue<WeightedEdge> tree = new ArrayDeque<>();
private final Queue<WeightedEdge> priority = new PriorityQueue<>();
private SpanningTreeBuilder(EdgeWeightedGraph graph) {
int vertex = graph.startingVertex();
visit(graph.adjacentTo(vertex), vertex);
walkOverGraph(graph);
}
private void walkOverGraph(EdgeWeightedGraph graph) {
WeightedEdge edge;
while ((edge = priority.poll()) != null) {
int v = edge.either();
int w = edge.other(v);
if (!marked.contains(v) || !marked.contains(w)) {
tree.add(edge);
}
if (!marked.contains(v)) {
visit(graph.adjacentTo(v), v);
}
if (!marked.contains(w)) {
visit(graph.adjacentTo(w), w);
}
}
}
private void visit(Stream<WeightedEdge> adjacent, int vertex) {
marked.add(vertex);
priority.addAll(adjacent.filter(e -> !marked.contains(e.other(vertex))).collect(Collectors.toList()));
}
Queue<WeightedEdge> createTree() {
return tree;
}
}
}
|
#!/bin/sh
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
#
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
# Other names may be trademarks of their respective owners.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
# This script expects JAVA_HOME to point to the correct JDK 5.0 installation
# In case you need to customize it, please uncomment and modify the following lines
# JAVA_HOME=/opt/java/jdk1.5.0_04
# export JAVA_HOME
OLD_PWD=`pwd`
cd `dirname $0`
INSTALL_DIR=`pwd`
cd $OLD_PWD
unset OLD_PWD
$JAVA_HOME/bin/java -javaagent:$INSTALL_DIR/../lib/jfluid-server-15.jar org.netbeans.lib.profiler.server.ProfilerCalibrator
|
#!/bin/bash
# AutoBuild Module by Hyy2001 <https://github.com/Hyy2001X/AutoBuild-Actions>
# AutoBuild Functions
Firmware-Diy_Before() {
ECHO "[Firmware-Diy_Before] Start ..."
CD ${GITHUB_WORKSPACE}/openwrt
Diy_Core
Home="${GITHUB_WORKSPACE}/openwrt"
[[ -f ${GITHUB_WORKSPACE}/Openwrt.info ]] && source ${GITHUB_WORKSPACE}/Openwrt.info
[[ ${Short_Firmware_Date} == true ]] && Compile_Date="$(echo ${Compile_Date} | cut -c1-8)"
Author_Repository="$(grep "https://github.com/[a-zA-Z0-9]" ${GITHUB_WORKSPACE}/.git/config | cut -c8-100 | sed 's/^[ \t]*//g')"
[[ -z ${Author} ]] && Author="$(echo "${Author_Repository}" | cut -d "/" -f4)"
OP_Maintainer="$(echo "${Openwrt_Repository}" | cut -d "/" -f4)"
OP_REPO_NAME="$(echo "${Openwrt_Repository}" | cut -d "/" -f5)"
OP_BRANCH="$(GET_Branch)"
if [[ ${OP_BRANCH} == master || ${OP_BRANCH} == main ]];then
Openwrt_Version_Head="R$(date +%y.%m)-"
else
OP_BRANCH="$(echo ${OP_BRANCH} | egrep -o "[0-9]+.[0-9]+")"
Openwrt_Version_Head="R${OP_BRANCH}-"
fi
case "${OP_Maintainer}/${OP_REPO_NAME}" in
coolsnowwolf/lede)
Version_File=package/lean/default-settings/files/zzz-default-settings
zzz_Default_Version="$(egrep -o "R[0-9]+\.[0-9]+\.[0-9]+" ${Version_File})"
CURRENT_Version="${zzz_Default_Version}-${Compile_Date}"
;;
immortalwrt/immortalwrt)
Version_File=${base_files}/etc/openwrt_release
CURRENT_Version="${Openwrt_Version_Head}${Compile_Date}"
;;
*)
CURRENT_Version="${Openwrt_Version_Head}${Compile_Date}"
;;
esac
while [[ -z ${x86_Test} ]];do
x86_Test="$(egrep -o "CONFIG_TARGET.*DEVICE.*=y" .config | sed -r 's/CONFIG_TARGET_(.*)_DEVICE_(.*)=y/\1/')"
[[ -n ${x86_Test} ]] && break
x86_Test="$(egrep -o "CONFIG_TARGET.*Generic=y" .config | sed -r 's/CONFIG_TARGET_(.*)_Generic=y/\1/')"
[[ -z ${x86_Test} ]] && break
done
[[ ${x86_Test} == x86_64 ]] && {
TARGET_PROFILE=x86_64
} || {
TARGET_PROFILE="$(egrep -o "CONFIG_TARGET.*DEVICE.*=y" .config | sed -r 's/.*DEVICE_(.*)=y/\1/')"
}
[[ -z ${TARGET_PROFILE} ]] && ECHO "Unable to obtain the [TARGET_PROFILE] !"
TARGET_BOARD="$(awk -F '[="]+' '/TARGET_BOARD/{print $2}' .config)"
TARGET_SUBTARGET="$(awk -F '[="]+' '/TARGET_SUBTARGET/{print $2}' .config)"
[[ -z ${Firmware_Format} || ${Firmware_Format} == false ]] && {
case "${TARGET_BOARD}" in
ramips | reltek | ipq40xx | ath79 | ipq807x)
Firmware_Format=bin
;;
rockchip | x86)
[[ $(cat ${Home}/.config) =~ CONFIG_TARGET_IMAGES_GZIP=y ]] && {
Firmware_Format=img.gz || Firmware_Format=img
}
;;
esac
}
case "${TARGET_BOARD}" in
x86)
AutoBuild_Firmware='AutoBuild-${OP_REPO_NAME}-${TARGET_PROFILE}-${CURRENT_Version}-${FW_Boot_Type}-$(Get_SHA256 $1).${Firmware_Format_Defined}'
;;
*)
AutoBuild_Firmware='AutoBuild-${OP_REPO_NAME}-${TARGET_PROFILE}-${CURRENT_Version}-$(Get_SHA256 $1).${Firmware_Format_Defined}'
;;
esac
cat >> ${Home}/VARIABLE_Main <<EOF
Author=${Author}
Github=${Author_Repository}
TARGET_PROFILE=${TARGET_PROFILE}
TARGET_BOARD=${TARGET_BOARD}
TARGET_SUBTARGET=${TARGET_SUBTARGET}
Firmware_Format=${Firmware_Format}
CURRENT_Version=${CURRENT_Version}
OP_Maintainer=${OP_Maintainer}
OP_BRANCH=${OP_BRANCH}
OP_REPO_NAME=${OP_REPO_NAME}
EOF
cat >> ${Home}/VARIABLE_FILE <<EOF
Home=${Home}
PKG_Compatible="${INCLUDE_Obsolete_PKG_Compatible}"
Checkout_Virtual_Images="${Checkout_Virtual_Images}"
Firmware_Path=${Home}/bin/targets/${TARGET_BOARD}/${TARGET_SUBTARGET}
AutoBuild_Firmware=${AutoBuild_Firmware}
CustomFiles=${GITHUB_WORKSPACE}/CustomFiles
Scripts=${GITHUB_WORKSPACE}/Scripts
feeds_luci=${GITHUB_WORKSPACE}/openwrt/package/feeds/luci
feeds_pkgs=${GITHUB_WORKSPACE}/openwrt/package/feeds/packages
base_files=${GITHUB_WORKSPACE}/openwrt/package/base-files/files
Banner_Title="${Banner_Title}"
REGEX_Skip_Checkout="${REGEX_Skip_Checkout}"
EOF
echo "$(cat ${Home}/VARIABLE_Main)" >> ${Home}/VARIABLE_FILE
echo -e "### SYS-VARIABLE LIST ###\n$(cat ${Home}/VARIABLE_FILE)\n"
ECHO "[Firmware-Diy_Before] Done."
}
Firmware-Diy_Main() {
Firmware-Diy_Before
ECHO "[Firmware-Diy_Main] Start ..."
CD ${Home}
source ${Home}/VARIABLE_FILE
chmod +x -R ${Scripts}
chmod 777 -R ${CustomFiles}
[[ ${Load_CustomPackages_List} == true ]] && {
bash -n ${Scripts}/AutoBuild_ExtraPackages.sh
[[ ! $? == 0 ]] && ECHO "AutoBuild_ExtraPackages.sh syntax error,skip ..." || {
. ${Scripts}/AutoBuild_ExtraPackages.sh
}
}
if [[ ${INCLUDE_AutoBuild_Features} == true ]];then
MKDIR ${base_files}/etc/AutoBuild
cp ${Home}/VARIABLE_Main ${base_files}/etc/AutoBuild/Default_Variable
Copy ${CustomFiles}/Depends/Custom_Variable ${base_files}/etc/AutoBuild
Copy ${Scripts}/AutoBuild_Tools.sh ${base_files}/bin
Copy ${Scripts}/AutoUpdate.sh ${base_files}/bin
AddPackage svn lean luci-app-autoupdate Hyy2001X/AutoBuild-Packages/trunk
Copy ${CustomFiles}/Depends/profile ${base_files}/etc
Copy ${CustomFiles}/Depends/base-files-essential ${base_files}/lib/upgrade/keep.d
AutoUpdate_Version=$(awk -F '=' '/Version/{print $2}' ${base_files}/bin/AutoUpdate.sh | awk 'NR==1')
case "${OP_Maintainer}/${OP_REPO_NAME}" in
coolsnowwolf/lede)
Copy ${CustomFiles}/Depends/coremark.sh ${Home}/$(PKG_Finder d "package feeds" coremark)
sed -i '\/etc\/firewall.user/d;/exit 0/d' ${Version_File}
cat >> ${Version_File} <<EOF
sed -i '/check_signature/d' /etc/opkg.conf
# sed -i 's#mirrors.cloud.tencent.com/lede#downloads.immortalwrt.cnsztl.eu.org#g' /etc/opkg/distfeeds.conf
# sed -i 's#18.06.9/##g' /etc/opkg/distfeeds.conf
# sed -i 's#releases/#snapshots/#g' /etc/opkg/distfeeds.conf
sed -i 's/\"services\"/\"nas\"/g' /usr/lib/lua/luci/controller/aliyundrive-webdav.lua
sed -i 's/services/nas/g' /usr/lib/lua/luci/view/aliyundrive-webdav/aliyundrive-webdav_log.htm
sed -i 's/services/nas/g' /usr/lib/lua/luci/view/aliyundrive-webdav/aliyundrive-webdav_status.htm
sed -i 's/\"services\"/\"vpn\"/g' /usr/lib/lua/luci/controller/v2ray_server.lua
sed -i 's/\"services\"/\"vpn\"/g' /usr/lib/lua/luci/model/cbi/v2ray_server/index.lua
sed -i 's/\"services\"/\"vpn\"/g' /usr/lib/lua/luci/model/cbi/v2ray_server/user.lua
sed -i 's/services/vpn/g' /usr/lib/lua/luci/view/v2ray_server/log.htm
sed -i 's/services/vpn/g' /usr/lib/lua/luci/view/v2ray_server/users_list_status.htm
sed -i 's/services/vpn/g' /usr/lib/lua/luci/view/v2ray_server/users_list_status.htm
sed -i 's/services/vpn/g' /usr/lib/lua/luci/view/v2ray_server/v2ray.htm
if [ -z "\$(grep "REDIRECT --to-ports 53" /etc/firewall.user 2> /dev/null)" ]
then
echo '#iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 53' >> /etc/firewall.user
echo '#iptables -t nat -A PREROUTING -p tcp --dport 53 -j REDIRECT --to-ports 53' >> /etc/firewall.user
echo '#[ -n "\$(command -v ip6tables)" ] && ip6tables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 53' >> /etc/firewall.user
echo '#[ -n "\$(command -v ip6tables)" ] && ip6tables -t nat -A PREROUTING -p tcp --dport 53 -j REDIRECT --to-ports 53' >> /etc/firewall.user
fi
exit 0
EOF
sed -i "s?${zzz_Default_Version}?${zzz_Default_Version} @ ${Author} [${Display_Date}]?g" ${Version_File}
ECHO "Downloading [ShadowSocksR Plus+] for coolsnowwolf/lede ..."
AddPackage git other helloworld fw876 master
sed -i 's/143/143,8080,8443/' $(PKG_Finder d package luci-app-ssr-plus)/root/etc/init.d/shadowsocksr
;;
immortalwrt/immortalwrt)
Copy ${CustomFiles}/Depends/openwrt_release_${OP_Maintainer} ${base_files}/etc openwrt_release
sed -i "s?ImmortalWrt?ImmortalWrt @ ${Author} [${Display_Date}]?g" ${Version_File}
;;
esac
sed -i "s?By?By ${Author}?g" ${CustomFiles}/Depends/banner
sed -i "s?Openwrt?Openwrt ${CURRENT_Version} / AutoUpdate ${AutoUpdate_Version}?g" ${CustomFiles}/Depends/banner
[[ -n ${Banner_Title} ]] && sed -i "s?Powered by AutoBuild-Actions?${Banner_Title}?g" ${CustomFiles}/Depends/banner
case "${OP_Maintainer}/${OP_REPO_NAME}" in
immortalwrt/immortalwrt)
Copy ${CustomFiles}/Depends/banner ${Home}/$(PKG_Finder d package default-settings)/files openwrt_banner
;;
*)
Copy ${CustomFiles}/Depends/banner ${base_files}/etc
;;
esac
fi
[[ -n ${Before_IP_Address} ]] && Default_LAN_IP="${Before_IP_Address}"
[[ -n ${Default_LAN_IP} && ${Default_LAN_IP} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && {
Old_IP_Address=$(awk -F '[="]+' '/ipaddr:-/{print $3}' ${base_files}/bin/config_generate | awk 'NR==1')
if [[ ! ${Default_LAN_IP} == ${Old_IP_Address} ]];then
ECHO "Setting default IP Address to ${Default_LAN_IP} ..."
sed -i "s/${Old_IP_Address}/${Default_LAN_IP}/g" ${base_files}/bin/config_generate
fi
}
[[ ${INCLUDE_DRM_I915} == true && ${TARGET_BOARD} == x86 ]] && {
Copy ${CustomFiles}/Depends/DRM-I915 ${Home}/target/linux/x86
for X in $(ls -1 target/linux/x86 | grep "config-"); do echo -e "\n$(cat target/linux/x86/DRM-I915)" >> target/linux/x86/${X}; done
}
ECHO "[Firmware-Diy_Main] Done."
}
Firmware-Diy_Other() {
ECHO "[Firmware-Diy_Other] Start ..."
CD ${GITHUB_WORKSPACE}/openwrt
source ${GITHUB_WORKSPACE}/openwrt/VARIABLE_FILE
case "${PKG_Compatible}" in
19.07)
OP_BRANCH=19.07
Force_mode=1
PKG_Compatible=true
;;
21.02)
OP_BRANCH=21.02
Force_mode=1
PKG_Compatible=true
;;
esac
if [[ ${PKG_Compatible} == true ]];then
if [[ ${OP_Maintainer} == openwrt || ${OP_Maintainer} == [Ll]ienol || ${Force_mode} == 1 ]];then
ECHO "Start running Obsolete_Package_Compatible Script ..."
case "${OP_BRANCH}" in
19.07 | 21.02 | main)
[[ ${OP_BRANCH} == main ]] && OP_BRANCH=21.02
cat >> .config <<EOF
# CONFIG_PACKAGE_dnsmasq is not set
CONFIG_PACKAGE_dnsmasq-full=y
# CONFIG_PACKAGE_wpad-wolfssl is not set
CONFIG_PACKAGE_wpad-openssl=y
EOF
Copy ${CustomFiles}/Patches/0003-upx-ucl-${OP_BRANCH}.patch ${Home}
cat 0003-upx-ucl-${OP_BRANCH}.patch | patch -p1 > /dev/null 2>&1
AddPackage svn feeds/packages golang coolsnowwolf/packages/trunk/lang
ECHO "Starting to convert zh-cn translation files to zh_Hans ..."
cd package && ${Scripts}/Convert_Translation.sh && cd -
;;
*)
ECHO "[${OP_BRANCH}]: Current Branch is not supported ..."
;;
esac
else
ECHO "[${OP_Maintainer}]: Current Source_Maintainer is not supported ..."
fi
fi
cat >> .config <<EOF
CONFIG_KERNEL_BUILD_USER="${Author}"
CONFIG_KERNEL_BUILD_DOMAIN="${Github}"
EOF
ECHO "[Firmware-Diy_Other] Done."
}
Firmware-Diy_End() {
ECHO "[Firmware-Diy_End] Start ..."
CD ${GITHUB_WORKSPACE}/openwrt
source ${GITHUB_WORKSPACE}/openwrt/VARIABLE_FILE
MKDIR bin/Firmware
SHA256_File="${Firmware_Path}/sha256sums"
cd ${Firmware_Path}
echo -e "### FIRMWARE OUTPUT ###\n$(ls -1 | egrep -v "packages|buildinfo|sha256sums|manifest")\n"
case "${TARGET_BOARD}" in
x86)
[[ ${Checkout_Virtual_Images} == true ]] && {
Process_Firmware $(List_Format)
} || {
Process_Firmware ${Firmware_Format}
}
;;
*)
Process_Firmware ${Firmware_Format}
;;
esac
[[ $(ls) =~ 'AutoBuild-' ]] && cp -a AutoBuild-* ${Home}/bin/Firmware
cd -
echo "[$(date "+%H:%M:%S")] Actions Avaliable: $(df -h | grep "/dev/root" | awk '{printf $4}')"
ECHO "[Firmware-Diy_End] Done."
}
Process_Firmware() {
while [[ $1 ]];do
Process_Firmware_Core $1 $(List_Firmware $1)
shift
done
}
Process_Firmware_Core() {
Firmware_Format_Defined=$1
shift
while [[ $1 ]];do
case "${TARGET_BOARD}" in
x86)
[[ $1 =~ efi ]] && {
FW_Boot_Type=UEFI
} || {
FW_Boot_Type=Legacy
}
;;
esac
eval AutoBuild_Firmware=$(Get_Variable AutoBuild_Firmware=)
[[ -f $1 ]] && {
ECHO "Copying [$1] to [${AutoBuild_Firmware}] ..."
cp -a $1 ${AutoBuild_Firmware}
} || ECHO "Unable to access [${AutoBuild_Firmware}] ..."
shift
done
}
List_Firmware() {
[[ -z $* ]] && {
List_REGEX | while read X;do
echo $X | cut -d "*" -f2
done
} || {
while [[ $1 ]];do
for X in $(echo $(List_REGEX));do
[[ $X == *$1 ]] && echo "$X" | cut -d "*" -f2
done
shift
done
}
}
List_Format() {
echo "$(List_REGEX | cut -d "*" -f2 | cut -d "." -f2-3)" | sort | uniq
}
List_REGEX() {
[[ -n ${REGEX_Skip_Checkout} ]] && {
egrep -v "${REGEX_Skip_Checkout}" ${SHA256_File} | tr -s '\n'
} || egrep -v "packages|buildinfo|sha256sums|manifest|kernel|rootfs|factory" ${SHA256_File} | tr -s '\n'
}
Get_SHA256() {
List_REGEX | grep "$1" | cut -c1-5
}
Get_Variable() {
grep "$1" ${GITHUB_WORKSPACE}/openwrt/VARIABLE_FILE | cut -c$(echo $1 | wc -c)-200 | cut -d ":" -f2
}
GET_Branch() {
git -C $(pwd) rev-parse --abbrev-ref HEAD | grep -v HEAD || \
git -C $(pwd) describe --exact-match HEAD || \
git -C $(pwd) rev-parse HEAD
}
ECHO() {
echo "[$(date "+%H:%M:%S")] $*"
}
PKG_Finder() {
local Result
[[ $# -ne 3 ]] && {
ECHO "Usage: PKG_Finder <f | d> Search_Path Target_Name/Target_Path"
return 0
}
Result=$(find $2 -name $3 -type $1 -exec echo {} \;)
[[ -n ${Result} ]] && echo "${Result}"
}
CD() {
cd $1
[[ ! $? == 0 ]] && ECHO "Unable to enter target directory $1 ..." || ECHO "Current runnning directory: $(pwd)"
}
MKDIR() {
while [[ $1 ]];do
if [[ ! -d $1 ]];then
mkdir -p $1 || ECHO "Failed to create target directory: [$1] ..."
fi
shift
done
}
AddPackage() {
[[ $# -lt 4 ]] && {
ECHO "Syntax error: [$#] [$*]"
return 0
}
PKG_PROTO=$1
case "${PKG_PROTO}" in
git | svn)
:
;;
*)
ECHO "Unknown content: ${PKG_PROTO}"
return 0
;;
esac
PKG_DIR=$2
[[ ! ${PKG_DIR} =~ ${GITHUB_WORKSPACE} ]] && PKG_DIR=package/${PKG_DIR}
PKG_NAME=$3
REPO_URL="https://github.com/$4"
REPO_BRANCH=$5
[[ ${REPO_URL} =~ "${OP_Maintainer}/${OP_REPO_NAME}" ]] && return 0
MKDIR ${PKG_DIR}
[[ -d ${PKG_DIR}/${PKG_NAME} ]] && {
ECHO "Removing old package: [${PKG_NAME}] ..."
rm -rf ${PKG_DIR}/${PKG_NAME}
}
ECHO "Checking out package [${PKG_NAME}] to ${PKG_DIR} ..."
case "${PKG_PROTO}" in
git)
[[ -z ${REPO_BRANCH} ]] && {
ECHO "WARNING: Syntax missing <branch> ,using default branch: [master]"
REPO_BRANCH=master
}
PKG_URL="$(echo ${REPO_URL}/${PKG_NAME} | sed s/[[:space:]]//g)"
git clone -b ${REPO_BRANCH} ${PKG_URL} ${PKG_NAME} > /dev/null 2>&1
;;
svn)
svn checkout ${REPO_URL}/${PKG_NAME} ${PKG_NAME} > /dev/null 2>&1
;;
esac
[[ -f ${PKG_NAME}/Makefile || -n $(ls -A ${PKG_NAME}) ]] && {
mv -f "${PKG_NAME}" "${PKG_DIR}"
[[ $? == 0 ]] && ECHO "Done."
} || ECHO "Failed to download package ${PKG_NAME} ..."
}
Copy() {
[[ ! $# =~ [23] ]] && {
ECHO "Syntax error: [$#] [$*]"
return 0
}
[[ ! -f $1 ]] && [[ ! -d $1 ]] && {
ECHO "$1: No such file or directory ..."
return 0
}
MKDIR $2
if [[ -z $3 ]];then
ECHO "Copying $1 to $2 ..."
cp -a $1 $2
else
ECHO "Copy and renaming $1 to $2/$3 ..."
cp -a $1 $2/$3
fi
[[ $? == 0 ]] && ECHO "Done." || ECHO "Failed."
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.