hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
056b6c1185f21235d024aa7cc29ef94fa955d289 | 2,101 | rs | Rust | src/backend/mysql.rs | Txuritan/snowfall | b1b9b6c7063ec4ac11f1e77a60fee878e2b2c9c3 | [
"MIT"
] | null | null | null | src/backend/mysql.rs | Txuritan/snowfall | b1b9b6c7063ec4ac11f1e77a60fee878e2b2c9c3 | [
"MIT"
] | null | null | null | src/backend/mysql.rs | Txuritan/snowfall | b1b9b6c7063ec4ac11f1e77a60fee878e2b2c9c3 | [
"MIT"
] | null | null | null | //! # r2d2-mysql
//! MySQL support for the r2d2 connection pool (Rust) . see [`r2d2`](http://github.com/sfackler/r2d2.git) .
//!
//! #### Install
//! Just include another `[dependencies.*]` section into your Cargo.toml:
//!
//! ```toml
//! [dependencies.r2d2_mysql]
//! git = "https://github.com/outersky/r2d2-mysql"
//! version="*"
//! ```
//! #### Sample
//!
//! ```
//! extern crate mysql;
//! extern crate r2d2_mysql;
//! extern crate r2d2;
//! use std::env;
//! use std::sync::Arc;
//! use std::thread;
//! use mysql::{Opts,OptsBuilder};
//! use r2d2_mysql::MysqlConnectionManager;
//!
//! fn main() {
//! let db_url = env::var("DATABASE_URL").unwrap();
//! let opts = Opts::from_url(&db_url).unwrap();
//! let builder = OptsBuilder::from_opts(opts);
//! let manager = MysqlConnectionManager::new(builder);
//! let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());
//!
//! let mut tasks = vec![];
//!
//! for i in 0..3 {
//! let pool = pool.clone();
//! let th = thread::spawn(move || {
//! let mut conn = pool.get().unwrap();
//! conn.query("select user()").unwrap();
//! println!("thread {} end!" , i );
//! });
//! tasks.push(th);
//! }
//!
//! for th in tasks {
//! let _ = th.join();
//! }
//! }
//! ```
//!
use mysql::{error::Error, Conn, Opts, OptsBuilder};
#[derive(Clone, Debug)]
pub struct MysqlConnectionManager {
params: Opts,
}
impl MysqlConnectionManager {
pub fn new(params: OptsBuilder) -> MysqlConnectionManager {
MysqlConnectionManager {
params: Opts::from(params),
}
}
}
impl r2d2::ManageConnection for MysqlConnectionManager {
type Connection = Conn;
type Error = Error;
fn connect(&self) -> Result<Conn, Error> {
Conn::new(self.params.clone())
}
fn is_valid(&self, conn: &mut Conn) -> Result<(), Error> {
conn.query("SELECT version()").map(|_| ())
}
fn has_broken(&self, conn: &mut Conn) -> bool {
self.is_valid(conn).is_err()
}
}
| 25.938272 | 108 | 0.558782 |
c501ffd6223c5a8b0cdeabfe8aa26376a89e2937 | 716 | css | CSS | client/src/index.css | oughtinc/mosaic | 40729257a8ea2d23a02eb2f6b9117d38defde022 | [
"MIT"
] | 24 | 2018-07-20T23:10:58.000Z | 2021-09-03T14:14:29.000Z | client/src/index.css | oughtinc/mosaic | 40729257a8ea2d23a02eb2f6b9117d38defde022 | [
"MIT"
] | 541 | 2018-07-18T18:05:19.000Z | 2022-03-08T22:41:47.000Z | client/src/index.css | oughtinc/mosaic | 40729257a8ea2d23a02eb2f6b9117d38defde022 | [
"MIT"
] | 5 | 2018-12-13T01:30:39.000Z | 2021-05-10T18:44:39.000Z | body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #eee;
}
.menu > * {
display: inline-block;
}
.menu > * + * {
margin-left: 15px;
}
.toolbar-menu {
position: relative;
padding: 1px 18px 17px;
margin: 0 -20px;
border-bottom: 2px solid #eee;
margin-bottom: 20px;
}
.toolbar-menu .search {
position: relative;
}
.toolbar-menu .search-icon {
position: absolute;
top: 0.5em;
left: 0.5em;
color: #ccc;
}
.toolbar-menu .search-box {
padding-left: 2em;
width: 100%;
}
.hover-menu {
position: absolute;
z-index: 1;
top: -10000px;
left: -10000px;
opacity: 0;
}
.fade.in.modal {
width: auto !important;
}
.modal-dialog {
width: 1020px;
}
| 13.018182 | 33 | 0.618715 |
a1bdfc40888811e86492a12dba546b228c78be18 | 925 | sql | SQL | test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestData/TSqlFormatter/TestFiles/KeywordCaseConversion.sql | Thomas-S-B/sqltoolsservice | e2b0e013789dc392f8b5ef3dc35a4859698f7e68 | [
"MIT"
] | 176 | 2016-11-18T04:11:38.000Z | 2019-05-04T07:11:11.000Z | test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestData/TSqlFormatter/TestFiles/KeywordCaseConversion.sql | Thomas-S-B/sqltoolsservice | e2b0e013789dc392f8b5ef3dc35a4859698f7e68 | [
"MIT"
] | 588 | 2016-11-16T21:15:11.000Z | 2019-05-03T21:27:59.000Z | test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestData/TSqlFormatter/TestFiles/KeywordCaseConversion.sql | Thomas-S-B/sqltoolsservice | e2b0e013789dc392f8b5ef3dc35a4859698f7e68 | [
"MIT"
] | 67 | 2016-11-25T17:43:20.000Z | 2019-04-29T04:50:10.000Z | -- Case: common type keywords
cReaTe tAbLe [SimpleTable]
(
-- this is a comment before document
[DocumentID] INT iDentIty (1, 1) NOT NULL,
-- this is a comment before Title
[Title] NVARCHAR (50) NOT NULL,
-- this is a comment before FileName
[FileName] NVARCHAR (400) NOT NULL,
-- this is a comment before FileExtension
[FileExtension] nvarchar(8)
);
GO
CREATE vIEw v1 aS select * from [SimpleTable]
GO
CREATE pRoceduRe p1 aS
bEgIn
select * from [SimpleTable]
eNd
GO
iNsert iNto t dEfault vAlues
GO
GO
iNsert oPenQUERY (OracleSvr, 'SELECT name FROM joe.titles')
VALUES ('NewTitle');
GO
INSERT INTO myTable(FileName, FileType, Document)
SELECT 'Text1.txt' AS FileName,
'.txt' AS FileType,
* FROM openROWSET(bUlK N'C:\Text1.txt', siNGLE_BLOB) AS Document;
GO
sELECT *
FROM openXML (@idoc, '/ROOT/Customers')
exEC sp_xml_removedocument @idoc; | 22.560976 | 73 | 0.681081 |
dd9e94ae6db649288500bbba7f5726dbdbe7c3aa | 1,873 | dart | Dart | test/widget_test.dart | AndriousSolutions/app_template | 6937c151b924f42a214b00bb6def005e700c7a53 | [
"BSD-2-Clause"
] | 1 | 2021-12-20T10:19:08.000Z | 2021-12-20T10:19:08.000Z | test/widget_test.dart | AndriousSolutions/app_template | 6937c151b924f42a214b00bb6def005e700c7a53 | [
"BSD-2-Clause"
] | null | null | null | test/widget_test.dart | AndriousSolutions/app_template | 6937c151b924f42a214b00bb6def005e700c7a53 | [
"BSD-2-Clause"
] | null | null | null | ///
import 'src/view.dart';
void main() {
/// Define a test. The TestWidgets function also provides a WidgetTester
/// to work with. The WidgetTester allows you to build and interact
/// with widgets in the test environment.
testWidgets('app_template testing', (WidgetTester tester) async {
//
await tester.pumpWidget(TemplateApp());
/// Flutter won’t automatically rebuild your widget in the test environment.
/// Use pump() or pumpAndSettle() to ask Flutter to rebuild the widget.
/// pumpAndSettle() waits for all animations to complete.
await tester.pumpAndSettle();
final con = TemplateController();
// for (var interface = 1; interface <= 2; interface++) {
//
int cnt = 1;
while (cnt <= 3) {
switch (con.application) {
case 'Counter':
/// Counter app testing
await counterTest(tester);
break;
case 'Word Pairs':
/// Random Word Pairs app
await wordsTest(tester);
break;
case 'Contacts':
/// Contacts app
await contactsTest(tester);
break;
}
/// Switch the app programmatically.
// con.changeApp();
/// Switch the app through the popupmenu
await openApplicationMenu(tester);
/// Wait for the transition in the Interface
await tester.pumpAndSettle();
cnt++;
}
/// Open the Locale window
await openLocaleMenu(tester);
/// Open About menu
await openAboutMenu(tester);
/// Switch the Interface
await openInterfaceMenu(tester);
// }
/// Unit testing does not involve integration or widget testing.
/// WordPairs App Model Unit Testing
await wordPairsModelTest(tester);
/// Unit testing the App's controller object
await testTemplateController(tester);
reportTestErrors();
});
}
| 24.973333 | 80 | 0.6252 |
e5902b445cf25928a537a552d8b72f9bef862fae | 5,277 | go | Go | google/SheetData.go | RescueDen/restlib | 91c3050fdf31305bc8576a5da06d505ce8be9eb6 | [
"MIT"
] | 1 | 2019-07-26T23:15:21.000Z | 2019-07-26T23:15:21.000Z | google/SheetData.go | RescueDen/restlib | 91c3050fdf31305bc8576a5da06d505ce8be9eb6 | [
"MIT"
] | 4 | 2020-06-24T23:04:11.000Z | 2020-11-19T20:23:34.000Z | google/SheetData.go | RescueDen/restlib | 91c3050fdf31305bc8576a5da06d505ce8be9eb6 | [
"MIT"
] | 2 | 2019-11-23T21:10:13.000Z | 2020-05-23T21:37:23.000Z | // Copyright 2019 Reaction Engineering International. All rights reserved.
// Use of this source code is governed by the MIT license in the file LICENSE.txt.
package google
import (
"errors"
"fmt"
"strings"
)
/**
Used to store a row of data
*/
type SheetData struct {
//Store the values in the row
Values [][]interface{} //[row][col]
//Store the Headers
Headers []string
//Store a map from the Headers to location
headersLoc map[string]int
//Store a list of original row numbers
RowNumb []int
}
//Create a new sheet data
func NewSheetData(values [][]interface{}) (*SheetData, error) {
//We need at least a header row
if len(values) == 0 {
return nil, errors.New("header row missing from sheet")
}
//Get the size
headerSize := len(values[0])
//Build the needed header info
data := &SheetData{
Headers: make([]string, headerSize),
headersLoc: make(map[string]int, 0),
RowNumb: make([]int, len(values)-1), //No need for the header
Values: values[1:], //Remove the header row from the data
}
//Now store each of the Headers location for easy look up
for loc, name := range values[0] {
//Convert the name to a string
nameString := fmt.Sprint(name)
//Save the info
data.headersLoc[SanitizeHeader(nameString)] = loc
data.Headers[loc] = nameString
}
//Now just set the values for the row location
for i := 0; i < len(data.RowNumb); i++ {
data.RowNumb[i] = i + 2 //C style index plus the missing header row
}
return data, nil
}
//March over each header and look for value
func (sheet *SheetData) findHeaderContaining(header string) int {
for ind, value := range sheet.Headers {
if strings.Contains(strings.ToLower(value), header) {
return ind
}
}
return -1
}
//Create a new sheet data
func (sheet *SheetData) FilterSheet(header string, value string) *SheetData {
//See if we have the header
headerCol := sheet.findHeaderContaining(header)
//If it is there, return nil
if headerCol < 0 {
return nil
}
//Now create a new data sheet
newSheet := &SheetData{
Headers: sheet.Headers, //Headers are the same
headersLoc: sheet.headersLoc, //Headers are the same
RowNumb: make([]int, 0), //No need for the header
Values: make([][]interface{}, 0),
}
//Clean up the value
value = strings.TrimSpace(value)
//Now check to see if each row has the data
for r, rowData := range sheet.Values {
//Make sure we have enough data to check
if len(rowData) > headerCol {
//If they are equal
if strings.EqualFold(value, strings.TrimSpace(fmt.Sprint(rowData[headerCol]))) {
//Add the data
newSheet.Values = append(newSheet.Values, rowData)
newSheet.RowNumb = append(newSheet.RowNumb, sheet.RowNumb[r])
}
}
}
//Return the new sheet
return newSheet
}
//Create a new sheet data
func (sheet *SheetData) GetColumn(col int) []interface{} {
//We need to transpose the data
colData := make([]interface{}, 0)
//March over each row
for r := range sheet.Values {
//If it has the column add it
if len(sheet.Values[r]) > col+1 {
colData = append(colData, sheet.Values[r][col])
}
}
return colData
}
//Create a new sheet data
func (sheet *SheetData) GetRow(row int) *SheetDataRow {
//Look up the row number
indexNumber := -1
//Now search over the rows for the row index,
for index, rowTest := range sheet.RowNumb {
if rowTest == row {
indexNumber = index
}
}
//If it avaiable return
if indexNumber < 0 {
return nil
}
//Extract the row info
dataRow := &SheetDataRow{
Values: sheet.Values[indexNumber],
Headers: sheet.Headers,
headersLoc: sheet.headersLoc,
RowNumber: row,
}
//If we have fewer values then header size
if len(dataRow.Values) < len(dataRow.Headers) {
//Make a new array
array := make([]interface{}, len(dataRow.Headers)-len(dataRow.Values))
dataRow.Values = append(dataRow.Values, array...)
}
//Return the new sheet
return dataRow
}
//Create a new sheet data
func (sheet *SheetData) GetEmptyDataRow() *SheetDataRow {
//Get the size. number of headers
size := len(sheet.Headers)
//Extract the row info
dataRow := &SheetDataRow{
Values: make([]interface{}, size),
Headers: sheet.Headers,
headersLoc: sheet.headersLoc,
RowNumber: -1,
}
//Return the new sheet
return dataRow
}
//Create a new sheet data
func (sheet *SheetData) PrintToScreen() {
//March over each header
fmt.Print("row,")
for _, header := range sheet.Headers {
fmt.Print(header)
fmt.Print(",")
}
fmt.Println()
//Now print each row
for r, rowData := range sheet.Values {
//Now print the row number
fmt.Print(sheet.RowNumb[r])
fmt.Print(",")
//Now each data
for _, data := range rowData {
fmt.Print(data)
fmt.Print(",")
}
fmt.Println()
}
}
//Create a new sheet data
func (sheet *SheetData) NumberRows() int {
return len(sheet.Values)
}
/**
Count the number of entries for this column
*/
func (sheet *SheetData) CountEntries(index int) int {
//Start with a count
count := 0
//March over each row
for _, rowData := range sheet.Values {
//If the row as data in the index
if index < len(rowData) {
//If there is data
if rowData[index] != nil && len(fmt.Sprint(rowData[index])) > 0 {
count++
}
}
}
return count
}
| 21.627049 | 83 | 0.672162 |
76c53600a0c898212b2b38c8b97e26fdc07df1b4 | 5,268 | h | C | Source/UnrealExtendedFramework/Libraries/AI/EFAILibrary.h | ElderDeveloper/UnrealExtendedFramework | 9eda70583773159f80e8bc4406a85c476d0c80e5 | [
"MIT"
] | 1 | 2022-01-13T07:21:19.000Z | 2022-01-13T07:21:19.000Z | Source/UnrealExtendedFramework/Libraries/AI/EFAILibrary.h | ElderDeveloper/UnrealExtendedFramework | 9eda70583773159f80e8bc4406a85c476d0c80e5 | [
"MIT"
] | null | null | null | Source/UnrealExtendedFramework/Libraries/AI/EFAILibrary.h | ElderDeveloper/UnrealExtendedFramework | 9eda70583773159f80e8bc4406a85c476d0c80e5 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "EFAILibrary.generated.h"
/**
*
*/
UCLASS()
class UNREALEXTENDEDFRAMEWORK_API UEFAILibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< BLACKBOARD GETTERS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Bool",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Bool", BlueprintThreadSafe),Category="AI|Blackboard|Get")
static bool ExtendedGetBlackboardBool(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Class",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Class", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static TSubclassOf<UObject> ExtendedGetBlackboardClass(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Enum",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Enum", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static uint8 ExtendedGetBlackboardEnum(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Float",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Float", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static float ExtendedGetBlackboardFloat(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Int",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Int", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static int32 ExtendedGetBlackboardInt(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Name",DefaultToSelf="OwningActor", CompactNodeTitle = "Board Name", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static FName ExtendedGetBlackboardName(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Object", DefaultToSelf="OwningActor",CompactNodeTitle = "Board Object", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static UObject* ExtendedGetBlackboardObject(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Rotator", DefaultToSelf="OwningActor",CompactNodeTitle = "Board Rotator", BlueprintThreadSafe),Category="AI|Blackboard|Get")
static FRotator ExtendedGetBlackboardRotator(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard String", DefaultToSelf="OwningActor",CompactNodeTitle = "Board String", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static FString ExtendedGetBlackboardString(AActor* OwningActor , FName KeyName);
UFUNCTION(BlueprintPure, meta=(DisplayName = "Extended Get Blackboard Vector", DefaultToSelf="OwningActor",CompactNodeTitle = "Board Vector", BlueprintThreadSafe), Category="AI|Blackboard|Get")
static FVector ExtendedGetBlackboardVector(AActor* OwningActor , FName KeyName);
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< BLACKBOARD SETTERS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardBool(AActor* OwningActor , FName KeyName , bool Value);
UFUNCTION(BlueprintCallable,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardClass(AActor* OwningActor , FName KeyName , TSubclassOf<UObject> Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardEnum(AActor* OwningActor , FName KeyName , uint8 Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardFloat(AActor* OwningActor , FName KeyName , float Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardInt(AActor* OwningActor , FName KeyName , int32 Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") ,Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardName(AActor* OwningActor , FName KeyName , FName Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") , Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardObject(AActor* OwningActor , FName KeyName , UObject* Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") ,Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardRotator(AActor* OwningActor , FName KeyName ,FRotator Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") ,Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardString(AActor* OwningActor , FName KeyName , FString Value);
UFUNCTION(BlueprintCallable ,meta=(DefaultToSelf="OwningActor") ,Category="AI|Blackboard|Set")
static bool ExtendedSetBlackboardVector(AActor* OwningActor , FName KeyName , FVector Value);
};
| 64.243902 | 195 | 0.768413 |
789cbfdb9dbc8cb7d5937be7dfc6d84d7076dd04 | 1,269 | sql | SQL | tools/openmldb_online_env/prepare_data.sql | tobegit3hub/openmldb_lab | 0c271d4f622426ae6fe23cc4279fd0b7cedea2cb | [
"Apache-2.0"
] | null | null | null | tools/openmldb_online_env/prepare_data.sql | tobegit3hub/openmldb_lab | 0c271d4f622426ae6fe23cc4279fd0b7cedea2cb | [
"Apache-2.0"
] | null | null | null | tools/openmldb_online_env/prepare_data.sql | tobegit3hub/openmldb_lab | 0c271d4f622426ae6fe23cc4279fd0b7cedea2cb | [
"Apache-2.0"
] | null | null | null | CREATE DATABASE db1;
USE db1;
CREATE TABLE user (id int, name string, age int, gender string);
INSERT INTO user VALUES (1, "Venus", 18, "female");
INSERT INTO user VALUES (2, "Diana", 28, "female");
INSERT INTO user VALUES (3, "Apollo", 19, "male");
INSERT INTO user VALUES (4, "Mars", 20, "male");
INSERT INTO user VALUES (5, "Minerva", 25, "female");
INSERT INTO user VALUES (6, "Juno", 40, "female");
INSERT INTO user VALUES (7, "Neptunus", 29, "male");
INSERT INTO user VALUES (8, "Jupiter", 41, "male");
CREATE TABLE score (uid int, score float);
INSERT INTO score VALUES (1, 85.0);
INSERT INTO score VALUES (2, 80.5);
INSERT INTO score VALUES (3, 90.0);
INSERT INTO score VALUES (4, 91.5);
INSERT INTO score VALUES (5, 95.0);
INSERT INTO score VALUES (6, 99.0);
INSERT INTO score VALUES (7, 92.0);
INSERT INTO score VALUES (8, 99.9);
CREATE DATABASE db2;
USE db2;
CREATE TABLE t1 (c1 string, c2 int, c3 bigint, c4 float, c5 double, c6 timestamp, c7 date);
INSERT INTO t1 VALUES ("aa", 13, 22, 3.2, 13.3, 1636097490000, "2021-05-20");
INSERT INTO t1 VALUES ("bb", 16, 22, 6.2, 16.3, 1636097790000, "2021-05-20");
INSERT INTO t1 VALUES ("cc", 17, 22, 7.2, 17.3, 1636097890000, "2021-05-26");
set @@SESSION.execute_mode = "offline";
SELECT 100;
SELECT "foo";
| 34.297297 | 91 | 0.676911 |
0706b2d2e14e9958627b79b42033b3a1a6f67853 | 389 | rb | Ruby | app/models/manageiq/providers/azure/cloud_manager/refresher.rb | psav/manageiq | 5cc942b414e91a1485103134729f96915f074991 | [
"Apache-2.0"
] | null | null | null | app/models/manageiq/providers/azure/cloud_manager/refresher.rb | psav/manageiq | 5cc942b414e91a1485103134729f96915f074991 | [
"Apache-2.0"
] | null | null | null | app/models/manageiq/providers/azure/cloud_manager/refresher.rb | psav/manageiq | 5cc942b414e91a1485103134729f96915f074991 | [
"Apache-2.0"
] | null | null | null | module ManageIQ::Providers::Azure
class CloudManager::Refresher < ManageIQ::Providers::BaseManager::Refresher
include ::EmsRefresh::Refreshers::EmsRefresherMixin
def parse_inventory(ems, _targets)
ManageIQ::Providers::Azure::CloudManager::RefreshParser.ems_inv_to_hashes(ems, refresher_options)
end
def post_process_refresh_classes
[::Vm]
end
end
end
| 27.785714 | 103 | 0.753213 |
9fbc2805e0ab8578a82f5e410f2c815ab3c3a6b8 | 252 | lua | Lua | AddonManager/locales/tw.lua | Syvokobylenko/RunesofMagic_Addon_Pack | 3edeacf3823c62b176d202d76fd87658f5ff8295 | [
"Unlicense"
] | null | null | null | AddonManager/locales/tw.lua | Syvokobylenko/RunesofMagic_Addon_Pack | 3edeacf3823c62b176d202d76fd87658f5ff8295 | [
"Unlicense"
] | null | null | null | AddonManager/locales/tw.lua | Syvokobylenko/RunesofMagic_Addon_Pack | 3edeacf3823c62b176d202d76fd87658f5ff8295 | [
"Unlicense"
] | null | null | null | -- coding: utf-8
--[[
-- PLEASE DO "NOT" EDIT THIS FILE!
-- This file is generated by script.
--
-- If you want to apply corrections visit:
-- http://rom.curseforge.com/addons/addonmanager/localization/
--]]
local lang={}
lang.CAT = {
}
return lang
| 15.75 | 62 | 0.666667 |
1b64f8422f89b2ef0564e6975e379c017248d34f | 654 | dart | Dart | lib/app/utils/values/enum_navigation.dart | Rohit-ChauhanRC/flutter_templates | 673d86348a68443b1fa0c7134a0d1dd45b9993f6 | [
"MIT"
] | null | null | null | lib/app/utils/values/enum_navigation.dart | Rohit-ChauhanRC/flutter_templates | 673d86348a68443b1fa0c7134a0d1dd45b9993f6 | [
"MIT"
] | null | null | null | lib/app/utils/values/enum_navigation.dart | Rohit-ChauhanRC/flutter_templates | 673d86348a68443b1fa0c7134a0d1dd45b9993f6 | [
"MIT"
] | null | null | null | enum NavigationFrom {
orderDetailsCod,
orderPickedCod,
orderReceivePayment,
orderPaymentReceived,
orderDeliverCod,
orderDelivered,
orderRequestDetail,
updatedStatusOrder,
updatedStatusDelivered,
statusUpdated,
}
enum NavigationPackedOrder {
acceptOrder,
orderPicked,
startDelivery,
onGoing,
collectPayment,
finishOrder,
}
enum NavigationTansactions {
allTansactions,
b2bTansactions,
codTansactions,
onlineTansactions,
}
enum ImageType {
vehicleImage,
drivingLicense,
aadharCard,
profileImage,
}
enum IsSignUpOrLogin {
signUp,
login,
forgotPassword,
}
enum CreatePassword {
rememberPassword,
}
| 14.217391 | 28 | 0.766055 |
2cc5f51496ea15b87e6ce86cfca1d00aad746846 | 651 | py | Python | tests/_support/tree/__init__.py | crazy-penguins/raft | 3eb829f1c0d90608743cadac4c5a04017c93c607 | [
"BSD-2-Clause"
] | null | null | null | tests/_support/tree/__init__.py | crazy-penguins/raft | 3eb829f1c0d90608743cadac4c5a04017c93c607 | [
"BSD-2-Clause"
] | null | null | null | tests/_support/tree/__init__.py | crazy-penguins/raft | 3eb829f1c0d90608743cadac4c5a04017c93c607 | [
"BSD-2-Clause"
] | null | null | null | from raft import task, Collection
from . import build, deploy, provision
@task(aliases=["ipython"])
def shell(c):
"Load a REPL with project state already set up."
pass
@task(aliases=["run_tests"], default=True)
def test(c):
"Run the test suite with baked-in args."
pass
# NOTE: using build's internal collection directly as a way of ensuring a
# corner case (collection 'named' via local kwarg) gets tested for --list.
# NOTE: Docstring cloning in effect to preserve the final organic looking
# result...
localbuild = build.ns
localbuild.__doc__ = build.__doc__
ns = Collection(shell, test, deploy, provision, build=localbuild)
| 26.04 | 74 | 0.729647 |
5ad2ec958c0ad062a4858976ee80ba2c29a45a0d | 3,554 | cs | C# | test/vstest.ProgrammerTests/Fakes/FakeCommunicationEndpoint.cs | ntovas/vstest | 631c5821d22163d29cc8140ad23543bc33e595c1 | [
"MIT"
] | 480 | 2017-01-19T20:53:39.000Z | 2019-05-03T11:13:06.000Z | test/vstest.ProgrammerTests/Fakes/FakeCommunicationEndpoint.cs | ntovas/vstest | 631c5821d22163d29cc8140ad23543bc33e595c1 | [
"MIT"
] | 1,381 | 2017-01-19T19:55:42.000Z | 2019-05-06T16:45:27.000Z | test/vstest.ProgrammerTests/Fakes/FakeCommunicationEndpoint.cs | ntovas/vstest | 631c5821d22163d29cc8140ad23543bc33e595c1 | [
"MIT"
] | 169 | 2017-01-19T18:38:53.000Z | 2019-04-10T15:34:39.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.Utilities;
namespace vstest.ProgrammerTests.Fakes;
internal class FakeCommunicationEndpoint : ICommunicationEndPoint
{
private bool _stopped;
public FakeCommunicationEndpoint(FakeCommunicationChannel fakeCommunicationChannel, FakeErrorAggregator fakeErrorAggregator)
{
Channel = fakeCommunicationChannel;
FakeErrorAggregator = fakeErrorAggregator;
TestHostConnectionInfo = new TestHostConnectionInfo
{
Endpoint = $"127.0.0.1:{fakeCommunicationChannel.Id}",
Role = ConnectionRole.Client,
Transport = Transport.Sockets,
};
}
public FakeErrorAggregator FakeErrorAggregator { get; }
public FakeCommunicationChannel Channel { get; }
public TestHostConnectionInfo TestHostConnectionInfo { get; }
/// <summary>
/// Notify the caller that we disconnected, this happens if process exits unexpectedly and leads to abort flow.
/// In success case use Stop instead, to just "close" the channel, because the other side already disconnected from us
/// and told us to tear down.
/// </summary>
public void Disconnect()
{
Disconnected?.Invoke(this, new DisconnectedEventArgs());
_stopped = true;
}
#region ICommunicationEndPoint
public event EventHandler<ConnectedEventArgs>? Connected;
public event EventHandler<DisconnectedEventArgs>? Disconnected;
public string Start(string endPoint)
{
// In normal run this endpoint can be a client or a server. When we are a client we will get an address and a port and
// we will try to connect to it.
// If we are a server, we will get an address and port 0, which means we should figure out a port that is free
// and return the address and port back to the caller.
//
// In our fake scenario we know the "port" from the get go, we set it to an id that was given to the testhost
// because that is currently the only way for us to check if we are connecting to the expected fake testhost
// that has a list of canned responses, which must correlate with the requests. So e.g. if we get request for mstest1.dll
// we should return the responses we have prepared for mstest1.dll, and not for mstest2.dll.
//
// We use the port number because the rest of the IP address is validated. We force sockets and IP usage in multiple places,
// so we cannot just past the dll path (or something similar) as the endpoint name, because the other side will check if that is
// a valid IP address and port.
if (endPoint != TestHostConnectionInfo.Endpoint)
{
throw new InvalidOperationException($"Expected to connect to {endPoint} but instead got channel with {TestHostConnectionInfo.Endpoint}.");
}
Connected?.SafeInvoke(this, new ConnectedEventArgs(Channel), "FakeCommunicationEndpoint.Start");
return endPoint;
}
public void Stop()
{
if (!_stopped)
{
// Do not allow stop to be called multiple times, because it will end up calling us back and stack overflows.
_stopped = true;
}
}
#endregion
}
| 44.425 | 150 | 0.700338 |
14badeb4963b1f6ea5606ddc8ec37a874847c02e | 318 | ts | TypeScript | src/interfaces/igenetic-algorithm.ts | tom-weatherhead/thaw-genetic | 7671a4358159ad53d08808e4141e3452a080bfd1 | [
"MIT"
] | null | null | null | src/interfaces/igenetic-algorithm.ts | tom-weatherhead/thaw-genetic | 7671a4358159ad53d08808e4141e3452a080bfd1 | [
"MIT"
] | null | null | null | src/interfaces/igenetic-algorithm.ts | tom-weatherhead/thaw-genetic | 7671a4358159ad53d08808e4141e3452a080bfd1 | [
"MIT"
] | null | null | null | // thaw-genetic/src/interfaces/igenetic-algorithm.ts
import { Observable } from 'rxjs';
import { IChromosome } from './ichromosome';
import { IGeneticAlgorithmResult } from './igenetic-algorithm-result';
export interface IGeneticAlgorithm<T extends IChromosome> {
run(): Observable<IGeneticAlgorithmResult<T>>;
}
| 26.5 | 70 | 0.764151 |
af2a406838efea757cc4acb358285b7045e3197f | 5,021 | py | Python | code/figures/Chure2019_FigS17-FigS18_IND_pairwise_comparison.py | RPGroup-PBoC/mwc_mutants | 35581602c35793fc8ec42c8aff37b8305c5e54e1 | [
"MIT"
] | 3 | 2020-11-11T21:33:26.000Z | 2021-07-14T21:22:43.000Z | code/figures/Chure2019_FigS17-FigS18_IND_pairwise_comparison.py | RPGroup-PBoC/mwc_mutants | 35581602c35793fc8ec42c8aff37b8305c5e54e1 | [
"MIT"
] | null | null | null | code/figures/Chure2019_FigS17-FigS18_IND_pairwise_comparison.py | RPGroup-PBoC/mwc_mutants | 35581602c35793fc8ec42c8aff37b8305c5e54e1 | [
"MIT"
] | 1 | 2021-07-14T21:22:45.000Z | 2021-07-14T21:22:45.000Z | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mut.thermo
import mut.stats
import mut.viz
color = mut.viz.color_selector('mut')
pboc = mut.viz.color_selector('pboc')
constants = mut.thermo.load_constants()
mut.viz.plotting_style()
# Load the data
data = pd.read_csv('../../data/Chure2019_summarized_data.csv', comment='#')
data = data[data['class'] == 'IND']
KaKi_only_samples = pd.read_csv('../../data/Chure2019_KaKi_only_samples.csv')
KaKi_epAI_samples = pd.read_csv('../../data/Chure2019_KaKi_epAI_samples.csv')
# Determine the unique repressor copy numbers
ops = np.sort(data['operator'].unique())
c_range = np.logspace(-2, 4, 200)
c_range[0] = 0
# Change this parameter to decide which plot to make
MODEL = 'KaKi_epAI'
# ##############################################################################
# FIGURE WITH KAKI FIT ONLY
# ##############################################################################
fig, ax = plt.subplots(len(ops),len(ops), figsize=(7,5), sharex=True, sharey=True)
# Format the axes
for a in ax.ravel():
a.xaxis.set_tick_params(labelsize=8)
a.yaxis.set_tick_params(labelsize=8)
a.set_xscale('symlog', linthreshx=1E-2)
# Add appropriate labels
for i in range(len(ops)):
ax[i, 0].set_ylabel('fold-change', fontsize=8)
ax[-1, i].set_xlabel('IPTG [µM]', fontsize=8)
ax[i, 0].text(-0.5, 0.55, ops[i], fontsize=8, backgroundcolor=pboc['pale_yellow'],
transform=ax[i,0].transAxes, rotation='vertical')
ax[0, i].set_title(ops[i], fontsize=8, backgroundcolor=pboc['pale_yellow'], y=1.08)
ax[i, i].set_facecolor('#e4e7ec')
for i in range(3):
ax[-1, i].set_xticks([0, 1E-2, 1E0, 1E2, 1E4])
# Add predictor titles
fig.text(-0.04, 0.53, 'fit strain', fontsize=8, backgroundcolor='#E3DCD0', rotation='vertical')
fig.text(0.435, 0.98, 'comparison strain', fontsize=8, backgroundcolor='#E3DCD0', rotation='horizontal')
# Plot the data.
for g, d in data.groupby(['mutant']):
g = g.upper()
for i, _ in enumerate(ops):
for j, _ in enumerate(ops):
_d = d[d['operator'] == ops[j]]
if i == j:
face = 'w'
edge = color[g]
else:
face = color[g]
edge = color[g]
if g == 'F164T':
label = 'F161T'
elif g == 'Q294K':
label = 'Q291K'
elif g == 'Q294V':
label = 'Q291V'
elif g == 'Q294R':
label = 'Q291R'
else:
label = g
_ = ax[i, j].errorbar(_d['IPTGuM'], _d['mean'], _d['sem'], markerfacecolor=face,
markeredgecolor=edge, color=edge, lw=0.15, linestyle='none', fmt='o',
ms=2.5, label=label)
# Plot the best-fit lines.
for k, m in enumerate(data['mutant'].unique()):
_d = data[(data['mutant']==m) & (data['operator'] == ops[i])]
# Get the binding energies.
if MODEL == 'KaKi_only':
_samps = KaKi_only_samples[(KaKi_only_samples['mutant']==m) &\
(KaKi_only_samples['operator']==ops[i])]
_samps['ep_AI'] = 4.5
else:
_samps = KaKi_epAI_samples[(KaKi_epAI_samples['mutant']==m) &\
(KaKi_epAI_samples['operator']==ops[i])]
Ka = _samps['Ka']
Ki = _samps['Ki']
epAI = _samps['ep_AI']
cred_region = np.zeros((2, len(c_range)))
for z, c in enumerate(c_range):
# Compute the fold-change
fc = mut.thermo.SimpleRepression(R=constants['RBS1027'],
ep_r=constants[ops[j]], ka=Ka,
ki=Ki, ep_ai=epAI,
effector_conc=c, n_sites=constants['n_sites'],
n_ns=constants['Nns']).fold_change()
cred_region[:, z] = mut.stats.compute_hpd(fc, 0.95)
# Plot the fit.
# _ = ax[i, j].plot(c_range / 1E6, fc[:, 0], color=color[m], lw=0.75)
_ = ax[i, j].fill_between(c_range, cred_region[0, :],
cred_region[1, :], color=color[m], alpha=0.2)
cred_region[0, :]
cred_region[1, :]
_ = ax[0, 2].legend(fontsize=8, bbox_to_anchor=(1.04, 0.95))
plt.subplots_adjust(wspace=0.05, hspace=0.05)
if MODEL == 'KaKi_only':
plt.savefig('../../figures/Chure2019_FigS18_KaKi_IND_pairwise_predictions.pdf',
bbox_inches='tight', facecolor='white')
elif MODEL == 'KaKi_epAI':
plt.savefig('../../figures/Chure2019_FigS19_KaKi_epAI_IND_pairwise_predictions.pdf',
bbox_inches='tight', facecolor='white')
| 41.495868 | 104 | 0.520215 |
e27214e5385893d35837af6ee99a8f609104855b | 5,580 | py | Python | mupf/log/_tracks.py | kimbar/mupf_project | 21de9ed94f604220f8b8dcc64d45e30a0b94d2a1 | [
"MIT"
] | null | null | null | mupf/log/_tracks.py | kimbar/mupf_project | 21de9ed94f604220f8b8dcc64d45e30a0b94d2a1 | [
"MIT"
] | 44 | 2019-06-14T03:43:43.000Z | 2020-12-27T19:17:15.000Z | mupf/log/_tracks.py | kimbar/mupf_project | 21de9ed94f604220f8b8dcc64d45e30a0b94d2a1 | [
"MIT"
] | null | null | null | from . import _main as main
from . import settings
_tracks = []
_styles = dict(
_reference = "|,`}+-{><.T^tE",
default = "│┌└├┼─┤><·┐┘─E",
rounded = "│╭╰├┼─┤><·╮╯─E",
simple = "|,`|+-|><*,'-E",
)
glyphs = {}
ligatures = {}
def get_style(name):
if not isinstance(name, str):
name = name.value
return _styles.get(name, "default")
def set_style(characters):
global ligatures, glyphs, _styles
if len(characters) != len(_styles['_reference']):
raise ValueError('Wrong length of character set')
glyphs = {_styles['_reference'][i]:characters[i] for i in range(len(characters))}
ligatures = {lig: "".join(characters[_styles['_reference'].index(ch)] for ch in lig) for lig in (
"<-", "->", "<{", "}>", "E}>"
)}
set_style(_styles['default'])
def is_occupied(n):
""" Check if track is already taken """
global _tracks
if n >= len(_tracks):
return False
else:
return _tracks[n]
def reserve(n):
""" Reserve a track w/o checking """
global _tracks
if n >= len(_tracks):
_tracks += [False]*(n-len(_tracks)+1)
_tracks[n] = True
def free(n):
""" Free a track w/o checking """
global _tracks
_tracks[n] = False
while not _tracks[-1]:
_tracks.pop()
if len(_tracks) == 0:
break
def find_free(min_=0):
""" Find a free track, but at least `min_` one """
while is_occupied(min_):
min_ += 1
return min_
def write(branch=None, branch_track=None, inner=True, connect_to=None):
""" Print tracks for a single line
The line is connected to the line (branched) if `branch_track` number is given. The track number
`branch_track` should be occupied. `branch` can have three values: `"start"` or `"end"` if the
branch should start or end the track, `"mid"` if the branch should only attach to a track. Any
other value to only mark the track for single line. When the single line is used, the `"<"`
draws left pointing arrow after the track mark; `">"` draws right pointing arrow; and `"."`
draws no arrow (only the track mark).
"""
global _tracks, glyphs
if inner:
result = " "
else:
if branch == 'start':
result = glyphs[">"]
elif branch == 'end':
result = glyphs["<"]
else:
result = glyphs["-"]
for n, track in enumerate(_tracks):
if track:
if branch:
if n < branch_track:
if n == connect_to:
result += glyphs["}"]
elif inner or branch == 'mid':
result += glyphs["|"]
else:
result += glyphs["+"]
elif n == branch_track:
if branch == 'start':
if inner:
result += glyphs[","]
else:
result += glyphs["T"]
elif branch == 'end':
if inner:
result += glyphs["`"]
else:
result += glyphs["^"]
elif branch == 'mid':
if inner:
result += glyphs["}"]
else:
result += glyphs["|"]
else:
result += glyphs["."]
elif n > branch_track:
result += glyphs["+"]
else:
result += glyphs["|"]
else:
if branch:
if n < branch_track:
if inner or branch == 'mid':
result += " "
else:
result += glyphs["-"]
elif n == branch_track:
result += "?"
elif n > branch_track:
result += glyphs["-"]
else:
result += " "
if inner:
if branch:
if branch == 'start' or branch == '<':
result += ligatures['<-']
elif branch == 'end' or branch == '>':
result += ligatures['->']
else:
result += glyphs["-"]+glyphs["-"]
else:
result += " "
else:
if branch == '<':
result += ligatures['<-']
elif branch == '>':
result += ligatures['->']
else:
result += glyphs["-"]+glyphs["-"]
return result+":"
_groups_indent = {}
_last_group_indent = 0
def get_group_indent(group):
global _groups_indent, _last_group_indent
if group not in _groups_indent:
if len(_groups_indent) > 0:
_last_group_indent += settings.GROUP_WIDTH
_groups_indent[group] = _last_group_indent
return _groups_indent[group]
_stack_frames_by_track = {}
_tracks_by_stack_frames = {}
def register_stack_frame(frame, track):
global _stack_frames_by_track, _tracks_by_stack_frames
_stack_frames_by_track[track] = frame
_tracks_by_stack_frames[frame] = track
def deregister_stack_frame(track):
global _stack_frames_by_track, _tracks_by_stack_frames
if track in _stack_frames_by_track:
frame = _stack_frames_by_track[track]
del _tracks_by_stack_frames[frame]
del _stack_frames_by_track[track]
def get_track_by_stack_frame(frame):
global _tracks_by_stack_frames
return _tracks_by_stack_frames.get(frame, None)
| 31.348315 | 101 | 0.505556 |
ed1e220ef9fa5dccba98d6f8293ae2afced8c17a | 3,892 | html | HTML | index.html | matusmarcin/matusmarcin.com | 815bcf842e31be9727cd69dab587dce606363fb8 | [
"CC-BY-3.0"
] | null | null | null | index.html | matusmarcin/matusmarcin.com | 815bcf842e31be9727cd69dab587dce606363fb8 | [
"CC-BY-3.0"
] | null | null | null | index.html | matusmarcin/matusmarcin.com | 815bcf842e31be9727cd69dab587dce606363fb8 | [
"CC-BY-3.0"
] | null | null | null | <!DOCTYPE HTML>
<!--
Astral by HTML5 UP
html5up.net | @n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Matúš Marcin · Web Consultant</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
</head>
<body>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-314729-21', 'auto');
ga('send', 'pageview');
</script>
<!-- Wrapper-->
<div id="wrapper">
<!-- Nav -->
<nav id="nav">
<a href="#me" class="icon fa-home active"><span>Home</span></a>
<a href="#work" class="icon fa-cog"><span>Work</span></a>
<a href="#contact" class="icon fa-envelope"><span>Contact</span></a>
<a href="http://twitter.com/faster" class="icon fa-twitter"><span>Twitter</span></a>
</nav>
<!-- Main -->
<div id="main">
<!-- Me -->
<article id="me" class="panel">
<header>
<h1>Matúš Marcin</h1>
<p>Consultant</p>
</header>
<a href="#work" class="jumplink pic">
<span class="arrow icon fa-chevron-right"><span>See my work</span></span>
<img src="images/matusmarcin.jpg" alt="" />
</a>
</article>
<!-- Work -->
<article id="work" class="panel">
<header>
<h2>Work</h2>
</header>
<p>
I have <mark>12+ years</mark> of experience as a <mark>full-stack web developer</mark>.
</p>
<p>
My passion is everything <mark>web</mark>. I am no stranger to UX, mobile, scrum, teaching and barefoot running.
</p>
<p>
My references include <mark>The Economist, GlobalLogic, Heineken, Ness</mark> and many small to medium size companies in <mark>Slovakia</mark>.
</p>
<section class="text-center">
<a href="CVMatusMarcin.html" class="button">View my CV</a>
<br />
or <a href="CVMatusMarcin.pdf">Download it</a>
</section>
</article>
<!-- Contact -->
<article id="contact" class="panel">
<header>
<h2>Contact Me</h2>
</header>
<p>Feel free to email me at <mark>me (at) matusmarcin.com</mark>,
find me on <mark><a href="https://www.linkedin.com/in/matusmarcin">LinkedIn</a></mark> or <mark>tweet <a href="http://twitter.com/faster">@faster</a></mark>.
</p>
<p>My GitHub <a href="https://github.com/matusmarcin">is on GitHub</a>!</p>
<p>Looking forward to hearing from you.</p>
</article>
</div>
<!-- Footer -->
<div id="footer">
<ul class="copyright">
<li>© Matus Marcin.</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/skel-viewport.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>
</html>
| 36.037037 | 166 | 0.556269 |
dd87b45e565ff5f447da8f75cb968e5cc987c707 | 1,504 | java | Java | taxiguider/taxiassign_eng/src/main/java/taxiguider/Taxiassign.java | acw0626/asman_readme | b6b73a00fd33c020874f2f97fa3597b30325d15b | [
"MIT"
] | null | null | null | taxiguider/taxiassign_eng/src/main/java/taxiguider/Taxiassign.java | acw0626/asman_readme | b6b73a00fd33c020874f2f97fa3597b30325d15b | [
"MIT"
] | null | null | null | taxiguider/taxiassign_eng/src/main/java/taxiguider/Taxiassign.java | acw0626/asman_readme | b6b73a00fd33c020874f2f97fa3597b30325d15b | [
"MIT"
] | null | null | null | package taxiguider;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
@Entity
@Table(name="Taxiassign_table")
public class Taxiassign {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String status; //호출,호출중,호출확정,호출취소
private String taxiid;
private String driver;
private String drivertel;
@PrePersist
public void onPrePersist(){
System.out.println("==============수리기사할당================");
//할당확인됨 할당확인됨 = new 할당확인됨();
//BeanUtils.copyProperties(this, 할당확인됨);
//할당확인됨.publishAfterCommit();
//할당취소됨 할당취소됨 = new 할당취소됨();
//BeanUtils.copyProperties(this, 할당취소됨);
//할당취소됨.publishAfterCommit();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTaxiid() {
return taxiid;
}
public void setTaxiid(String taxiid) {
this.taxiid = taxiid;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getDrivertel() {
return drivertel;
}
public void setDrivertel(String drivertel) {
this.drivertel = drivertel;
}
}
| 17.090909 | 64 | 0.65758 |
5af6f26dff87173fff4aea931788c99a27c09db6 | 188 | cs | C# | Backend/AnimalRescue/AnimalRescue.DataAccess.Mongodb/Interfaces/Repositories/IVacancyRepository.cs | AlexeyDerepa/AnimalRescue | 04715710ee0949e018dc8b7f0a40ad91bc446072 | [
"Apache-2.0"
] | null | null | null | Backend/AnimalRescue/AnimalRescue.DataAccess.Mongodb/Interfaces/Repositories/IVacancyRepository.cs | AlexeyDerepa/AnimalRescue | 04715710ee0949e018dc8b7f0a40ad91bc446072 | [
"Apache-2.0"
] | null | null | null | Backend/AnimalRescue/AnimalRescue.DataAccess.Mongodb/Interfaces/Repositories/IVacancyRepository.cs | AlexeyDerepa/AnimalRescue | 04715710ee0949e018dc8b7f0a40ad91bc446072 | [
"Apache-2.0"
] | null | null | null | using AnimalRescue.DataAccess.Mongodb.Models;
namespace AnimalRescue.DataAccess.Mongodb.Interfaces.Repositories
{
public interface IVacancyRepository : IBaseRepository<Vacancy>
{
}
}
| 20.888889 | 65 | 0.824468 |
df58dc41b4f33b0c14401ee148520bc4d8aecc0a | 10,350 | cs | C# | ryuk/gtk-gui/ryuk.RemoteLogin.cs | OtisCat/gazLaxe | c8ffb888419af96df7952fdd083aadbbfc4b57ca | [
"MIT"
] | null | null | null | ryuk/gtk-gui/ryuk.RemoteLogin.cs | OtisCat/gazLaxe | c8ffb888419af96df7952fdd083aadbbfc4b57ca | [
"MIT"
] | null | null | null | ryuk/gtk-gui/ryuk.RemoteLogin.cs | OtisCat/gazLaxe | c8ffb888419af96df7952fdd083aadbbfc4b57ca | [
"MIT"
] | null | null | null |
// This file has been generated by the GUI designer. Do not modify.
namespace ryuk
{
public partial class RemoteLogin
{
private global::Gtk.UIManager UIManager;
private global::Gtk.Action FileAction;
private global::Gtk.Action EditAction;
private global::Gtk.Action WindowAction;
private global::Gtk.VBox vbox3;
private global::Gtk.MenuBar menubar3;
private global::Gtk.Table table3;
private global::Gtk.ComboBoxEntry comboboxentry5;
private global::Gtk.ComboBoxEntry comboboxentry7;
private global::Gtk.Entry entry3;
private global::Gtk.Label label11;
private global::Gtk.Label label7;
private global::Gtk.Label label9;
private global::Gtk.Expander expander3;
private global::Gtk.Table table5;
private global::Gtk.CheckButton checkbutton6;
private global::Gtk.Entry entry11;
private global::Gtk.Entry entry9;
private global::Gtk.Label label17;
private global::Gtk.Label label19;
private global::Gtk.Label GtkLabel4;
private global::Gtk.Button button3;
protected virtual void Build()
{
global::Stetic.Gui.Initialize(this);
// Widget ryuk.RemoteLogin
this.UIManager = new global::Gtk.UIManager();
global::Gtk.ActionGroup w1 = new global::Gtk.ActionGroup("Default");
this.FileAction = new global::Gtk.Action("FileAction", global::Mono.Unix.Catalog.GetString("File"), null, null);
this.FileAction.ShortLabel = global::Mono.Unix.Catalog.GetString("File");
w1.Add(this.FileAction, null);
this.EditAction = new global::Gtk.Action("EditAction", global::Mono.Unix.Catalog.GetString("Edit"), null, null);
this.EditAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Edit");
w1.Add(this.EditAction, null);
this.WindowAction = new global::Gtk.Action("WindowAction", global::Mono.Unix.Catalog.GetString("Window"), null, null);
this.WindowAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Window");
w1.Add(this.WindowAction, null);
this.UIManager.InsertActionGroup(w1, 0);
this.AddAccelGroup(this.UIManager.AccelGroup);
this.Name = "ryuk.RemoteLogin";
this.Title = global::Mono.Unix.Catalog.GetString("RemoteLogin");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child ryuk.RemoteLogin.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.UIManager.AddUiFromString("<ui><menubar name=\'menubar3\'><menu name=\'FileAction\' action=\'FileAction\'/><menu n" +
"ame=\'EditAction\' action=\'EditAction\'/><menu name=\'WindowAction\' action=\'WindowAc" +
"tion\'/></menubar></ui>");
this.menubar3 = ((global::Gtk.MenuBar)(this.UIManager.GetWidget("/menubar3")));
this.menubar3.Name = "menubar3";
this.vbox3.Add(this.menubar3);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.menubar3]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.table3 = new global::Gtk.Table(((uint)(3)), ((uint)(2)), false);
this.table3.Name = "table3";
this.table3.RowSpacing = ((uint)(6));
this.table3.ColumnSpacing = ((uint)(6));
// Container child table3.Gtk.Table+TableChild
this.comboboxentry5 = global::Gtk.ComboBoxEntry.NewText();
this.comboboxentry5.Name = "comboboxentry5";
this.table3.Add(this.comboboxentry5);
global::Gtk.Table.TableChild w3 = ((global::Gtk.Table.TableChild)(this.table3[this.comboboxentry5]));
w3.LeftAttach = ((uint)(1));
w3.RightAttach = ((uint)(2));
w3.YOptions = ((global::Gtk.AttachOptions)(1));
// Container child table3.Gtk.Table+TableChild
this.comboboxentry7 = global::Gtk.ComboBoxEntry.NewText();
this.comboboxentry7.Name = "comboboxentry7";
this.table3.Add(this.comboboxentry7);
global::Gtk.Table.TableChild w4 = ((global::Gtk.Table.TableChild)(this.table3[this.comboboxentry7]));
w4.TopAttach = ((uint)(1));
w4.BottomAttach = ((uint)(2));
w4.LeftAttach = ((uint)(1));
w4.RightAttach = ((uint)(2));
w4.YOptions = ((global::Gtk.AttachOptions)(1));
// Container child table3.Gtk.Table+TableChild
this.entry3 = new global::Gtk.Entry();
this.entry3.CanFocus = true;
this.entry3.Name = "entry3";
this.entry3.IsEditable = true;
this.entry3.InvisibleChar = '●';
this.table3.Add(this.entry3);
global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table3[this.entry3]));
w5.TopAttach = ((uint)(2));
w5.BottomAttach = ((uint)(3));
w5.LeftAttach = ((uint)(1));
w5.RightAttach = ((uint)(2));
// Container child table3.Gtk.Table+TableChild
this.label11 = new global::Gtk.Label();
this.label11.Name = "label11";
this.label11.LabelProp = global::Mono.Unix.Catalog.GetString("Domain");
this.table3.Add(this.label11);
// Container child table3.Gtk.Table+TableChild
this.label7 = new global::Gtk.Label();
this.label7.Name = "label7";
this.label7.LabelProp = global::Mono.Unix.Catalog.GetString("Username");
this.table3.Add(this.label7);
global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table3[this.label7]));
w7.TopAttach = ((uint)(1));
w7.BottomAttach = ((uint)(2));
// Container child table3.Gtk.Table+TableChild
this.label9 = new global::Gtk.Label();
this.label9.Name = "label9";
this.label9.LabelProp = global::Mono.Unix.Catalog.GetString("Password");
this.table3.Add(this.label9);
global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table3[this.label9]));
w8.TopAttach = ((uint)(2));
w8.BottomAttach = ((uint)(3));
this.vbox3.Add(this.table3);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.table3]));
w9.Position = 1;
// Container child vbox3.Gtk.Box+BoxChild
this.expander3 = new global::Gtk.Expander(null);
this.expander3.CanFocus = true;
this.expander3.Name = "expander3";
this.expander3.Expanded = true;
// Container child expander3.Gtk.Container+ContainerChild
this.table5 = new global::Gtk.Table(((uint)(3)), ((uint)(2)), false);
this.table5.Name = "table5";
this.table5.RowSpacing = ((uint)(6));
this.table5.ColumnSpacing = ((uint)(6));
// Container child table5.Gtk.Table+TableChild
this.checkbutton6 = new global::Gtk.CheckButton();
this.checkbutton6.CanFocus = true;
this.checkbutton6.Name = "checkbutton6";
this.checkbutton6.Label = global::Mono.Unix.Catalog.GetString("Use Key Encryption");
this.checkbutton6.DrawIndicator = true;
this.checkbutton6.UseUnderline = true;
this.table5.Add(this.checkbutton6);
global::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table5[this.checkbutton6]));
w10.XOptions = ((global::Gtk.AttachOptions)(4));
w10.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table5.Gtk.Table+TableChild
this.entry11 = new global::Gtk.Entry();
this.entry11.CanFocus = true;
this.entry11.Name = "entry11";
this.entry11.IsEditable = true;
this.entry11.InvisibleChar = '●';
this.table5.Add(this.entry11);
global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table5[this.entry11]));
w11.TopAttach = ((uint)(2));
w11.BottomAttach = ((uint)(3));
w11.LeftAttach = ((uint)(1));
w11.RightAttach = ((uint)(2));
w11.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table5.Gtk.Table+TableChild
this.entry9 = new global::Gtk.Entry();
this.entry9.CanFocus = true;
this.entry9.Name = "entry9";
this.entry9.IsEditable = true;
this.entry9.InvisibleChar = '●';
this.table5.Add(this.entry9);
global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.table5[this.entry9]));
w12.TopAttach = ((uint)(1));
w12.BottomAttach = ((uint)(2));
w12.LeftAttach = ((uint)(1));
w12.RightAttach = ((uint)(2));
w12.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table5.Gtk.Table+TableChild
this.label17 = new global::Gtk.Label();
this.label17.Name = "label17";
this.label17.LabelProp = global::Mono.Unix.Catalog.GetString("Private Key");
this.table5.Add(this.label17);
global::Gtk.Table.TableChild w13 = ((global::Gtk.Table.TableChild)(this.table5[this.label17]));
w13.TopAttach = ((uint)(1));
w13.BottomAttach = ((uint)(2));
w13.XOptions = ((global::Gtk.AttachOptions)(4));
w13.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table5.Gtk.Table+TableChild
this.label19 = new global::Gtk.Label();
this.label19.Name = "label19";
this.label19.LabelProp = global::Mono.Unix.Catalog.GetString("Passphrase");
this.table5.Add(this.label19);
global::Gtk.Table.TableChild w14 = ((global::Gtk.Table.TableChild)(this.table5[this.label19]));
w14.TopAttach = ((uint)(2));
w14.BottomAttach = ((uint)(3));
w14.XOptions = ((global::Gtk.AttachOptions)(4));
w14.YOptions = ((global::Gtk.AttachOptions)(4));
this.expander3.Add(this.table5);
this.GtkLabel4 = new global::Gtk.Label();
this.GtkLabel4.Name = "GtkLabel4";
this.GtkLabel4.LabelProp = global::Mono.Unix.Catalog.GetString("Extra Options");
this.GtkLabel4.UseUnderline = true;
this.expander3.LabelWidget = this.GtkLabel4;
this.vbox3.Add(this.expander3);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.expander3]));
w16.Position = 2;
w16.Expand = false;
w16.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.button3 = new global::Gtk.Button();
this.button3.CanFocus = true;
this.button3.Name = "button3";
this.button3.UseUnderline = true;
this.button3.Label = global::Mono.Unix.Catalog.GetString("Start Whatever");
this.vbox3.Add(this.button3);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.button3]));
w17.Position = 3;
this.Add(this.vbox3);
if ((this.Child != null))
{
this.Child.ShowAll();
}
this.DefaultWidth = 375;
this.DefaultHeight = 283;
this.Show();
this.entry3.Changed += new global::System.EventHandler(this.PasswordChanged);
this.comboboxentry7.Changed += new global::System.EventHandler(this.UsernameChanged);
this.comboboxentry5.Changed += new global::System.EventHandler(this.DomainChanged);
this.button3.Clicked += new global::System.EventHandler(this.StartClicked);
}
}
}
| 41.902834 | 125 | 0.695845 |
20e16cb94dcb9dfa59991a388be7903b9e6de468 | 5,829 | py | Python | chemml/chem/magpie_python/attributes/generators/composition/YangOmegaAttributeGenerator.py | iamchetry/DataChallenge-Fall2021 | fa7748c9ea2f3c0f6bde8d0b094fc75463e28f33 | [
"BSD-3-Clause"
] | 108 | 2018-03-23T20:06:03.000Z | 2022-01-06T19:32:46.000Z | chemml/chem/magpie_python/attributes/generators/composition/YangOmegaAttributeGenerator.py | hachmannlab/ChemML | 42b152579872a57c834884596f700c76b9320280 | [
"BSD-3-Clause"
] | 18 | 2019-08-09T21:16:14.000Z | 2022-02-14T21:52:06.000Z | chemml/chem/magpie_python/attributes/generators/composition/YangOmegaAttributeGenerator.py | hachmannlab/ChemML | 42b152579872a57c834884596f700c76b9320280 | [
"BSD-3-Clause"
] | 28 | 2018-04-28T17:07:33.000Z | 2022-02-28T07:22:56.000Z | # coding=utf-8
import math
import types
import numpy as np
import pandas as pd
from ....data.materials.CompositionEntry import CompositionEntry
from ....data.materials.util.LookUpData import LookUpData
class YangOmegaAttributeGenerator:
"""Class to compute the attributes :math:`\Omega` and :math:`\delta`
developed by Yang and Zhang [1].
These parameters are based on the liquid formation enthalpy and atomic
sizes of elements respectively and were originally developed to predict
whether a metal alloy will form a solid solution of bulk metallic glass.
Notes
-----
:math: `\Omega` is derived from the melting temperature, ideal mixing
entropy, and regular solution solution interaction parameter (
:math: `\Omega_{i,j}`) predicted by the Miedema model for binary liquids.
Specifically, it is computed using the relationship:
.. math:: \Omega = \displaystyle\frac{T_m \Delta S_{mix}} {|\Delta H_{mix}|}
where :math: `T_m` is the composition-weighted average of the melting
temperature, :math: `\Delta S_{mix}` is the ideal solution entropy,
and :math: `\Delta H_{mix}` is the mixing enthalpy. The mixing enthalpy
is computed using the Miedema mixing enthalpies tabulated by Takeuchi and
Inoue [2] where:
.. math:: \Delta H_{mix} = \displaystyle\sum \Omega_{i,j} c_i c_j
and :math: `\Omega_{i,j} = 4 * \Delta H_{mix}`.
:math: `\delta` is related to the polydispersity of atomic sizes, and is
computed using the relationship:
.. math:: \delta = [\displaystyle\sum c_i (1 - \frac{r_i}{r_{
average})^2]^0.5
where :math: `r_i` is the atomic size. Here, we use the atomic radii
compiled by Miracle et al. [3] rather than those compiled by Kittel,
as in the original work.
References
----------
.. [1] X. Yang and Y. Zhang, "Prediction of high-entropy stabilized
solid-solution in multi-component alloys," Materials Chemistry and
Physics, vol. 132, no. 2--3, pp. 233--238, Feb. 2012.
.. [2] A. Takeuchi and A. Inoue, "Classification of Bulk Metallic Glasses
by Atomic Size Difference, Heat of Mixing and Period of Constituent
Elements and Its Application to Characterization of the Main Alloying
Element," MATERIALS TRANSACTIONS, vol. 46, no. 12, pp. 2817--2829, 2005.
.. [3] D. B. Miracle, D. V. Louzguine-Luzgin, L. V. Louzguina-Luzgina,
and A. Inoue, "An assessment of binary metallic glasses: correlations
between structure, glass forming ability and stability," International
Materials Reviews, vol. 55, no. 4, pp. 218--256, Jul. 2010.
"""
def generate_features(self, entries):
"""Function to generate features as mentioned in the class description.
Parameters
----------
entries : array-like
Compositions for which features are to be generated. A list of
CompositionEntry's.
Returns
----------
features : DataFrame
Features for the given entries. Pandas data frame containing the
names and values of the descriptors.
Raises
------
ValueError
If input is not of type list.
If items in the list are not CompositionEntry instances.
"""
# Initialize lists of feature values and headers for pandas data frame.
feat_values = []
feat_headers = []
# Raise exception if input argument is not of type list of
# CompositionEntry's.
if not isinstance(entries, list):
raise ValueError("Argument should be of type list of "
"CompositionEntry's")
elif (entries and not isinstance(entries[0], CompositionEntry)):
raise ValueError("Argument should be of type list of "
"CompositionEntry's")
# Insert header names here.
feat_headers.append("Yang_Omega")
feat_headers.append("Yang_delta")
# Load property values here.
radii = LookUpData.load_property("MiracleRadius")
meltingT = LookUpData.load_property("MeltingT")
miedema = LookUpData.load_pair_property("MiedemaLiquidDeltaHf")
for entry in entries:
tmp_list = []
tmp_radii = []
tmp_meltingT = []
elem_fracs = entry.get_element_fractions()
elem_ids = entry.get_element_ids()
for elem_id in elem_ids:
tmp_radii.append(radii[elem_id])
tmp_meltingT.append(meltingT[elem_id])
# Compute the average melting point.
averageTm = np.average(tmp_meltingT, weights=elem_fracs)
# Compute the ideal entropy.
entropy = 0.0
for f in elem_fracs:
entropy += f*math.log(f) if f > 0 else 0.0
entropy *= 8.314/1000
# Compute the enthalpy
enthalpy = 0.0
for i in range(len(elem_ids)):
for j in range(i + 1, len(elem_ids)):
enthalpy += miedema[max(elem_ids[i], elem_ids[j])][min(
elem_ids[i], elem_ids[j])] * elem_fracs[i] * \
elem_fracs[j]
enthalpy *= 4
# Compute omega
tmp_list.append(abs(averageTm * entropy / enthalpy))
# Compute delta
delta_squared = 0.0
average_r = np.average(tmp_radii, weights=elem_fracs)
for i in range(len(elem_ids)):
delta_squared += elem_fracs[i] * (1 - tmp_radii[i] /
average_r)**2
tmp_list.append(math.sqrt(delta_squared))
feat_values.append(tmp_list)
features = pd.DataFrame(feat_values, columns=feat_headers)
return features
| 40.2 | 80 | 0.618974 |
79e258b0797f1b5aaec2c5b64b4af1cc94103e7b | 16,371 | php | PHP | inc/customizer/panels/clients.php | runthemes/fargo | 539ef3dfa3c81eca992c58a36c8cb488a6563f2b | [
"MIT"
] | null | null | null | inc/customizer/panels/clients.php | runthemes/fargo | 539ef3dfa3c81eca992c58a36c8cb488a6563f2b | [
"MIT"
] | null | null | null | inc/customizer/panels/clients.php | runthemes/fargo | 539ef3dfa3c81eca992c58a36c8cb488a6563f2b | [
"MIT"
] | null | null | null | <?php
/**
* Clients Section Customizer Options
*
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Variable
*/
$panel = 'fargo_panel_clients';
$prefix = 'fargo';
/**
* Panel
*/
$wp_customize->add_section( $panel, array(
'priority' => fargo_get_section_position($panel),
'capability' => 'edit_theme_options',
'theme_supports' => '',
'title' => esc_html__( 'Clients', 'fargo' ),
'panel' => 'fargo_frontpage_panel'
) );
/**
* Tabs
*/
$wp_customize->add_setting( $prefix . '_clients_tab', array(
'transport' => 'postMessage',
'sanitize_callback' => 'wp_kses_post',
) );
$wp_customize->add_control( new Fargo_Customizer_Tab_Control( $wp_customize, $prefix . '_clients_tab', array(
'type' => 'epsilon-tab',
'section' => $panel,
'buttons' => array(
array(
'name' => esc_html__( 'General', 'fargo' ),
'fields' => array(
$prefix . '_clients_general_enable',
$prefix . '_clients_general_title',
$prefix . '_clients_general_subtitle',
$prefix . '_clients_general_content',
),
'active' => true
),
array(
'name' => esc_html__( 'Settings', 'fargo' ),
'fields' => array(
$prefix . '_clients_general_width',
$prefix . '_clients_settings_layout',
),
),
array(
'name' => esc_html__( 'Colors', 'fargo' ),
'fields' => array(
$prefix . '_clients_colors_background',
$prefix . '_clients_colors_title',
$prefix . '_clients_colors_subtitle',
$prefix . '_clients_colors_content_title',
$prefix . '_clients_colors_content_text',
),
),
array(
'name' => esc_html__( 'Backgrounds', 'fargo' ),
'fields' => array(
$prefix . '_clients_backgrounds_image',
$prefix . '_clients_backgrounds_position',
$prefix . '_clients_backgrounds_size',
$prefix . '_clients_backgrounds_repeat',
$prefix . '_clients_backgrounds_attachment',
$prefix . '_clients_backgrounds_overlay',
$prefix . '_clients_backgrounds_overlay_color',
),
),
),
) )
);
/**
* GENERAL
*/
/**
* Section Enable
*/
$wp_customize->add_setting( $prefix . '_clients_general_enable', array(
'sanitize_callback' => 'fargo_sanitize_checkbox',
'default' => 1,
) );
$wp_customize->add_control( new Fargo_Customizer_Toggle_Control( $wp_customize, $prefix . '_clients_general_enable', array(
'type' => 'mte-toggle',
'label' => esc_html__( 'Section Enable', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_general_enable',
) ) );
/**
* Title
*/
$wp_customize->add_setting( $prefix . '_clients_general_title', array(
'transport' => 'postMessage',
'sanitize_callback' => 'sanitize_text_field',
'default' => esc_html__( 'CLIENTS', 'fargo' ),
) );
$wp_customize->add_control( $prefix . '_clients_general_title', array(
'label' => esc_html__( 'Title', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_general_title',
) );
$wp_customize->selective_refresh->add_partial( $prefix .'_clients_general_title', array(
'selector' => '#clients.front-page-section .section-header h2',
) );
/**
* Sub Title
*/
$wp_customize->add_setting( $prefix . '_clients_general_subtitle', array(
'transport' => 'postMessage',
'sanitize_callback' => 'wp_kses_post',
'default' => esc_html__( 'This is a description for the Clients section. You can set it up in the Customizer > Front Page Sections > Clients and add items by clicking on Add or edit Clients.', 'fargo' ),
) );
$wp_customize->add_control( $prefix . '_clients_general_subtitle', array(
'label' => esc_html__( 'Subtitle', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_general_subtitle',
) );
$wp_customize->selective_refresh->add_partial( $prefix .'_clients_general_subtitle', array(
'selector' => '#clients.front-page-section .section-header h5',
) );
/**
* General Content
*/
$wp_customize->add_setting( $prefix . '_clients_general_content', array(
'transport' => $selective_refresh ? 'postMessage' : 'refresh',
) );
$hestia_clients_content_control = $wp_customize->get_setting( $prefix .'_clients_general_content' );
if ( ! empty( $hestia_clients_content_control ) ) {
$hestia_clients_content_control->default = json_encode( array(
array(
'icon_value' => 'fa-wechat',
'title' => esc_html__( 'Responsive', 'themeisle-companion' ),
'text' => esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'themeisle-companion' ),
'link' => '#',
'id' => 'customizer_repeater_56d7ea7f40b56',
'color' => '#e91e63',
),
array(
'icon_value' => 'fa-check',
'title' => esc_html__( 'Quality', 'themeisle-companion' ),
'text' => esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'themeisle-companion' ),
'link' => '#',
'id' => 'customizer_repeater_56d7ea7f40b66',
'color' => '#00bcd4',
),
array(
'icon_value' => 'fa-support',
'title' => esc_html__( 'Support', 'themeisle-companion' ),
'text' => esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'themeisle-companion' ),
'link' => '#',
'id' => 'customizer_repeater_56d7ea7f40b86',
'color' => '#4caf50',
),
) );
}
$wp_customize->add_control( new Fargo_Repeater( $wp_customize, $prefix . '_clients_general_content', array(
'label' => esc_html__( 'Clients Content', 'fargo' ),
'section' => $panel,
'add_field_label' => esc_html__( 'Add Client', 'fargo' ),
'item_name' => esc_html__( 'Client', 'fargo' ),
'customizer_repeater_icon_control' => true,
'customizer_repeater_title_control' => true,
'customizer_repeater_text_control' => true,
'customizer_repeater_link_control' => true,
'customizer_repeater_color_control' => true,
'priority' => 19,
) ) );
function clients_general_content_callback() {
$clients_general_content = get_theme_mod( $prefix . '_clients_general_content' );
clients_general_content( $clients_general_content, true );
}
/**
* SETTINGS
*/
/**
* Full Width
*/
$wp_customize->add_setting( $prefix . '_clients_general_width', array(
'sanitize_callback' => $prefix . '_sanitize_checkbox',
'default' => 0,
'transport' => 'postMessage',
) );
$wp_customize->add_control( new Fargo_Customizer_Toggle_Control( $wp_customize, $prefix . '_clients_general_width', array(
'type' => 'mte-toggle',
'label' => esc_html__( 'Full Width', 'fargo' ),
'section' => $panel,
) ) );
/**
* Layout
*/
$wp_customize->add_setting( $prefix .'_clients_settings_layout', array(
'default' => 3,
) );
$wp_customize->add_control( new Fargo_Customizer_Range_Control( $wp_customize, $prefix .'_clients_settings_layout', array(
'label' => esc_html__( 'Layouts', 'fargo' ),
'section' => $panel,
'choices' => array(
'min' => 1,
'max' => 5,
'step' => 1,
),
) ) );
/**
* COLORS
*/
/**
* Background Color
*/
$wp_customize->add_setting( $prefix . '_clients_colors_background', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_colors_background', array(
'label' => esc_html__( 'Background Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_colors_background',
) ) );
/**
* Title Color
*/
$wp_customize->add_setting( $prefix . '_clients_colors_title', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_colors_title', array(
'label' => esc_html__( 'Title Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_colors_title',
) ) );
/**
* Sub Title Color
*/
$wp_customize->add_setting( $prefix . '_clients_colors_subtitle', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_colors_subtitle', array(
'label' => esc_html__( 'Subtitle Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_colors_subtitle',
) ) );
/**
* Content Title Color
*/
$wp_customize->add_setting( $prefix . '_clients_colors_content_title', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_colors_content_title', array(
'label' => esc_html__( 'Content Title Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_colors_content_title',
) ) );
/**
* Content Title Color
*/
$wp_customize->add_setting( $prefix . '_clients_colors_content_text', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_colors_content_text', array(
'label' => esc_html__( 'Content Text Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_colors_content_text',
) ) );
/**
* BACKGROUNDS
*/
/**
* Background Image
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_image', array(
'transport' => 'postMessage',
'sanitize_callback' => 'esc_url',
'default' => '',
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, $prefix . '_clients_backgrounds_image', array(
'label' => esc_html__( 'Background Image', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_image',
) ) );
/**
* Background Position
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_position', array(
'transport' => 'postMessage',
'sanitize_callback' => 'sanitize_text_field',
'default' => 'initial',
) );
$wp_customize->add_control( $prefix . '_clients_backgrounds_position', array(
'label' => esc_html__( 'Background Position', 'fargo' ),
'type' => 'select',
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_position',
'choices' => array(
'initial' => esc_html__( 'Default', 'fargo' ),
'top left' => esc_html__( 'Top Left', 'fargo' ),
'top center' => esc_html__( 'Top Center', 'fargo' ),
'top right' => esc_html__( 'Top Right', 'fargo' ),
'center left' => esc_html__( 'Center Left', 'fargo' ),
'center center' => esc_html__( 'Center Center', 'fargo' ),
'center right' => esc_html__( 'Center Right', 'fargo' ),
'bottom left' => esc_html__( 'Bottom Left', 'fargo' ),
'bottom center' => esc_html__( 'Bottom Center', 'fargo' ),
'bottom right' => esc_html__( 'Bottom Right', 'fargo' ),
),
) );
/**
* Background Size
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_size', array(
'transport' => 'postMessage',
'sanitize_callback' => 'sanitize_text_field',
'default' => 'auto',
) );
$wp_customize->add_control( $prefix . '_clients_backgrounds_size', array(
'label' => esc_html__( 'Background Size', 'fargo' ),
'type' => 'select',
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_size',
'choices' => array(
'auto' => esc_html__( 'Default', 'fargo' ),
'contain' => esc_html__( 'Fit to Screen', 'fargo' ),
'cover' => esc_html__( 'Fill Screen', 'fargo' ),
),
) );
/**
* Background Repeat
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_repeat', array(
'transport' => 'postMessage',
'sanitize_callback' => 'sanitize_text_field',
'default' => 'initial',
) );
$wp_customize->add_control( $prefix . '_clients_backgrounds_repeat', array(
'label' => esc_html__( 'Background Repeat', 'fargo' ),
'type' => 'select',
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_repeat',
'choices' => array(
'initial' => esc_html__( 'Default', 'fargo' ),
'no-repeat' => esc_html__( 'No-repeat', 'fargo' ),
'repeat' => esc_html__( 'Repeat', 'fargo' ),
'repeat-x' => esc_html__( 'Repeat-x', 'fargo' ),
'repeat-y' => esc_html__( 'Repeat-y', 'fargo' ),
),
) );
/**
* Background Attachment
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_attachment', array(
'transport' => 'postMessage',
'sanitize_callback' => 'sanitize_text_field',
'default' => 'initial',
) );
$wp_customize->add_control( $prefix . '_clients_backgrounds_attachment', array(
'label' => esc_html__( 'Background Attachment', 'fargo' ),
'type' => 'select',
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_attachment',
'choices' => array(
'initial' => esc_html__( 'Default', 'fargo' ),
'scroll' => esc_html__( 'Scroll', 'fargo' ),
'fixed' => esc_html__( 'Fixed', 'fargo' )
),
) );
/**
* Background Overlay Enable
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_overlay', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_checkbox',
'default' => 0,
) );
$wp_customize->add_control( new Fargo_Customizer_Toggle_Control( $wp_customize, $prefix . '_clients_backgrounds_overlay', array(
'label' => esc_html__( 'Overlay Enable', 'fargo' ),
'type' => 'mte-toggle',
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_overlay',
) ) );
/**
* Background Overlay Color
*/
$wp_customize->add_setting( $prefix . '_clients_backgrounds_overlay_color', array(
'transport' => 'postMessage',
'sanitize_callback' => 'fargo_sanitize_color',
'default' => '#ffffff',
) );
$wp_customize->add_control( new Fargo_Customizer_Color_Control( $wp_customize, $prefix . '_clients_backgrounds_overlay_color', array(
'label' => esc_html__( 'Overlay Color', 'fargo' ),
'section' => $panel,
'settings' => $prefix . '_clients_backgrounds_overlay_color',
) ) ); | 36.139073 | 218 | 0.568444 |
cc5a995a36519f8aa76dd6074016a674c50f7258 | 2,827 | dart | Dart | test/editor_test.dart | icedman/flutter_editor | 3ed8bba5774c3d5653a7c07dc5572ee85996d5fc | [
"MIT"
] | 6 | 2022-03-12T23:20:52.000Z | 2022-03-21T03:13:54.000Z | test/editor_test.dart | icedman/flutter_editor | 3ed8bba5774c3d5653a7c07dc5572ee85996d5fc | [
"MIT"
] | 1 | 2022-03-29T15:25:49.000Z | 2022-03-30T01:53:53.000Z | test/editor_test.dart | icedman/flutter_editor | 3ed8bba5774c3d5653a7c07dc5572ee85996d5fc | [
"MIT"
] | 3 | 2022-03-17T00:18:57.000Z | 2022-03-29T12:13:03.000Z | import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:editor/editor/editor.dart';
import 'package:editor/explorer/explorer.dart';
import 'package:editor/services/ffi/bridge.dart';
import 'package:editor/services/app.dart';
import 'package:editor/services/ui/ui.dart';
import 'package:editor/services/highlight/theme.dart';
import 'package:editor/services/highlight/tmparser.dart';
import 'package:editor/services/highlight/highlighter.dart';
bool hSplit = true;
bool vSplit = true;
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
FFIBridge.load();
String extPath = '/home/iceman/.editor/extensions/';
String path = './tests/tinywl.c';
// path = './tests/sqlite3.c';
if (Platform.isAndroid) {
extPath = '/sdcard/.editor/extensions/';
path = '/sdcard/Developer/tests/tinywl.c';
}
if (args.isNotEmpty) {
path = args[args.length - 1];
}
FFIBridge.initialize(extPath);
TMParser(); // loads the theme
AppProvider app = AppProvider();
UIProvider ui = UIProvider();
HLTheme theme = HLTheme.instance();
return runApp(MultiProvider(providers: [
ChangeNotifierProvider(create: (context) => app),
ChangeNotifierProvider(create: (context) => ui),
ChangeNotifierProvider(create: (context) => theme),
], child: App(path: path)));
}
class App extends StatelessWidget {
App({String this.path = ''});
String path = '';
@override
Widget build(BuildContext context) {
UIProvider ui = Provider.of<UIProvider>(context);
HLTheme theme = Provider.of<HLTheme>(context);
ThemeData themeData = ThemeData(
fontFamily: 'FiraCode',
primaryColor: theme.foreground,
backgroundColor: theme.background,
scaffoldBackgroundColor: theme.background,
);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: themeData,
home: Scaffold(
body: Stack(children: [
Row(children: [
if (hSplit) ...[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: Editor(path: path)))
],
Expanded(
flex: 2,
child: Column(children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: Editor(path: path))),
if (vSplit) ...[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: Editor(path: path)))
],
]))
]),
...ui.popups
])));
}
}
| 28.555556 | 61 | 0.589317 |
d909db37a85554d284582740ea8aa6a31892dc8b | 16,333 | rs | Rust | src/check/parse.rs | naokikob/hoice | f019ec168dc5e6bb7a069c9790a80685bd06e0cb | [
"Apache-2.0"
] | 43 | 2017-10-25T07:11:06.000Z | 2021-11-23T08:49:16.000Z | src/check/parse.rs | naokikob/hoice | f019ec168dc5e6bb7a069c9790a80685bd06e0cb | [
"Apache-2.0"
] | 24 | 2017-09-26T08:16:58.000Z | 2021-06-29T14:55:03.000Z | src/check/parse.rs | naokikob/hoice | f019ec168dc5e6bb7a069c9790a80685bd06e0cb | [
"Apache-2.0"
] | 10 | 2017-07-25T06:10:13.000Z | 2021-10-09T14:25:18.000Z | //! Parsers used by the checker.
use std::iter::Extend;
use crate::check::*;
/// Parser.
#[derive(Clone)]
pub struct InParser<'a> {
/// Unknown stuff. Datatype declarations, recursive function definitions and
/// such.
pub unknown: Vec<String>,
/// Predicate definitions.
pub pred_defs: Vec<PredDef>,
/// Predicate declarations.
pub pred_decs: Vec<PredDec>,
/// Function definitions.
pub fun_defs: Vec<FunDef>,
/// Clauses.
pub clauses: Vec<Clause>,
/// Characters.
chars: ::std::str::Chars<'a>,
/// Buffer storing characters pushed back.
buf: Vec<char>,
}
impl<'a> InParser<'a> {
/// Constructor.
pub fn new(s: &'a str) -> Self {
InParser {
unknown: vec![],
pred_defs: vec![],
pred_decs: vec![],
fun_defs: vec![],
clauses: vec![],
chars: s.chars(),
buf: vec![],
}
}
/// Swaps input characters.
pub fn swap(&mut self, s: &'a str) {
self.chars = s.chars();
assert!(self.buf.is_empty())
}
/// True if there is a next character.
fn has_next(&mut self) -> bool {
if !self.buf.is_empty() {
true
} else if let Some(c) = self.next() {
self.buf.push(c);
true
} else {
false
}
}
/// Next character.
fn next(&mut self) -> Option<char> {
if let Some(c) = self.buf.pop() {
Some(c)
} else {
self.chars.next()
}
}
/// Pushes back a character.
fn txen(&mut self, c: char) {
self.buf.push(c)
}
/// Backtracks some characters.
fn backtrack<I>(&mut self, mem: impl IntoIterator<IntoIter = I>)
where
I: Iterator<Item = char> + DoubleEndedIterator,
{
for c in mem.into_iter().rev() {
self.buf.push(c)
}
}
/// Parses a tag or fails.
fn tag(&mut self, tag: &str) -> Res<()> {
if !self.tag_opt(tag) {
error_chain::bail!("expected tag `{}`", conf.emph(tag))
} else {
Ok(())
}
}
/// Tries to parse a tag.
fn tag_opt(&mut self, tag: &str) -> bool {
let mut mem = vec![];
for c in tag.chars() {
if let Some(next) = self.next() {
mem.push(next);
if c != next {
self.backtrack(mem);
return false;
}
} else {
self.backtrack(mem);
return false;
}
}
true
}
/// Parses a character or fails.
fn char(&mut self, c: char) -> Res<()> {
if !self.char_opt(c) {
error_chain::bail!(
"expected character `{}`, got `{}`",
conf.emph(&c.to_string()),
conf.sad(if let Some(c) = self.next() {
format!("{}", c)
} else {
"<eof>".into()
})
)
} else {
Ok(())
}
}
/// Tries to parse a character.
fn char_opt(&mut self, c: char) -> bool {
if let Some(next) = self.next() {
if next == c {
true
} else {
self.txen(next);
false
}
} else {
false
}
}
/// Parses everything it can until (and excluding) some character.
fn not_char(&mut self, c: char) -> String {
let mut s = String::new();
while let Some(next) = self.next() {
if next == c {
self.txen(next);
break;
} else {
s.push(next)
}
}
s
}
/// Parses an sexpression.
fn sexpr(&mut self) -> Res<Term> {
if self.tag_opt("true") {
return Ok("true".into());
} else if self.tag_opt("false") {
return Ok("false".into());
} else if let Some(id) = self.ident_opt()? {
return Ok(id);
}
let mut s = String::new();
let mut cnt = 0;
while let Some(next) = self.next() {
s.push(next);
if next == '(' {
cnt += 1;
} else if next == ')' {
cnt -= 1;
if cnt == 0 {
break;
}
}
}
if cnt != 0 {
error_chain::bail!("found eof while parsing sexpr")
}
Ok(s)
}
/// Reads whitespaces and comments.
fn ws_cmt(&mut self) {
'ws: while let Some(next) = self.next() {
if !next.is_whitespace() {
if next == ';' {
'cmt: while let Some(next) = self.next() {
if next == '\n' {
break 'cmt;
}
}
} else {
self.txen(next);
break 'ws;
}
}
}
}
/// Unquoted identifier char.
fn ident_char(c: char) -> bool {
if c.is_alphanumeric() {
true
} else {
match c {
'~' | '!' | '@' | '$' | '%' | '^' | '&' | '*' | ':' | '_' | '-' | '+' | '='
| '<' | '>' | '.' | '?' | '/' => true,
_ => false,
}
}
}
/// Identifier or fails.
fn ident(&mut self) -> Res<Ident> {
if let Some(id) = self.ident_opt()? {
Ok(id)
} else {
error_chain::bail!("expected identifier")
}
}
/// Identifier.
fn ident_opt(&mut self) -> Res<Option<Ident>> {
if let Some(next) = self.next() {
let id = if next == '|' {
let id = self.not_char('|');
self.char('|')?;
id
} else if Self::ident_char(next) && !next.is_numeric() {
let mut id = String::new();
id.push(next);
while let Some(next) = self.next() {
if Self::ident_char(next) {
id.push(next)
} else {
self.txen(next);
break;
}
}
id
} else {
self.txen(next);
return Ok(None);
};
Ok(Some(format!("|{}|", id)))
} else {
Ok(None)
}
}
/// Set-logic.
fn set_logic(&mut self) -> Res<bool> {
if !self.tag_opt("set-logic") {
return Ok(false);
}
self.ws_cmt();
self.tag("HORN")?;
Ok(true)
}
/// Set-info.
fn set_info(&mut self) -> Res<bool> {
if !self.tag_opt("set-info") {
return Ok(false);
}
self.ws_cmt();
self.char(':')?;
self.ident()?;
self.ws_cmt();
if self.char_opt('|') {
self.not_char('|');
self.char('|')?
} else if self.char_opt('"') {
let _blah = self.not_char('"');
self.char('"')?
} else {
let _blah = self.not_char(')');
}
Ok(true)
}
/// Set-option.
fn set_option(&mut self) -> Res<Option<(String, String)>> {
if !self.tag_opt("set-option") {
return Ok(None);
}
self.ws_cmt();
self.char(':')?;
let key = self.ident()?;
self.ws_cmt();
let val = if self.char_opt('|') {
let res = self.not_char('|');
self.char('|')?;
res
} else if self.char_opt('"') {
let res = self.not_char('"');
self.char('"')?;
res
} else {
let res = self.not_char(')');
res.trim().into()
};
Ok(Some((key, val)))
}
/// Declare-fun.
fn declare_fun(&mut self) -> Res<bool> {
if !self.tag_opt("declare-fun") {
return Ok(false);
}
self.ws_cmt();
let pred = self.ident()?;
self.ws_cmt();
self.char('(')?;
self.ws_cmt();
let mut sig = vec![];
while !self.char_opt(')') {
sig.push(self.sexpr()?);
self.ws_cmt()
}
self.ws_cmt();
self.tag("Bool")?;
self.pred_decs.push(PredDec { pred, sig });
Ok(true)
}
/// Arguments.
fn args(&mut self) -> Res<Args> {
self.char('(')?;
self.ws_cmt();
let mut args = vec![];
while self.char_opt('(') {
let id = self.ident()?;
self.ws_cmt();
let ty = self.sexpr()?;
self.ws_cmt();
self.char(')')?;
self.ws_cmt();
args.push((id, ty))
}
self.char(')')?;
Ok(args)
}
/// Assert.
fn assert(&mut self) -> Res<bool> {
if !self.tag_opt("assert") {
return Ok(false);
}
self.ws_cmt();
let mut cnt = 0;
let negated = if self.char_opt('(') {
if self.tag_opt("not") {
self.ws_cmt();
if self.char_opt('(') {
cnt += 1;
}
true
} else {
cnt += 1;
false
}
} else {
false
};
let (args, body) = if self.tag_opt("forall") {
if negated {
error_chain::bail!("negated forall in assertion")
}
self.ws_cmt();
let mut args = vec![];
loop {
let these_args = self.args().chain_err(|| "while parsing arguments")?;
args.extend(these_args);
self.ws_cmt();
if self.char_opt('(') {
self.ws_cmt();
if self.tag_opt("forall") {
cnt += 1;
self.ws_cmt()
} else {
self.txen('(');
break;
}
} else {
break;
}
}
self.ws_cmt();
let body = self.sexpr().chain_err(|| "while parsing body")?;
(args, body)
} else if self.tag_opt("exists") {
self.ws_cmt();
let args = self.args().chain_err(|| "while parsing arguments")?;
self.ws_cmt();
let body = self.sexpr().chain_err(|| "while parsing body")?;
(args, body)
} else {
if cnt > 0 {
self.backtrack(Some('('));
cnt -= 1;
}
let body = self.sexpr().chain_err(|| "while parsing body")?;
(Vec::new(), body)
};
self.ws_cmt();
let body = if negated {
format!("(not {})", body)
} else {
body
};
while cnt > 0 {
self.char(')').chain_err(|| "closing qualifier")?;
self.ws_cmt();
cnt -= 1
}
if negated {
self.char(')').chain_err(|| "closing negation")?;
}
self.clauses.push(Clause { args, body });
Ok(true)
}
/// Parses anything.
fn parse_unknown(&mut self) -> Res<()> {
let mut s = "(".to_string();
let mut count = 1;
while let Some(char) = self.next() {
s.push(char);
match char {
')' => count -= 1,
'(' => count += 1,
_ => (),
}
if count == 0 {
self.backtrack(vec![')']);
self.unknown.push(s);
return Ok(());
}
}
error_chain::bail!("expected closing paren, found <eof>")
}
/// Parses an `smt2` file.
pub fn parse_input(mut self) -> Res<Input> {
self.ws_cmt();
while self.char_opt('(') {
self.ws_cmt();
if self.set_logic() ?
|| self.set_info() ?
|| self.set_option()?.is_some()
|| self.declare_fun() ?
// || self.define_fun() ?
|| self.assert() ?
|| self.tag_opt("check-sat")
|| self.tag_opt("get-model")
|| self.tag_opt("exit")
{
()
} else {
self.parse_unknown()?
// print!("> `") ;
// while let Some(next) = self.next() {
// if next != '\n' {
// print!("{}", next)
// } else {
// break
// }
// }
// println!("`") ;
// error_chain::bail!("expected item")
}
self.ws_cmt();
self.char(')').chain_err(|| "closing item")?;
self.ws_cmt()
}
if self.has_next() {
print!("> `");
while let Some(next) = self.next() {
if next != '\n' {
print!("{}", next)
} else {
break;
}
}
println!("`");
error_chain::bail!("could not parse the whole input file")
}
Ok(Input {
unknown: self.unknown,
pred_decs: self.pred_decs,
fun_defs: self.fun_defs,
clauses: self.clauses,
})
}
/// Define-fun.
fn define_pred(&mut self) -> Res<bool> {
if !self.tag_opt("define-fun") {
return Ok(false);
}
self.ws_cmt();
let name = self
.ident()
.chain_err(|| "while parsing predicate identifier")?;
self.ws_cmt();
let args = self.args().chain_err(|| "while parsing arguments")?;
self.ws_cmt();
let typ = self.sexpr()?;
self.ws_cmt();
let body = self.sexpr().chain_err(|| "while parsing body")?;
self.ws_cmt();
if typ == "|Bool|" {
self.pred_defs.push(PredDef {
pred: name,
args,
body: Some(body),
})
} else {
self.fun_defs.push(FunDef {
name,
args,
typ,
body,
})
}
Ok(true)
}
/// Parses an `smt2` file.
pub fn parse_output(mut self) -> Res<Output> {
if conf.check_eld {
self.ws_cmt();
self.tag_opt("Warning: ignoring get-model");
}
self.ws_cmt();
if self.tag_opt("sat") {
self.ws_cmt();
}
let error = "expected `(model (define-fun ...))`";
if !conf.check_eld {
self.char('(').chain_err(|| error)?;
self.ws_cmt();
self.tag("model").chain_err(|| error)?;
self.ws_cmt()
}
while self.char_opt('(') {
self.ws_cmt();
if self
.define_pred()
.chain_err(|| "while parsing a define-fun")?
{
()
} else {
print!("> `");
while let Some(next) = self.next() {
if next != '\n' {
print!("{}", next)
} else {
break;
}
}
println!("`");
error_chain::bail!("expected define-fun")
}
self.ws_cmt();
self.char(')').chain_err(|| "closing define-fun")?;
self.ws_cmt()
}
if !conf.check_eld {
self.char(')').chain_err(|| "closing model")?;
self.ws_cmt();
}
if self.has_next() {
print!("> `");
while let Some(next) = self.next() {
if next != '\n' {
print!("{}", next)
} else {
break;
}
}
println!("`");
error_chain::bail!("could not parse the whole output file")
}
Ok(Output {
pred_defs: self.pred_defs,
})
}
}
| 26.644372 | 91 | 0.389396 |
58a091139d0180b572c5804f007511c46bc56f9d | 851 | css | CSS | public/css/style.css | kongyay/VoiceFromYourHeart | 87d2f1fcd8503871ee4c85fdcb67f6f2e59384ab | [
"MIT"
] | null | null | null | public/css/style.css | kongyay/VoiceFromYourHeart | 87d2f1fcd8503871ee4c85fdcb67f6f2e59384ab | [
"MIT"
] | null | null | null | public/css/style.css | kongyay/VoiceFromYourHeart | 87d2f1fcd8503871ee4c85fdcb67f6f2e59384ab | [
"MIT"
] | null | null | null | html,
body {
overflow: hidden;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background-color: #FFF;
color: black;
font-family: 'Open Sans', sans-serif;
font-family: 'Kanit', sans-serif;
}
h1 {
in-height: 100%; /* Fallback for browsers do NOT support vh unit */
min-height: 100vh; /* These two lines are counted as one :-) */
display: flex;
align-items: center;
position: absolute;
justify-content: center;
flex-direction: column;
text-align: center;
width: 100%;
color: #222;
font-size: 18px;
opacity: 1;
}
#option {
font-size: 10px;
width: 100%;
position: absolute;
bottom: 2px;
text-align: center;
}
.btn {
font-size: 10px;
padding: 1px;
}
.vignette {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-shadow: 0 0 50px rgba(0,0,0,0.3) inset;
}
| 15.759259 | 71 | 0.616921 |
a33713d3fd164525c00a76d8a519d21c006da38d | 2,507 | java | Java | src/test/java/net/digitallogic/MatrixRotationTest.java | Digital-Logic/JavaInterviewQuestions | 9681fe33812d7e8c0c150cb84db9464a0fc4928f | [
"MIT"
] | null | null | null | src/test/java/net/digitallogic/MatrixRotationTest.java | Digital-Logic/JavaInterviewQuestions | 9681fe33812d7e8c0c150cb84db9464a0fc4928f | [
"MIT"
] | null | null | null | src/test/java/net/digitallogic/MatrixRotationTest.java | Digital-Logic/JavaInterviewQuestions | 9681fe33812d7e8c0c150cb84db9464a0fc4928f | [
"MIT"
] | null | null | null | package net.digitallogic;
import lombok.Value;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
class MatrixRotationTest {
@Test
void AtLestOneSolutionProvided() {
assertThat(
findTestMethods()
).describedAs("No solutions found to test.")
.hasAtLeastOneElementOfType(Method.class);
}
@TestFactory
Stream<DynamicNode> dynamicTests() {
return findTestMethods()
.map(m -> dynamicContainer(m.getName(),
testCases()
.map(args -> dynamicTest(args.getName(), () -> {
int[][] result = (int[][]) m.invoke(new MatrixRotation(), (Object) args.getGrid());
assertThat(result).isDeepEqualTo(args.getExpected());
}))
));
}
Stream<Method> findTestMethods() {
return Arrays.stream(MatrixRotation.class.getDeclaredMethods())
.filter(m -> Modifier.isPublic(m.getModifiers()))
.filter(m -> m.getAnnotation(Disabled.class) == null)
.filter(m -> {
Class<?>[] args = m.getParameterTypes();
return args.length == 1 &&
args[0] == int[][].class &&
m.getReturnType() == int[][].class;
});
}
Stream<Args> testCases() {
return Stream.of(
Args.of("2x2", new int[][]{{1,2},{3,4}}, new int[][]{{3,1},{4,2}}),
Args.of("3x3", new int[][]{{1,2,3},{4,5,6},{7,8,9}}, new int[][]{{7,4,1},{8,5,2},{9,6,3}}),
Args.of("4x4",
new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}},
new int[][]{{13,9,5,1},{14,10,6,2},{15,11,7,3},{16,12,8,4}}),
Args.of("5x5",
new int[][]{{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}},
new int[][]{{21,16,11,6,1},{22,17,12,7,2},{23,18,13,8,3},{24,19,14,9,4},{25,20,15,10,5}}
),
Args.of("6x6",
new int[][]{{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,32,33,34,35,36}},
new int[][]{{31,25,19,13,7,1},{32,26,20,14,8,2},{33,27,21,15,9,3},{34,28,22,16,10,4},{35,29,23,17,11,5},{36,30,24,18,12,6}})
);
}
@Value(staticConstructor = "of")
private static class Args {
String name;
int[][] grid;
int[][] expected;
}
} | 32.986842 | 128 | 0.631432 |
436b2fb5e70b742be20bb7f44f7334fff8a3eedc | 237 | ts | TypeScript | packages/app/src/config/hosts.ts | evertonlf9/monorepo-micro-front-end | fb3d2513f75a06c4c28aeacb67f7274ab6ec7de9 | [
"MIT"
] | null | null | null | packages/app/src/config/hosts.ts | evertonlf9/monorepo-micro-front-end | fb3d2513f75a06c4c28aeacb67f7274ab6ec7de9 | [
"MIT"
] | null | null | null | packages/app/src/config/hosts.ts | evertonlf9/monorepo-micro-front-end | fb3d2513f75a06c4c28aeacb67f7274ab6ec7de9 | [
"MIT"
] | null | null | null | interface Hosts {
starwars: string;
marvel: string;
myapp: string;
}
export default {
starwars: process.env.REACT_APP_MF_STAR_WARS,
marvel: process.env.REACT_APP_MF_MARVEL,
myapp: process.env.REACT_APP_MF_MYAPP,
} as Hosts;
| 19.75 | 47 | 0.755274 |
81505f43723262f1738ec0f8d1b3ca530077a941 | 391 | php | PHP | migrations/m180626_094739_add_affiliates_to_person.php | igor-bulygin/tdvs-gthb | 7e8e6d86382acfe33de154279963daf8e18fbc1e | [
"BSD-3-Clause"
] | null | null | null | migrations/m180626_094739_add_affiliates_to_person.php | igor-bulygin/tdvs-gthb | 7e8e6d86382acfe33de154279963daf8e18fbc1e | [
"BSD-3-Clause"
] | null | null | null | migrations/m180626_094739_add_affiliates_to_person.php | igor-bulygin/tdvs-gthb | 7e8e6d86382acfe33de154279963daf8e18fbc1e | [
"BSD-3-Clause"
] | null | null | null | <?php
class m180626_094739_add_affiliates_to_person extends \yii\mongodb\Migration
{
public function up()
{
$this->createIndex('person', 'affiliate_id');
$this->createIndex('person', 'parent_affiliate_id');
}
public function down()
{
$this->dropIndex('person', 'affiliate_id');
$this->dropIndex('person', 'parent_affiliate_id');
}
}
| 23 | 76 | 0.636829 |
c9c1e31c09372b69859779f18abd9ede075add2a | 4,779 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_1050.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_1050.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_1050.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x17e87, %rdi
nop
nop
nop
nop
xor %r11, %r11
and $0xffffffffffffffc0, %rdi
vmovaps (%rdi), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %r10
nop
and $3209, %rbp
lea addresses_A_ht+0xb087, %rsi
lea addresses_UC_ht+0x1da87, %rdi
nop
and $42828, %rax
mov $87, %rcx
rep movsq
nop
nop
nop
nop
nop
dec %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %r8
push %r9
push %rbx
push %rcx
push %rdx
// Store
lea addresses_D+0x24fd, %rcx
nop
nop
cmp %r13, %r13
mov $0x5152535455565758, %r9
movq %r9, (%rcx)
nop
nop
nop
and $13558, %r13
// Faulty Load
lea addresses_normal+0x5687, %r8
clflush (%r8)
add %r14, %r14
vmovups (%r8), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %rbx
lea oracles, %rcx
and $0xff, %rbx
shlq $12, %rbx
mov (%rcx,%rbx,1), %rbx
pop %rdx
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D', 'congruent': 1}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal', 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 11}}
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_A_ht'}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
| 48.765306 | 2,999 | 0.663109 |
32e6430d3f62795d2d4ef0164c069cedf24f9394 | 4,580 | rs | Rust | library/std/src/os/unix/ucred.rs | mbc-git/rust | 2c7bc5e33c25e29058cbafefe680da8d5e9220e9 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 66,762 | 2015-01-01T08:32:03.000Z | 2022-03-31T23:26:40.000Z | library/std/src/os/unix/ucred.rs | maxrovskyi/rust | 51558ccb8e7cea87c6d1c494abad5451e5759979 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 76,993 | 2015-01-01T00:06:33.000Z | 2022-03-31T23:59:15.000Z | library/std/src/os/unix/ucred.rs | maxrovskyi/rust | 51558ccb8e7cea87c6d1c494abad5451e5759979 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11,787 | 2015-01-01T00:01:19.000Z | 2022-03-31T19:03:42.000Z | //! Unix peer credentials.
// NOTE: Code in this file is heavily based on work done in PR 13 from the tokio-uds repository on
// GitHub.
//
// For reference, the link is here: https://github.com/tokio-rs/tokio-uds/pull/13
// Credit to Martin Habovštiak (GitHub username Kixunil) and contributors for this work.
use libc::{gid_t, pid_t, uid_t};
/// Credentials for a UNIX process for credentials passing.
#[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct UCred {
/// The UID part of the peer credential. This is the effective UID of the process at the domain
/// socket's endpoint.
pub uid: uid_t,
/// The GID part of the peer credential. This is the effective GID of the process at the domain
/// socket's endpoint.
pub gid: gid_t,
/// The PID part of the peer credential. This field is optional because the PID part of the
/// peer credentials is not supported on every platform. On platforms where the mechanism to
/// discover the PID exists, this field will be populated to the PID of the process at the
/// domain socket's endpoint. Otherwise, it will be set to None.
pub pid: Option<pid_t>,
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::impl_linux::peer_cred;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd"
))]
pub use self::impl_bsd::peer_cred;
#[cfg(any(target_os = "macos", target_os = "ios",))]
pub use self::impl_mac::peer_cred;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod impl_linux {
use super::UCred;
use crate::os::unix::io::AsRawFd;
use crate::os::unix::net::UnixStream;
use crate::{io, mem};
use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED};
pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
let ucred_size = mem::size_of::<ucred>();
// Trivial sanity checks.
assert!(mem::size_of::<u32>() <= mem::size_of::<usize>());
assert!(ucred_size <= u32::MAX as usize);
let mut ucred_size = ucred_size as socklen_t;
let mut ucred: ucred = ucred { pid: 1, uid: 1, gid: 1 };
unsafe {
let ret = getsockopt(
socket.as_raw_fd(),
SOL_SOCKET,
SO_PEERCRED,
&mut ucred as *mut ucred as *mut c_void,
&mut ucred_size,
);
if ret == 0 && ucred_size as usize == mem::size_of::<ucred>() {
Ok(UCred { uid: ucred.uid, gid: ucred.gid, pid: Some(ucred.pid) })
} else {
Err(io::Error::last_os_error())
}
}
}
}
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd"
))]
pub mod impl_bsd {
use super::UCred;
use crate::io;
use crate::os::unix::io::AsRawFd;
use crate::os::unix::net::UnixStream;
pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
let mut cred = UCred { uid: 1, gid: 1, pid: None };
unsafe {
let ret = libc::getpeereid(socket.as_raw_fd(), &mut cred.uid, &mut cred.gid);
if ret == 0 { Ok(cred) } else { Err(io::Error::last_os_error()) }
}
}
}
#[cfg(any(target_os = "macos", target_os = "ios",))]
pub mod impl_mac {
use super::UCred;
use crate::os::unix::io::AsRawFd;
use crate::os::unix::net::UnixStream;
use crate::{io, mem};
use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL};
pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
let mut cred = UCred { uid: 1, gid: 1, pid: None };
unsafe {
let ret = getpeereid(socket.as_raw_fd(), &mut cred.uid, &mut cred.gid);
if ret != 0 {
return Err(io::Error::last_os_error());
}
let mut pid: pid_t = 1;
let mut pid_size = mem::size_of::<pid_t>() as socklen_t;
let ret = getsockopt(
socket.as_raw_fd(),
SOL_LOCAL,
LOCAL_PEERPID,
&mut pid as *mut pid_t as *mut c_void,
&mut pid_size,
);
if ret == 0 && pid_size as usize == mem::size_of::<pid_t>() {
cred.pid = Some(pid);
Ok(cred)
} else {
Err(io::Error::last_os_error())
}
}
}
}
| 33.430657 | 99 | 0.577948 |
ff3b83c1bc4abab56af565c86089c90d17512e62 | 10,151 | py | Python | app.py | crazyzete/AppSecAssignment4 | a31da1f56f0b1211a643859de090ca180177cf73 | [
"MIT"
] | null | null | null | app.py | crazyzete/AppSecAssignment4 | a31da1f56f0b1211a643859de090ca180177cf73 | [
"MIT"
] | null | null | null | app.py | crazyzete/AppSecAssignment4 | a31da1f56f0b1211a643859de090ca180177cf73 | [
"MIT"
] | null | null | null | from flask import Flask, request, redirect, render_template, make_response, Response
from flask_login import LoginManager, login_user, login_required, logout_user, UserMixin, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField
from wtforms.validators import DataRequired
from flask_wtf.csrf import CSRFProtect
import secrets
import subprocess
import os
import datetime
from passlib.hash import sha256_crypt
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load Secrets
# Load App Key
secret_file = open("/run/secrets/spell_check_app_key", "r")
app.secret_key = secret_file.read().strip()
secret_file.close()
# Load Admin pword
secret_file = open("/run/secrets/spell_check_admin_password", "r")
admin_password = secret_file.read().strip()
secret_file.close()
# Load Admin 2fa
secret_file = open("/run/secrets/spell_check_admin_2fa", "r")
admin_2fa = secret_file.read().strip()
secret_file.close()
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///theDB.db'
csrf = CSRFProtect(app)
db = SQLAlchemy()
class User(UserMixin, db.Model):
"""Model for user accounts."""
__tablename__ = 'users'
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
uname = db.Column(db.String(25), nullable=False, unique=True)
pword = db.Column(db.String(80), nullable=False)
twofa = db.Column(db.String(25))
isAdmin = db.Column(db.Boolean, nullable=False)
def __init__(self, uname, pword, twofa):
self.uname = uname
self.pword = pword
self.twofa = twofa
def getPassword(self):
return self.pword
def get2FA(self):
return self.twofa
def getUname(self):
return self.uname
def get_id(self):
return self.getUname()
# I'm not including a seperate SALT, the project requirements do not specify it. I am using passlib which generates
# a hash including the salt and automatically handles that part.
def __repr__(self):
return '<User {}>'.format(self.username)
class LoginRecord(db.Model):
__tablename__ = 'login_records'
record_number = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False)
log_on = db.Column(db.DateTime, nullable=False)
log_off = db.Column(db.DateTime, nullable=True)
user = db.relationship(User)
class QueryRecord(db.Model):
__tablename__ = 'query_records'
record_number = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False)
query_text = db.Column(db.Text, nullable=True)
query_result = db.Column(db.Text, nullable=True)
time = db.Column(db.DateTime, nullable=False)
user = db.relationship(User)
@login_manager.user_loader
def load_user(id):
existing_user = User.query.filter_by(uname=id).first()
return existing_user
with app.app_context():
db.init_app(app)
db.create_all()
if not load_user('admin'):
adminUser = User('admin', sha256_crypt.hash(admin_password), admin_2fa)
adminUser.isAdmin = True
db.session.add(adminUser)
db.session.commit()
class UserForm(FlaskForm):
uname = StringField('User Name:', validators=[DataRequired()])
pword = StringField('Password: ', validators=[DataRequired()])
twofa = StringField('2FA Token:', validators=[], id='2fa')
def addUser(uname, pword, twofa):
user = User(uname, sha256_crypt.hash(pword), twofa)
user.isAdmin = False
db.session.add(user)
db.session.commit()
def passwordMatch(user, pword):
if sha256_crypt.verify(pword, user.getPassword()):
return True
else:
return False
def twofaMatch(user, twofa):
if user.get2FA() == twofa:
return True
else:
return False
def addLogonRecord(uname):
record = LoginRecord()
record.user_id = uname
record.log_on = datetime.datetime.utcnow()
db.session.add(record)
db.session.commit()
def updateLogonRecordAtLogoff(uname):
earliestLogin = LoginRecord.query.filter_by(user_id=uname, log_off=None).order_by(LoginRecord.log_on).first()
earliestLogin.log_off = datetime.datetime.utcnow()
db.session.add(earliestLogin)
db.session.commit()
def addQueryRecord(querytext, queryresult):
query = QueryRecord()
query.user_id = current_user.getUname()
query.query_text = querytext
query.query_result = queryresult
query.time = datetime.datetime.utcnow()
db.session.add(query)
db.session.commit()
def secureResponse(render):
response = make_response(render)
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Content-Security-Policy'] = "default-src '127.0.0.1:5000'"
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
return response
@app.errorhandler(404)
def not_found(e):
return secureResponse(render_template("PageNotFound.html"))
@app.route('/register', methods=('GET', 'POST'))
def register():
form = UserForm()
if form.validate_on_submit():
# return redirect('/success')
user = form.uname.data
pword = form.pword.data
twofa = form.twofa.data
if (load_user(user)) or (not user) or (not pword):
return secureResponse(render_template('registrationResult.html', success="Failure"))
else:
addUser(user, pword, twofa)
return secureResponse(render_template('registrationResult.html', success="Success"))
return secureResponse(render_template('registerForm.html', form=form))
@app.route('/login', methods=('GET', 'POST'))
def login():
form = UserForm()
if form.validate_on_submit():
# return redirect('/success')
global userDict
user = form.uname.data
pword = form.pword.data
twofa = form.twofa.data
theUser = load_user(user)
if theUser:
if passwordMatch(theUser, pword):
if twofaMatch(theUser, twofa):
login_user(theUser, remember=True)
addLogonRecord(theUser.uname)
return secureResponse(render_template('loginResult.html', result="Success"))
else:
return secureResponse(render_template('loginResult.html', result="Two-factor Failure"))
else:
return secureResponse(render_template('loginResult.html', result="Incorrect"))
else:
return secureResponse(render_template('loginResult.html', result="Incorrect"))
return secureResponse(render_template('userLoginForm.html', form=form))
@app.route('/logout')
def logout():
if current_user.is_authenticated:
updateLogonRecordAtLogoff(current_user.getUname())
logout_user()
return redirect('/login')
class AdminHistoryForm(FlaskForm):
userquery = StringField('Username to Query:', validators=[DataRequired()])
@app.route('/history/query<int:query_number>')
@login_required
def queryReview(query_number):
record = QueryRecord.query.filter_by(record_number=query_number).first()
if record is None:
return secureResponse(render_template('QueryNotFound.html'))
elif current_user.isAdmin or (record.user_id == current_user.getUname()):
return secureResponse(render_template('queryReview.html', query_number=record.record_number, uname=record.user_id,
text=record.query_text, results=record.query_result))
else:
return secureResponse(render_template('QueryNotAuthorized.html'))
@app.route('/history', methods=('GET', 'POST'))
@login_required
def history():
form = AdminHistoryForm()
uname = current_user.getUname()
if current_user.isAdmin and form.validate_on_submit():
uname = form.userquery.data
elif current_user.isAdmin:
return secureResponse(render_template('historyAdminForm.html', form=form))
results = QueryRecord.query.filter_by(user_id=uname).order_by(QueryRecord.record_number)
return secureResponse(render_template('recordResults.html', records=results, count=results.count()))
@app.route('/login_history', methods=('GET', 'POST'))
@login_required
def login_history():
form = AdminHistoryForm()
if current_user.is_anonymous:
return secureResponse(render_template('QueryNotAuthorized.html'))
else:
uname = current_user.getUname()
if current_user.isAdmin and form.validate_on_submit():
results = LoginRecord.query.filter_by(user_id=form.userquery.data).order_by(LoginRecord.record_number)
return secureResponse(render_template('loginHistory.html', records=results))
elif current_user.isAdmin:
return secureResponse(render_template('loginHistoryForm.html', form=form))
else:
return secureResponse(render_template('QueryNotAuthorized.html'))
class spellCheckForm(FlaskForm):
inputtext = TextAreaField(u'Text to Check', [DataRequired()], render_kw={"rows": 40, "cols": 100})
@app.route('/spell_check', methods=('GET', 'POST'))
@login_required
def spellcheck():
form = spellCheckForm()
if form.validate_on_submit():
# return redirect('/success')
text = form.inputtext.data
f = open("tempUserInput", "w")
f.write(text)
f.close()
process = subprocess.run(['./a.out', 'tempUserInput', 'wordlist.txt'], check=True, stdout=subprocess.PIPE,
universal_newlines=True)
output = process.stdout
os.remove("tempUserInput")
misspelledOut = output.replace("\n", ", ").strip().strip(',')
addQueryRecord(text, misspelledOut)
return secureResponse(render_template('spellCheckResult.html', misspelled=misspelledOut, textout=text))
else:
return secureResponse(render_template('spellCheckForm.html', form=form))
if __name__ == '__main__':
app.run(debug=True)
| 31.821317 | 122 | 0.692149 |
be3922d18c6120c11563e6101f16589df23b4c90 | 1,483 | ts | TypeScript | src/ts/tool/shapeStroke.ts | wjheesen/vector-art | d73729c1b0ee236fe9d45a879e5e83cb00e245a0 | [
"MIT"
] | null | null | null | src/ts/tool/shapeStroke.ts | wjheesen/vector-art | d73729c1b0ee236fe9d45a879e5e83cb00e245a0 | [
"MIT"
] | null | null | null | src/ts/tool/shapeStroke.ts | wjheesen/vector-art | d73729c1b0ee236fe9d45a879e5e83cb00e245a0 | [
"MIT"
] | null | null | null | import { MouseOrTouchEvent } from '../event/mouseOrTouch';
import { Surface } from '../rendering/surface';
import { Status } from 'gl2d/event/status';
import { Point } from 'gl2d/struct/point';
import { MouseOrTouchTool } from 'gl2d/tool/mouseOrTouch';
export class ShapeStrokeTool extends MouseOrTouchTool<Surface> {
private previous: Point;
onSurfaceEvent(event: MouseOrTouchEvent): void {
switch(event.status){
case Status.Start:
return this.onStart(event);
case Status.Drag:
return this.onDrag(event);
case Status.End:
return this.onEnd(event);
}
}
onStart(event: MouseOrTouchEvent) {
this.previous = this.getPrimaryPointer(event);
}
onDrag(event: MouseOrTouchEvent) {
if(!this.previous) { return; }
let surface = event.target;
let stroke = surface.getTempShapeBatch();
let thickness = surface.lineWidth;
let current = this.getPrimaryPointer(event);
let previous = this.previous;
// Add line from current to previous shape if there is room
if(current.distance2(previous) > thickness * thickness){
this.previous = stroke.addLine(previous, current, thickness);
surface.requestRender();
}
}
onEnd(event: MouseOrTouchEvent) {
let surface = event.target;
surface.addTempShapeBatch();
surface.requestRender();
}
} | 31.553191 | 73 | 0.626433 |
019a8d22bc0493010a4cf929142fde4b7dff5090 | 1,259 | asm | Assembly | dv3/qlsd/1sec.asm | olifink/smsqe | c546d882b26566a46d71820d1539bed9ea8af108 | [
"BSD-2-Clause"
] | null | null | null | dv3/qlsd/1sec.asm | olifink/smsqe | c546d882b26566a46d71820d1539bed9ea8af108 | [
"BSD-2-Clause"
] | null | null | null | dv3/qlsd/1sec.asm | olifink/smsqe | c546d882b26566a46d71820d1539bed9ea8af108 | [
"BSD-2-Clause"
] | null | null | null | ; QLSD 1 second loop timer 1999 Tony Tebby
section dv3
xdef qlsd_1sec
include 'dev8_keys_sys'
include 'dev8_keys_qlhw'
include 'dev8_keys_qdos_sms'
include 'dev8_dv3_qlsd_keys'
;+++
; Set up 1 second loop timer
;
; d0 r 1 second timer
;
;---
qlsd.1sec reg d5/d6/d7/a0/a5
qlsd_1sec
movem.l qlsd.1sec,-(sp)
move.w sr,d7
moveq #sms.info,d0
trap #1
trap #0
ori.w #$0700,sr ; disable interrupts for this
lea if_base+spi_read,a5 ; address of QLSD read register
moveq #2,d6
sd1s_wait
moveq #pc.intrf,d0
and.b pc_intr,d0 ; frame interrupt?
beq.s sd1s_wait ; ... no
or.b sys_qlir(a0),d0 ; clear interrupt flag value
move.b d0,pc_intr ; clear interrupt bit
subq.w #1,d6 ; make sure it is genuine
bgt.s sd1s_wait
sd1s_count
move.l #4096/50,d5 ; dummy (large) counter
moveq #0,d0
sd1s_loop
and.b (a5),d0
bne.s sd1s_loop ; never true
subq.l #1,d5
bgt.s sd1s_loop ; time-out loop
addq.l #1,d6
moveq #pc.intrf,d0
and.b pc_intr,d0 ; frame interrupt?
beq.s sd1s_count ; ... no
or.b sys_qlir(a0),d0 ; clear interrupt flag value
move.b d0,pc_intr ; clear interrupt bit
lsl.l #8,d6 ; multiply loop timer by 4096
lsl.l #4,d6
move.l d6,d0
move.w d7,sr
movem.l (sp)+,qlsd.1sec
rts
end
| 18.791045 | 57 | 0.677522 |
944c14e902127faa07a787e5c3c04d319c6b159f | 1,111 | lua | Lua | WIP/Set/Negation.spec.lua | Novaly-Studios/TableUtil | c9ed2ed3b7f4a43947f6d539f0f1cff0774260ee | [
"MIT"
] | null | null | null | WIP/Set/Negation.spec.lua | Novaly-Studios/TableUtil | c9ed2ed3b7f4a43947f6d539f0f1cff0774260ee | [
"MIT"
] | null | null | null | WIP/Set/Negation.spec.lua | Novaly-Studios/TableUtil | c9ed2ed3b7f4a43947f6d539f0f1cff0774260ee | [
"MIT"
] | null | null | null | return function()
local Negation = require(script.Parent.Negation)
local FromValues = require(script.Parent.FromValues)
describe("Set/Negation", function()
it("should return a blank set from two blank set inputs", function()
local Result = Negation(FromValues( {} ), FromValues( {} ))
expect(next(Result)).never.to.be.ok()
end)
it("should remove the latter from the former with one item", function()
local Result = Negation(FromValues( {1} ), FromValues( {1} ))
expect(next(Result)).never.to.be.ok()
end)
it("should remove the latter from the former with multiple items", function()
local Result = Negation(FromValues( {1, 4, 8} ), FromValues( {4, 8, 1} ))
expect(next(Result)).never.to.be.ok()
end)
it("should remove the latter from the former with multiple items and leave non-negated present", function()
local Result = Negation(FromValues( {1, 4, 8, 2} ), FromValues( {4, 8, 1} ))
expect(Result[2]).to.equal(true)
end)
end)
end | 42.730769 | 115 | 0.605761 |
6dd1375e60146a50ad53a11bfe29e9ae6b88570a | 83 | h | C | netbsd/sys/arch/mvmeppc/include/fpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/arch/mvmeppc/include/fpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/arch/mvmeppc/include/fpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: fpu.h,v 1.1 2002/02/27 21:02:15 scw Exp $ */
#include <powerpc/fpu.h>
| 20.75 | 56 | 0.614458 |
e07fec80deb3194634d05734f5d449ec357ce1bd | 1,298 | h | C | src/common/AsioServicePool.h | cmstest/buzz-ftpd | cd0440acbdc2ee555a76b629c65fbd522b65446d | [
"BSD-3-Clause"
] | 1 | 2022-03-02T21:17:31.000Z | 2022-03-02T21:17:31.000Z | src/common/AsioServicePool.h | cmstest/buzz-ftpd | cd0440acbdc2ee555a76b629c65fbd522b65446d | [
"BSD-3-Clause"
] | null | null | null | src/common/AsioServicePool.h | cmstest/buzz-ftpd | cd0440acbdc2ee555a76b629c65fbd522b65446d | [
"BSD-3-Clause"
] | null | null | null | //
// AsioServicePool.h - part of buzz-ftpd
// Copyright (c) 2011, cxxjoe
// Please refer to the LICENSE file for details.
//
// Based on:
// io_service_pool.hpp
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
#ifndef _ASIO_SERVICE_POOL_H
#define _ASIO_SERVICE_POOL_H
#include "buzzconfig.h"
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <vector>
/**
* Provides a pool of io_service objects.
**/
class CAsioServicePool :
private boost::noncopyable
{
public:
CAsioServicePool(size_t a_poolSize);
// Starts all io_services in the pool and blocks until stopped:
void Run();
// Stops all io_services in the pool:
void Stop();
// Returns a ready-to-use io_service:
boost::asio::io_service& GetIOService();
protected:
typedef boost::shared_ptr<boost::asio::io_service> PIOService;
typedef boost::shared_ptr<boost::asio::io_service::work> PIOWork;
// The pool of io_services:
std::vector<PIOService> m_ioServices;
// The work that keeps the io_services alive:
std::vector<PIOWork> m_ioWork;
// Index of the next io_service that GetIOService returns:
size_t m_nextIndex;
};
typedef boost::shared_ptr<CAsioServicePool> PAsioServicePool;
#endif /* !_ASIO_SERVICE_POOL_H */
| 23.6 | 78 | 0.735747 |
7bf9cbe1cbc9f4fa673a7b264adb680247c22f70 | 220 | rb | Ruby | spec/redistry_spec.rb | Lytol/redistry | e55aa1d2195cb690ba0c75f2eb30224416033a91 | [
"MIT"
] | 1 | 2016-09-24T07:21:54.000Z | 2016-09-24T07:21:54.000Z | spec/redistry_spec.rb | Lytol/redistry | e55aa1d2195cb690ba0c75f2eb30224416033a91 | [
"MIT"
] | null | null | null | spec/redistry_spec.rb | Lytol/redistry | e55aa1d2195cb690ba0c75f2eb30224416033a91 | [
"MIT"
] | null | null | null | require 'spec_helper'
describe Redistry do
it "should have VERSION" do
Redistry::VERSION.should =~ /^\d+\.\d+\.\d+$/
end
it "should have default client" do
Redistry.client.class.should == Redis
end
end
| 18.333333 | 49 | 0.668182 |
4fb27b2a752ebc76f1e9344236d51ddc3f3162be | 154 | rb | Ruby | config/environment.rb | viitoo/Beatstream | 601c88e15d805cbd3cd82051a601f32d9a8ce744 | [
"Unlicense"
] | 72 | 2015-01-18T06:48:39.000Z | 2021-12-28T16:52:01.000Z | config/environment.rb | viitoo/Beatstream | 601c88e15d805cbd3cd82051a601f32d9a8ce744 | [
"Unlicense"
] | 7 | 2015-05-16T18:05:38.000Z | 2016-10-28T12:55:26.000Z | config/environment.rb | viitoo/Beatstream | 601c88e15d805cbd3cd82051a601f32d9a8ce744 | [
"Unlicense"
] | 34 | 2015-01-18T05:31:19.000Z | 2020-07-23T05:03:02.000Z | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Beatstream::Application.initialize!
| 25.666667 | 52 | 0.805195 |
f64e1d74027d448ea856d893613a9544aa81cacb | 46,045 | cpp | C++ | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HISE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace hise { using namespace juce;
JavascriptMidiProcessor::JavascriptMidiProcessor(MainController *mc, const String &id) :
ScriptBaseMidiProcessor(mc, id),
JavascriptProcessor(mc),
onInitCallback(new SnippetDocument("onInit")),
onNoteOnCallback(new SnippetDocument("onNoteOn")),
onNoteOffCallback(new SnippetDocument("onNoteOff")),
onControllerCallback(new SnippetDocument("onController")),
onTimerCallback(new SnippetDocument("onTimer")),
onControlCallback(new SnippetDocument("onControl", "number value")),
front(false),
deferred(false),
deferredExecutioner(this),
deferredUpdatePending(false)
{
initContent();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onTimerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
setEditorState(Identifier("contentShown"), true);
setEditorState(Identifier("onInitOpen"), true);
}
JavascriptMidiProcessor::~JavascriptMidiProcessor()
{
cleanupEngine();
clearExternalWindows();
serverObject = nullptr;
onInitCallback = nullptr;
onNoteOnCallback = nullptr;
onNoteOffCallback = nullptr;
onControllerCallback = nullptr;
onTimerCallback = nullptr;
onControlCallback = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMidiProcessor::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ValueTree JavascriptMidiProcessor::exportAsValueTree() const
{
ValueTree v = ScriptBaseMidiProcessor::exportAsValueTree();
saveScript(v);
return v;
}
void JavascriptMidiProcessor::restoreFromValueTree(const ValueTree &v)
{
restoreScript(v);
ScriptBaseMidiProcessor::restoreFromValueTree(v);
}
JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c)
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
const JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c) const
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
ProcessorEditorBody *JavascriptMidiProcessor::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
};
void JavascriptMidiProcessor::processHiseEvent(HiseEvent &m)
{
if (isDeferred())
{
deferredExecutioner.addPendingEvent(m);
}
else
{
ADD_GLITCH_DETECTOR(this, DebugLogger::Location::ScriptMidiEventCallback);
if (currentMidiMessage != nullptr)
{
ScopedValueSetter<HiseEvent*> svs(currentEvent, &m);
currentMidiMessage->setHiseEvent(m);
runScriptCallbacks();
}
}
}
void JavascriptMidiProcessor::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
front = false;
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), getOwnerSynth());
scriptEngine->registerApiClass(new ScriptingApi::ModuleIds(getOwnerSynth()));
samplerObject = new ScriptingApi::Sampler(this, dynamic_cast<ModulatorSampler*>(getOwnerSynth()));
scriptEngine->registerNativeObject("Content", getScriptingContent());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(serverObject = new ScriptingApi::Server(this));
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Colours());
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerApiClass(samplerObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMidiProcessor::addToFront(bool addToFront_) noexcept
{
front = addToFront_;
#if USE_FRONTEND
content->getUpdateDispatcher()->suspendUpdates(false);
#endif
}
void JavascriptMidiProcessor::runScriptCallbacks()
{
if (currentEvent->isAllNotesOff())
{
synthObject->handleNoteCounter(*currentEvent);
// All notes off are controller message, so they should not be processed, or it can lead to loop.
currentMidiMessage->onAllNotesOff();
return;
}
#if ENABLE_SCRIPTING_BREAKPOINTS
breakpointWasHit(-1);
#endif
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.03);
synthObject->handleNoteCounter(*currentEvent);
switch (currentEvent->getType())
{
case HiseEvent::Type::NoteOn:
{
if (onNoteOnCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::NoteOff:
{
if (onNoteOffCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::Controller:
case HiseEvent::Type::PitchBend:
case HiseEvent::Type::Aftertouch:
case HiseEvent::Type::ProgramChange:
{
if (currentEvent->isControllerOfType(64))
{
synthObject->setSustainPedal(currentEvent->getControllerValue() > 64);
}
if (onControllerCallback->isSnippetEmpty()) return;
Result r = Result::ok();
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::TimerEvent:
{
if (!currentEvent->isIgnored() && currentEvent->getChannel() == getIndexInChain())
{
runTimerCallback(currentEvent->getTimeStamp());
currentEvent->ignoreEvent(true);
}
break;
}
case HiseEvent::Type::AllNotesOff:
{
break;
}
case HiseEvent::Type::Empty:
case HiseEvent::Type::SongPosition:
case HiseEvent::Type::MidiStart:
case HiseEvent::Type::MidiStop:
case HiseEvent::Type::VolumeFade:
case HiseEvent::Type::PitchFade:
case HiseEvent::Type::numTypes:
break;
}
#if 0
else if (currentEvent->isSongPositionPointer())
{
Result r = Result::ok();
static const Identifier onClock("onClock");
var args = currentEvent->getSongPositionPointerMidiBeat();
scriptEngine->callInlineFunction(onClock, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
if (!r.wasOk()) debugError(this, r.getErrorMessage());
}
else if (currentEvent->isMidiStart() || currentEvent->isMidiStop())
{
Result r = Result::ok();
static const Identifier onTransport("onTransport");
var args = currentEvent->isMidiStart();
scriptEngine->callInlineFunction(onTransport, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
}
#endif
}
void JavascriptMidiProcessor::runTimerCallback(int /*offsetInBuffer*//*=-1*/)
{
if (isBypassed() || onTimerCallback->isSnippetEmpty()) return;
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.002);
if (lastResult.failed()) return;
scriptEngine->executeCallback(onTimer, &lastResult);
if (isDeferred())
{
sendSynchronousChangeMessage();
}
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
void JavascriptMidiProcessor::deferCallbacks(bool addToFront_)
{
deferred = addToFront_;
if (deferred)
{
getOwnerSynth()->stopSynthTimer(getIndexInChain());
}
else
{
stopTimer();
}
};
StringArray JavascriptMidiProcessor::getImageFileNames() const
{
jassert(isFront());
StringArray fileNames;
for (int i = 0; i < content->getNumComponents(); i++)
{
const ScriptingApi::Content::ScriptImage *image = dynamic_cast<const ScriptingApi::Content::ScriptImage*>(content->getComponent(i));
if (image != nullptr) fileNames.add(image->getScriptObjectProperty(ScriptingApi::Content::ScriptImage::FileName));
}
return fileNames;
}
JavascriptPolyphonicEffect::JavascriptPolyphonicEffect(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceEffectProcessor(mc, id, numVoices),
onInitCallback(new SnippetDocument("onInit")),
onControlCallback(new SnippetDocument("onControl"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptPolyphonicEffect::~JavascriptPolyphonicEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
juce::Path JavascriptPolyphonicEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptPolyphonicEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptPolyphonicEffect::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptPolyphonicEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptPolyphonicEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
VoiceEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
if (sampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
auto numChannels = dynamic_cast<RoutableProcessor*>(getParentProcessor(true))->getMatrix().getNumSourceChannels();
n->setNumChannels(numChannels);
n->prepareToPlay(sampleRate, (double)samplesPerBlock);
}
}
void JavascriptPolyphonicEffect::renderVoice(int voiceIndex, AudioSampleBuffer &b, int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
float* channels[NUM_MAX_CHANNELS];
int numChannels = b.getNumChannels();
memcpy(channels, b.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
scriptnode::DspNetwork::VoiceSetter vs(*n, voiceIndex);
n->getRootNode()->process(d);
}
}
void JavascriptPolyphonicEffect::startVoice(int voiceIndex, const HiseEvent& e)
{
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, e);
}
}
void JavascriptPolyphonicEffect::reset(int voiceIndex)
{
voiceData.reset(voiceIndex);
}
void JavascriptPolyphonicEffect::handleHiseEvent(const HiseEvent &m)
{
if (m.isNoteOn())
return;
HiseEvent c(m);
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
JavascriptMasterEffect::JavascriptMasterEffect(MainController *mc, const String &id):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
MasterEffectProcessor(mc, id),
onInitCallback(new SnippetDocument("onInit")),
prepareToPlayCallback(new SnippetDocument("prepareToPlay", "sampleRate blockSize")),
processBlockCallback(new SnippetDocument("processBlock", "channels")),
onControlCallback(new SnippetDocument("onControl", "number value"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
getMatrix().setNumAllowedConnections(NUM_MAX_CHANNELS);
for (int i = 0; i < NUM_MAX_CHANNELS; i++)
{
buffers[i] = new VariantBuffer(0);
}
channels.ensureStorageAllocated(16);
channelIndexes.ensureStorageAllocated(16);
channelData = var(channels);
connectionChanged();
}
JavascriptMasterEffect::~JavascriptMasterEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMasterEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
void JavascriptMasterEffect::connectionChanged()
{
channels.clear();
channelIndexes.clear();
for (int i = 0; i < getMatrix().getNumSourceChannels(); i++)
{
if (getMatrix().getConnectionForSourceChannel(i) >= 0)
{
channels.add(buffers[channelIndexes.size()]);
channelIndexes.add(i);
}
}
auto numChannels = channels.size();
for (auto n : networks)
{
n->setNumChannels(numChannels);
}
channelData = var(channels);
}
ProcessorEditorBody * JavascriptMasterEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptMasterEffect::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMasterEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptMasterEffect::voicesKilled()
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
bool JavascriptMasterEffect::hasTail() const
{
if (auto n = getActiveNetwork())
{
return n->hasTail();
}
return false;
}
void JavascriptMasterEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
MasterEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
connectionChanged();
if (getActiveNetwork() != nullptr)
getActiveNetwork()->prepareToPlay(sampleRate, samplesPerBlock);
if (!prepareToPlayCallback->isSnippetEmpty() && lastResult.wasOk())
{
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 0, sampleRate);
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 1, samplesPerBlock);
scriptEngine->executeCallback((int)Callback::prepareToPlay, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::renderWholeBuffer(AudioSampleBuffer &buffer)
{
if (channelIndexes.size() == 2)
{
MasterEffectProcessor::renderWholeBuffer(buffer);
}
else
{
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(buffer, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
const int numSamples = buffer.getNumSamples();
jassert(channelIndexes.size() == channels.size());
for (int i = 0; i < channelIndexes.size(); i++)
{
float* d = buffer.getWritePointer(channelIndexes[i], 0);
CHECK_AND_LOG_BUFFER_DATA(this, DebugLogger::Location::ScriptFXRendering, d, true, numSamples);
auto b = channels[i].getBuffer();
if (b != nullptr)
b->referToData(d, numSamples);
}
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
}
void JavascriptMasterEffect::applyEffect(AudioSampleBuffer &b, int startSample, int numSamples)
{
ignoreUnused(startSample);
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(b, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
jassert(startSample == 0);
CHECK_AND_LOG_ASSERTION(this, DebugLogger::Location::ScriptFXRendering, startSample == 0, startSample);
float *l = b.getWritePointer(0, 0);
float *r = b.getWritePointer(1, 0);
if (auto lb = channels[0].getBuffer())
lb->referToData(l, numSamples);
if (auto rb = channels[1].getBuffer())
rb->referToData(r, numSamples);
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::setBypassed(bool shouldBeBypassed, NotificationType notifyChangeHandler) noexcept
{
MasterEffectProcessor::setBypassed(shouldBeBypassed, notifyChangeHandler);
if (!shouldBeBypassed)
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
}
JavascriptVoiceStartModulator::JavascriptVoiceStartModulator(MainController *mc, const String &id, int voiceAmount, Modulation::Mode m) :
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceStartModulator(mc, id, voiceAmount, m),
Modulation(m)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onVoiceStartCallback = new SnippetDocument("onVoiceStart", "voiceIndex");
onVoiceStopCallback = new SnippetDocument("onVoiceStop", "voiceIndex");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onVoiceStartOpen");
editorStateIdentifiers.add("onVoiceStopOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptVoiceStartModulator::~JavascriptVoiceStartModulator()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptVoiceStartModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptVoiceStartModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptVoiceStartModulator::handleHiseEvent(const HiseEvent& m)
{
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOff())
{
if (!onVoiceStopCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(onVoiceStop, 0, 0);
scriptEngine->executeCallback(onVoiceStop, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
float JavascriptVoiceStartModulator::startVoice(int voiceIndex)
{
if (!onVoiceStartCallback->isSnippetEmpty())
{
synthObject->setVoiceGainValue(voiceIndex, 1.0f);
synthObject->setVoicePitchValue(voiceIndex, 1.0f);
scriptEngine->setCallbackParameter(onVoiceStart, 0, voiceIndex);
unsavedValue = (float)scriptEngine->executeCallback(onVoiceStart, &lastResult);
}
return VoiceStartModulator::startVoice(voiceIndex);
}
JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptVoiceStartModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
}
JavascriptTimeVariantModulator::JavascriptTimeVariantModulator(MainController *mc, const String &id, Modulation::Mode m) :
TimeVariantModulator(mc, id, m),
Modulation(m),
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
buffer(new VariantBuffer(0))
{
initContent();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptTimeVariantModulator::~JavascriptTimeVariantModulator()
{
clearExternalWindows();
cleanupEngine();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
bufferVar = var::undefined();
buffer = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptTimeVariantModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptTimeVariantModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptTimeVariantModulator::handleHiseEvent(const HiseEvent &m)
{
if (auto n = getActiveNetwork())
{
HiseEvent c(m);
n->getRootNode()->handleHiseEvent(c);
}
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOn())
{
if (!onNoteOnCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isNoteOff())
{
if (!onNoteOffCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
TimeVariantModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
if(internalBuffer.getNumChannels() > 0)
buffer->referToData(internalBuffer.getWritePointer(0), samplesPerBlock);
bufferVar = var(buffer.get());
if (!prepareToPlayCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(Callback::prepare, 0, sampleRate);
scriptEngine->setCallbackParameter(Callback::prepare, 1, samplesPerBlock);
scriptEngine->executeCallback(Callback::prepare, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
auto ptr = internalBuffer.getWritePointer(0, startSample);
FloatVectorOperations::clear(ptr, numSamples);
snex::Types::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
FloatVectorOperations::clip(ptr, ptr, 0.0f, 1.0f, numSamples);
}
else if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
buffer->referToData(internalBuffer.getWritePointer(0, startSample), numSamples);
scriptEngine->setCallbackParameter(Callback::processBlock, 0, bufferVar);
scriptEngine->executeCallback(Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
JavascriptProcessor::SnippetDocument* JavascriptTimeVariantModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptTimeVariantModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptTimeVariantModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptTimeVariantModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptEnvelopeModulator::JavascriptEnvelopeModulator(MainController *mc, const String &id, int numVoices, Modulation::Mode m):
ProcessorWithScriptingContent(mc),
JavascriptProcessor(mc),
EnvelopeModulator(mc, id, numVoices, m),
Modulation(m)
{
setVoiceKillerToUse(this);
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
for (int i = 0; i < polyManager.getVoiceAmount(); i++) states.add(createSubclassedState(i));
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptEnvelopeModulator::~JavascriptEnvelopeModulator()
{
cleanupEngine();
clearExternalWindows();
}
Path JavascriptEnvelopeModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
int JavascriptEnvelopeModulator::getNumActiveVoices() const
{
int counter = 0;
for (int i = 0; i < polyManager.getVoiceAmount(); i++)
{
if (auto ses = static_cast<ScriptEnvelopeState*>(states[i]))
{
if (ses->isPlaying)
counter++;
}
}
return counter;
}
ProcessorEditorBody * JavascriptEnvelopeModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptEnvelopeModulator::handleHiseEvent(const HiseEvent &m)
{
currentMidiMessage->setHiseEvent(m);
if (m.isNoteOn())
lastNoteOn = m;
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
void JavascriptEnvelopeModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
EnvelopeModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
}
void JavascriptEnvelopeModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
scriptnode::DspNetwork::VoiceSetter vs(*n, polyManager.getCurrentVoice());
float* ptr = internalBuffer.getWritePointer(0, startSample);
memset(ptr, 0, sizeof(float)*numSamples);
scriptnode::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
float JavascriptEnvelopeModulator::startVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = true;
state->isRingingOff = false;
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, lastNoteOn);
}
return 0.0f;
}
void JavascriptEnvelopeModulator::stopVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->isRingingOff = true;
}
void JavascriptEnvelopeModulator::reset(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = false;
state->isRingingOff = false;
voiceData.reset(voiceIndex);
}
bool JavascriptEnvelopeModulator::isPlaying(int voiceIndex) const
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
return state->isPlaying;
}
JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c)
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c) const
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
void JavascriptEnvelopeModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptEnvelopeModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptSynthesiser::JavascriptSynthesiser(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
ModulatorSynth(mc, id, numVoices)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
modChains += { this, "Extra1" };
modChains += { this, "Extra2" };
finaliseModChains();
modChains[Extra1].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra1].setExpandToAudioRate(false);
modChains[Extra2].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra2].setExpandToAudioRate(false);
modChains[Extra1].getChain()->setColour(Colour(0xFF888888));
modChains[Extra2].getChain()->setColour(Colour(0xFF888888));
for (int i = 0; i < numVoices; i++)
{
addVoice(new Voice(this));
}
addSound(new Sound());
}
JavascriptSynthesiser::~JavascriptSynthesiser()
{
}
juce::Path JavascriptSynthesiser::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptSynthesiser::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptSynthesiser::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptSynthesiser::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptSynthesiser::preHiseEventCallback(HiseEvent &e)
{
ModulatorSynth::preHiseEventCallback(e);
if (e.isNoteOn())
return; // will be handled by preStartVoice
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), e);
}
}
void JavascriptSynthesiser::preStartVoice(int voiceIndex, const HiseEvent& e)
{
ModulatorSynth::preStartVoice(voiceIndex, e);
if (auto n = getActiveNetwork())
{
static_cast<Voice*>(getVoice(voiceIndex))->setVoiceStartDataForNextRenderCallback();
currentVoiceStartSample = jlimit(0, getLargestBlockSize(), e.getTimeStamp());
}
}
void JavascriptSynthesiser::prepareToPlay(double newSampleRate, int samplesPerBlock)
{
ModulatorSynth::prepareToPlay(newSampleRate, samplesPerBlock);
if (newSampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
n->prepareToPlay(newSampleRate, (double)samplesPerBlock);
n->setNumChannels(getMatrix().getNumSourceChannels());
}
}
void JavascriptSynthesiser::restoreFromValueTree(const ValueTree &v)
{
ModulatorSynth::restoreFromValueTree(v);
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
restoreScript(v);
restoreContent(v);
}
void JavascriptSynthesiser::Voice::calculateBlock(int startSample, int numSamples)
{
if (auto n = synth->getActiveNetwork())
{
if (isVoiceStart)
{
n->setVoiceKiller(synth->vk);
synth->voiceData.startVoice(*n, *n->getPolyHandler(), getVoiceIndex(), getCurrentHiseEvent());
isVoiceStart = false;
}
float* channels[NUM_MAX_CHANNELS];
voiceBuffer.clear();
int numChannels = voiceBuffer.getNumChannels();
memcpy(channels, voiceBuffer.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
{
scriptnode::DspNetwork::VoiceSetter vs(*n, getVoiceIndex());
n->process(d);
}
if (auto modValues = getOwnerSynth()->getVoiceGainValues())
{
for(int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), modValues + startSample, numSamples);
}
else
{
const float gainValue = getOwnerSynth()->getConstantGainModValue();
for (int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), gainValue, numSamples);
}
getOwnerSynth()->effectChain->renderVoice(voiceIndex, voiceBuffer, startSample, numSamples);
}
}
hise::ProcessorEditorBody * ScriptnodeVoiceKiller::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new EmptyProcessorEditorBody(parentEditor);;
#else
ignoreUnused(parentEditor);
return nullptr;
#endif
}
void VoiceDataStack::reset(int voiceIndex)
{
for (int i = 0; i < voiceNoteOns.size(); i++)
{
if (voiceNoteOns[i].voiceIndex == voiceIndex)
{
voiceNoteOns.removeElement(i--);
break;
}
}
}
} // namespace hise
| 28.248466 | 154 | 0.738473 |
8da676e012b390ad6d966e87aba38198b5a6f3f5 | 64,448 | js | JavaScript | lib/bible-tools/bibles/en/nasb/books/16.js | saiba-mais/bible-lessons | 6c352c1060c48b80f74f8bf0c1cbff5450de2fe6 | [
"MIT"
] | null | null | null | lib/bible-tools/bibles/en/nasb/books/16.js | saiba-mais/bible-lessons | 6c352c1060c48b80f74f8bf0c1cbff5450de2fe6 | [
"MIT"
] | null | null | null | lib/bible-tools/bibles/en/nasb/books/16.js | saiba-mais/bible-lessons | 6c352c1060c48b80f74f8bf0c1cbff5450de2fe6 | [
"MIT"
] | null | null | null | var book = {
"name": "Nehemiah",
"numChapters": 13,
"chapters": {
"1": {
"1": "<sup>1</sup> The words of Nehemiah the son of Hacaliah. Now it happened in the month Chislev, in the twentieth year, while I was in Susa the capitol,",
"2": "<sup>2</sup> that Hanani, one of my brothers, and some men from Judah came; and I asked them concerning the Jews who had escaped and had survived the captivity, and about Jerusalem.",
"3": "<sup>3</sup> They said to me, \"The remnant there in the province who survived the captivity are in great distress and reproach, and the wall of Jerusalem is broken down and its gates are burned with fire.\"",
"4": "<sup>4</sup> When I heard these words, I sat down and wept and mourned for days; and I was fasting and praying before the God of heaven.",
"5": "<sup>5</sup> I said, \"I beseech You, O Lord God of heaven, the great and awesome God, who preserves the covenant and lovingkindness for those who love Him and keep His commandments,",
"6": "<sup>6</sup> let Your ear now be attentive and Your eyes open to hear the prayer of Your servant which I am praying before You now, day and night, on behalf of the sons of Israel Your servants, confessing the sins of the sons of Israel which we have sinned against You; I and my father's house have sinned.",
"7": "<sup>7</sup> We have acted very corruptly against You and have not kept the commandments, nor the statutes, nor the ordinances which You commanded Your servant Moses.",
"8": "<sup>8</sup> Remember the word which You commanded Your servant Moses, saying, 'If you are unfaithful I will scatter you among the peoples;",
"9": "<sup>9</sup> but if you return to Me and keep My commandments and do them, though those of you who have been scattered were in the most remote part of the heavens, I will gather them from there and will bring them to the place where I have chosen to cause My name to dwell.'",
"10": "<sup>10</sup> They are Your servants and Your people whom You redeemed by Your great power and by Your strong hand.",
"11": "<sup>11</sup> O Lord, I beseech You, may Your ear be attentive to the prayer of Your servant and the prayer of Your servants who delight to revere Your name, and make Your servant successful today and grant him compassion before this man.\" Now I was the cupbearer to the king."
},
"2": {
"1": "<sup>1</sup> And it came about in the month Nisan, in the twentieth year of King Artaxerxes, that wine was before him, and I took up the wine and gave it to the king. Now I had not been sad in his presence.",
"2": "<sup>2</sup> So the king said to me, \"Why is your face sad though you are not sick? This is nothing but sadness of heart.\" Then I was very much afraid.",
"3": "<sup>3</sup> I said to the king, \"Let the king live forever. Why should my face not be sad when the city, the place of my fathers' tombs, lies desolate and its gates have been consumed by fire?\"",
"4": "<sup>4</sup> Then the king said to me, \"What would you request?\" So I prayed to the God of heaven.",
"5": "<sup>5</sup> I said to the king, \"If it please the king, and if your servant has found favor before you, send me to Judah, to the city of my fathers' tombs, that I may rebuild it.\"",
"6": "<sup>6</sup> Then the king said to me, the queen sitting beside him, \"How long will your journey be, and when will you return?\" So it pleased the king to send me, and I gave him a definite time.",
"7": "<sup>7</sup> And I said to the king, \"If it please the king, let letters be given me for the governors of the provinces beyond the River, that they may allow me to pass through until I come to Judah,",
"8": "<sup>8</sup> and a letter to Asaph the keeper of the king's forest, that he may give me timber to make beams for the gates of the fortress which is by the temple, for the wall of the city and for the house to which I will go.\" And the king granted them to me because the good hand of my God was on me.",
"9": "<sup>9</sup> Then I came to the governors of the provinces beyond the River and gave them the king's letters. Now the king had sent with me officers of the army and horsemen.",
"10": "<sup>10</sup> When Sanballat the Horonite and Tobiah the Ammonite official heard about it, it was very displeasing to them that someone had come to seek the welfare of the sons of Israel.",
"11": "<sup>11</sup> So I came to Jerusalem and was there three days.",
"12": "<sup>12</sup> And I arose in the night, I and a few men with me. I did not tell anyone what my God was putting into my mind to do for Jerusalem and there was no animal with me except the animal on which I was riding.",
"13": "<sup>13</sup> So I went out at night by the Valley Gate in the direction of the Dragon's Well and on to the Refuse Gate, inspecting the walls of Jerusalem which were broken down and its gates which were consumed by fire.",
"14": "<sup>14</sup> Then I passed on to the Fountain Gate and the King's Pool, but there was no place for my mount to pass.",
"15": "<sup>15</sup> So I went up at night by the ravine and inspected the wall. Then I entered the Valley Gate again and returned.",
"16": "<sup>16</sup> The officials did not know where I had gone or what I had done; nor had I as yet told the Jews, the priests, the nobles, the officials or the rest who did the work.",
"17": "<sup>17</sup> Then I said to them, \"You see the bad situation we are in, that Jerusalem is desolate and its gates burned by fire. Come, let us rebuild the wall of Jerusalem so that we will no longer be a reproach.\"",
"18": "<sup>18</sup> I told them how the hand of my God had been favorable to me and also about the king's words which he had spoken to me. Then they said, \"Let us arise and build.\" So they put their hands to the good work.",
"19": "<sup>19</sup> But when Sanballat the Horonite and Tobiah the Ammonite official, and Geshem the Arab heard it, they mocked us and despised us and said, \"What is this thing you are doing? Are you rebelling against the king?\"",
"20": "<sup>20</sup> So I answered them and said to them, \"The God of heaven will give us success; therefore we His servants will arise and build, but you have no portion, right or memorial in Jerusalem.\""
},
"3": {
"1": "<sup>1</sup> Then Eliashib the high priest arose with his brothers the priests and built the Sheep Gate; they consecrated it and hung its doors. They consecrated the wall to the Tower of the Hundred and the Tower of Hananel.",
"2": "<sup>2</sup> Next to him the men of Jericho built, and next to them Zaccur the son of Imri built.",
"3": "<sup>3</sup> Now the sons of Hassenaah built the Fish Gate; they laid its beams and hung its doors with its bolts and bars.",
"4": "<sup>4</sup> Next to them Meremoth the son of Uriah the son of Hakkoz made repairs. And next to him Meshullam the son of Berechiah the son of Meshezabel made repairs. And next to him Zadok the son of Baana also made repairs.",
"5": "<sup>5</sup> Moreover, next to him the Tekoites made repairs, but their nobles did not support the work of their masters.",
"6": "<sup>6</sup> Joiada the son of Paseah and Meshullam the son of Besodeiah repaired the Old Gate; they laid its beams and hung its doors with its bolts and its bars.",
"7": "<sup>7</sup> Next to them Melatiah the Gibeonite and Jadon the Meronothite, the men of Gibeon and of Mizpah, also made repairs for the official seat of the governor of the province beyond the River.",
"8": "<sup>8</sup> Next to him Uzziel the son of Harhaiah of the goldsmiths made repairs. And next to him Hananiah, one of the perfumers, made repairs, and they restored Jerusalem as far as the Broad Wall.",
"9": "<sup>9</sup> Next to them Rephaiah the son of Hur, the official of half the district of Jerusalem, made repairs.",
"10": "<sup>10</sup> Next to them Jedaiah the son of Harumaph made repairs opposite his house. And next to him Hattush the son of Hashabneiah made repairs.",
"11": "<sup>11</sup> Malchijah the son of Harim and Hasshub the son of Pahath-moab repaired another section and the Tower of Furnaces.",
"12": "<sup>12</sup> Next to him Shallum the son of Hallohesh, the official of half the district of Jerusalem, made repairs, he and his daughters.",
"13": "<sup>13</sup> Hanun and the inhabitants of Zanoah repaired the Valley Gate. They built it and hung its doors with its bolts and its bars, and a thousand cubits of the wall to the Refuse Gate.",
"14": "<sup>14</sup> Malchijah the son of Rechab, the official of the district of Beth-haccherem repaired the Refuse Gate. He built it and hung its doors with its bolts and its bars.",
"15": "<sup>15</sup> Shallum the son of Col-hozeh, the official of the district of Mizpah, repaired the Fountain Gate. He built it, covered it and hung its doors with its bolts and its bars, and the wall of the Pool of Shelah at the king's garden as far as the steps that descend from the city of David.",
"16": "<sup>16</sup> After him Nehemiah the son of Azbuk, official of half the district of Beth-zur, made repairs as far as a point opposite the tombs of David, and as far as the artificial pool and the house of the mighty men.",
"17": "<sup>17</sup> After him the Levites carried out repairs under Rehum the son of Bani. Next to him Hashabiah, the official of half the district of Keilah, carried out repairs for his district.",
"18": "<sup>18</sup> After him their brothers carried out repairs under Bavvai the son of Henadad, official of the other half of the district of Keilah.",
"19": "<sup>19</sup> Next to him Ezer the son of Jeshua, the official of Mizpah, repaired another section in front of the ascent of the armory at the Angle.",
"20": "<sup>20</sup> After him Baruch the son of Zabbai zealously repaired another section, from the Angle to the doorway of the house of Eliashib the high priest.",
"21": "<sup>21</sup> After him Meremoth the son of Uriah the son of Hakkoz repaired another section, from the doorway of Eliashib's house even as far as the end of his house.",
"22": "<sup>22</sup> After him the priests, the men of the valley, carried out repairs.",
"23": "<sup>23</sup> After them Benjamin and Hasshub carried out repairs in front of their house. After them Azariah the son of Maaseiah, son of Ananiah, carried out repairs beside his house.",
"24": "<sup>24</sup> After him Binnui the son of Henadad repaired another section, from the house of Azariah as far as the Angle and as far as the corner.",
"25": "<sup>25</sup> Palal the son of Uzai made repairs in front of the Angle and the tower projecting from the upper house of the king, which is by the court of the guard. After him Pedaiah the son of Parosh made repairs.",
"26": "<sup>26</sup> The temple servants living in Ophel made repairs as far as the front of the Water Gate toward the east and the projecting tower.",
"27": "<sup>27</sup> After them the Tekoites repaired another section in front of the great projecting tower and as far as the wall of Ophel.",
"28": "<sup>28</sup> Above the Horse Gate the priests carried out repairs, each in front of his house.",
"29": "<sup>29</sup> After them Zadok the son of Immer carried out repairs in front of his house. And after him Shemaiah the son of Shecaniah, the keeper of the East Gate, carried out repairs.",
"30": "<sup>30</sup> After him Hananiah the son of Shelemiah, and Hanun the sixth son of Zalaph, repaired another section. After him Meshullam the son of Berechiah carried out repairs in front of his own quarters.",
"31": "<sup>31</sup> After him Malchijah, one of the goldsmiths, carried out repairs as far as the house of the temple servants and of the merchants, in front of the Inspection Gate and as far as the upper room of the corner.",
"32": "<sup>32</sup> Between the upper room of the corner and the Sheep Gate the goldsmiths and the merchants carried out repairs."
},
"4": {
"1": "<sup>1</sup> Now it came about that when Sanballat heard that we were rebuilding the wall, he became furious and very angry and mocked the Jews.",
"2": "<sup>2</sup> He spoke in the presence of his brothers and the wealthy men of Samaria and said, \"What are these feeble Jews doing? Are they going to restore it for themselves? Can they offer sacrifices? Can they finish in a day? Can they revive the stones from the dusty rubble even the burned ones?\"",
"3": "<sup>3</sup> Now Tobiah the Ammonite was near him and he said, \"Even what they are building-if a fox should jump on it, he would break their stone wall down!\"",
"4": "<sup>4</sup> Hear, O our God, how we are despised! Return their reproach on their own heads and give them up for plunder in a land of captivity.",
"5": "<sup>5</sup> Do not forgive their iniquity and let not their sin be blotted out before You, for they have demoralized the builders.",
"6": "<sup>6</sup> So we built the wall and the whole wall was joined together to half its height, for the people had a mind to work.",
"7": "<sup>7</sup> Now when Sanballat, Tobiah, the Arabs, the Ammonites and the Ashdodites heard that the repair of the walls of Jerusalem went on, and that the breaches began to be closed, they were very angry.",
"8": "<sup>8</sup> All of them conspired together to come and fight against Jerusalem and to cause a disturbance in it.",
"9": "<sup>9</sup> But we prayed to our God, and because of them we set up a guard against them day and night.",
"10": "<sup>10</sup> Thus in Judah it was said, \"The strength of the burden bearers is failing, Yet there is much rubbish; And we ourselves are unable To rebuild the wall.\"",
"11": "<sup>11</sup> Our enemies said, \"They will not know or see until we come among them, kill them and put a stop to the work.\"",
"12": "<sup>12</sup> When the Jews who lived near them came and told us ten times, \"They will come up against us from every place where you may turn,\"",
"13": "<sup>13</sup> then I stationed men in the lowest parts of the space behind the wall, the exposed places, and I stationed the people in families with their swords, spears and bows.",
"14": "<sup>14</sup> When I saw their fear, I rose and spoke to the nobles, the officials and the rest of the people: \"Do not be afraid of them; remember the Lord who is great and awesome, and fight for your brothers, your sons, your daughters, your wives and your houses.\"",
"15": "<sup>15</sup> When our enemies heard that it was known to us, and that God had frustrated their plan, then all of us returned to the wall, each one to his work.",
"16": "<sup>16</sup> From that day on, half of my servants carried on the work while half of them held the spears, the shields, the bows and the breastplates; and the captains were behind the whole house of Judah.",
"17": "<sup>17</sup> Those who were rebuilding the wall and those who carried burdens took their load with one hand doing the work and the other holding a weapon.",
"18": "<sup>18</sup> As for the builders, each wore his sword girded at his side as he built, while the trumpeter stood near me.",
"19": "<sup>19</sup> I said to the nobles, the officials and the rest of the people, \"The work is great and extensive, and we are separated on the wall far from one another.",
"20": "<sup>20</sup> At whatever place you hear the sound of the trumpet, rally to us there. Our God will fight for us.\"",
"21": "<sup>21</sup> So we carried on the work with half of them holding spears from dawn until the stars appeared.",
"22": "<sup>22</sup> At that time I also said to the people, \"Let each man with his servant spend the night within Jerusalem so that they may be a guard for us by night and a laborer by day.\"",
"23": "<sup>23</sup> So neither I, my brothers, my servants, nor the men of the guard who followed me, none of us removed our clothes, each took his weapon even to the water."
},
"5": {
"1": "<sup>1</sup> Now there was a great outcry of the people and of their wives against their Jewish brothers.",
"2": "<sup>2</sup> For there were those who said, \"We, our sons and our daughters are many; therefore let us get grain that we may eat and live.\"",
"3": "<sup>3</sup> There were others who said, \"We are mortgaging our fields, our vineyards and our houses that we might get grain because of the famine.\"",
"4": "<sup>4</sup> Also there were those who said, \"We have borrowed money for the king's tax on our fields and our vineyards.",
"5": "<sup>5</sup> Now our flesh is like the flesh of our brothers, our children like their children. Yet behold, we are forcing our sons and our daughters to be slaves, and some of our daughters are forced into bondage already, and we are helpless because our fields and vineyards belong to others.\"",
"6": "<sup>6</sup> Then I was very angry when I had heard their outcry and these words.",
"7": "<sup>7</sup> I consulted with myself and contended with the nobles and the rulers and said to them, \"You are exacting usury, each from his brother!\" Therefore, I held a great assembly against them.",
"8": "<sup>8</sup> I said to them, \"We according to our ability have redeemed our Jewish brothers who were sold to the nations; now would you even sell your brothers that they may be sold to us?\" Then they were silent and could not find a word to say.",
"9": "<sup>9</sup> Again I said, \"The thing which you are doing is not good; should you not walk in the fear of our God because of the reproach of the nations, our enemies?",
"10": "<sup>10</sup> And likewise I, my brothers and my servants are lending them money and grain. Please, let us leave off this usury.",
"11": "<sup>11</sup> Please, give back to them this very day their fields, their vineyards, their olive groves and their houses, also the hundredth part of the money and of the grain, the new wine and the oil that you are exacting from them.\"",
"12": "<sup>12</sup> Then they said, \"We will give it back and will require nothing from them; we will do exactly as you say.\" So I called the priests and took an oath from them that they would do according to this promise.",
"13": "<sup>13</sup> I also shook out the front of my garment and said, \"Thus may God shake out every man from his house and from his possessions who does not fulfill this promise; even thus may he be shaken out and emptied.\" And all the assembly said, \"Amen!\" And they praised the Lord. Then the people did according to this promise.",
"14": "<sup>14</sup> Moreover, from the day that I was appointed to be their governor in the land of Judah, from the twentieth year to the thirty-second year of King Artaxerxes, for twelve years, neither I nor my kinsmen have eaten the governor's food allowance.",
"15": "<sup>15</sup> But the former governors who were before me laid burdens on the people and took from them bread and wine besides forty shekels of silver; even their servants domineered the people. But I did not do so because of the fear of God.",
"16": "<sup>16</sup> I also applied myself to the work on this wall; we did not buy any land, and all my servants were gathered there for the work.",
"17": "<sup>17</sup> Moreover, there were at my table one hundred and fifty Jews and officials, besides those who came to us from the nations that were around us.",
"18": "<sup>18</sup> Now that which was prepared for each day was one ox and six choice sheep, also birds were prepared for me; and once in ten days all sorts of wine were furnished in abundance. Yet for all this I did not demand the governor's food allowance, because the servitude was heavy on this people.",
"19": "<sup>19</sup> Remember me, O my God, for good, according to all that I have done for this people."
},
"6": {
"1": "<sup>1</sup> Now when it was reported to Sanballat, Tobiah, to Geshem the Arab and to the rest of our enemies that I had rebuilt the wall, and that no breach remained in it, although at that time I had not set up the doors in the gates,",
"2": "<sup>2</sup> then Sanballat and Geshem sent a message to me, saying, \"Come, let us meet together at Chephirim in the plain of Ono.\" But they were planning to harm me.",
"3": "<sup>3</sup> So I sent messengers to them, saying, \"I am doing a great work and I cannot come down. Why should the work stop while I leave it and come down to you?\"",
"4": "<sup>4</sup> They sent messages to me four times in this manner, and I answered them in the same way.",
"5": "<sup>5</sup> Then Sanballat sent his servant to me in the same manner a fifth time with an open letter in his hand.",
"6": "<sup>6</sup> In it was written, \"It is reported among the nations, and Gashmu says, that you and the Jews are planning to rebel; therefore you are rebuilding the wall. And you are to be their king, according to these reports.",
"7": "<sup>7</sup> You have also appointed prophets to proclaim in Jerusalem concerning you, 'A king is in Judah!' And now it will be reported to the king according to these reports. So come now, let us take counsel together.\"",
"8": "<sup>8</sup> Then I sent a message to him saying, \"Such things as you are saying have not been done, but you are inventing them in your own mind.\"",
"9": "<sup>9</sup> For all of them were trying to frighten us, thinking, \"They will become discouraged with the work and it will not be done.\" But now, O God, strengthen my hands.",
"10": "<sup>10</sup> When I entered the house of Shemaiah the son of Delaiah, son of Mehetabel, who was confined at home, he said, \"Let us meet together in the house of God, within the temple, and let us close the doors of the temple, for they are coming to kill you, and they are coming to kill you at night.\"",
"11": "<sup>11</sup> But I said, \"Should a man like me flee? And could one such as I go into the temple to save his life? I will not go in.\"",
"12": "<sup>12</sup> Then I perceived that surely God had not sent him, but he uttered his prophecy against me because Tobiah and Sanballat had hired him.",
"13": "<sup>13</sup> He was hired for this reason, that I might become frightened and act accordingly and sin, so that they might have an evil report in order that they could reproach me.",
"14": "<sup>14</sup> Remember, O my God, Tobiah and Sanballat according to these works of theirs, and also Noadiah the prophetess and the rest of the prophets who were trying to frighten me.",
"15": "<sup>15</sup> So the wall was completed on the twenty-fifth of the month Elul, in fifty-two days.",
"16": "<sup>16</sup> When all our enemies heard of it, and all the nations surrounding us saw it, they lost their confidence; for they recognized that this work had been accomplished with the help of our God.",
"17": "<sup>17</sup> Also in those days many letters went from the nobles of Judah to Tobiah, and Tobiah's letters came to them.",
"18": "<sup>18</sup> For many in Judah were bound by oath to him because he was the son-in-law of Shecaniah the son of Arah, and his son Jehohanan had married the daughter of Meshullam the son of Berechiah.",
"19": "<sup>19</sup> Moreover, they were speaking about his good deeds in my presence and reported my words to him. Then Tobiah sent letters to frighten me."
},
"7": {
"1": "<sup>1</sup> Now when the wall was rebuilt and I had set up the doors, and the gatekeepers and the singers and the Levites were appointed,",
"2": "<sup>2</sup> then I put Hanani my brother, and Hananiah the commander of the fortress, in charge of Jerusalem, for he was a faithful man and feared God more than many.",
"3": "<sup>3</sup> Then I said to them, \"Do not let the gates of Jerusalem be opened until the sun is hot, and while they are standing guard, let them shut and bolt the doors. Also appoint guards from the inhabitants of Jerusalem, each at his post, and each in front of his own house.\"",
"4": "<sup>4</sup> Now the city was large and spacious, but the people in it were few and the houses were not built.",
"5": "<sup>5</sup> Then my God put it into my heart to assemble the nobles, the officials and the people to be enrolled by genealogies. Then I found the book of the genealogy of those who came up first in which I found the following record:",
"6": "<sup>6</sup> These are the people of the province who came up from the captivity of the exiles whom Nebuchadnezzar the king of Babylon had carried away, and who returned to Jerusalem and Judah, each to his city,",
"7": "<sup>7</sup> who came with Zerubbabel, Jeshua, Nehemiah, Azariah, Raamiah, Nahamani, Mordecai, Bilshan, Mispereth, Bigvai, Nehum, Baanah. The number of men of the people of Israel:",
"8": "<sup>8</sup> the sons of Parosh, 2,172;",
"9": "<sup>9</sup> the sons of Shephatiah, 372;",
"10": "<sup>10</sup> the sons of Arah, 652;",
"11": "<sup>11</sup> the sons of Pahath-moab of the sons of Jeshua and Joab, 2,818;",
"12": "<sup>12</sup> the sons of Elam, 1,254;",
"13": "<sup>13</sup> the sons of Zattu, 845;",
"14": "<sup>14</sup> the sons of Zaccai, 760;",
"15": "<sup>15</sup> the sons of Binnui, 648;",
"16": "<sup>16</sup> the sons of Bebai, 628;",
"17": "<sup>17</sup> the sons of Azgad, 2,322;",
"18": "<sup>18</sup> the sons of Adonikam, 667;",
"19": "<sup>19</sup> the sons of Bigvai, 2,067;",
"20": "<sup>20</sup> the sons of Adin, 655;",
"21": "<sup>21</sup> the sons of Ater, of Hezekiah, 98;",
"22": "<sup>22</sup> the sons of Hashum, 328;",
"23": "<sup>23</sup> the sons of Bezai, 324;",
"24": "<sup>24</sup> the sons of Hariph, 112;",
"25": "<sup>25</sup> the sons of Gibeon, 95;",
"26": "<sup>26</sup> the men of Bethlehem and Netophah, 188;",
"27": "<sup>27</sup> the men of Anathoth, 128;",
"28": "<sup>28</sup> the men of Beth-azmaveth, 42;",
"29": "<sup>29</sup> the men of Kiriath-jearim, Chephirah and Beeroth, 743;",
"30": "<sup>30</sup> the men of Ramah and Geba, 621;",
"31": "<sup>31</sup> the men of Michmas, 122;",
"32": "<sup>32</sup> the men of Bethel and Ai, 123;",
"33": "<sup>33</sup> the men of the other Nebo, 52;",
"34": "<sup>34</sup> the sons of the other Elam, 1,254;",
"35": "<sup>35</sup> the sons of Harim, 320;",
"36": "<sup>36</sup> the men of Jericho, 345;",
"37": "<sup>37</sup> the sons of Lod, Hadid and Ono, 721;",
"38": "<sup>38</sup> the sons of Senaah, 3,930.",
"39": "<sup>39</sup> The priests: the sons of Jedaiah of the house of Jeshua, 973;",
"40": "<sup>40</sup> the sons of Immer, 1,052;",
"41": "<sup>41</sup> the sons of Pashhur, 1,247;",
"42": "<sup>42</sup> the sons of Harim, 1,017.",
"43": "<sup>43</sup> The Levites: the sons of Jeshua, of Kadmiel, of the sons of Hodevah, 74.",
"44": "<sup>44</sup> The singers: the sons of Asaph, 148.",
"45": "<sup>45</sup> The gatekeepers: the sons of Shallum, the sons of Ater, the sons of Talmon, the sons of Akkub, the sons of Hatita, the sons of Shobai, 138.",
"46": "<sup>46</sup> The temple servants: the sons of Ziha, the sons of Hasupha, the sons of Tabbaoth,",
"47": "<sup>47</sup> the sons of Keros, the sons of Sia, the sons of Padon,",
"48": "<sup>48</sup> the sons of Lebana, the sons of Hagaba, the sons of Shalmai,",
"49": "<sup>49</sup> the sons of Hanan, the sons of Giddel, the sons of Gahar,",
"50": "<sup>50</sup> the sons of Reaiah, the sons of Rezin, the sons of Nekoda,",
"51": "<sup>51</sup> the sons of Gazzam, the sons of Uzza, the sons of Paseah,",
"52": "<sup>52</sup> the sons of Besai, the sons of Meunim, the sons of Nephushesim,",
"53": "<sup>53</sup> the sons of Bakbuk, the sons of Hakupha, the sons of Harhur,",
"54": "<sup>54</sup> the sons of Bazlith, the sons of Mehida, the sons of Harsha,",
"55": "<sup>55</sup> the sons of Barkos, the sons of Sisera, the sons of Temah,",
"56": "<sup>56</sup> the sons of Neziah, the sons of Hatipha.",
"57": "<sup>57</sup> The sons of Solomon's servants: the sons of Sotai, the sons of Sophereth, the sons of Perida,",
"58": "<sup>58</sup> the sons of Jaala, the sons of Darkon, the sons of Giddel,",
"59": "<sup>59</sup> the sons of Shephatiah, the sons of Hattil, the sons of Pochereth-hazzebaim, the sons of Amon.",
"60": "<sup>60</sup> All the temple servants and the sons of Solomon's servants were 392.",
"61": "<sup>61</sup> These were they who came up from Tel-melah, Tel-harsha, Cherub, Addon and Immer; but they could not show their fathers' houses or their descendants, whether they were of Israel:",
"62": "<sup>62</sup> the sons of Delaiah, the sons of Tobiah, the sons of Nekoda, 642.",
"63": "<sup>63</sup> Of the priests: the sons of Hobaiah, the sons of Hakkoz, the sons of Barzillai, who took a wife of the daughters of Barzillai, the Gileadite, and was named after them.",
"64": "<sup>64</sup> These searched among their ancestral registration, but it could not be located; therefore they were considered unclean and excluded from the priesthood.",
"65": "<sup>65</sup> The governor said to them that they should not eat from the most holy things until a priest arose with Urim and Thummim.",
"66": "<sup>66</sup> The whole assembly together was 42,360,",
"67": "<sup>67</sup> besides their male and their female servants, of whom there were 7,337; and they had 245 male and female singers.",
"68": "<sup>68</sup> Their horses were 736; their mules, 245;",
"69": "<sup>69</sup> their camels, 435; their donkeys, 6,720.",
"70": "<sup>70</sup> Some from among the heads of fathers' households gave to the work. The governor gave to the treasury 1,000 gold drachmas, 50 basins, 530 priests' garments.",
"71": "<sup>71</sup> Some of the heads of fathers' households gave into the treasury of the work 20,000 gold drachmas and 2,200 silver minas.",
"72": "<sup>72</sup> That which the rest of the people gave was 20,000 gold drachmas and 2,000 silver minas and 67 priests' garments.",
"73": "<sup>73</sup> Now the priests, the Levites, the gatekeepers, the singers, some of the people, the temple servants and all Israel, lived in their cities. And when the seventh month came, the sons of Israel were in their cities."
},
"8": {
"1": "<sup>1</sup> And all the people gathered as one man at the square which was in front of the Water Gate, and they asked Ezra the scribe to bring the book of the law of Moses which the Lord had given to Israel.",
"2": "<sup>2</sup> Then Ezra the priest brought the law before the assembly of men, women and all who could listen with understanding, on the first day of the seventh month.",
"3": "<sup>3</sup> He read from it before the square which was in front of the Water Gate from early morning until midday, in the presence of men and women, those who could understand; and all the people were attentive to the book of the law.",
"4": "<sup>4</sup> Ezra the scribe stood at a wooden podium which they had made for the purpose. And beside him stood Mattithiah, Shema, Anaiah, Uriah, Hilkiah, and Maaseiah on his right hand; and Pedaiah, Mishael, Malchijah, Hashum, Hashbaddanah, Zechariah and Meshullam on his left hand.",
"5": "<sup>5</sup> Ezra opened the book in the sight of all the people for he was standing above all the people; and when he opened it, all the people stood up.",
"6": "<sup>6</sup> Then Ezra blessed the Lord the great God. And all the people answered, \"Amen, Amen!\" while lifting up their hands; then they bowed low and worshiped the Lord with their faces to the ground.",
"7": "<sup>7</sup> Also Jeshua, Bani, Sherebiah, Jamin, Akkub, Shabbethai, Hodiah, Maaseiah, Kelita, Azariah, Jozabad, Hanan, Pelaiah, the Levites, explained the law to the people while the people remained in their place.",
"8": "<sup>8</sup> They read from the book, from the law of God, translating to give the sense so that they understood the reading.",
"9": "<sup>9</sup> Then Nehemiah, who was the governor, and Ezra the priest and scribe, and the Levites who taught the people said to all the people, \"This day is holy to the Lord your God; do not mourn or weep.\" For all the people were weeping when they heard the words of the law.",
"10": "<sup>10</sup> Then he said to them, \"Go, eat of the fat, drink of the sweet, and send portions to him who has nothing prepared; for this day is holy to our Lord. Do not be grieved, for the joy of the Lord is your strength.\"",
"11": "<sup>11</sup> So the Levites calmed all the people, saying, \"Be still, for the day is holy; do not be grieved.\"",
"12": "<sup>12</sup> All the people went away to eat, to drink, to send portions and to celebrate a great festival, because they understood the words which had been made known to them.",
"13": "<sup>13</sup> Then on the second day the heads of fathers' households of all the people, the priests and the Levites were gathered to Ezra the scribe that they might gain insight into the words of the law.",
"14": "<sup>14</sup> They found written in the law how the Lord had commanded through Moses that the sons of Israel should live in booths during the feast of the seventh month.",
"15": "<sup>15</sup> So they proclaimed and circulated a proclamation in all their cities and in Jerusalem, saying, \"Go out to the hills, and bring olive branches and wild olive branches, myrtle branches, palm branches and branches of other leafy trees, to make booths, as it is written.\"",
"16": "<sup>16</sup> So the people went out and brought them and made booths for themselves, each on his roof, and in their courts and in the courts of the house of God, and in the square at the Water Gate and in the square at the Gate of Ephraim.",
"17": "<sup>17</sup> The entire assembly of those who had returned from the captivity made booths and lived in them. The sons of Israel had indeed not done so from the days of Joshua the son of Nun to that day. And there was great rejoicing.",
"18": "<sup>18</sup> He read from the book of the law of God daily, from the first day to the last day. And they celebrated the feast seven days, and on the eighth day there was a solemn assembly according to the ordinance."
},
"9": {
"1": "<sup>1</sup> Now on the twenty-fourth day of this month the sons of Israel assembled with fasting, in sackcloth and with dirt upon them.",
"2": "<sup>2</sup> The descendants of Israel separated themselves from all foreigners, and stood and confessed their sins and the iniquities of their fathers.",
"3": "<sup>3</sup> While they stood in their place, they read from the book of the law of the Lord their God for a fourth of the day; and for another fourth they confessed and worshiped the Lord their God.",
"4": "<sup>4</sup> Now on the Levites' platform stood Jeshua, Bani, Kadmiel, Shebaniah, Bunni, Sherebiah, Bani and Chenani, and they cried with a loud voice to the Lord their God.",
"5": "<sup>5</sup> Then the Levites, Jeshua, Kadmiel, Bani, Hashabneiah, Sherebiah, Hodiah, Shebaniah and Pethahiah, said, \"Arise, bless the Lord your God forever and ever! O may Your glorious name be blessed And exalted above all blessing and praise!",
"6": "<sup>6</sup> \"You alone are the Lord. You have made the heavens, The heaven of heavens with all their host, The earth and all that is on it, The seas and all that is in them. You give life to all of them And the heavenly host bows down before You.",
"7": "<sup>7</sup> \"You are the Lord God, Who chose Abram And brought him out from Ur of the Chaldees, And gave him the name Abraham.",
"8": "<sup>8</sup> \"You found his heart faithful before You, And made a covenant with him To give him the land of the Canaanite, Of the Hittite and the Amorite, Of the Perizzite, the Jebusite and the Girgashite- To give it to his descendants. And You have fulfilled Your promise, For You are righteous.",
"9": "<sup>9</sup> \"You saw the affliction of our fathers in Egypt, And heard their cry by the Red Sea.",
"10": "<sup>10</sup> \"Then You performed signs and wonders against Pharaoh, Against all his servants and all the people of his land; For You knew that they acted arrogantly toward them, And made a name for Yourself as it is this day.",
"11": "<sup>11</sup> \"You divided the sea before them, So they passed through the midst of the sea on dry ground; And their pursuers You hurled into the depths, Like a stone into raging waters.",
"12": "<sup>12</sup> \"And with a pillar of cloud You led them by day, And with a pillar of fire by night To light for them the way In which they were to go.",
"13": "<sup>13</sup> \"Then You came down on Mount Sinai, And spoke with them from heaven; You gave them just ordinances and true laws, Good statutes and commandments.",
"14": "<sup>14</sup> \"So You made known to them Your holy sabbath, And laid down for them commandments, statutes and law, Through Your servant Moses.",
"15": "<sup>15</sup> \"You provided bread from heaven for them for their hunger, You brought forth water from a rock for them for their thirst, And You told them to enter in order to possess The land which You swore to give them.",
"16": "<sup>16</sup> \"But they, our fathers, acted arrogantly; They became stubborn and would not listen to Your commandments.",
"17": "<sup>17</sup> \"They refused to listen, And did not remember Your wondrous deeds which You had performed among them; So they became stubborn and appointed a leader to return to their slavery in Egypt. But You are a God of forgiveness, Gracious and compassionate, Slow to anger and abounding in lovingkindness; And You did not forsake them.",
"18": "<sup>18</sup> \"Even when they made for themselves A calf of molten metal And said, 'This is your God Who brought you up from Egypt,' And committed great blasphemies,",
"19": "<sup>19</sup> You, in Your great compassion, Did not forsake them in the wilderness; The pillar of cloud did not leave them by day, To guide them on their way, Nor the pillar of fire by night, to light for them the way in which they were to go.",
"20": "<sup>20</sup> \"You gave Your good Spirit to instruct them, Your manna You did not withhold from their mouth, And You gave them water for their thirst.",
"21": "<sup>21</sup> \"Indeed, forty years You provided for them in the wilderness and they were not in want; Their clothes did not wear out, nor did their feet swell.",
"22": "<sup>22</sup> \"You also gave them kingdoms and peoples, And allotted them to them as a boundary. They took possession of the land of Sihon the king of Heshbon And the land of Og the king of Bashan.",
"23": "<sup>23</sup> \"You made their sons numerous as the stars of heaven, And You brought them into the land Which You had told their fathers to enter and possess.",
"24": "<sup>24</sup> \"So their sons entered and possessed the land. And You subdued before them the inhabitants of the land, the Canaanites, And You gave them into their hand, with their kings and the peoples of the land, To do with them as they desired.",
"25": "<sup>25</sup> \"They captured fortified cities and a fertile land. They took possession of houses full of every good thing, Hewn cisterns, vineyards, olive groves, Fruit trees in abundance. So they ate, were filled and grew fat, And reveled in Your great goodness.",
"26": "<sup>26</sup> \"But they became disobedient and rebelled against You, And cast Your law behind their backs And killed Your prophets who had admonished them So that they might return to You, And they committed great blasphemies.",
"27": "<sup>27</sup> \"Therefore You delivered them into the hand of their oppressors who oppressed them, But when they cried to You in the time of their distress, You heard from heaven, and according to Your great compassion You gave them deliverers who delivered them from the hand of their oppressors.",
"28": "<sup>28</sup> \"But as soon as they had rest, they did evil again before You; Therefore You abandoned them to the hand of their enemies, so that they ruled over them. When they cried again to You, You heard from heaven, And many times You rescued them according to Your compassion,",
"29": "<sup>29</sup> And admonished them in order to turn them back to Your law. Yet they acted arrogantly and did not listen to Your commandments but sinned against Your ordinances, By which if a man observes them he shall live. And they turned a stubborn shoulder and stiffened their neck, and would not listen.",
"30": "<sup>30</sup> \"However, You bore with them for many years, And admonished them by Your Spirit through Your prophets, Yet they would not give ear. Therefore You gave them into the hand of the peoples of the lands.",
"31": "<sup>31</sup> \"Nevertheless, in Your great compassion You did not make an end of them or forsake them, For You are a gracious and compassionate God.",
"32": "<sup>32</sup> \"Now therefore, our God, the great, the mighty, and the awesome God, who keeps covenant and lovingkindness, Do not let all the hardship seem insignificant before You, Which has come upon us, our kings, our princes, our priests, our prophets, our fathers and on all Your people, From the days of the kings of Assyria to this day.",
"33": "<sup>33</sup> \"However, You are just in all that has come upon us; For You have dealt faithfully, but we have acted wickedly.",
"34": "<sup>34</sup> \"For our kings, our leaders, our priests and our fathers have not kept Your law Or paid attention to Your commandments and Your admonitions with which You have admonished them.",
"35": "<sup>35</sup> \"But they, in their own kingdom, With Your great goodness which You gave them, With the broad and rich land which You set before them, Did not serve You or turn from their evil deeds.",
"36": "<sup>36</sup> \"Behold, we are slaves today, And as to the land which You gave to our fathers to eat of its fruit and its bounty, Behold, we are slaves in it.",
"37": "<sup>37</sup> \"Its abundant produce is for the kings Whom You have set over us because of our sins; They also rule over our bodies And over our cattle as they please, So we are in great distress.",
"38": "<sup>38</sup> \"Now because of all this We are making an agreement in writing; And on the sealed document are the names of our leaders, our Levites and our priests.\""
},
"10": {
"1": "<sup>1</sup> Now on the sealed document were the names of: Nehemiah the governor, the son of Hacaliah, and Zedekiah,",
"2": "<sup>2</sup> Seraiah, Azariah, Jeremiah,",
"3": "<sup>3</sup> Pashhur, Amariah, Malchijah,",
"4": "<sup>4</sup> Hattush, Shebaniah, Malluch,",
"5": "<sup>5</sup> Harim, Meremoth, Obadiah,",
"6": "<sup>6</sup> Daniel, Ginnethon, Baruch,",
"7": "<sup>7</sup> Meshullam, Abijah, Mijamin,",
"8": "<sup>8</sup> Maaziah, Bilgai, Shemaiah. These were the priests.",
"9": "<sup>9</sup> And the Levites: Jeshua the son of Azaniah, Binnui of the sons of Henadad, Kadmiel;",
"10": "<sup>10</sup> also their brothers Shebaniah, Hodiah, Kelita, Pelaiah, Hanan,",
"11": "<sup>11</sup> Mica, Rehob, Hashabiah,",
"12": "<sup>12</sup> Zaccur, Sherebiah, Shebaniah,",
"13": "<sup>13</sup> Hodiah, Bani, Beninu.",
"14": "<sup>14</sup> The leaders of the people: Parosh, Pahath-moab, Elam, Zattu, Bani,",
"15": "<sup>15</sup> Bunni, Azgad, Bebai,",
"16": "<sup>16</sup> Adonijah, Bigvai, Adin,",
"17": "<sup>17</sup> Ater, Hezekiah, Azzur,",
"18": "<sup>18</sup> Hodiah, Hashum, Bezai,",
"19": "<sup>19</sup> Hariph, Anathoth, Nebai,",
"20": "<sup>20</sup> Magpiash, Meshullam, Hezir,",
"21": "<sup>21</sup> Meshezabel, Zadok, Jaddua,",
"22": "<sup>22</sup> Pelatiah, Hanan, Anaiah,",
"23": "<sup>23</sup> Hoshea, Hananiah, Hasshub,",
"24": "<sup>24</sup> Hallohesh, Pilha, Shobek,",
"25": "<sup>25</sup> Rehum, Hashabnah, Maaseiah,",
"26": "<sup>26</sup> Ahiah, Hanan, Anan,",
"27": "<sup>27</sup> Malluch, Harim, Baanah.",
"28": "<sup>28</sup> Now the rest of the people, the priests, the Levites, the gatekeepers, the singers, the temple servants and all those who had separated themselves from the peoples of the lands to the law of God, their wives, their sons and their daughters, all those who had knowledge and understanding,",
"29": "<sup>29</sup> are joining with their kinsmen, their nobles, and are taking on themselves a curse and an oath to walk in God's law, which was given through Moses, God's servant, and to keep and to observe all the commandments of God our Lord, and His ordinances and His statutes;",
"30": "<sup>30</sup> and that we will not give our daughters to the peoples of the land or take their daughters for our sons.",
"31": "<sup>31</sup> As for the peoples of the land who bring wares or any grain on the sabbath day to sell, we will not buy from them on the sabbath or a holy day; and we will forego the crops the seventh year and the exaction of every debt.",
"32": "<sup>32</sup> We also placed ourselves under obligation to contribute yearly one third of a shekel for the service of the house of our God:",
"33": "<sup>33</sup> for the showbread, for the continual grain offering, for the continual burnt offering, the sabbaths, the new moon, for the appointed times, for the holy things and for the sin offerings to make atonement for Israel, and all the work of the house of our God.",
"34": "<sup>34</sup> Likewise we cast lots for the supply of wood among the priests, the Levites and the people so that they might bring it to the house of our God, according to our fathers' households, at fixed times annually, to burn on the altar of the Lord our God, as it is written in the law;",
"35": "<sup>35</sup> and that they might bring the first fruits of our ground and the first fruits of all the fruit of every tree to the house of the Lord annually,",
"36": "<sup>36</sup> and bring to the house of our God the firstborn of our sons and of our cattle, and the firstborn of our herds and our flocks as it is written in the law, for the priests who are ministering in the house of our God.",
"37": "<sup>37</sup> We will also bring the first of our dough, our contributions, the fruit of every tree, the new wine and the oil to the priests at the chambers of the house of our God, and the tithe of our ground to the Levites, for the Levites are they who receive the tithes in all the rural towns.",
"38": "<sup>38</sup> The priest, the son of Aaron, shall be with the Levites when the Levites receive tithes, and the Levites shall bring up the tenth of the tithes to the house of our God, to the chambers of the storehouse.",
"39": "<sup>39</sup> For the sons of Israel and the sons of Levi shall bring the contribution of the grain, the new wine and the oil to the chambers; there are the utensils of the sanctuary, the priests who are ministering, the gatekeepers and the singers. Thus we will not neglect the house of our God."
},
"11": {
"1": "<sup>1</sup> Now the leaders of the people lived in Jerusalem, but the rest of the people cast lots to bring one out of ten to live in Jerusalem, the holy city, while nine-tenths remained in the other cities.",
"2": "<sup>2</sup> And the people blessed all the men who volunteered to live in Jerusalem.",
"3": "<sup>3</sup> Now these are the heads of the provinces who lived in Jerusalem, but in the cities of Judah each lived on his own property in their cities-the Israelites, the priests, the Levites, the temple servants and the descendants of Solomon's servants.",
"4": "<sup>4</sup> Some of the sons of Judah and some of the sons of Benjamin lived in Jerusalem. From the sons of Judah: Athaiah the son of Uzziah, the son of Zechariah, the son of Amariah, the son of Shephatiah, the son of Mahalalel, of the sons of Perez;",
"5": "<sup>5</sup> and Maaseiah the son of Baruch, the son of Col-hozeh, the son of Hazaiah, the son of Adaiah, the son of Joiarib, the son of Zechariah, the son of the Shilonite.",
"6": "<sup>6</sup> All the sons of Perez who lived in Jerusalem were 468 able men.",
"7": "<sup>7</sup> Now these are the sons of Benjamin: Sallu the son of Meshullam, the son of Joed, the son of Pedaiah, the son of Kolaiah, the son of Maaseiah, the son of Ithiel, the son of Jeshaiah;",
"8": "<sup>8</sup> and after him Gabbai and Sallai, 928.",
"9": "<sup>9</sup> Joel the son of Zichri was their overseer, and Judah the son of Hassenuah was second in command of the city.",
"10": "<sup>10</sup> From the priests: Jedaiah the son of Joiarib, Jachin,",
"11": "<sup>11</sup> Seraiah the son of Hilkiah, the son of Meshullam, the son of Zadok, the son of Meraioth, the son of Ahitub, the leader of the house of God,",
"12": "<sup>12</sup> and their kinsmen who performed the work of the temple, 822; and Adaiah the son of Jeroham, the son of Pelaliah, the son of Amzi, the son of Zechariah, the son of Pashhur, the son of Malchijah,",
"13": "<sup>13</sup> and his kinsmen, heads of fathers' households, 242; and Amashsai the son of Azarel, the son of Ahzai, the son of Meshillemoth, the son of Immer,",
"14": "<sup>14</sup> and their brothers, valiant warriors, 128. And their overseer was Zabdiel, the son of Haggedolim.",
"15": "<sup>15</sup> Now from the Levites: Shemaiah the son of Hasshub, the son of Azrikam, the son of Hashabiah, the son of Bunni;",
"16": "<sup>16</sup> and Shabbethai and Jozabad, from the leaders of the Levites, who were in charge of the outside work of the house of God;",
"17": "<sup>17</sup> and Mattaniah the son of Mica, the son of Zabdi, the son of Asaph, who was the leader in beginning the thanksgiving at prayer, and Bakbukiah, the second among his brethren; and Abda the son of Shammua, the son of Galal, the son of Jeduthun.",
"18": "<sup>18</sup> All the Levites in the holy city were 284.",
"19": "<sup>19</sup> Also the gatekeepers, Akkub, Talmon and their brethren who kept watch at the gates, were 172.",
"20": "<sup>20</sup> The rest of Israel, of the priests and of the Levites, were in all the cities of Judah, each on his own inheritance.",
"21": "<sup>21</sup> But the temple servants were living in Ophel, and Ziha and Gishpa were in charge of the temple servants.",
"22": "<sup>22</sup> Now the overseer of the Levites in Jerusalem was Uzzi the son of Bani, the son of Hashabiah, the son of Mattaniah, the son of Mica, from the sons of Asaph, who were the singers for the service of the house of God.",
"23": "<sup>23</sup> For there was a commandment from the king concerning them and a firm regulation for the song leaders day by day.",
"24": "<sup>24</sup> Pethahiah the son of Meshezabel, of the sons of Zerah the son of Judah, was the king's representative in all matters concerning the people.",
"25": "<sup>25</sup> Now as for the villages with their fields, some of the sons of Judah lived in Kiriath-arba and its towns, in Dibon and its towns, and in Jekabzeel and its villages,",
"26": "<sup>26</sup> and in Jeshua, in Moladah and Beth-pelet,",
"27": "<sup>27</sup> and in Hazar-shual, in Beersheba and its towns,",
"28": "<sup>28</sup> and in Ziklag, in Meconah and in its towns,",
"29": "<sup>29</sup> and in En-rimmon, in Zorah and in Jarmuth,",
"30": "<sup>30</sup> Zanoah, Adullam, and their villages, Lachish and its fields, Azekah and its towns. So they encamped from Beersheba as far as the valley of Hinnom.",
"31": "<sup>31</sup> The sons of Benjamin also lived from Geba onward, at Michmash and Aija, at Bethel and its towns,",
"32": "<sup>32</sup> at Anathoth, Nob, Ananiah,",
"33": "<sup>33</sup> Hazor, Ramah, Gittaim,",
"34": "<sup>34</sup> Hadid, Zeboim, Neballat,",
"35": "<sup>35</sup> Lod and Ono, the valley of craftsmen.",
"36": "<sup>36</sup> From the Levites, some divisions in Judah belonged to Benjamin."
},
"12": {
"1": "<sup>1</sup> Now these are the priests and the Levites who came up with Zerubbabel the son of Shealtiel, and Jeshua: Seraiah, Jeremiah, Ezra,",
"2": "<sup>2</sup> Amariah, Malluch, Hattush,",
"3": "<sup>3</sup> Shecaniah, Rehum, Meremoth,",
"4": "<sup>4</sup> Iddo, Ginnethoi, Abijah,",
"5": "<sup>5</sup> Mijamin, Maadiah, Bilgah,",
"6": "<sup>6</sup> Shemaiah and Joiarib, Jedaiah,",
"7": "<sup>7</sup> Sallu, Amok, Hilkiah and Jedaiah. These were the heads of the priests and their kinsmen in the days of Jeshua.",
"8": "<sup>8</sup> The Levites were Jeshua, Binnui, Kadmiel, Sherebiah, Judah, and Mattaniah who was in charge of the songs of thanksgiving, he and his brothers.",
"9": "<sup>9</sup> Also Bakbukiah and Unni, their brothers, stood opposite them in their service divisions.",
"10": "<sup>10</sup> Jeshua became the father of Joiakim, and Joiakim became the father of Eliashib, and Eliashib became the father of Joiada,",
"11": "<sup>11</sup> and Joiada became the father of Jonathan, and Jonathan became the father of Jaddua.",
"12": "<sup>12</sup> Now in the days of Joiakim, the priests, the heads of fathers' households were: of Seraiah, Meraiah; of Jeremiah, Hananiah;",
"13": "<sup>13</sup> of Ezra, Meshullam; of Amariah, Jehohanan;",
"14": "<sup>14</sup> of Malluchi, Jonathan; of Shebaniah, Joseph;",
"15": "<sup>15</sup> of Harim, Adna; of Meraioth, Helkai;",
"16": "<sup>16</sup> of Iddo, Zechariah; of Ginnethon, Meshullam;",
"17": "<sup>17</sup> of Abijah, Zichri; of Miniamin, of Moadiah, Piltai;",
"18": "<sup>18</sup> of Bilgah, Shammua; of Shemaiah, Jehonathan;",
"19": "<sup>19</sup> of Joiarib, Mattenai; of Jedaiah, Uzzi;",
"20": "<sup>20</sup> of Sallai, Kallai; of Amok, Eber;",
"21": "<sup>21</sup> of Hilkiah, Hashabiah; of Jedaiah, Nethanel.",
"22": "<sup>22</sup> As for the Levites, the heads of fathers' households were registered in the days of Eliashib, Joiada, and Johanan and Jaddua; so were the priests in the reign of Darius the Persian.",
"23": "<sup>23</sup> The sons of Levi, the heads of fathers' households, were registered in the Book of the Chronicles up to the days of Johanan the son of Eliashib.",
"24": "<sup>24</sup> The heads of the Levites were Hashabiah, Sherebiah and Jeshua the son of Kadmiel, with their brothers opposite them, to praise and give thanks, as prescribed by David the man of God, division corresponding to division.",
"25": "<sup>25</sup> Mattaniah, Bakbukiah, Obadiah, Meshullam, Talmon and Akkub were gatekeepers keeping watch at the storehouses of the gates.",
"26": "<sup>26</sup> These served in the days of Joiakim the son of Jeshua, the son of Jozadak, and in the days of Nehemiah the governor and of Ezra the priest and scribe.",
"27": "<sup>27</sup> Now at the dedication of the wall of Jerusalem they sought out the Levites from all their places, to bring them to Jerusalem so that they might celebrate the dedication with gladness, with hymns of thanksgiving and with songs to the accompaniment of cymbals, harps and lyres.",
"28": "<sup>28</sup> So the sons of the singers were assembled from the district around Jerusalem, and from the villages of the Netophathites,",
"29": "<sup>29</sup> from Beth-gilgal and from their fields in Geba and Azmaveth, for the singers had built themselves villages around Jerusalem.",
"30": "<sup>30</sup> The priests and the Levites purified themselves; they also purified the people, the gates and the wall.",
"31": "<sup>31</sup> Then I had the leaders of Judah come up on top of the wall, and I appointed two great choirs, the first proceeding to the right on top of the wall toward the Refuse Gate.",
"32": "<sup>32</sup> Hoshaiah and half of the leaders of Judah followed them,",
"33": "<sup>33</sup> with Azariah, Ezra, Meshullam,",
"34": "<sup>34</sup> Judah, Benjamin, Shemaiah, Jeremiah,",
"35": "<sup>35</sup> and some of the sons of the priests with trumpets; and Zechariah the son of Jonathan, the son of Shemaiah, the son of Mattaniah, the son of Micaiah, the son of Zaccur, the son of Asaph,",
"36": "<sup>36</sup> and his kinsmen, Shemaiah, Azarel, Milalai, Gilalai, Maai, Nethanel, Judah and Hanani, with the musical instruments of David the man of God. And Ezra the scribe went before them.",
"37": "<sup>37</sup> At the Fountain Gate they went directly up the steps of the city of David by the stairway of the wall above the house of David to the Water Gate on the east.",
"38": "<sup>38</sup> The second choir proceeded to the left, while I followed them with half of the people on the wall, above the Tower of Furnaces, to the Broad Wall,",
"39": "<sup>39</sup> and above the Gate of Ephraim, by the Old Gate, by the Fish Gate, the Tower of Hananel and the Tower of the Hundred, as far as the Sheep Gate; and they stopped at the Gate of the Guard.",
"40": "<sup>40</sup> Then the two choirs took their stand in the house of God. So did I and half of the officials with me;",
"41": "<sup>41</sup> and the priests, Eliakim, Maaseiah, Miniamin, Micaiah, Elioenai, Zechariah and Hananiah, with the trumpets;",
"42": "<sup>42</sup> and Maaseiah, Shemaiah, Eleazar, Uzzi, Jehohanan, Malchijah, Elam and Ezer. And the singers sang, with Jezrahiah their leader,",
"43": "<sup>43</sup> and on that day they offered great sacrifices and rejoiced because God had given them great joy, even the women and children rejoiced, so that the joy of Jerusalem was heard from afar.",
"44": "<sup>44</sup> On that day men were also appointed over the chambers for the stores, the contributions, the first fruits and the tithes, to gather into them from the fields of the cities the portions required by the law for the priests and Levites; for Judah rejoiced over the priests and Levites who served.",
"45": "<sup>45</sup> For they performed the worship of their God and the service of purification, together with the singers and the gatekeepers in accordance with the command of David and of his son Solomon.",
"46": "<sup>46</sup> For in the days of David and Asaph, in ancient times, there were leaders of the singers, songs of praise and hymns of thanksgiving to God.",
"47": "<sup>47</sup> So all Israel in the days of Zerubbabel and Nehemiah gave the portions due the singers and the gatekeepers as each day required, and set apart the consecrated portion for the Levites, and the Levites set apart the consecrated portion for the sons of Aaron."
},
"13": {
"1": "<sup>1</sup> On that day they read aloud from the book of Moses in the hearing of the people; and there was found written in it that no Ammonite or Moabite should ever enter the assembly of God,",
"2": "<sup>2</sup> because they did not meet the sons of Israel with bread and water, but hired Balaam against them to curse them. However, our God turned the curse into a blessing.",
"3": "<sup>3</sup> So when they heard the law, they excluded all foreigners from Israel.",
"4": "<sup>4</sup> Now prior to this, Eliashib the priest, who was appointed over the chambers of the house of our God, being related to Tobiah,",
"5": "<sup>5</sup> had prepared a large room for him, where formerly they put the grain offerings, the frankincense, the utensils and the tithes of grain, wine and oil prescribed for the Levites, the singers and the gatekeepers, and the contributions for the priests.",
"6": "<sup>6</sup> But during all this time I was not in Jerusalem, for in the thirty-second year of Artaxerxes king of Babylon I had gone to the king. After some time, however, I asked leave from the king,",
"7": "<sup>7</sup> and I came to Jerusalem and learned about the evil that Eliashib had done for Tobiah, by preparing a room for him in the courts of the house of God.",
"8": "<sup>8</sup> It was very displeasing to me, so I threw all of Tobiah's household goods out of the room.",
"9": "<sup>9</sup> Then I gave an order and they cleansed the rooms; and I returned there the utensils of the house of God with the grain offerings and the frankincense.",
"10": "<sup>10</sup> I also discovered that the portions of the Levites had not been given them, so that the Levites and the singers who performed the service had gone away, each to his own field.",
"11": "<sup>11</sup> So I reprimanded the officials and said, \"Why is the house of God forsaken?\" Then I gathered them together and restored them to their posts.",
"12": "<sup>12</sup> All Judah then brought the tithe of the grain, wine and oil into the storehouses.",
"13": "<sup>13</sup> In charge of the storehouses I appointed Shelemiah the priest, Zadok the scribe, and Pedaiah of the Levites, and in addition to them was Hanan the son of Zaccur, the son of Mattaniah; for they were considered reliable, and it was their task to distribute to their kinsmen.",
"14": "<sup>14</sup> Remember me for this, O my God, and do not blot out my loyal deeds which I have performed for the house of my God and its services.",
"15": "<sup>15</sup> In those days I saw in Judah some who were treading wine presses on the sabbath, and bringing in sacks of grain and loading them on donkeys, as well as wine, grapes, figs and all kinds of loads, and they brought them into Jerusalem on the sabbath day. So I admonished them on the day they sold food.",
"16": "<sup>16</sup> Also men of Tyre were living there who imported fish and all kinds of merchandise, and sold them to the sons of Judah on the sabbath, even in Jerusalem.",
"17": "<sup>17</sup> Then I reprimanded the nobles of Judah and said to them, \"What is this evil thing you are doing, by profaning the sabbath day?",
"18": "<sup>18</sup> Did not your fathers do the same, so that our God brought on us and on this city all this trouble? Yet you are adding to the wrath on Israel by profaning the sabbath.\"",
"19": "<sup>19</sup> It came about that just as it grew dark at the gates of Jerusalem before the sabbath, I commanded that the doors should be shut and that they should not open them until after the sabbath. Then I stationed some of my servants at the gates so that no load would enter on the sabbath day.",
"20": "<sup>20</sup> Once or twice the traders and merchants of every kind of merchandise spent the night outside Jerusalem.",
"21": "<sup>21</sup> Then I warned them and said to them, \"Why do you spend the night in front of the wall? If you do so again, I will use force against you.\" From that time on they did not come on the sabbath.",
"22": "<sup>22</sup> And I commanded the Levites that they should purify themselves and come as gatekeepers to sanctify the sabbath day. For this also remember me, O my God, and have compassion on me according to the greatness of Your lovingkindness.",
"23": "<sup>23</sup> In those days I also saw that the Jews had married women from Ashdod, Ammon and Moab.",
"24": "<sup>24</sup> As for their children, half spoke in the language of Ashdod, and none of them was able to speak the language of Judah, but the language of his own people.",
"25": "<sup>25</sup> So I contended with them and cursed them and struck some of them and pulled out their hair, and made them swear by God, \"You shall not give your daughters to their sons, nor take of their daughters for your sons or for yourselves.",
"26": "<sup>26</sup> Did not Solomon king of Israel sin regarding these things? Yet among the many nations there was no king like him, and he was loved by his God, and God made him king over all Israel; nevertheless the foreign women caused even him to sin.",
"27": "<sup>27</sup> Do we then hear about you that you have committed all this great evil by acting unfaithfully against our God by marrying foreign women?\"",
"28": "<sup>28</sup> Even one of the sons of Joiada, the son of Eliashib the high priest, was a son-in-law of Sanballat the Horonite, so I drove him away from me.",
"29": "<sup>29</sup> Remember them, O my God, because they have defiled the priesthood and the covenant of the priesthood and the Levites.",
"30": "<sup>30</sup> Thus I purified them from everything foreign and appointed duties for the priests and the Levites, each in his task,",
"31": "<sup>31</sup> and I arranged for the supply of wood at appointed times and for the first fruits. Remember me, O my God, for good."
}
}
};
module.exports = book; | 146.806378 | 355 | 0.713568 |
9a77b16ff4748c476d05c6552b2373420ea79b64 | 104 | sql | SQL | back/sql/challenge_type.sql | G1ng3r/foobar | 625699680b2b31d0e269c58a3309ba46f86fc031 | [
"MIT"
] | null | null | null | back/sql/challenge_type.sql | G1ng3r/foobar | 625699680b2b31d0e269c58a3309ba46f86fc031 | [
"MIT"
] | null | null | null | back/sql/challenge_type.sql | G1ng3r/foobar | 625699680b2b31d0e269c58a3309ba46f86fc031 | [
"MIT"
] | null | null | null | create table challenge_type (
id serial,
title varchar(100),
description varchar(500)
); | 20.8 | 30 | 0.663462 |
b3d72b97e1d1388dcb0301857ffac6eca9501b72 | 2,438 | rs | Rust | src/responses/status.rs | basiliqio/ciboulette | c13b45a8320d283e01f1239b01e947f61e0f6d6b | [
"Apache-2.0",
"MIT"
] | null | null | null | src/responses/status.rs | basiliqio/ciboulette | c13b45a8320d283e01f1239b01e947f61e0f6d6b | [
"Apache-2.0",
"MIT"
] | 15 | 2021-05-03T10:05:37.000Z | 2021-05-20T10:58:24.000Z | src/responses/status.rs | basiliqio/ciboulette | c13b45a8320d283e01f1239b01e947f61e0f6d6b | [
"Apache-2.0",
"MIT"
] | null | null | null | use super::*;
/// The status a response should send
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CibouletteResponseStatus {
/// HTTP 200
Ok,
/// HTTP 204
OkEmpty,
/// HTTP 202
OkAsync,
/// HTTP 201
Created,
/// HTTP 403
Unsupported,
/// HTTP 404
NotFound,
/// HTTP 409
Conflict,
}
impl CibouletteResponseStatus {
pub fn is_success(&self) -> bool {
match self {
CibouletteResponseStatus::Ok
| CibouletteResponseStatus::OkEmpty
| CibouletteResponseStatus::OkAsync
| CibouletteResponseStatus::Created => true,
CibouletteResponseStatus::Unsupported
| CibouletteResponseStatus::NotFound
| CibouletteResponseStatus::Conflict => false,
}
}
/// Get a response status for a given request type and data.
///
/// Applicable only if the request was a success
pub fn get_status_for_ok_response<'request, 'response, B>(
request: &dyn CibouletteRequestCommons<'request>,
response_body: &CibouletteResponseBody<'response, B>,
) -> Self {
match (request.intention(), response_body.data()) {
(CibouletteIntention::Create, CibouletteOptionalData::Object(_)) => {
CibouletteResponseStatus::Created
}
(CibouletteIntention::Create, CibouletteOptionalData::Null(_)) => {
CibouletteResponseStatus::Ok
// TODO : In the future, CibouletteResponseStatus::OkEmpty should be used
}
// TODO : In the future, (CibouletteIntention::Delete, _) => CibouletteResponseStatus::OkEmpty should be used,
(CibouletteIntention::Delete, _) => CibouletteResponseStatus::Ok,
(CibouletteIntention::Read, CibouletteOptionalData::Object(_)) => {
CibouletteResponseStatus::Ok
}
(CibouletteIntention::Read, CibouletteOptionalData::Null(_)) => {
CibouletteResponseStatus::NotFound
}
(CibouletteIntention::Update, CibouletteOptionalData::Object(_)) => {
CibouletteResponseStatus::Ok
}
(CibouletteIntention::Update, CibouletteOptionalData::Null(_)) => {
CibouletteResponseStatus::Ok
// TODO : In the future, CibouletteResponseStatus::OkEmpty should be used
}
}
}
}
| 35.852941 | 124 | 0.603363 |
7f31382669fd9aa0b8d4c2d07d07d9a0a6919cbc | 46 | php | PHP | 404.php | jacob-larsen-netbooster/jlnb | 400df069a523801f01bc11a3b2c0e8cbb208f3d3 | [
"0BSD"
] | null | null | null | 404.php | jacob-larsen-netbooster/jlnb | 400df069a523801f01bc11a3b2c0e8cbb208f3d3 | [
"0BSD"
] | null | null | null | 404.php | jacob-larsen-netbooster/jlnb | 400df069a523801f01bc11a3b2c0e8cbb208f3d3 | [
"0BSD"
] | null | null | null | <?php get_header( '404' ); ?>
<h2>404 pis</h2> | 23 | 29 | 0.565217 |
f2bba62eff196765d84e6972deb39163bbe5f3d2 | 519 | swift | Swift | Cosmos-IOS/Cosmostation/Cosmostation/Cell/ValidatorDetailHistoryEmpty.swift | RNSSolution/colorplatform-mobile | 6fcecf7a3029adca69d066d5d18590af0664bb6a | [
"MIT"
] | 97 | 2019-06-28T12:31:40.000Z | 2022-03-29T05:38:32.000Z | Cosmos-IOS/Cosmostation/Cosmostation/Cell/ValidatorDetailHistoryEmpty.swift | RNSSolution/colorplatform-mobile | 6fcecf7a3029adca69d066d5d18590af0664bb6a | [
"MIT"
] | 84 | 2019-09-17T10:01:29.000Z | 2021-10-21T07:55:10.000Z | Cosmos-IOS/Cosmostation/Cosmostation/Cell/ValidatorDetailHistoryEmpty.swift | RNSSolution/colorplatform-mobile | 6fcecf7a3029adca69d066d5d18590af0664bb6a | [
"MIT"
] | 44 | 2019-07-18T04:26:49.000Z | 2022-03-14T06:40:36.000Z | //
// ValidatorDetailHistoryEmpty.swift
// Cosmostation
//
// Created by yongjoo on 04/04/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
class ValidatorDetailHistoryEmpty: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.76 | 65 | 0.678227 |
8da0dad66a0dc2d6e91ec516a6dd3ceeb9cfa8d5 | 186 | js | JavaScript | src/utils/checkSavedSettings.js | wwwal2/Cinema | dcf0ee435b88b1b9e1ba27e15d0e1d250b66f896 | [
"MIT"
] | null | null | null | src/utils/checkSavedSettings.js | wwwal2/Cinema | dcf0ee435b88b1b9e1ba27e15d0e1d250b66f896 | [
"MIT"
] | 5 | 2021-03-10T20:52:24.000Z | 2022-02-26T22:46:51.000Z | src/utils/checkSavedSettings.js | wwwal2/Cinema | dcf0ee435b88b1b9e1ba27e15d0e1d250b66f896 | [
"MIT"
] | null | null | null | export default (defaultOptions) => {
try {
const loaded = JSON.parse(localStorage.getItem('cinema'));
return loaded || defaultOptions;
} catch (e) {
return false;
}
};
| 20.666667 | 62 | 0.634409 |
a33c31a4f4421634f453d83289366a271e70fef5 | 3,443 | java | Java | app/src/main/java/com/stratagile/qlink/view/FreeSelectPopWindow.java | qlinkDev/qlink | 1c8066e4ebbb53c7401751ea3887a6315ccbe5eb | [
"MIT"
] | 30 | 2017-12-31T15:59:47.000Z | 2018-04-24T07:41:29.000Z | app/src/main/java/com/stratagile/qlink/view/FreeSelectPopWindow.java | huzhipeng111/WinQ | 39925732597fd4822cd554429fab655e8c858c4b | [
"MIT"
] | 46 | 2020-03-29T06:32:02.000Z | 2021-05-14T07:27:39.000Z | app/src/main/java/com/stratagile/qlink/view/FreeSelectPopWindow.java | huzhipeng111/WinQ | 39925732597fd4822cd554429fab655e8c858c4b | [
"MIT"
] | 11 | 2018-05-07T21:15:28.000Z | 2019-08-03T10:33:11.000Z | package com.stratagile.qlink.view;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.IdRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import com.stratagile.qlink.R;
public class FreeSelectPopWindow extends PopupWindow {
private OnItemClickListener mOnItemClickListener;
@SuppressLint("InflateParams")
public FreeSelectPopWindow(final Activity context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View content = inflater.inflate(R.layout.popupwindow_add, null);
// 设置SelectPicPopupWindow的View
this.setContentView(content);
// 设置SelectPicPopupWindow弹出窗体的宽
this.setWidth(LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow弹出窗体的高
this.setHeight(LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow弹出窗体可点击
this.setFocusable(true);
this.setOutsideTouchable(true);
// 刷新状态
this.update();
// 实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0000000000);
// 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ,设置其他控件变化等操作
this.setBackgroundDrawable(dw);
// 设置SelectPicPopupWindow弹出窗体动画效果
this.setAnimationStyle(R.style.AnimationPreview);
RelativeLayout rlAll = (RelativeLayout) content.findViewById(R.id.rl_all);
RelativeLayout rlGain = (RelativeLayout) content.findViewById(R.id.rl_gain);
RelativeLayout rlUsed = (RelativeLayout) content.findViewById(R.id.rl_used);
rlAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FreeSelectPopWindow.this.dismiss();
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v.getId());
}
}
});
rlGain.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FreeSelectPopWindow.this.dismiss();
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v.getId());
}
}
});
rlUsed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FreeSelectPopWindow.this.dismiss();
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v.getId());
}
}
});
}
/**
* 显示popupWindow
*
* @param parent
*/
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
// 以下拉方式显示popupwindow
this.showAsDropDown(parent, -120, 20);
} else {
this.dismiss();
}
}
public interface OnItemClickListener {
void onItemClick(@IdRes int id);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
}
| 31.87963 | 85 | 0.641882 |
dd9885e92b9de8ba35c1a28a284d59c0444ce58f | 795 | java | Java | src/minecraft/net/minecraft/src/WorldSettings.java | GreenCubes-org/GreenCubesOldClient | d6a362443479035ff8c1659b838774008f96b914 | [
"Apache-2.0",
"MIT"
] | 5 | 2020-04-08T10:42:27.000Z | 2022-01-30T17:53:46.000Z | src/minecraft/net/minecraft/src/WorldSettings.java | GreenCubes-org/GreenCubesOldClient | d6a362443479035ff8c1659b838774008f96b914 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/minecraft/net/minecraft/src/WorldSettings.java | GreenCubes-org/GreenCubesOldClient | d6a362443479035ff8c1659b838774008f96b914 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-05-16T17:18:15.000Z | 2020-06-09T22:58:10.000Z | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
public final class WorldSettings {
private final long worldSeed;
private final int worldType;
private final boolean mapFeaturesEnabled;
private final boolean hardcoreEnabled;
public WorldSettings(long l, int i, boolean flag, boolean flag1) {
worldSeed = l;
worldType = i;
mapFeaturesEnabled = flag;
hardcoreEnabled = flag1;
}
public long getSeed() {
return worldSeed;
}
public int getGameType() {
return worldType;
}
public boolean getHardcoreEnabled() {
return hardcoreEnabled;
}
public boolean isMapFeaturesEnabled() {
return mapFeaturesEnabled;
}
}
| 21.486486 | 67 | 0.748428 |
82c0727db5bb48548d15e5d3dd0e33b9462140d6 | 1,687 | rb | Ruby | test/started.test.rb | andrew-aladev/ocg | 4ca44f711f88c212a70dd62f022631c390602712 | [
"MIT"
] | null | null | null | test/started.test.rb | andrew-aladev/ocg | 4ca44f711f88c212a70dd62f022631c390602712 | [
"MIT"
] | 1 | 2020-10-16T20:37:23.000Z | 2020-10-16T21:45:34.000Z | test/started.test.rb | andrew-aladev/ocg | 4ca44f711f88c212a70dd62f022631c390602712 | [
"MIT"
] | null | null | null | # Option combination generator.
# Copyright (c) 2019 AUTHORS, MIT License.
require_relative "common"
require_relative "minitest"
class OCG
module Test
class Started < Minitest::Test
def test_basic
Test.get_datas do |generator, combinations|
refute generator.started?
combinations.each do |combination|
assert_equal generator.next, combination
test_started generator, combinations
end
test_started generator, combinations
end
end
def test_after_reset
Test.get_datas do |generator, combinations|
refute generator.started?
test_first_option generator, combinations
# First reset calls after first combination.
# Second reset calls after all combinations.
2.times do
generator.reset
refute generator.started?
combinations.each do |combination|
assert_equal generator.next, combination
test_started generator, combinations
end
test_started generator, combinations
end
end
end
protected def test_started(generator, combinations)
if combinations.empty?
refute generator.started?
else
assert generator.started?
end
end
protected def test_first_option(generator, combinations)
if combinations.empty?
assert_nil generator.next
refute generator.started?
else
assert_equal generator.next, combinations[0]
assert generator.started?
end
end
end
Minitest << Started
end
end
| 25.179104 | 62 | 0.625963 |
0de3993e7e421904e4b938a6da1d9ddd0ac7b634 | 8,092 | cs | C# | ServerManager.cs | pay-map/PayMap-Server | ce9232746fd9a67e703b222d3b3a41df264f7949 | [
"MIT"
] | 1 | 2020-06-20T18:53:35.000Z | 2020-06-20T18:53:35.000Z | ServerManager.cs | pay-map/PayMap-Server | ce9232746fd9a67e703b222d3b3a41df264f7949 | [
"MIT"
] | 1 | 2020-06-05T13:08:43.000Z | 2020-06-13T15:09:49.000Z | ServerManager.cs | pay-map/PayMap-Server | ce9232746fd9a67e703b222d3b3a41df264f7949 | [
"MIT"
] | 1 | 2020-06-21T10:05:32.000Z | 2020-06-21T10:05:32.000Z | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Utilities;
namespace PAYMAP_BACKEND
{
public class ServerManager
{
private static ServerManager _instance;
public static bool IsModuleRunning = false;
public static bool IsModuleHealthy = false;
private WebServer webServerGeocode;
private WebServer webServerZeroPay;
private ServerManager()
{
}
public static ServerManager GetInstance()
{
return _instance ?? (_instance = new ServerManager());
}
public void StartWebServer()
{
webServerGeocode = new WebServer(GeocodeResponse, "http://devx.kr:9991/geocode/");
webServerGeocode.Run();
webServerZeroPay = new WebServer(ZeroPayResponse, "http://devx.kr:9991/zeropay/");
webServerZeroPay.Run();
}
public void StopWebServer()
{
webServerGeocode?.Stop();
webServerZeroPay?.Stop();
}
public static string GeocodeResponse(HttpListenerRequest request)
{
NameValueCollection queryCollection = HttpUtility.ParseQueryString(request.Url.Query);
string inputId = queryCollection.Get("id");
if (inputId == null || inputId.Equals(String.Empty)) inputId = Constants.NAVER_SB_ID;
string inputKey = queryCollection.Get("key");
if (inputKey == null || inputKey.Equals(String.Empty)) inputKey = Constants.NAVER_SB_KEY;
string[] inputAddressArray;
string inputAddress = queryCollection.Get("address");
if (inputAddress == null || inputAddress.Equals(String.Empty)) inputAddress = "";
inputAddressArray = inputAddress.Split('|');
string inputCoordinate = queryCollection.Get("coordinate");
if (inputCoordinate == null || inputCoordinate.Equals(String.Empty)) inputCoordinate = "";
string[] headerId;
string[] headerKey;
string[] headerAddress;
string[] headerCoordinate;
headerId = request.Headers.GetValues("id");
if (headerId != null && headerId.Length > 0)
{
inputId = headerId[0];
}
headerKey = request.Headers.GetValues("key");
if (headerKey != null && headerKey.Length > 0)
{
inputKey = headerKey[0];
}
headerAddress = request.Headers.GetValues("address");
if (headerAddress != null && headerAddress.Length > 0)
{
inputAddressArray = headerAddress;
}
headerCoordinate = request.Headers.GetValues("coordinate");
if (headerCoordinate != null && headerCoordinate.Length > 0)
{
inputCoordinate = headerCoordinate[0];
}
JArray naverGeocodeResultArray = new JArray();
WebClient naverGeocodeClient = new WebClient {Encoding = Encoding.UTF8};
naverGeocodeClient.Headers.Add("X-NCP-APIGW-API-KEY-ID", inputId);
naverGeocodeClient.Headers.Add("X-NCP-APIGW-API-KEY", inputKey);
for (int i = 0; i < inputAddressArray.Length; i ++)
{
string requestURL = $"https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query={inputAddressArray[i]}&coordinate={inputCoordinate}";
JObject resultObject = JObject.Parse(naverGeocodeClient.DownloadString(requestURL));
naverGeocodeResultArray.Add(resultObject);
}
return naverGeocodeResultArray.ToString();
}
public static string ZeroPayResponse(HttpListenerRequest request)
{
NameValueCollection queryCollection = HttpUtility.ParseQueryString(request.Url.Query);
string inputSido = queryCollection.Get("sido");
if (inputSido == null || inputSido.Equals(String.Empty)) inputSido = "0";
string inputSigungu = queryCollection.Get("sigungu");
if (inputSigungu == null || inputSigungu.Equals(String.Empty)) inputSigungu = "0";
string inputAddress = queryCollection.Get("address");
string inputName = queryCollection.Get("name");
string inputType = queryCollection.Get("type");
string inputMax = queryCollection.Get("max");
if (inputMax == null || inputMax.Equals(String.Empty)) inputMax = "1000";
JArray zeroResult = DatabaseManager.GetInstance().SearchShop(int.Parse(inputSido), int.Parse(inputSigungu), inputAddress, inputName, inputType, int.Parse(inputMax));
return zeroResult.ToString();
}
}
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
{
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
}
if (prefixes == null || prefixes.Count == 0)
{
throw new ArgumentException("URI prefixes are required");
}
if (method == null)
{
throw new ArgumentException("responder method required");
}
foreach (var s in prefixes)
{
_listener.Prefixes.Add(s);
}
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method)
{
}
public void Run()
{
ThreadPool.QueueUserWorkItem(o =>
{
LogManager.NewLog(LogType.ServerManager, LogLevel.Info, "WebServer:Run", "WebServer Started");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(c =>
{
var ctx = c as HttpListenerContext;
try
{
if (ctx == null)
{
return;
}
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.Headers["Access-Control-Allow-Origin"] = "*";
ctx.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
ctx.Response.Headers["Access-Control-Allow-Methods"] = "GET,POST,PUT,DELETE,OPTIONS";
ctx.Response.Headers["Access-Control-Allow-Credentials"] = "true";
ctx.Response.Headers["Content-Type"] = "application/json; charset=utf-8";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
ctx.Response.ContentEncoding = Encoding.UTF8;
}
catch
{
// ignored
}
finally
{
// always close the stream
if (ctx != null)
{
ctx.Response.OutputStream.Close();
}
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
// ignored
}
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
} | 37.462963 | 176 | 0.552274 |
a0d13a5998d4240ae2ecb36941a5b1f7a6cf6d92 | 232 | swift | Swift | Pixie/Pixie/Classes/Tools/String/String+CapitalizedFirst.swift | gsagadyn/Pixie | 30186159c4c712ce0d37537f11e0b22c47889a7c | [
"MIT"
] | 2 | 2020-04-17T08:48:42.000Z | 2020-05-14T00:12:46.000Z | Pixie/Pixie/Classes/Tools/String/String+CapitalizedFirst.swift | gsagadyn/Pixie | 30186159c4c712ce0d37537f11e0b22c47889a7c | [
"MIT"
] | null | null | null | Pixie/Pixie/Classes/Tools/String/String+CapitalizedFirst.swift | gsagadyn/Pixie | 30186159c4c712ce0d37537f11e0b22c47889a7c | [
"MIT"
] | null | null | null | //
// String+CapitalizedFirst.swift
// Pixie
//
// Created by Kamil Modzelewski on 05/06/2020.
//
import Foundation
extension String {
public var capitalizedFirst: Self {
prefix(1).capitalized + dropFirst()
}
}
| 15.466667 | 47 | 0.663793 |
389f2c2e9e6a68f55de6bdec1bec7f1ef3dce6c9 | 592 | php | PHP | app/Http/Models/Brands.php | Charu91/carebulls | 0c9ac38e25c675da1c63f5349c66923e75f648db | [
"MIT"
] | null | null | null | app/Http/Models/Brands.php | Charu91/carebulls | 0c9ac38e25c675da1c63f5349c66923e75f648db | [
"MIT"
] | null | null | null | app/Http/Models/Brands.php | Charu91/carebulls | 0c9ac38e25c675da1c63f5349c66923e75f648db | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Brands extends Model
{
/**
* Fillable fields
*
* @var array
*/
protected $fillable = [
'username',
];
protected $hidden = array('password');
protected $table = 'brands';
/*
public function next()
{
// get next user
return Brands::where('id', '>', $this->id)->orderBy('id','asc')->first();
}
public function previous()
{
// get previous user
return Brands::where('id', '<', $this->id)->orderBy('id','desc')->first();
}
*/
} | 16.914286 | 77 | 0.5625 |
bb6776a28cf695409da6b0efe3458320e8448e39 | 1,999 | cs | C# | BepuPhysics/Constraints/Contact/ContactConvexCommon.cs | FEETB24/bepuphysics2 | 328d946a8174307eee8418b63d2c80cfbf52997b | [
"Apache-2.0"
] | 1,245 | 2017-10-22T13:29:19.000Z | 2022-03-31T17:22:58.000Z | BepuPhysics/Constraints/Contact/ContactConvexCommon.cs | FEETB24/bepuphysics2 | 328d946a8174307eee8418b63d2c80cfbf52997b | [
"Apache-2.0"
] | 155 | 2017-10-22T02:05:33.000Z | 2022-03-31T03:34:06.000Z | BepuPhysics/Constraints/Contact/ContactConvexCommon.cs | FEETB24/bepuphysics2 | 328d946a8174307eee8418b63d2c80cfbf52997b | [
"Apache-2.0"
] | 174 | 2017-11-14T05:28:17.000Z | 2022-03-31T12:24:39.000Z | using BepuPhysics.CollisionDetection;
using BepuUtilities;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace BepuPhysics.Constraints.Contact
{
public struct ConvexContactWide
{
public Vector3Wide OffsetA;
public Vector<float> Depth;
}
public struct MaterialPropertiesWide
{
public Vector<float> FrictionCoefficient;
public SpringSettingsWide SpringSettings;
public Vector<float> MaximumRecoveryVelocity;
}
public interface IContactPrestep<TPrestep> where TPrestep : struct, IContactPrestep<TPrestep>
{
ref MaterialPropertiesWide GetMaterialProperties(ref TPrestep prestep);
int ContactCount { get; }
int BodyCount { get; }
}
public interface IConvexContactPrestep<TPrestep> : IContactPrestep<TPrestep> where TPrestep : struct, IConvexContactPrestep<TPrestep>
{
ref Vector3Wide GetNormal(ref TPrestep prestep);
ref ConvexContactWide GetContact(ref TPrestep prestep, int index);
}
public interface ITwoBodyConvexContactPrestep<TPrestep> : IConvexContactPrestep<TPrestep> where TPrestep : struct, ITwoBodyConvexContactPrestep<TPrestep>
{
ref Vector3Wide GetOffsetB(ref TPrestep prestep);
}
public interface IContactAccumulatedImpulses<TAccumulatedImpulses> where TAccumulatedImpulses : struct, IContactAccumulatedImpulses<TAccumulatedImpulses>
{
int ContactCount { get; }
}
public interface IConvexContactAccumulatedImpulses<TAccumulatedImpulses> : IContactAccumulatedImpulses<TAccumulatedImpulses> where TAccumulatedImpulses : struct, IConvexContactAccumulatedImpulses<TAccumulatedImpulses>
{
ref Vector2Wide GetTangentFriction(ref TAccumulatedImpulses impulses);
ref Vector<float> GetTwistFriction(ref TAccumulatedImpulses impulses);
ref Vector<float> GetPenetrationImpulseForContact(ref TAccumulatedImpulses impulses, int index);
}
}
| 35.696429 | 221 | 0.75938 |
8ec0b449087e8fd6e050277444b63492438c019c | 572 | js | JavaScript | frontend/ozon/src/views/Common/TextArea/TextArea.js | DuckLuckBreakout/ozonBackend | 90e0d95f70308ada460b6b675bf47e50ec0cef47 | [
"MIT"
] | null | null | null | frontend/ozon/src/views/Common/TextArea/TextArea.js | DuckLuckBreakout/ozonBackend | 90e0d95f70308ada460b6b675bf47e50ec0cef47 | [
"MIT"
] | 1 | 2022-01-02T13:08:32.000Z | 2022-01-02T13:08:32.000Z | frontend/ozon/src/views/Common/TextArea/TextArea.js | DuckLuckBreakout/web | 90e0d95f70308ada460b6b675bf47e50ec0cef47 | [
"MIT"
] | 2 | 2022-01-03T08:39:33.000Z | 2022-01-05T17:21:28.000Z | /**
* @class TextArea
* @classdesc This class is using for construct html via templates. One of the common views
*/
class TextArea {
/**
*
* @param {string} name name of a text area
* @param {number} rows amount of rows in text area
* @param {number} cols amount of columns in text aread
*/
constructor(
{
name,
rows,
cols,
} = {}) {
this.objectType = 'textarea';
this.name = name;
this.rows = rows;
this.cols = cols;
}
}
export default TextArea;
| 22 | 91 | 0.538462 |
a3514f9052bd6cc7baa05092431ac5b7eddd2173 | 2,433 | tsx | TypeScript | src/list.component.tsx | serlo/athene2-blue-gum | 9ac6be49e1774c8f42b849b85501325f3c1b9144 | [
"Apache-2.0"
] | 3 | 2019-04-17T15:13:08.000Z | 2020-03-10T10:40:54.000Z | src/list.component.tsx | serlo/athene2-blue-gum | 9ac6be49e1774c8f42b849b85501325f3c1b9144 | [
"Apache-2.0"
] | 38 | 2019-01-28T16:35:01.000Z | 2019-09-09T07:21:08.000Z | src/list.component.tsx | serlo/athene2-blue-gum | 9ac6be49e1774c8f42b849b85501325f3c1b9144 | [
"Apache-2.0"
] | 3 | 2019-02-23T17:04:35.000Z | 2019-06-18T07:05:47.000Z | import * as React from 'react'
import styled, { css } from 'styled-components'
import { getColor, lightenColor } from './provider.component'
export interface ListProps {
ordered?: boolean
unstyled?: boolean
}
export const List: React.FunctionComponent<ListProps> = props => {
return (
<StyledList
ordered={props.ordered}
unstyled={props.unstyled}
as={props.ordered ? 'ol' : undefined}
>
{props.children}
</StyledList>
)
}
List.defaultProps = {
ordered: false,
unstyled: false
}
interface StyledListProps {
ordered?: boolean
unstyled?: boolean
}
const StyledList = styled.ul<StyledListProps>`
margin-top: 0.3em;
margin-left: 0;
padding-left: 0;
counter-reset: list-counter;
list-style-type: none;
> li {
margin-top: 0.2rem;
}
${props =>
!props.unstyled && !props.ordered
? css`
> li {
padding-left: 1.1rem;
&:hover:before {
color: #fff;
background-color: ${getColor('brand')};
transform: scale(1.6);
}
&:before {
position: absolute;
background-color: ${getColor('lighterblue')};
display: inline-block;
width: 0.5em;
content: ' ' !important;
height: 0.5em;
border-radius: 3em;
margin-left: -0.9em;
margin-top: 0.45em;
}
}
`
: null}
${props =>
!props.unstyled && props.ordered
? css`
> li {
padding-left: 1.6rem;
&:hover:before {
color: #fff;
background-color: ${getColor('brand')};
}
&:before {
position: absolute;
content: counter(list-counter);
counter-increment: list-counter;
color: ${getColor('brand')};
font-weight: bold;
vertical-align: top;
display: inline-block;
text-align: right;
margin-left: -2.2em;
margin-top: 0.2em;
background-color: ${lightenColor('brand', 0.55)};
border-radius: 4em;
width: 1.1rem;
height: 1.1rem;
font-size: 0.7em;
text-align: center;
line-height: 1.6em;
}
}
`
: null}
`
| 23.171429 | 66 | 0.493629 |
af084a2090d0c901bb2835b698b7129a87ce9a66 | 2,887 | py | Python | ahc_tools/test/test_utils.py | rdo-management/ahc-tools | 5f27a7a38b5e12bcac12e28b851fcc9bd368a6d8 | [
"Apache-2.0"
] | null | null | null | ahc_tools/test/test_utils.py | rdo-management/ahc-tools | 5f27a7a38b5e12bcac12e28b851fcc9bd368a6d8 | [
"Apache-2.0"
] | null | null | null | ahc_tools/test/test_utils.py | rdo-management/ahc-tools | 5f27a7a38b5e12bcac12e28b851fcc9bd368a6d8 | [
"Apache-2.0"
] | 1 | 2015-04-15T11:39:40.000Z | 2015-04-15T11:39:40.000Z | # 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.
import json
import mock
from ironicclient.exc import AmbiguousAuthSystem
from ahc_tools.test import base
from ahc_tools import utils
class TestGetFacts(base.BaseTest):
@mock.patch.object(utils.swift, 'SwiftAPI', autospec=True)
def test_facts(self, swift_mock):
swift_conn = swift_mock.return_value
obj = json.dumps([[u'cpu', u'logical_0', u'bogomips', u'4199.99'],
[u'cpu', u'logical_0', u'cache_size', u'4096KB']])
swift_conn.get_object.return_value = obj
name = 'extra_hardware-UUID1'
node = mock.Mock(extra={'hardware_swift_object': name})
expected = [(u'cpu', u'logical_0', u'bogomips', u'4199.99'),
(u'cpu', u'logical_0', u'cache_size', u'4096KB')]
facts = utils.get_facts(node)
self.assertEqual(expected, facts)
swift_conn.get_object.assert_called_once_with(name)
def test_no_facts(self):
node = mock.Mock(extra={})
err_msg = ("You must run introspection on the nodes before "
"running this tool.\n")
self.assertRaisesRegexp(SystemExit, err_msg,
utils.get_facts, node)
@mock.patch.object(utils.client, 'get_client', autospec=True,
side_effect=AmbiguousAuthSystem)
class TestGetIronicClient(base.BaseTest):
def test_no_credentials(self, ic_mock):
utils.CONF.config_file = ['ahc-tools.conf']
err_msg = '.*credentials.*missing.*ironic.*searched.*ahc-tools.conf'
self.assertRaisesRegexp(SystemExit, err_msg,
utils.get_ironic_client)
self.assertTrue(ic_mock.called)
class TestGetIronicNodes(base.BaseTest):
def test_only_matchable_nodes_returned(self):
available_node = mock.Mock(provision_state='available')
manageable_node = mock.Mock(provision_state='manageable')
active_node = mock.Mock(provision_state='active')
ironic_client = mock.Mock()
ironic_client.node.list.return_value = [available_node,
manageable_node,
active_node]
expected = [available_node, manageable_node]
returned_nodes = utils.get_ironic_nodes(ironic_client)
self.assertEqual(expected, returned_nodes)
| 41.242857 | 76 | 0.660201 |
e66f58a899e8a48455201eb9647b54173529a288 | 1,153 | c | C | d/islands/elf/ice/rampart.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/islands/elf/ice/rampart.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/islands/elf/ice/rampart.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include "elf.h"
#include <std.h>
inherit ROOM;
void create() {
::create();
set_terrain(ICE);
set_travel(SLICK_FLOOR);
set_climate("arctic");
set_name("ruined rampart");
set_short("ruined rampart");
set_long("%^CYAN%^This is a the ruins of a defensive"+
" rampart that has been mostly destroyed by the "+
"relentless %^BOLD%^ice%^RESET%^%^CYAN%^ around it. The ground is a mix of"+
" ice with stone blocks lodged within them. There"+
" is a large %^BOLD%^throne%^RESET%^%^CYAN%^ made of ice sitting strangely"+
" on top of the highest point of the ruins.");
set_listen("default","You hear the sound of cold wind rushing"+
" through the mountains.");
set_items(([
"ice" : "Glacial ice has destroyed the rampart.",
"rocks" :"These rocks look to be the remains of a wall.",
({"throne","chair"}) : "This throne seems made of"+
" icicles going from the ground to the sky. "+
" It would be very cold and uncomfortable to sit in.",
]));
set_exits(([
"down" : ROOMS"ruin",
]));
}
| 34.939394 | 79 | 0.584562 |
d02fa762e7c129999f73e53a95ced23af429a711 | 34,360 | cpp | C++ | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | null | null | null | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | null | null | null | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | 1 | 2021-10-06T19:09:58.000Z | 2021-10-06T19:09:58.000Z | #include "snarls/algorithms/three_edge_connected_components.hpp"
#include <structures/union_find.hpp>
#include <limits>
#include <cassert>
#include <iostream>
#include <sstream>
//#define debug
namespace snarls {
namespace algorithms {
using namespace std;
void three_edge_connected_component_merges_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(size_t, size_t)>& same_component) {
// Independent implementation of Norouzi and Tsin (2014) "A simple 3-edge
// connected component algorithm revisited", which can't really be
// understood without Tsin (2007) "A Simple 3-Edge-Connected Component
// Algorithm".
// That algorithm assumes that all bridge edges are removed (i.e.
// everything is at least 2-connected), but we hack it a bit to generalize
// to graphs with bridge edges. It also assumes there are no self loops,
// but this implementation detects and allows self loops.
// The algorithm does a depth-first search through the graph, and is based
// on this "absorb-eject" operation. You do it at a node, across ("on") an
// edge. It (conceptually) steals all the edges from the node at the other
// end of the edge, deletes the edge, and deletes the other node as well if
// it has a degree greater than 2. (The original algorithm didn't have to
// deal with degree 1; here we treat it about the same as degree 2 and
// leave the node floating in its own 3 edge connected component, while
// hiding the single edge from the real logic of the algorithm.)
// Because of guarantees about the order in which we traverse the graph, we
// don't actually have to *do* any of the absorb-eject graph topology
// modifications. Instead, we just have to keep track of updates to nodes'
// "effective degree" in what would be the modified graph, and allow
// certain paths that we track during the algorithm to traverse the stolen
// edges.
// For each node, we keep track of a path. Because of guarantees we get
// from the algorithm, we know that paths can safely share tails. So to
// represent the tail of a path, we can just point to another node (or
// nowhere if the path ends). The head of a path is tougher, because a
// node's path can be empty. The node may not be on its own path. It is not
// immediately clear from analyzing the algorithm whether a node can have a
// nonempty path that it itself is not on, or be the tail of another node's
// path without being on that path. To support those cases, we also give
// each node a flag for whether it is on its own path.
// TODO: should we template this on an integer size so we can fit more work
// in less memory bandwidth when possible?
using number_t = size_t;
assert(node_count < numeric_limits<number_t>::max());
/// This defines the data we track for each node in the graph
struct TsinNode {
/// When in the DFS were we first visited?
number_t dfs_counter;
/// When in the DFS were we last visited?
/// Needed for finding replacement neighbors to implement path range
/// absorption in part 1.3, when we're asked for a range to a neighbor
/// that got eaten.
number_t dfs_exit;
/// What is our "low point" in the search. This is the earliest
/// dfs_counter for a node that this node or any node in its DFS
/// subtree has a back-edge to.
number_t low_point;
/// What is the effective degree of this node in the graph with all the
/// absorb-eject modifications applied?
number_t effective_degree = 0;
/// What node has the continuation of this node's path? If equal to
/// numeric_limits<number_t>::max(), the path ends after here.
/// The node's path is the path from this node, into its DFS subtree,
/// to (one of) the nodes in the subtree that has the back-edge that
/// caused this node's low point to be so low. Basically a low point
/// traceback.
number_t path_tail;
/// Is this node actually on its own path?
/// Nodes can be removed from their paths if those nodes don't matter
/// any more (i.e. got absorbed) but their paths still need to be tails
/// for other paths.
bool is_on_path;
/// Has the node been visited yet? Must be 0. TODO: Move to its own
/// vector to make zeroing them all free-ish with page table
/// shenanigans.
bool visited = false;
};
// We need to have all the nodes pre-allocated, so node references don't
// invalidate when we follow edges.
vector<TsinNode> nodes(node_count);
// We need to say how to absorb-eject along a whole path.
//
// We let you specify the node to absorb into; if it isn't
// numeric_limits<number_t>::max(), it is assumed to be the first node, and
// actually on the path, and path_start (if itself on its path) is also
// absorbed into it. This lets you absorb into a path with something
// prepended, without constructing the path.
//
// Similarly, we let you specify a past end to stop before. If this isn't
// numeric_limits<number_t>::max(), we stop and don't absorb the specified
// node, if we reach it. This lets us implement absorbing a range of a
// path, as called for in the algorithm.
//
// If you specify a past_end, and we never reach it, but also don't have
// just a single-node, no-edge "null" path, then something has gone wrong
// and we've violated known truths about the algorithm.
auto absorb_all_along_path = [&](number_t into, number_t path_start, number_t path_past_end) {
#ifdef debug
cerr << "(Absorbing all along path into " << into << " from " << path_start << " to before " << path_past_end << ")" << endl;
#endif
// Set this to false as soon as we cross an edge
bool path_null = true;
number_t here = path_start;
while (here != path_past_end) {
// Until we hit the end of the path
#ifdef debug
cerr << "(\tAt " << here << ")" << endl;
#endif
if (here == numeric_limits<number_t>::max()) {
// We hit the end of the path and never saw path_past_end.
#ifdef debug
cerr << "(\t\tReached path end and missed waypoint)" << endl;
#endif
// Only allowed if the path was actually edge-free and no merges needed to happen.
assert(path_null);
#ifdef debug
cerr << "(\t\t\tBut path was empty of edges)" << endl;
#endif
// Stop now.
break;
}
// Find the node we are at
auto& here_node = nodes[here];
if (here_node.is_on_path) {
// We're actually on the path.
#ifdef debug
cerr << "(\t\tOn path)" << endl;
#endif
if (into == numeric_limits<number_t>::max()) {
// We haven't found a first node to merge into yet; it is
// this one.
#ifdef debug
cerr << "(\t\tUse as into)" << endl;
#endif
into = here;
} else {
// We already have a first node to merge into, so merge.
#ifdef debug
cerr << "(\t\tMerge with " << into << ")" << endl;
#endif
// We are doing a merge! We'd better actually find the
// ending range bound, or something is wrong with our
// implementation of the algorithm.
path_null = false;
// Update the effective degrees as if we merged this node
// with the connected into node.
nodes[into].effective_degree = (nodes[into].effective_degree +
here_node.effective_degree - 2);
// Merge us into the same 3 edge connected component
same_component(into, here);
}
}
// Advance to the tail of the path
here = here_node.path_tail;
#ifdef debug
cerr << "(\t\tNext: " << here << ")" << endl;
#endif
}
#ifdef debug
cerr << "(Done absorbing)" << endl;
#endif
};
// For debugging, we need to be able to dump a node's stored path
auto path_to_string = [&](number_t node) {
stringstream s;
number_t here = node;
bool first = true;
while (here != numeric_limits<number_t>::max()) {
if (nodes[here].is_on_path) {
if (first && nodes[here].path_tail == numeric_limits<number_t>::max()) {
// Just a single node, no edge
s << "(just " << here << ")";
break;
}
if (first) {
first = false;
} else {
s << "-";
}
s << here;
}
here = nodes[here].path_tail;
}
return s.str();
};
// We need a DFS stack that we manage ourselves, to avoid stack-overflowing
// as we e.g. walk along big cycles.
struct DFSStackFrame {
/// Track the node that this stack frame represents
number_t current;
/// Track all the neighbors left to visit.
/// When we visit a neighbor we pop it off the back.
vector<number_t> neighbors;
/// When we look at the neighbors, we need to be able to tell the tree
/// edge to the parent from further back edges to the parent. So we
/// have a flag for whether we have seen the parent tree edge already,
/// and the first neighbors entry that is our parent will get called
/// the tree edge.
bool saw_parent_tree_edge = false;
/// Track whether we made a recursive DFS call into the last neighbor
/// or not. If we did, we need to do some work when we come out of it
/// and return to this frame.
bool recursing = false;
};
vector<DFSStackFrame> stack;
// We need a way to produce unvisited nodes when we run out of nodes in a
// connected component. This will always point to the next unvisited node
// in order. If it points to node_count, all nodes are visited. When we
// fisit this node, we have to scan ahead for the next unvisited node, in
// number order.
number_t next_unvisited = 0;
// We also keep a global DFS counter, so we don't have to track parent
// relationships when filling it in on the nodes.
//
// The paper starts it at 1, so we do too.
number_t dfs_counter = 1;
while (next_unvisited != node_count) {
// We haven't visited everything yet.
if (!nodes[first_root].visited) {
// If possible start at the suggested root
stack.emplace_back();
stack.back().current = first_root;
} else {
// Stack up the next unvisited node.
stack.emplace_back();
stack.back().current = next_unvisited;
}
#ifdef debug
cerr << "Root a search at " << stack.back().current << endl;
#endif
while (!stack.empty()) {
// While there's still nodes on the DFS stack from the last component we broke into
// Grab the stack frame.
// Note that this reference will be invalidated if we add stuff to the stack!
auto& frame = stack.back();
// And the current node
auto& node = nodes[frame.current];
if (!node.visited) {
// This is the first time we are in this stack frame. We need
// to do the initial visit of the node and set up the frame
// with the list of edges to do.
node.visited = true;
#ifdef debug
cerr << "First visit of node " << frame.current << endl;
#endif
if (frame.current == next_unvisited) {
// We need to find the next unvisited node, if any, since
// we just visited what it used to be.
do {
next_unvisited++;
} while (next_unvisited != node_count && nodes[next_unvisited].visited);
}
node.dfs_counter = dfs_counter;
dfs_counter++;
node.low_point = node.dfs_counter;
// Make sure the node's path is just itself
node.path_tail = numeric_limits<number_t>::max();
node.is_on_path = true;
#ifdef debug
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// Stack up all the edges to follow.
for_each_connected_node(frame.current, [&](size_t connected) {
frame.neighbors.push_back(connected);
});
#ifdef debug
cerr << "\tPut " << frame.neighbors.size() << " edges on to do list" << endl;
#endif
// Now we're in a state where we can process edges.
// So kick back to the work loop as if we just processed an edge.
continue;
} else {
// We have (possibly 0) edges left to do for this node.
if (!frame.neighbors.empty()) {
#ifdef debug
cerr << "Return to node " << frame.current << " with more edges to do" << endl;
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// We have an edge to do!
// Look up the neighboring node.
number_t neighbor_number = frame.neighbors.back();
auto& neighbor = nodes[neighbor_number];
if (!frame.recursing) {
// This is the first time we are thinking about this neighbor.
#ifdef debug
cerr << "\tThink of edge to neighbor " << neighbor_number << " for the first time" << endl;
#endif
// Increment degree of the node we're coming from
node.effective_degree++;
#ifdef debug
cerr << "\t\tBump degree to " << node.effective_degree << endl;
#endif
if (!neighbor.visited) {
// We need to recurse on this neighbor.
#ifdef debug
cerr << "\t\tRecurse on unvisited neighbor" << endl;
#endif
// So remember we are recursing.
frame.recursing = true;
// And set up the recursive frame.
stack.emplace_back();
stack.back().current = neighbor_number;
// Kick back to the work loop; we will see the
// unvisited node on top of the stack and do its
// visit and add its edges to its to do list.
} else {
// No need to recurse.This is either a back-edge or the back side of the tree edge to the parent.
if (stack.size() > 1 && neighbor_number == stack[stack.size() - 2].current && !frame.saw_parent_tree_edge) {
// This is the edge we took to get here (tree edge)
#ifdef debug
cerr << "\t\tNeighbor is parent; this is the tree edge in." << endl;
#endif
// For tree edges, since they aren't either kind of back edge, neither 1.2 nor 1.3 fires.
// But the next edge to the parent will be a back edge.
frame.saw_parent_tree_edge = true;
} else if (neighbor.dfs_counter < node.dfs_counter) {
// The edge to the neighbor is an outgoing
// back-edge (i.e. the neighbor was visited
// first). Paper step 1.2.
#ifdef debug
cerr << "\t\tNeighbor is upstream of us (outgoing back edge)." << endl;
#endif
if (neighbor.dfs_counter < node.low_point) {
// The neighbor is below our low point.
#ifdef debug
cerr << "\t\t\tNeighbor has a lower low point ("
<< neighbor.dfs_counter << " < " << node.low_point << ")" << endl;
cerr << "\t\t\t\tAbsorb along path to old low point source" << endl;
#endif
// Absorb along our whole path.
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
numeric_limits<number_t>::max());
// Adopt the neighbor's DFS counter as our
// new, lower low point.
node.low_point = neighbor.dfs_counter;
#ifdef debug
cerr << "\t\t\t\tNew lower low point " << node.low_point << endl;
#endif
// Our path is now just us.
node.is_on_path = true;
node.path_tail = numeric_limits<number_t>::max();
#ifdef debug
cerr << "\t\t\t\tNew path " << path_to_string(frame.current) << endl;
#endif
} else {
#ifdef debug
cerr << "\t\t\tWe have a sufficiently low low point" << endl;
#endif
}
} else if (node.dfs_counter < neighbor.dfs_counter) {
// The edge to the neighbor is an incoming
// back-edge (i.e. we were visited first, but
// we recursed into something that got us to
// this neighbor already). Paper step 1.3.
#ifdef debug
cerr << "\t\tWe are upstream of neighbor (incoming back edge)." << endl;
#endif
// Drop our effective degree by 2 (I think
// we're closing a cycle or something?)
node.effective_degree -= 2;
#ifdef debug
cerr << "\t\t\tDrop degree to " << node.effective_degree << endl;
cerr << "\t\t\tWant to absorb along path towards low point source through neighbor" << endl;
#endif
// Now, the algorithm says to absorb
// "P_w[w..u]", a notation that it does not
// rigorously define. w is here, and u is the
// neighbor. The neighbor is not necessarily
// actually *on* our path at this point, not
// least of which because the neighbor may have
// already been eaten and merged into another
// node, which in theory adopted the back edge
// we are looking at. In practice we don't have
// the data structure to find that node. So
// here's the part where we have to do
// something clever to "allow certain paths
// that we track to traverse the stolen edges".
// What we have to do is find the node that
// *is* along our path that either is or ate
// the neighbor. We don't track the union-find
// logic we would need to answer that question,
// but both 2007 algorithm implementations I've
// seen deal with this by tracking DFS counter
// intervals/subtree sizes, and deciding that
// the last thin on our path visited no later
// than the neighbor, and exited no earlier
// than the neighbor (i.e. the last ancestor of
// the neighbor on our path) should be our
// replacement neighbor.
// This makes sense because if the neighbor
// merged into anything, it's an ancestor of
// the neighbor. So we go looking for it.
// TODO: let absorb_all_along_path do this instead?
// Start out with ourselves as the replacement neighbor ancestor.
number_t replacement_neighbor_number = frame.current;
// Consider the next candidate
number_t candidate = nodes[replacement_neighbor_number].path_tail;
while (candidate != numeric_limits<number_t>::max() &&
nodes[candidate].dfs_counter <= neighbor.dfs_counter &&
nodes[candidate].dfs_exit >= neighbor.dfs_exit) {
// This candidate is a lower ancestor of the neighbor, so adopt it.
replacement_neighbor_number = candidate;
candidate = nodes[replacement_neighbor_number].path_tail;
}
auto& replacement_neighbor = nodes[replacement_neighbor_number];
#ifdef debug
cerr << "\t\t\tNeighbor currently belongs to node " << replacement_neighbor_number << endl;
cerr << "\t\t\tAbsorb along path towards low point source through there" << endl;
#endif
// Absorb along our path from ourselves to the
// replacement neighbor, inclusive.
// Ignores trivial paths.
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
replacement_neighbor.path_tail);
// We also have to (or at least can) adopt the
// path of the replacement neighbor as our own
// path now. That's basically the rest of the
// path that we didn't merge.
// This isn't mentioned in the paper either,
// but I've seen the official implementation do
// it, and if we don't do it our path is going
// to go through a bunch of stuff we already
// merged, and waste time when we merge again.
// If we ever merge us down our path again,
// continue with the part we didn't already
// eat.
node.path_tail = replacement_neighbor.path_tail;
} else {
// The other possibility is the neighbor is just
// us. Officially self loops aren't allowed, so
// we censor the edge.
#ifdef debug
cerr << "\t\tWe are neighbor (self loop). Hide edge!" << endl;
#endif
node.effective_degree--;
}
// Clean up the neighbor from the to do list; we
// finished it without recursing.
frame.neighbors.pop_back();
// Kick back to the work loop to do the next
// neighbor, if any.
}
} else {
// We have returned from a recursive call on this neighbor.
#ifdef debug
cerr << "\tReturned from recursion on neighbor " << neighbor_number << endl;
#endif
// Support bridge edges: detect if we are returning
// across a bridge edge and censor it. Norouzi and Tsin
// 2014 as written in the paper assumes no bridge
// edges, and what we're about to do relies on all
// neighbors connecting back somewhere.
if (neighbor.low_point == neighbor.dfs_counter) {
// It has no back-edges out of its own subtree, so it must be across a bridge.
#ifdef debug
cerr << "\t\tNeighbor is across a bridge edge! Hide edge!" << endl;
#endif
// Hide the edge we just took from degree calculations.
neighbor.effective_degree--;
node.effective_degree--;
// Don't do anything else with the edge
} else {
// Wasn't a bridge edge, so we care about more than just traversing that part of the graph.
// Do steps 1.1.1 and 1.1.2 of the algorithm as described in the paper.
if (neighbor.effective_degree == 2) {
// This neighbor gets absorbed and possibly ejected.
#ifdef debug
cerr << "\t\tNeighbor is on a stick" << endl;
cerr << "\t\t\tEdge " << frame.current << "-" << neighbor_number << " should never be seen again" << endl;
#endif
// Take it off of its own path.
neighbor.is_on_path = false;
#ifdef debug
cerr << "\t\t\tNew neighbor path: " << path_to_string(neighbor_number) << endl;
#endif
}
// Because we hid the bridge edges, degree 1 nodes should never happen
assert(neighbor.effective_degree != 1);
if (node.low_point <= neighbor.low_point) {
#ifdef debug
cerr << "\t\tWe have a sufficiently low low point; neighbor comes back in in our subtree" << endl;
cerr << "\t\t\tAbsorb us and then the neighbor's path to the end" << endl;
#endif
// Absorb all along the path starting with here and
// continuing with this neighbor's path, to the
// end.
absorb_all_along_path(frame.current,
neighbor_number,
numeric_limits<number_t>::max());
} else {
#ifdef debug
cerr << "\t\tNeighbor has a lower low point ("
<< neighbor.low_point << " < " << node.low_point << "); comes back in outside our subtree" << endl;
#endif
// Lower our low point to that of the neighbor
node.low_point = neighbor.low_point;
#ifdef debug
cerr << "\t\t\tNew low point: " << node.low_point << endl;
cerr << "\t\t\tAbsorb along path to old low point soure" << endl;
#endif
// Absorb all along our own path
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
numeric_limits<number_t>::max());
// Adjust our path to be us and then our neighbor's path
node.is_on_path = true;
node.path_tail = neighbor_number;
#ifdef debug
cerr << "\t\t\tNew path " << path_to_string(frame.current) << endl;
#endif
}
}
// Say we aren't coming back from a recursive call
// anymore.
frame.recursing = false;
// Clean up the neighbor,
frame.neighbors.pop_back();
// Kick back to the work loop to do the next neighbor,
// if any.
}
#ifdef debug
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
} else {
// All the neighbors left to do for this node are done.
#ifdef debug
cerr << "\tNode is visited and no neighbors are on the to do list." << endl;
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// This node is done.
// Remember when we exited it
node.dfs_exit = dfs_counter;
// Clean up the stack frame.
stack.pop_back();
}
}
}
}
// When we run out of unvisited nodes and the stack is empty, we've
// completed out search through all connected components of the graph.
}
void three_edge_connected_components_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(size_t)>&)>&)>& component_callback) {
// Make a union-find over all the nodes
structures::UnionFind uf(node_count, true);
// Call Tsin's Algorithm
three_edge_connected_component_merges_dense(node_count, first_root, for_each_connected_node, [&](size_t a, size_t b) {
// When it says to do a merge, do it
uf.union_groups(a, b);
});
for (auto& component : uf.all_groups()) {
// Call the callback for each group
component_callback([&](const function<void(size_t)>& emit_member) {
// And whrn it asks for the members
for (auto& member : component) {
// Send them all
emit_member(member);
}
});
}
}
}
}
| 47.855153 | 138 | 0.472934 |
da4523b0c5007da8d8fd558a4c19c219c5fbd90a | 508 | php | PHP | app/Model/ProjectAdmin.php | michael34-cwa/CWA | 09afac759b29c1cef1994196882c667ecf26c7a6 | [
"MIT"
] | null | null | null | app/Model/ProjectAdmin.php | michael34-cwa/CWA | 09afac759b29c1cef1994196882c667ecf26c7a6 | [
"MIT"
] | 2 | 2020-04-22T13:24:13.000Z | 2021-05-11T08:00:54.000Z | app/Model/ProjectAdmin.php | michael34-cwa/CWA | 09afac759b29c1cef1994196882c667ecf26c7a6 | [
"MIT"
] | null | null | null | <?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class ProjectAdmin extends Model
{
protected $table = 'project_admins';
// public $timestamps = false;
protected $fillable = ['school_id', 'project_admin_id', 'created_by'];
public function User()
{
return $this->belongsTo('App\User', 'project_admin_id', 'id');
}
public function ActivationsUser()
{
return $this->hasOne('App\Model\Activations', 'user_id', 'project_admin_id');
}
}
| 20.32 | 85 | 0.655512 |
93c607bc8fed12e9f670f1559c58686586550bea | 258 | cs | C# | CBreeze/UncommonSense.CBreeze.Core/TextEncoding.cs | mprise-indigo/UncommonSense.CBreeze | 579d09bf9736f200aba5e92203755ab9082e59d3 | [
"MIT"
] | 6 | 2018-04-12T09:46:42.000Z | 2020-09-29T20:09:52.000Z | CBreeze/UncommonSense.CBreeze.Core/TextEncoding.cs | mprise-indigo/UncommonSense.CBreeze | 579d09bf9736f200aba5e92203755ab9082e59d3 | [
"MIT"
] | 32 | 2018-01-26T20:48:27.000Z | 2018-11-01T19:02:18.000Z | CBreeze/UncommonSense.CBreeze.Core/TextEncoding.cs | mprise-indigo/UncommonSense.CBreeze | 579d09bf9736f200aba5e92203755ab9082e59d3 | [
"MIT"
] | 4 | 2018-05-18T10:08:27.000Z | 2019-04-12T08:32:31.000Z | using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace UncommonSense.CBreeze.Core
{
public enum TextEncoding
{
MsDos,
Utf8,
Utf16,
#if NAV2013R2
Windows
#endif
}
}
| 13.578947 | 36 | 0.655039 |
68cef1c7304fe50422adadf817642eb7e7dd94af | 403 | swift | Swift | ReformGraphics/ReformGraphics/Color.swift | laszlokorte/reform-swift | ee0380dae249111cb7bfba764ad80723a4deb16e | [
"MIT"
] | 299 | 2016-01-28T19:59:54.000Z | 2022-02-14T23:10:15.000Z | ReformGraphics/ReformGraphics/Color.swift | laszlokorte/reform-swift | ee0380dae249111cb7bfba764ad80723a4deb16e | [
"MIT"
] | 20 | 2016-06-25T16:05:38.000Z | 2021-07-10T10:48:40.000Z | ReformGraphics/ReformGraphics/Color.swift | laszlokorte/reform-swift | ee0380dae249111cb7bfba764ad80723a4deb16e | [
"MIT"
] | 26 | 2016-03-29T06:38:56.000Z | 2021-12-24T03:36:36.000Z | //
// Color.swift
// ReformGraphics
//
// Created by Laszlo Korte on 16.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public struct Color {
let red : UInt8
let green : UInt8
let blue: UInt8
let alpha : UInt8
public init(r:UInt8, g:UInt8, b:UInt8, a:UInt8) {
self.red = r
self.green = g
self.blue = b
self.alpha = a
}
} | 19.190476 | 55 | 0.57072 |
385b0ec82adf077c358d48651db1d0660c55017c | 103 | php | PHP | plugins/ari-adminer/adminer/wrapper_adminer.php | samuelmoses2011/Ocearch---WordPress | e0afe0f86b48b19f551ed096b5ba20db5c74b1b6 | [
"Unlicense"
] | 1 | 2017-08-03T04:57:37.000Z | 2017-08-03T04:57:37.000Z | plugins/ari-adminer/adminer/wrapper_adminer.php | samuelmoses2011/Ocearch---WordPress | e0afe0f86b48b19f551ed096b5ba20db5c74b1b6 | [
"Unlicense"
] | null | null | null | plugins/ari-adminer/adminer/wrapper_adminer.php | samuelmoses2011/Ocearch---WordPress | e0afe0f86b48b19f551ed096b5ba20db5c74b1b6 | [
"Unlicense"
] | null | null | null | <?php
define( 'ADMINER_WRAPPER_TYPE', 'adminer' );
require_once dirname( __FILE__ ) . '/wrapper.php';
| 20.6 | 50 | 0.708738 |
05cb604c87fea6779300d4d37db8a6a66707877e | 2,908 | py | Python | JPS_Chatbot/jps-chatbot/UI/source/Wikidata_Query/fuzzysearch_wiki.py | cambridge-cares/TheWorldAvatar | baf08ddc090414c6d01e48c74b408f2192461e9e | [
"MIT"
] | 21 | 2021-03-08T01:58:25.000Z | 2022-03-09T15:46:16.000Z | JPS_Chatbot/jps-chatbot/UI/source/Wikidata_Query/fuzzysearch_wiki.py | cambridge-cares/TheWorldAvatar | baf08ddc090414c6d01e48c74b408f2192461e9e | [
"MIT"
] | 63 | 2021-05-04T15:05:30.000Z | 2022-03-23T14:32:29.000Z | JPS_Chatbot/jps-chatbot/UI/source/Wikidata_Query/fuzzysearch_wiki.py | cambridge-cares/TheWorldAvatar | baf08ddc090414c6d01e48c74b408f2192461e9e | [
"MIT"
] | 15 | 2021-03-08T07:52:03.000Z | 2022-03-29T04:46:20.000Z | from rapidfuzz import process, fuzz
from .load_dicts import FORMULA_URI_DICT, SMILES_URI_DICT, NAME_URI_DICT, \
FORMULA_KEYS, NAME_KEYS, SMILES_KEYS, ATTRIBUTE_URI_DICT, \
ATTRIBUTE_KEYS, CLASS_URI_DICT, CLASS_KEYS, process_species, process_species_reversed
def find_nearest_match(entity_value, entity_type):
# rst = URI, score, candidate
if entity_type == 'attribute':
rst = find_nearest_match_in_attributes(entity_value)
elif entity_type == 'class':
rst = find_nearest_match_classes(entity_value)
elif entity_type == 'species':
rst = find_nearest_match_species(entity_value)
URI = [u.replace('http://www.wikidata.org/entity/', '') for u in rst[0]]
print('find_nearest_match - 16', URI)
score = rst[1]
candidate = rst[2]
return URI, candidate
def find_nearest_match_classes(_class):
_class = _class.upper()
KEYS = CLASS_KEYS
DICT = CLASS_URI_DICT
if _class not in DICT:
rst = process.extractOne(_class, KEYS, scorer=fuzz.ratio)
candidate = rst[0]
score = rst[1]
URI = DICT[candidate]
else:
score = 100
candidate = _class
URI = DICT[candidate]
return URI, score, candidate
def find_nearest_match_species(species):
species = process_species(species)
KEYS_LIST = [FORMULA_KEYS, SMILES_KEYS, NAME_KEYS]
DICT_LIST = [FORMULA_URI_DICT, SMILES_URI_DICT, NAME_URI_DICT]
LABELS = ['FORMULA', 'SMILE', 'NAME']
highest_score = 0
best_uri = []
best_label = ''
best_candidate = ''
for KEYS, DICTS, LABEL in zip(KEYS_LIST, DICT_LIST, LABELS):
rst = find_nearest_match_in_one_species(species, KEYS, DICTS)
URIS = rst[0]
score = rst[1]
candidate = rst[2]
if score > highest_score:
best_uri = URIS
best_label = LABEL
highest_score = score
best_candidate = candidate
return best_uri, highest_score, process_species_reversed(best_candidate), best_label
def find_nearest_match_in_one_species(species, KEYS, DICT):
if species not in DICT:
rst = process.extractOne(species, KEYS, scorer=fuzz.ratio)
candidate = process_species_reversed(rst[0])
score = rst[1]
URI = DICT[candidate]
else:
score = 100
candidate = process_species_reversed(species)
URI = DICT[species]
return URI, score, candidate
# it is exactly like the one for species
def find_nearest_match_in_attributes(attribute):
attribute = attribute.upper()
KEYS = ATTRIBUTE_KEYS
DICT = ATTRIBUTE_URI_DICT
if attribute not in DICT:
rst = process.extractOne(attribute, KEYS, scorer=fuzz.ratio)
candidate = rst[0]
score = rst[1]
URI = DICT[candidate]
else:
score = 100
candidate = attribute
URI = DICT[candidate]
return URI, score, candidate
| 33.425287 | 89 | 0.666437 |
ec599c31ee766ea0addb9f5920d71b72704fe3f0 | 161 | rb | Ruby | _plugins/timestamp.rb | luizeleno/LOM3260 | 4871994a2a313fd2bf11ece9a0f52fc509569e56 | [
"MIT"
] | 3 | 2018-12-05T18:34:49.000Z | 2020-05-31T04:47:31.000Z | _plugins/timestamp.rb | luizeleno/LOM3260 | 4871994a2a313fd2bf11ece9a0f52fc509569e56 | [
"MIT"
] | 8 | 2020-03-17T13:34:04.000Z | 2022-03-08T12:23:39.000Z | _plugins/timestamp.rb | luizeleno/LOM3260 | 4871994a2a313fd2bf11ece9a0f52fc509569e56 | [
"MIT"
] | null | null | null | module Jekyll
module MyFilters
def file_date(input)
File.mtime(input)
end
end
end
Liquid::Template.register_filter(Jekyll::MyFilters)
| 16.1 | 52 | 0.689441 |
e046d501ffb94c43eae876f33737d0ec5676aabd | 219 | h | C | SwiftNews/SwiftNews/Classes/Reading/Controller/YTReadingController.h | CoderHann/SwiftNews | 56b65e684066c050c1811dd65cf2402ee00445c7 | [
"MIT"
] | 2 | 2017-09-11T12:00:57.000Z | 2017-12-28T06:22:22.000Z | SwiftNews/SwiftNews/Classes/Reading/Controller/YTReadingController.h | CoderHann/SwiftNews | 56b65e684066c050c1811dd65cf2402ee00445c7 | [
"MIT"
] | null | null | null | SwiftNews/SwiftNews/Classes/Reading/Controller/YTReadingController.h | CoderHann/SwiftNews | 56b65e684066c050c1811dd65cf2402ee00445c7 | [
"MIT"
] | null | null | null | //
// YTReadingController.h
// SwiftNews
//
// Created by roki on 15/11/6.
// Copyright (c) 2015年 roki. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface YTReadingController : UITableViewController
@end
| 15.642857 | 54 | 0.703196 |
0e4087941c6818349ef148bb285f7d74cfa1b9ca | 172 | lua | Lua | test.lua | danielga/larithmetic | 21c81eea6459e6784e68677701786932b9f03a76 | [
"BSD-3-Clause"
] | null | null | null | test.lua | danielga/larithmetic | 21c81eea6459e6784e68677701786932b9f03a76 | [
"BSD-3-Clause"
] | null | null | null | test.lua | danielga/larithmetic | 21c81eea6459e6784e68677701786932b9f03a76 | [
"BSD-3-Clause"
] | null | null | null | -- tiny test script
require("arithmetic")
print(arithmetic.parser():parse("-3+4*2 / ( 1 - 5 ) ^ 2 ^ 3"):calculate())
print(arithmetic.parser():parse("-1-1"):calculate())
| 24.571429 | 74 | 0.639535 |
2ef9d6a67af820fa22c95827d5118f8149c3baef | 123 | css | CSS | src/app/modules/settings/style.css | arivin29/web_dev | f916463c912625a504867f352fe862ec1ae6de6d | [
"Apache-2.0"
] | 1 | 2018-12-29T14:58:40.000Z | 2018-12-29T14:58:40.000Z | src/app/modules/settings/style.css | arivin29/web_dev | f916463c912625a504867f352fe862ec1ae6de6d | [
"Apache-2.0"
] | 2 | 2018-09-22T10:18:17.000Z | 2018-11-25T03:06:00.000Z | src/app/modules/settings/style.css | arivin29/web_dev | f916463c912625a504867f352fe862ec1ae6de6d | [
"Apache-2.0"
] | 1 | 2018-09-18T14:48:21.000Z | 2018-09-18T14:48:21.000Z | p {
color: #000 !important;
background: #fff;
font-size: 40px;
padding: 90px;
display: block;
margin: 100px;
}
| 13.666667 | 25 | 0.626016 |
c973eea7ea90db27bcdd0dd94d544bfa16a85250 | 416 | ts | TypeScript | src/utilities/checkWinner.ts | josesaulguerrero/miminaxAlgorithm | c29a9b8f305e7b402da9a3ea14bbe7488c3bb91b | [
"MIT"
] | null | null | null | src/utilities/checkWinner.ts | josesaulguerrero/miminaxAlgorithm | c29a9b8f305e7b402da9a3ea14bbe7488c3bb91b | [
"MIT"
] | null | null | null | src/utilities/checkWinner.ts | josesaulguerrero/miminaxAlgorithm | c29a9b8f305e7b402da9a3ea14bbe7488c3bb91b | [
"MIT"
] | null | null | null | import { Board, PlayerMark } from "@types";
export const checkWinner = (
gameBoard: Board,
playerMark: PlayerMark
): boolean => {
const winCombinations: number[][] = [
[0, 1, 2],
[0, 4, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[2, 4, 6],
[3, 4, 5],
[6, 7, 8],
];
return winCombinations.some((combination: number[]) =>
combination.every((index: number) => gameBoard[index] === playerMark)
);
};
| 18.909091 | 71 | 0.567308 |
8ad716bea2edebce85ab992279671350c373d362 | 450 | asm | Assembly | libsrc/_DEVELOPMENT/adt/wv_priority_queue/c/sccz80/wv_priority_queue_push_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/_DEVELOPMENT/adt/wv_priority_queue/c/sccz80/wv_priority_queue_push_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/_DEVELOPMENT/adt/wv_priority_queue/c/sccz80/wv_priority_queue_push_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z |
; int wv_priority_queue_push(wv_priority_queue_t *q, void *item)
SECTION code_clib
SECTION code_adt_wv_priority_queue
PUBLIC wv_priority_queue_push_callee
EXTERN asm_wv_priority_queue_push
wv_priority_queue_push_callee:
pop hl
pop bc
ex (sp),hl
jp asm_wv_priority_queue_push
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _wv_priority_queue_push_callee
defc _wv_priority_queue_push_callee = wv_priority_queue_push_callee
ENDIF
| 18 | 67 | 0.837778 |
e72574ab84db3454f92a4d848900c04eed633069 | 4,181 | php | PHP | src/Action/FileSystem.php | rasclatt/nubersoft-cms | 10f90c35d2b5ad371fb436950cd9818c2d00135d | [
"MIT"
] | null | null | null | src/Action/FileSystem.php | rasclatt/nubersoft-cms | 10f90c35d2b5ad371fb436950cd9818c2d00135d | [
"MIT"
] | null | null | null | src/Action/FileSystem.php | rasclatt/nubersoft-cms | 10f90c35d2b5ad371fb436950cd9818c2d00135d | [
"MIT"
] | null | null | null | <?php
namespace NubersoftCms\Action;
use \NubersoftCms\Model\FileSystem as FileHelper;
use \Nubersoft\{
nFileHandler,
nObserver,
nApp
};
class FileSystem implements nObserver
{
private $POST, $nApp, $FileHelper;
/**
* @description
*/
public function __construct(
nApp $nApp,
FileHelper $FileHelper
)
{
$this->nApp = $nApp;
$this->FileHelper = $FileHelper;
$this->POST = $this->nApp->getPost();
}
/**
* @description
*/
public function listen()
{
switch ($this->getSubAction()) {
case ('update'):
if ($this->getDelete() == 'on') {
@unlink($this->getPath());
if (!is_file($this->getPath())) {
$this->nApp->ajaxResponse(["msg" => "File deleted"]);
}
} else {
if (!empty($this->getPath()) && !empty($this->getData())) {
# Save contents of file to disk
file_put_contents( $this->nApp->dec($this->getPath()), $this->nApp->dec($this->getData()));
# Set current name
$oldname = pathinfo($this->getPath(), PATHINFO_BASENAME);
# Filter name
$fname = preg_replace('/[^\dA-Z\.-_]/i', '', $this->getFname());
# rename the file and save to path if new name
if (!empty($fname)) {
if ($fname != $oldname) {
# Set the path
$filepath = pathinfo($this->getPath(), PATHINFO_DIRNAME);
# Rename file
rename($filepath . DS . $oldname, $filepath . DS . $fname);
# If the file just duplicates but doesn't delete
if (is_file($filepath . DS . $oldname) && is_file($filepath . DS . $fname))
unlink($filepath . DS . $oldname);
# Save back to POST array
$newpath = $this->setPath(pathinfo($this->getPath(), PATHINFO_DIRNAME) . DS . $fname);
}
}
}
}
default:
$item = $this->getPath();
$isfile = is_file($item);
$contents = $this->FileHelper->fetchContents(($isfile) ? $item : realpath($item));
if (empty($contents)) {
$contents = $this->FileHelper->setDataAttributes($item);
} else {
if ($isfile) {
$ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
$cont = file_get_contents($item);
$isImg = in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff', 'svg', 'psd']);
$rows = (!$isImg) ? count(file($item)) : false;
$fileData = ($isImg) ? '<img src="' . (new \Nubersoft\nImage())->toBase64($cont, $ext) . '" style="width: auto; height: auto;" />' : '<textarea class="textarea" name="file_edit" style="background-color: #111; font-family: Courier !important; padding: 1em; color: #FFF; width: calc(100% - 2em); height: 100%; font-size: 1em !important;" rows="' . $rows . '" data-path="' . $item . '">' . $this->nApp->enc($cont) . '</textarea>';
$contents = array_merge($contents, [
'contents' => $fileData
]);
}
}
$this->nApp->ajaxResponse($contents);
}
}
/**
* @description
*/
public function __call($method, $args = false)
{
$action = (stripos($method, 'set') !== false) ? 'set' : 'get';
$method = preg_replace('/^' . $action . '/', '', strtolower($method));
if ($action == 'set')
$this->POST[$method] = ($args[0]) ?? false;
return ($this->POST[$method]) ?? false;
}
}
| 43.103093 | 452 | 0.438412 |
c4dd6a879e608c28f2d3f92a4b6213cee9eef290 | 1,577 | cpp | C++ | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | tutorial_publisher/src/talker.cpp | ryo4432/ros2_tutorial_collection | 4e7ed30e35009f07bd219c762d68b4b8022d4d9d | [
"Apache-2.0"
] | null | null | null | /*
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/
#include <chrono>
#include <cstdio>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class Talker : public rclcpp::Node
{
private:
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_;
rclcpp::TimerBase::SharedPtr timer_;
public:
Talker(const std::string & node_name, const std::string & topic_name)
: Node(node_name)
{
pub_ = this->create_publisher<std_msgs::msg::String>(topic_name, 10);
auto msg_ = std_msgs::msg::String();
msg_.data = "Hello world";
auto publish_message =
[this, msg_]() -> void {
RCLCPP_INFO(this->get_logger(), "%s", msg_.data.c_str());
this->pub_->publish(msg_);
};
timer_ = create_wall_timer(100ms, publish_message);
}
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<Talker>("talker", "topic"));
rclcpp::shutdown();
return 0;
}
| 26.728814 | 74 | 0.700063 |
0108779abd26addf86a96f03f7440ba8aaf3a876 | 27 | dart | Dart | lib/video/index.dart | Kingtous/kommon-flutter | 72c20d7089e2c7602004e9ba1346edcb939a5116 | [
"BSD-3-Clause"
] | null | null | null | lib/video/index.dart | Kingtous/kommon-flutter | 72c20d7089e2c7602004e9ba1346edcb939a5116 | [
"BSD-3-Clause"
] | null | null | null | lib/video/index.dart | Kingtous/kommon-flutter | 72c20d7089e2c7602004e9ba1346edcb939a5116 | [
"BSD-3-Clause"
] | null | null | null | export 'video_player.dart'; | 27 | 27 | 0.814815 |
658d8f692d99daee04086f73bdfe432ab28f79f7 | 493 | dart | Dart | web/_old/performance/source/flying_flag.dart | bp74/StageXL_Samples | 8e50a5e95fafd580a87cdd77d74cb120e3486040 | [
"BSD-2-Clause"
] | 49 | 2015-04-11T16:01:11.000Z | 2022-01-08T10:27:25.000Z | web/_old/performance/source/flying_flag.dart | bp74/StageXL_Samples | 8e50a5e95fafd580a87cdd77d74cb120e3486040 | [
"BSD-2-Clause"
] | 6 | 2015-07-12T17:25:20.000Z | 2018-11-14T21:14:04.000Z | web/_old/performance/source/flying_flag.dart | bp74/StageXL_Samples | 8e50a5e95fafd580a87cdd77d74cb120e3486040 | [
"BSD-2-Clause"
] | 29 | 2015-01-02T21:57:20.000Z | 2021-03-30T15:48:01.000Z | part of performance;
class FlyingFlag extends Bitmap implements Animatable {
num vx, vy;
FlyingFlag(BitmapData bitmapData, this.vx, this.vy) : super(bitmapData) {
pivotX = 24;
pivotY = 24;
}
@override
bool advanceTime(num time) {
var tx = x + vx * time;
var ty = y + vy * time;
if (tx > 910 || tx < 30) {
vx = -vx;
} else {
x = tx;
}
if (ty > 480 || ty < 20) {
vy = -vy;
} else {
y = ty;
}
return true;
}
}
| 15.903226 | 75 | 0.513185 |
18467ec9b87924f8ab0a150ca8de1fa18be1a3a9 | 3,480 | swift | Swift | Tests/DatadogTests/Datadog/Mocks/LogsMocks.swift | reverbdotcom/dd-sdk-ios | 09ba5c8d542956ec7062b0a566b37660d12cca07 | [
"Apache-2.0"
] | null | null | null | Tests/DatadogTests/Datadog/Mocks/LogsMocks.swift | reverbdotcom/dd-sdk-ios | 09ba5c8d542956ec7062b0a566b37660d12cca07 | [
"Apache-2.0"
] | null | null | null | Tests/DatadogTests/Datadog/Mocks/LogsMocks.swift | reverbdotcom/dd-sdk-ios | 09ba5c8d542956ec7062b0a566b37660d12cca07 | [
"Apache-2.0"
] | null | null | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import Foundation
@testable import Datadog
/*
A collection of mocks for Logs objects.
It follows the mocking conventions described in `FoundationMocks.swift`.
*/
extension Log {
static func mockWith(
date: Date = .mockAny(),
status: Log.Status = .mockAny(),
message: String = .mockAny(),
serviceName: String = .mockAny(),
loggerName: String = .mockAny(),
loggerVersion: String = .mockAny(),
threadName: String = .mockAny(),
applicationVersion: String = .mockAny(),
userInfo: UserInfo = .mockAny(),
networkConnectionInfo: NetworkConnectionInfo = .mockAny(),
mobileCarrierInfo: CarrierInfo? = .mockAny(),
attributes: [String: EncodableValue]? = nil,
tags: [String]? = nil
) -> Log {
return Log(
date: date,
status: status,
message: message,
serviceName: serviceName,
loggerName: loggerName,
loggerVersion: loggerVersion,
threadName: threadName,
applicationVersion: applicationVersion,
userInfo: userInfo,
networkConnectionInfo: networkConnectionInfo,
mobileCarrierInfo: mobileCarrierInfo,
attributes: attributes,
tags: tags
)
}
static func mockRandom() -> Log {
return mockWith(
date: .mockRandomInThePast(),
status: .mockRandom(),
message: .mockRandom(length: 20),
serviceName: .mockRandom(),
loggerName: .mockRandom(),
loggerVersion: .mockRandom(),
threadName: .mockRandom(),
applicationVersion: .mockRandom(),
userInfo: .mockRandom(),
networkConnectionInfo: .mockRandom(),
mobileCarrierInfo: .mockRandom()
)
}
}
extension Log.Status {
static func mockAny() -> Log.Status {
return .info
}
static func mockRandom() -> Log.Status {
let statuses: [Log.Status] = [.debug, .info, .notice, .warn, .error, .critical]
return statuses.randomElement()!
}
}
extension EncodableValue {
static func mockAny() -> EncodableValue {
return EncodableValue(String.mockAny())
}
}
extension LogBuilder {
static func mockAny() -> LogBuilder {
return mockWith()
}
static func mockWith(
date: Date = .mockAny(),
appContext: AppContext = .mockAny(),
serviceName: String = .mockAny(),
loggerName: String = .mockAny(),
userInfoProvider: UserInfoProvider = .mockAny(),
networkConnectionInfoProvider: NetworkConnectionInfoProviderType = NetworkConnectionInfoProviderMock.mockAny(),
carrierInfoProvider: CarrierInfoProviderType = CarrierInfoProviderMock.mockAny()
) -> LogBuilder {
return LogBuilder(
appContext: appContext,
serviceName: serviceName,
loggerName: loggerName,
dateProvider: RelativeDateProvider(using: date),
userInfoProvider: userInfoProvider,
networkConnectionInfoProvider: networkConnectionInfoProvider,
carrierInfoProvider: carrierInfoProvider
)
}
}
| 32.523364 | 119 | 0.617816 |
8516eeb828e872903c1e06e6f390adea21b1d8f8 | 180 | cs | C# | Toggl.Multivac/Extensions/EmailExtensions.cs | HectorRPC/Toggl2Excel | 2ffe8ce8a5a92b6a6be3ea3a94c3156efa9403af | [
"BSD-3-Clause"
] | 3 | 2021-04-14T02:46:03.000Z | 2021-04-14T21:38:01.000Z | Toggl.Multivac/Extensions/EmailExtensions.cs | AzureMentor/mobileapp | 94cad6d11bc3cb8bed6cfc9c4c6cacc69a5594da | [
"BSD-3-Clause"
] | null | null | null | Toggl.Multivac/Extensions/EmailExtensions.cs | AzureMentor/mobileapp | 94cad6d11bc3cb8bed6cfc9c4c6cacc69a5594da | [
"BSD-3-Clause"
] | null | null | null | namespace Toggl.Multivac.Extensions
{
public static class EmailExtensions
{
public static Email ToEmail(this string self)
=> Email.From(self);
}
}
| 20 | 53 | 0.638889 |
076b585824c818a8889c9960d4f9b9da01291e2b | 190 | css | CSS | public/mer/css/chunk-237b1c4e.49cd87a9.css | youaremine/ozzo-- | 7f960555555837e2aff9cfa3adc3f106f3951923 | [
"Apache-2.0"
] | null | null | null | public/mer/css/chunk-237b1c4e.49cd87a9.css | youaremine/ozzo-- | 7f960555555837e2aff9cfa3adc3f106f3951923 | [
"Apache-2.0"
] | null | null | null | public/mer/css/chunk-237b1c4e.49cd87a9.css | youaremine/ozzo-- | 7f960555555837e2aff9cfa3adc3f106f3951923 | [
"Apache-2.0"
] | 1 | 2022-02-15T07:52:48.000Z | 2022-02-15T07:52:48.000Z | .selWidth[data-v-0698cd9f]{width:219px!important}.seachTiele[data-v-0698cd9f]{line-height:35px}.fr[data-v-0698cd9f]{float:right}[data-v-0698cd9f] .el-table-column--selection .cell{padding:0} | 190 | 190 | 0.784211 |
0f8c5e013c13cc12c1e5632e28312e4c6812a8f9 | 4,847 | lua | Lua | addons/cw2/lua/weapons/khr_mp40/shared.lua | JacubRSTNC/PoliceRP-OpenSource | adcf19f765331521b6934ecb1c180a978ba7f44d | [
"MIT"
] | 17 | 2021-08-17T16:05:20.000Z | 2022-03-17T09:55:24.000Z | addons/cw2/lua/weapons/khr_mp40/shared.lua | JacubRSTNC/PoliceRP-OpenSource | adcf19f765331521b6934ecb1c180a978ba7f44d | [
"MIT"
] | null | null | null | addons/cw2/lua/weapons/khr_mp40/shared.lua | JacubRSTNC/PoliceRP-OpenSource | adcf19f765331521b6934ecb1c180a978ba7f44d | [
"MIT"
] | 4 | 2021-08-19T11:41:36.000Z | 2022-03-20T08:56:28.000Z | AddCSLuaFile()
AddCSLuaFile("sh_sounds.lua")
include("sh_sounds.lua")
SWEP.magType = "smgMag"
SWEP.PrintName = "MP-40"
if CLIENT then
SWEP.DrawCrosshair = false
SWEP.CSMuzzleFlashes = true
SWEP.IconLetter = "w"
killicon.Add( "khr_mp40", "icons/killicons/khr_mp40", Color(255, 80, 0, 150))
SWEP.SelectIcon = surface.GetTextureID("icons/killicons/khr_mp40")
SWEP.EffectiveRange_Orig = 38 * 39.37
SWEP.DamageFallOff_Orig = .41
SWEP.MuzzleEffect = "muzzleflash_smg"
SWEP.PosBasedMuz = true
SWEP.Shell = "smallshell"
SWEP.ShellDelay = 0.04
SWEP.ShellScale = 0.5
SWEP.ShellOffsetMul = 1
SWEP.ShellPosOffset = {x = -2, y = 0, z = -2}
SWEP.SightWithRail = true
SWEP.DisableSprintViewSimulation = false
SWEP.BoltBone = "Bolt"
SWEP.BoltBonePositionRecoverySpeed = 50
SWEP.BoltShootOffset = Vector(2, 0, 0)
SWEP.IronsightPos = Vector(-1.885, 0, 0.939)
SWEP.IronsightAng = Vector(-0.12, 0, 0)
SWEP.KR_CMOREPos = Vector(-1.855, -1, 0.57)
SWEP.KR_CMOREAng = Vector(-1, 0, 0)
SWEP.SprintPos = Vector(1.169, -0.866, -2.87)
SWEP.SprintAng = Vector(1.85, 7.629, -6.34)
SWEP.AlternativePos = Vector(.5, .5, -0.202)
SWEP.AlternativeAng = Vector(0, 0, 0)
SWEP.AttachmentModelsVM = {
["md_saker222"] = { type = "Model", model = "models/cw2/attachments/556suppressor.mdl", bone = "body", rel = "", pos = Vector(0, 4.239, -0.401), angle = Angle(0, 0, 0), size = Vector(0.4, 0.4, 0.4), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["md_rail"] = { type = "Model", model = "models/wystan/attachments/rail.mdl", bone = "body", rel = "", pos = Vector(0.119, -1.5, 0.535), angle = Angle(0, 90, 0), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["odec3d_cmore_kry"] = { type = "Model", model = "models/weapons/krycek/sights/odec3d_cmore_reddot.mdl", bone = "body", rel = "", pos = Vector(-0.02, -2, 1.5), angle = Angle(0, -90, 0), size = Vector(0.15, 0.15, 0.15), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.CustomizationMenuScale = 0.015
SWEP.ViewModelMovementScale = 1
end
SWEP.MuzzleVelocity = 400 -- in meter/s
SWEP.LuaVMRecoilAxisMod = {vert = 1, hor = 1, roll = .25, forward = 1.5, pitch = 1.5}
SWEP.LuaViewmodelRecoil = true
SWEP.Attachments = {[2] = {header = "Barrel", offset = {150, -280}, atts = {"md_saker222"}},
[1] = {header = "Sight", offset = {750, -50}, atts = {"odec3d_cmore_kry"}},
["+reload"] = {header = "Ammo", offset = {-500, 200}, atts = {"am_magnum", "am_matchgrade"}}}
SWEP.Animations = {fire = {"shoot1", "shoot2", "shoot3", "shoot4", "shoot5", "shoot6", "shoot7", "shoot8", "shoot9", "shoot10"},
reload = "reload_3",
reload_empty = "reload_2",
idle = "idle",
draw = "draw_1"}
SWEP.Sounds = { draw = {{time = 0, sound = "MP40_CLOTH"}},
reload_3 = {[1] = {time = .8, sound = "MP40_MAGOUT"},
[2] = {time = 2.1, sound = "MP40_MAGIN"},
[3] = {time = 2.6, sound = "MP40_GRIP"}},
reload_2 = {[1] = {time = .8, sound = "MP40_MAGOUT"},
[2] = {time = 1.5, sound = "MP40_MAGIN"},
[3] = {time = 2.3, sound = "MP40_BOLT"},
[4] = {time = 2.9, sound = "MP40_GRIP"}}}
SWEP.HoldBoltWhileEmpty = true
SWEP.DontHoldWhenReloading = false
SWEP.Chamberable = false
SWEP.SpeedDec = 25
SWEP.Slot = 2
SWEP.SlotPos = 0
SWEP.NormalHoldType = "smg"
SWEP.RunHoldType = "passive"
SWEP.FireModes = {"auto"}
SWEP.Base = "cw_base"
SWEP.Category = "CW 2.0 - SMGs"
SWEP.Author = "Khris"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.OverallMouseSens = .9
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/khrcw2/v_khr_mp4.mdl"
SWEP.WorldModel = "models/weapons/w_smg_ump45.mdl"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.ClipSize = 32
SWEP.Primary.DefaultClip = 32
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "9x19MM"
SWEP.FireDelay = 60/550
SWEP.FireSound = "MP40_FIRE"
SWEP.FireSoundSuppressed = "KRISS_Firesup"
SWEP.Recoil = .79
SWEP.HipSpread = 0.038
SWEP.AimSpread = 0.0081
SWEP.VelocitySensitivity = 1
SWEP.MaxSpreadInc = 0.055
SWEP.SpreadPerShot = 0.004
SWEP.SpreadCooldown = 0.14
SWEP.Shots = 1
SWEP.Damage = 23
SWEP.DeployTime = 0.5
SWEP.ReloadSpeed = 1.2
SWEP.ReloadTime = 3
SWEP.ReloadTime_Empty = 3.2
SWEP.ReloadHalt = 3
SWEP.ReloadHalt_Empty = 3.2
function SWEP:IndividualThink()
self.EffectiveRange = 38 * 39.37
self.DamageFallOff = .41
if self.ActiveAttachments.am_matchgrade then
self.EffectiveRange = ((self.EffectiveRange + 5.7 * 39.37))
self.DamageFallOff = ((self.DamageFallOff - .0615))
end
if self.ActiveAttachments.md_saker222 then
self.EffectiveRange = ((self.EffectiveRange - 9.5 * 39.37))
self.DamageFallOff = ((self.DamageFallOff - .1025))
end
end | 32.313333 | 324 | 0.67093 |
ebced80f7bfa3f1dddb6145c3f46add17893d285 | 1,633 | css | CSS | css/bachparty.css | fdel15/fdel15.github.io | efd962313c7f7b9dc94b6ae0c40a1c3432469760 | [
"MIT"
] | null | null | null | css/bachparty.css | fdel15/fdel15.github.io | efd962313c7f7b9dc94b6ae0c40a1c3432469760 | [
"MIT"
] | 3 | 2021-05-18T18:23:17.000Z | 2022-02-26T03:04:29.000Z | css/bachparty.css | fdel15/fdel15.github.io | efd962313c7f7b9dc94b6ae0c40a1c3432469760 | [
"MIT"
] | null | null | null | .pic {
width: 100%;
max-width: 500px;
display: none;
}
#carousel p {
text-align: center;
}
.active {
display: initial;
}
#timer ul li {
display: inline-block;
width: 20%;
padding: 2%;
text-align: center;
}
#timer ul li p {
text-align: center;
}
audio {
display: none;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 50% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
text-align: center;
}
.modal-content ul {
padding: 0;
}
.modal-content ul li {
display: inline-block;
padding: 0;
width: 35%;
color: white;
border: solid #888;
}
#yes {
background-color: #58c43d;
}
#no {
background-color: #d03131;
}
#music {
display: none;
background-color: #58c43d;
width: 80%;
margin: 15px 10%;
border: solid #888;
color: white;
text-align: center;
padding: 5px;
}
#yes:hover, #no:hover, #music:hover {
cursor: pointer;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
} | 16.168317 | 69 | 0.597061 |
c67f51f6a9e71dbb65a10c37d39f5ae17058f1a1 | 1,072 | py | Python | vtt.py | hysothyrith/vocab_tools | 47a977531f73a0667644fcf32945ac5072ac4751 | [
"MIT"
] | null | null | null | vtt.py | hysothyrith/vocab_tools | 47a977531f73a0667644fcf32945ac5072ac4751 | [
"MIT"
] | null | null | null | vtt.py | hysothyrith/vocab_tools | 47a977531f73a0667644fcf32945ac5072ac4751 | [
"MIT"
] | null | null | null | import sys
import re
def parse_vtt(input_file_name, output_file_name):
all_words = []
seen_words = set()
with open(input_file_name, "r") as reader:
next(reader)
line = reader.readline()
while line != "":
if not re.match(r"(^\d*$|^\s*$|.*-->.*|^NOTE .*)", line):
parts = line.split()
words = map(lambda s: re.sub(r"<[^>]*>|[^\w]", "", s), parts)
for word in words:
if word != "" and word not in seen_words:
seen_words.add(word)
all_words.append(word)
line = reader.readline()
with open(output_file_name, "w") as writer:
writer.write(str(len(all_words)) + "\n\n")
writer.writelines(map(lambda s: s + "\n", all_words))
return output_file_name
def main():
output_file_name = parse_vtt(
sys.argv[1],
sys.argv[2] if (len(sys.argv) >= 3) else sys.argv[1][:-4] + "_vtt_out.txt",
)
print(output_file_name)
if __name__ == "__main__":
main()
| 27.487179 | 83 | 0.522388 |
8dab17afdff53a31a1b8a809dd2bc03669e409b0 | 1,620 | js | JavaScript | test/specs/Format_Spec.js | isuttell/Amber | 98b88a932b4845ae9550a50da10c9e32a743ad60 | [
"MIT"
] | 1 | 2018-12-13T08:08:00.000Z | 2018-12-13T08:08:00.000Z | test/specs/Format_Spec.js | isuttell/Amber | 98b88a932b4845ae9550a50da10c9e32a743ad60 | [
"MIT"
] | null | null | null | test/specs/Format_Spec.js | isuttell/Amber | 98b88a932b4845ae9550a50da10c9e32a743ad60 | [
"MIT"
] | null | null | null | describe("Amber.Format", function() {
it("should be defined", function() {
expect(Amber.Format).toBeDefined();
});
describe('numberWithCommas', function(){
it("should have a function to add commas to large numbers", function() {
expect(Amber.Format.numberWithCommas).toBeDefined();
expect(Amber.Format.numberWithCommas(1000)).toBe('1,000');
expect(Amber.Format.numberWithCommas(1000.5)).toBe('1,000.5');
expect(Amber.Format.numberWithCommas(500)).toBe('500');
expect(Amber.Format.numberWithCommas(500.1)).toBe('500.1');
expect(Amber.Format.numberWithCommas(-500)).toBe('-500');
expect(Amber.Format.numberWithCommas(1000000)).toBe('1,000,000');
});
it("should return the num if its not a number", function() {
expect(Amber.Format.numberWithCommas(false)).toBe(false);
});
});
describe('stripTrailingZero', function(){
it("should have a function to strip trailing zeros", function() {
expect(Amber.Format.stripTrailingZero).toBeDefined();
var number = '5.0',
result = Amber.Format.stripTrailingZero(number);
expect(result).toBe('5');
});
it("should return the num if its not a number", function() {
expect(Amber.Format.stripTrailingZero(false)).toBe(false);
});
});
describe('basicPluralize', function(){
it("should have a function to do basic plurization", function() {
expect(Amber.Format.basicPluralize).toBeDefined();
var word = 'number',
result = Amber.Format.basicPluralize('number', 2);
expect(result).toBe('numbers');
result = Amber.Format.basicPluralize('number', 1);
expect(result).toBe(word);
});
});
});
| 27.931034 | 74 | 0.687037 |
0d45e35e24e6350affa5974bb06d5ece05c0ff4d | 2,732 | cs | C# | Travelling Salesman Problem/Graph.cs | JR-Morgan/Travelling-Salesman-Problem | 99389190e7bb29af05904f1296c236eee4289704 | [
"MIT"
] | 4 | 2021-02-27T01:10:59.000Z | 2022-03-23T00:29:15.000Z | Travelling Salesman Problem/Graph.cs | JR-Morgan/Travelling-Salesman-Problem | 99389190e7bb29af05904f1296c236eee4289704 | [
"MIT"
] | null | null | null | Travelling Salesman Problem/Graph.cs | JR-Morgan/Travelling-Salesman-Problem | 99389190e7bb29af05904f1296c236eee4289704 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
namespace TSP
{
/// <summary>
/// This class encapsulates a graph of nodes
/// </summary>
public class Graph
{
public readonly List<Node> nodes;
public Node StartNode => nodes.First();
public int NodesCount => nodes.Count;
public Graph(List<Node> nodes)
{
this.nodes = nodes;
}
/// <summary>
/// Parses a <see cref="Graph"/> from <paramref name="file"/> in a CSV format<br/>
/// where column 1 is the Node id, column 2 is the X position, and column 3 is the Y position
/// </summary>
/// <example>
/// Example of a correct CSV line is
/// <code>1,38.24,20.42</code>
/// </example>
/// <param name="file">The file path of the file</param>
/// <returns>A Graph</returns>
public static Graph ParseGraphFromFile(string file)
{
var nodes = new List<Node>();
StreamReader reader = File.OpenText(file);
string? line;
var pattern = @"^\d+,-?\d+\.\d*,-?\d+\.\d*$";
while ((line = reader.ReadLine()) != null)
{
if (Regex.IsMatch(line, pattern))
{
string[] elements = line.Split(",");
nodes.Add(new Node(
id: int.Parse(elements[0]),
position: new Vector2(float.Parse(elements[1]),
float.Parse(elements[2]))
));
}
}
return new Graph(nodes);
}
/// <summary>
/// Generates and returns a random <see cref="Graph"/>
/// </summary>
/// <param name="numberOfNodes">The number of <see cref="Node"/>s to be generated</param>
/// <param name="bounds">The upper bounds for the <see cref="Node"/>s positions</param>
/// <param name="seed">The random seed</param>
/// <returns>The generated <see cref="Graph"/></returns>
public static Graph RandomGraph(uint numberOfNodes, Vector2 bounds, int seed)
{
Random random = new Random(seed);
var nodes = new List<Node>();
for(int i=0; i < numberOfNodes; i++)
{
nodes.Add(new Node(
id: i,
position: new Vector2((float)(random.NextDouble() * bounds.X), (float)(random.NextDouble() * bounds.Y))
));
}
return new Graph(nodes);
}
}
}
| 33.728395 | 127 | 0.499268 |
d37ce1ec292fab85f4730a7bf8a66a9883e09a7e | 2,926 | dart | Dart | pkg/analysis_server/lib/src/services/correction/dart/replace_cascade_with_dot.dart | lfkdsk/sdk | 07aa9ec332600b585b0edc8d3805fb413e4370bd | [
"BSD-3-Clause"
] | null | null | null | pkg/analysis_server/lib/src/services/correction/dart/replace_cascade_with_dot.dart | lfkdsk/sdk | 07aa9ec332600b585b0edc8d3805fb413e4370bd | [
"BSD-3-Clause"
] | null | null | null | pkg/analysis_server/lib/src/services/correction/dart/replace_cascade_with_dot.dart | lfkdsk/sdk | 07aa9ec332600b585b0edc8d3805fb413e4370bd | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
import 'package:analyzer_plugin/utilities/range_factory.dart';
class ReplaceCascadeWithDot extends CorrectionProducer {
@override
FixKind get fixKind => DartFixKind.REPLACE_CASCADE_WITH_DOT;
@override
Future<void> compute(ChangeBuilder builder) async {
var node = this.node;
if (node is CascadeExpression) {
var sections = node.cascadeSections;
if (sections.length == 1) {
var section = sections[0];
Token cascadeOperator;
if (section is MethodInvocation) {
cascadeOperator = section.operator;
} else if (section is PropertyAccess) {
cascadeOperator = section.operator;
} else if (section is IndexExpression) {
await _handleIndexExpression(builder, section);
return;
} else if (section is AssignmentExpression) {
var leftHandSide = section.leftHandSide;
if (leftHandSide is PropertyAccess) {
cascadeOperator = leftHandSide.operator;
} else if (leftHandSide is IndexExpression) {
await _handleIndexExpression(builder, leftHandSide);
return;
} else {
return;
}
} else {
return;
}
var type = cascadeOperator.type;
if (type == TokenType.PERIOD_PERIOD ||
type == TokenType.QUESTION_PERIOD_PERIOD) {
await builder.addDartFileEdit(file, (builder) {
var end = cascadeOperator.end;
builder.addDeletion(range.startOffsetEndOffset(end - 1, end));
});
}
}
}
}
void _handleIndexExpression(
ChangeBuilder builder, IndexExpression section) async {
var cascadeOperator = section.period;
var type = cascadeOperator.type;
if (type == TokenType.PERIOD_PERIOD) {
await builder.addDartFileEdit(file, (builder) {
builder.addDeletion(
range.startStart(cascadeOperator, section.leftBracket));
});
} else if (type == TokenType.QUESTION_PERIOD_PERIOD) {
await builder.addDartFileEdit(file, (builder) {
builder.addSimpleReplacement(range.token(cascadeOperator), '?');
});
}
}
/// Return an instance of this class. Used as a tear-off in `FixProcessor`.
static ReplaceCascadeWithDot newInstance() => ReplaceCascadeWithDot();
}
| 38.5 | 85 | 0.673958 |
46cefff5ed61863f93b98821cfc2c966db8b160e | 1,754 | py | Python | tests/test_radio_command.py | notfoundsam/smart-remote | 0c23fbb9b92ec1c8e7fbbf6d4613ae4b955eada8 | [
"Unlicense"
] | null | null | null | tests/test_radio_command.py | notfoundsam/smart-remote | 0c23fbb9b92ec1c8e7fbbf6d4613ae4b955eada8 | [
"Unlicense"
] | 14 | 2018-06-06T14:54:18.000Z | 2018-07-29T02:44:07.000Z | tests/test_radio_command.py | notfoundsam/smart-remote | 0c23fbb9b92ec1c8e7fbbf6d4613ae4b955eada8 | [
"Unlicense"
] | null | null | null | import serial
import time
import array
command = "status"
# radio_pipe = 'AABBCCDD33'
radio_pipe = 'AABBCCDD44'
success = 0
fail = 0
error = 0
ser = serial.Serial()
ser.baudrate = 500000
ser.port = '/dev/ttyUSB0'
ser.timeout = 10
ser.open()
# Only after writing sketch into Arduino
# print(repr(ser.readline()))
time.sleep(2)
ser.flushInput()
ser.flushOutput()
signal = '%sc%s\n' % (radio_pipe, command)
print(signal)
n = 32
partial_signal = [signal[i:i+n] for i in range(0, len(signal), n)]
try:
while True:
ser.flushInput()
ser.flushOutput()
print "-----------------"
response_in = ""
for part in partial_signal:
b_arr = bytearray(part)
ser.write(b_arr)
ser.flush()
response_in = ser.readline()
if response_in.rstrip() != 'next':
break;
response_in = ""
if response_in == "":
response_in = ser.readline()
response = response_in.rstrip()
data = response.split(':')
print(repr(response_in))
if data[1] == 'FAIL':
fail += 1
time.sleep(0.5)
elif data[1] == 'OK':
success += 1
else:
error += 1
print(repr(response_in))
print "Success: %d Fail: %d Error: %d" % (success, fail, error)
if data[0]:
print(data[0])
# sensors_data = dict(s.split(' ') for s in data[0].split(','))
# if 'bat' in sensors_data:
# bat = float(sensors_data['bat'])
# print(bat)
time.sleep(0.4)
except KeyboardInterrupt:
ser.flushInput()
ser.flushOutput()
ser.close()
print("QUIT")
| 20.880952 | 75 | 0.526226 |
8da7b06ae13182fd785d0ee481d3acafd9ca405a | 3,712 | lua | Lua | receiver_station.lua | technix/ham_radio | 809c86a18c41467f2dc86f1a5a5067894e297065 | [
"MIT"
] | 6 | 2019-12-06T18:22:49.000Z | 2021-05-27T13:27:51.000Z | receiver_station.lua | technix/ham_radio | 809c86a18c41467f2dc86f1a5a5067894e297065 | [
"MIT"
] | 3 | 2020-05-28T08:25:43.000Z | 2022-02-02T16:50:35.000Z | receiver_station.lua | technix/ham_radio | 809c86a18c41467f2dc86f1a5a5067894e297065 | [
"MIT"
] | 1 | 2022-02-02T12:03:27.000Z | 2022-02-02T12:03:27.000Z | ham_radio.receiver_update_infotext = function(meta)
local rds_message = meta:get_string("rds_message")
local infotext = 'Radio receiver'
if rds_message ~= "" then
infotext = rds_message
end
meta:set_string("infotext", infotext)
end
minetest.register_node("ham_radio:receiver", {
description = "Ham Radio Receiver",
tiles = {
"ham_radio_receiver_top.png",
"ham_radio_receiver_top.png",
"ham_radio_receiver_side.png",
"ham_radio_receiver_side.png",
"ham_radio_receiver_side.png",
"ham_radio_receiver_front.png"
},
groups = {cracky=2,oddly_breakable_by_hand=2},
sounds = default.node_sound_metal_defaults(),
paramtype2 = "facedir",
drawtype = "nodebox",
paramtype = "light",
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
light_source = 3,
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos);
local name = placer:get_player_name()
meta:set_string("formspec",
table.concat({
"size[7,4]",
"image[0,0;1,1;ham_radio_receiver_front.png]",
"field[0.25,2;7,1;frequency;Frequency;${frequency}]",
"tooltip[frequency;Integer number ",
ham_radio.settings.frequency.min,"-",
ham_radio.settings.frequency.max, "]",
"button_exit[2,3.5;3,1;;Done]"
},'')
)
meta:set_string("infotext", 'Radio Receiver')
end,
on_receive_fields = function(pos, formname, fields, sender)
if not minetest.is_player(sender) then
return
end
if (
fields.quit ~= "true"
or minetest.is_protected(pos, sender:get_player_name())
) then
return
end
if fields.frequency ~= nil then
local is_frequency_valid = ham_radio.validate_frequency(fields.frequency, true)
if is_frequency_valid.result == false then
ham_radio.errormsg(sender, is_frequency_valid.message)
else
local meta = minetest.get_meta(pos)
meta:set_string("frequency", fields.frequency)
meta:set_string("rds_message", "")
ham_radio.reset_receiver(pos)
ham_radio.receiver_update_infotext(meta)
ham_radio.play_tuning_sound(sender)
end
end
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local inv = meta:get_inventory()
local name = player:get_player_name()
return inv:is_empty("main") and not minetest.is_protected(pos, name)
end,
-- digiline
digiline = {
receptor = {action = function() end},
effector = {
action = ham_radio.digiline_effector_receiver
},
},
});
ham_radio.reset_receiver = function (pos)
local poshash = minetest.pos_to_string(pos, 0)
ham_radio.receiver_rds[poshash] = nil
end
minetest.register_abm(
{
label = "Listen Ham Radion Broadcast",
nodenames = {"ham_radio:receiver"},
interval = 5,
chance = 1,
catch_up = false,
action = function(pos, node)
local meta = minetest.get_meta(pos)
local frequency = meta:get_string("frequency")
if frequency == "" then
return
end
local poshash = minetest.pos_to_string(pos, 0)
if ham_radio.receiver_rds[poshash] == nil or not next(ham_radio.receiver_rds[poshash]) then
-- when all RDS messages are shown, reload them again
ham_radio.receiver_rds[poshash] = ham_radio.get_rds_messages(frequency, true)
end
ham_radio.get_next_rds_message(poshash, meta)
end
}
);
ham_radio.get_next_rds_message = function (poshash, meta)
local message = table.remove(ham_radio.receiver_rds[poshash])
if message ~= nil then
meta:set_string('rds_message', message)
ham_radio.receiver_update_infotext(meta)
end
end
| 29.935484 | 97 | 0.671067 |
6de7bd61cb2d7218b30b4d09fd42fc255a3f99eb | 34,513 | c | C | LRSS.c | pravinsrc/lightweight-reactive-snapshot-service | 6cf99bb79ca020fcced71b9a78850adb59e24edc | [
"Apache-2.0"
] | 3 | 2018-11-13T14:58:17.000Z | 2019-03-03T10:39:35.000Z | LRSS.c | pravinsrc/lightweight-reactive-snapshot-service | 6cf99bb79ca020fcced71b9a78850adb59e24edc | [
"Apache-2.0"
] | null | null | null | LRSS.c | pravinsrc/lightweight-reactive-snapshot-service | 6cf99bb79ca020fcced71b9a78850adb59e24edc | [
"Apache-2.0"
] | 2 | 2018-10-07T18:35:46.000Z | 2018-11-13T14:58:17.000Z | /*++
Module Name:
LRSS.c
Abstract:
This is the main module of the LRSS miniFilter driver.
Environment:
Kernel mode
--*/
#include <fltKernel.h>
#include <dontuse.h>
#include <suppress.h>
#include <ntstrsafe.h>
#include "FileList.h"
#include "EncryptionDetector.h"
#pragma prefast(disable:__WARNING_ENCODE_MEMBER_FUNCTION_POINTER, "Not valid for kernel mode drivers")
PFLT_FILTER gFilterHandle;
ULONG_PTR OperationStatusCtx = 1;
PLIST_ENTRY activeFilesHead = NULL;
LARGE_INTEGER renameIndexNumber = { 0 };
#define PTDBG_TRACE_ROUTINES 0x00000001
#define PTDBG_TRACE_OPERATION_STATUS 0x00000002
ULONG gTraceFlags = 0;
#define PT_DBG_PRINT( _dbgLevel, _string ) \
(FlagOn(gTraceFlags,(_dbgLevel)) ? \
DbgPrint _string : \
((int)0))
/*************************************************************************
Prototypes
*************************************************************************/
EXTERN_C_START
DRIVER_INITIALIZE DriverEntry;
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
);
NTSTATUS
LRSSUnload(
_In_ FLT_FILTER_UNLOAD_FLAGS Flags
);
FLT_POSTOP_CALLBACK_STATUS
LRSSPostCreate(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
);
FLT_PREOP_CALLBACK_STATUS
LRSSPreCleanup(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_PREOP_CALLBACK_STATUS
LRSSPreRename(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_POSTOP_CALLBACK_STATUS
LRSSPostRename(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
);
VOID
LRSSOperationStatusCallback(
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PFLT_IO_PARAMETER_BLOCK ParameterSnapshot,
_In_ NTSTATUS OperationStatus,
_In_ PVOID RequesterContext
);
BOOLEAN
LRSSDoRequestOperationStatus(
_In_ PFLT_CALLBACK_DATA Data
);
EXTERN_C_END
//
// Assign text sections for each routine.
//
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DriverEntry)
#pragma alloc_text(PAGE, LRSSUnload)
#endif
//
// operation registration
//
CONST FLT_OPERATION_REGISTRATION Callbacks[] = {
#if 1
{ IRP_MJ_CLEANUP,
FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO,
LRSSPreCleanup,
NULL },
{ IRP_MJ_CREATE,
FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO,
NULL,
LRSSPostCreate },
{ IRP_MJ_SET_INFORMATION,
FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO,
LRSSPreRename,
LRSSPostRename },
#endif
{ IRP_MJ_OPERATION_END }
};
//
// This defines what we want to filter with FltMgr
//
CONST FLT_REGISTRATION FilterRegistration = {
sizeof(FLT_REGISTRATION), // Size
FLT_REGISTRATION_VERSION, // Version
0, // Flags
NULL, // Context
Callbacks, // Operation callbacks
LRSSUnload, // MiniFilterUnload
NULL, // InstanceSetup
NULL, // InstanceQueryTeardown
NULL, // InstanceTeardownStart
NULL, // InstanceTeardownComplete
NULL, // GenerateFileName
NULL, // GenerateDestinationFileName
NULL // NormalizeNameComponent
};
/*************************************************************************
MiniFilter initialization and unload routines.
*************************************************************************/
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
This is the initialization routine for this miniFilter driver. This
registers with FltMgr and initializes all global data structures.
It executes when LRSS is loaded (e.g. from the command line).
Arguments:
DriverObject - Pointer to driver object created by the system to
represent this driver.
RegistryPath - Unicode string identifying where the parameters for this
driver are located in the registry.
Return Value:
Routine can return non success error codes.
--*/
{
// global variable initialization
activeFilesHead = ExAllocatePoolWithTag(PagedPool, sizeof(LIST_ENTRY), 'List');
InitializeListHead(activeFilesHead);
NTSTATUS status;
UNREFERENCED_PARAMETER(RegistryPath);
PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
("LRSS!DriverEntry: Entered\n"));
// Register with FltMgr to tell it our callback routines
status = FltRegisterFilter(DriverObject,
&FilterRegistration,
&gFilterHandle);
FLT_ASSERT(NT_SUCCESS(status));
if (NT_SUCCESS(status)) {
// Start filtering i/o
status = FltStartFiltering(gFilterHandle);
if (!NT_SUCCESS(status)) {
LRSSUnload(FLTFL_FILTER_UNLOAD_MANDATORY);
}
}
return status;
}
NTSTATUS
LRSSUnload(
_In_ FLT_FILTER_UNLOAD_FLAGS Flags
)
/*++
Routine Description:
This is the unload routine for this miniFilter driver. This is called
when the minifilter is about to be unloaded. We can fail this unload
request if this is not a mandatory unload indicated by the Flags
parameter.
Arguments:
Flags - Indicating if this is a mandatory unload.
Return Value:
Returns STATUS_SUCCESS.
--*/
{
UNREFERENCED_PARAMETER(Flags);
PAGED_CODE();
PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
("LRSS!LRSSUnload: Entered\n"));
// delete all snapshots.
NTSTATUS status;
// systematically delete unused snapshot files
if (activeFilesHead != NULL) {
PLIST_ENTRY currentEntry = activeFilesHead->Flink;
PSnapshot currentSnapshot;
while (currentEntry != activeFilesHead) {
currentSnapshot = (PSnapshot)CONTAINING_RECORD(currentEntry, snapshot, listEntry);
HANDLE snapshotHandle = currentSnapshot->file;
PLIST_ENTRY nextEntry = currentEntry->Flink;
RemoveEntryList(currentEntry);
ExFreePoolWithTag(currentSnapshot, 'List');
currentEntry = nextEntry;
status = FltClose(snapshotHandle);
if (!NT_SUCCESS(status)) {
DbgPrint("%s", "Failed to delete snapshot.");
}
}
}
// free activeFilesList handle
ExFreePoolWithTag(activeFilesHead, 'List');
FltUnregisterFilter(gFilterHandle);
return STATUS_SUCCESS;
}
/*************************************************************************
MiniFilter callback routines.
*************************************************************************/
FLT_POSTOP_CALLBACK_STATUS
LRSSPostCreate(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
)
/*++
Routine Description:
This routine is a post-create dispatch routine for this miniFilter.
It executes prior to a file create operation and creates read-only
snapshots of accessed files when they are opened with write-access.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The context for the completion routine for this
operation.
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(CompletionContext);
UNREFERENCED_PARAMETER(Flags);
//debugging statement
DbgPrint("%s", "Commencing pre-write routine");
// only works safely at passive IRQL
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
ACCESS_MASK desiredAccess = Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess;
// we only want to take snapshots of writes to EXISTING files - snapshots of new files often leads to false positives
if (Data->Iopb->TargetFileObject->WriteAccess && desiredAccess != FILE_CREATE && desiredAccess != FILE_SUPERSEDE && desiredAccess != FILE_OVERWRITE && desiredAccess != FILE_OVERWRITE_IF) {
NTSTATUS status;
FLT_FILE_NAME_INFORMATION *fileNameInfo;
// get file name
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED, &fileNameInfo);
if (NT_SUCCESS(status)) {
// prepare structures to open the active file
UNICODE_STRING fileName = fileNameInfo->Name;
FltParseFileNameInformation(fileNameInfo);
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK ioStatusBlock;
InitializeObjectAttributes(
&objectAttributes,
&fileName,
OBJ_KERNEL_HANDLE,
NULL,
NULL
);
HANDLE activeFileHandle;
PFILE_OBJECT activeFileObject;
// attempt to open file
status = FltCreateFileEx(gFilterHandle, FltObjects->Instance, &activeFileHandle, &activeFileObject, FILE_GENERIC_READ, &objectAttributes, &ioStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE, NULL, 0, IO_IGNORE_SHARE_ACCESS_CHECK);
//if file in question successfully opened
if (NT_SUCCESS(status)) {
// check whether the active file is a directory -> if so, nothing further is required
BOOLEAN isDirectory;
status = FltIsDirectory(activeFileObject, FltObjects->Instance, &isDirectory);
// only proceed if the file is not a directory.
if (NT_SUCCESS(status) && !isDirectory) {
// retrieve information about the file
FILE_INTERNAL_INFORMATION fileInfo;
status = FltQueryInformationFile(FltObjects->Instance, activeFileObject, &fileInfo, sizeof(FILE_INTERNAL_INFORMATION), FileInternalInformation, NULL);
//successfully retrieved file information
if (NT_SUCCESS(status)) {
//if file not in active files: need to create snapshot and log it in active files list
if ((activeFilesHead != NULL) && (IsListEmpty(activeFilesHead) || getFile(activeFilesHead, fileInfo.IndexNumber) == NULL)) {
// create snapshot file
// snapshot name construction
UNICODE_STRING snapshotFileName;
UNICODE_STRING snapshotDirectory;
RtlInitUnicodeString(&snapshotDirectory, L"\\Snapshots\\");
snapshotFileName.Buffer = ExAllocatePoolWithTag(PagedPool, fileNameInfo->Volume.Length + fileName.Length + snapshotDirectory.Length, 'snap');
snapshotFileName.MaximumLength = fileNameInfo->Volume.Length + fileName.Length + snapshotDirectory.Length;
snapshotFileName.Length = 0;
RtlCopyUnicodeString(&snapshotFileName, &fileNameInfo->Volume);
RtlUnicodeStringCat(&snapshotFileName, &snapshotDirectory);
RtlUnicodeStringCat(&snapshotFileName, &fileNameInfo->FinalComponent);
// initialized structures for snapshot file creation
OBJECT_ATTRIBUTES snapshotAttributes;
InitializeObjectAttributes(&snapshotAttributes, &snapshotFileName, OBJ_KERNEL_HANDLE, NULL, NULL);
HANDLE snapshotHandle;
PFILE_OBJECT snapshotFileObject;
IO_STATUS_BLOCK snapshotCreationStatusBlock;
// initialize the snapshot to the same size as active file
LARGE_INTEGER snapshotAllocationSize;
snapshotAllocationSize.QuadPart = activeFileObject->Size;
FILE_BASIC_INFORMATION fileBasicInfo;
status = FltQueryInformationFile(FltObjects->Instance, activeFileObject, &fileBasicInfo, sizeof(FILE_BASIC_INFORMATION), FileBasicInformation, NULL);
if (NT_SUCCESS(status)) {
// create snapshot file
status = FltCreateFileEx(gFilterHandle, FltObjects->Instance, &snapshotHandle, &snapshotFileObject, GENERIC_WRITE, &snapshotAttributes, &snapshotCreationStatusBlock, &snapshotAllocationSize, fileBasicInfo.FileAttributes, 0, FILE_SUPERSEDE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE | FILE_SYNCHRONOUS_IO_ALERT, NULL, 0, IO_IGNORE_SHARE_ACCESS_CHECK);
if (NT_SUCCESS(status)) {
// get volume sector size for I/O - this may no longer be necessary
FLT_VOLUME_PROPERTIES volumeProperties;
ULONG sectorSize;
status = FltGetVolumeProperties(FltObjects->Volume, &volumeProperties, sizeof(volumeProperties), §orSize);
if (!NT_ERROR(status)) {
// if the active file has read access enabled
if (activeFileObject->ReadAccess) {
sectorSize = volumeProperties.SectorSize;
//allocate read buffer
void* buffer = ExAllocatePoolWithTag(PagedPool, sectorSize, 'PWCP');
//check successful memory allocation
if (buffer != NULL) {
BOOLEAN successfulCopy = TRUE;
LARGE_INTEGER byteOffset = { 0 };
// read file and count byte occurrences
while (TRUE) {
ULONG bytesRead;
status = FltReadFile(FltObjects->Instance, activeFileObject, &byteOffset, sectorSize, buffer, FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET, &bytesRead, NULL, NULL);
// unsuccessful read -> check for expected error, otherwise conservatively return unencrypted
if (!NT_SUCCESS(status)) {
if (status == STATUS_END_OF_FILE) {
break;
}
// unexpected error code
else {
successfulCopy = FALSE;
break;
}
}
// successful read -> write buffer contents to snapshot
else {
ULONG bytesWritten;
status = FltWriteFile(FltObjects->Instance, snapshotFileObject, &byteOffset, bytesRead, buffer, FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET, &bytesWritten, NULL, NULL);
if (!NT_SUCCESS(status)) {
successfulCopy = FALSE;
break;
}
}
// extra error check
if (bytesRead < sectorSize) {
break;
}
// update read offset
byteOffset.QuadPart += bytesRead;
}
// if copy was successful, add snapshot to file list
if (successfulCopy) {
// make snapshot read-only
fileBasicInfo.FileAttributes = fileBasicInfo.FileAttributes | FILE_ATTRIBUTE_READONLY;
FltSetInformationFile(FltObjects->Instance, snapshotFileObject, &fileBasicInfo, sizeof(fileBasicInfo), FileBasicInformation);
// add to active files list
addFile(activeFilesHead, fileInfo.IndexNumber, snapshotHandle);
}
// otherwise, delete snapshot file
else {
if (snapshotHandle != NULL && snapshotFileObject != NULL) {
FltClose(snapshotHandle);
}
}
// free file read/write buffer
if (buffer != NULL) {
ExFreePoolWithTag(buffer, 'PWCP');
buffer = NULL;
}
}
else {
if (snapshotHandle != NULL && snapshotFileObject != NULL) {
FltClose(snapshotHandle);
}
}
}
}
else {
if (snapshotHandle != NULL && snapshotFileObject != NULL) {
FltClose(snapshotHandle);
}
}
}
else {
if (snapshotHandle != NULL && snapshotFileObject != NULL) {
FltClose(snapshotHandle);
}
}
}
ExFreePoolWithTag(snapshotFileName.Buffer, 'snap');
}
}
}
// done with active file
FltClose(activeFileHandle);
}
// free file name buffer
FltReleaseFileNameInformation(fileNameInfo);
}
}
}
// return with okay to continue with requested I/O
return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS
LRSSPreCleanup(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
This routine is a pre-cleanup dispatch routine for this miniFilter.
This routine executes when the last handle to a file is closed.
It checks whether the closed file has an associated snapshot,
then examines the contents of the file and its snapshot to
determine whether the file was encrypted.
If the file was encrypted, the snapshot is copied to the same directory
in case the file was encrypted by ransomware.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The context for the completion routine for this
operation.
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(CompletionContext);
PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
("LRSS!LRSSPreOperation: Entered\n"));
// can only safely operate at passive IRQL
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
// first check whether we have any snapshots
if (activeFilesHead != NULL && !IsListEmpty(activeFilesHead)) {
BOOLEAN isDirectory;
NTSTATUS status;
status = FltIsDirectory(Data->Iopb->TargetFileObject, FltObjects->Instance, &isDirectory);
// only perform further processing if the target file is not a directory
if (NT_SUCCESS(status) && !isDirectory) {
// we have snapshots, so we need to check for a match with the active file
FILE_INTERNAL_INFORMATION fileInfo;
status = FltQueryInformationFile(FltObjects->Instance, Data->Iopb->TargetFileObject, &fileInfo, sizeof(FILE_INTERNAL_INFORMATION), FileInternalInformation, NULL);
// successful query for file information?
if (NT_SUCCESS(status)) {
FILE_BASIC_INFORMATION fileBasicInfo;
status = FltQueryInformationFile(FltObjects->Instance, Data->Iopb->TargetFileObject, &fileBasicInfo, sizeof(FILE_BASIC_INFORMATION), FileBasicInformation, NULL);
if (NT_SUCCESS(status)) {
// check active file list for matching key
HANDLE snapshotHandle = removeFile(activeFilesHead, fileInfo.IndexNumber);
// snapshot found
if (snapshotHandle != NULL) {
// attempt to retrieve FILE_OBJECT from HANDLE
PVOID snapshotObjectVoid;
status = ObReferenceObjectByHandle(snapshotHandle, GENERIC_READ, *IoFileObjectType, KernelMode, &snapshotObjectVoid, NULL);
// successful retrieval of file object?
if (NT_SUCCESS(status)) {
PFILE_OBJECT snapshotObject = (PFILE_OBJECT)snapshotObjectVoid;
// retrieve volume sector size for non-cached I/O
FLT_VOLUME_PROPERTIES volumeProperties;
ULONG sectorSize;
status = FltGetVolumeProperties(FltObjects->Volume, &volumeProperties, sizeof(volumeProperties), §orSize);
if (!NT_ERROR(status)) {
// check whether active file looks encrypted
BOOLEAN fileIsEncrypted = isEncrypted(Data->Iopb->TargetFileObject, FltObjects->Instance, sectorSize);
if (fileIsEncrypted == TRUE) {
PFLT_FILE_NAME_INFORMATION fileNameInfo;
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED, &fileNameInfo);
if (NT_SUCCESS(status)) {
// parse target file name information
status = FltParseFileNameInformation(fileNameInfo);
if (NT_SUCCESS(status)) {
// retrieve target file's parent directory to place replacement file in
HANDLE targetFileParentDirHandle;
OBJECT_ATTRIBUTES targetFileParentDirAttributes;
IO_STATUS_BLOCK targetFileParentDirStatusBlock;
UNICODE_STRING parentDirectoryFullPath;
parentDirectoryFullPath.Buffer = ExAllocatePoolWithTag(PagedPool, (fileNameInfo->Volume.Length + fileNameInfo->ParentDir.Length), 'pdir');
parentDirectoryFullPath.Length = 0;
parentDirectoryFullPath.MaximumLength = fileNameInfo->Volume.Length + fileNameInfo->ParentDir.Length;
RtlCopyUnicodeString(&parentDirectoryFullPath, &(fileNameInfo->Volume));
RtlUnicodeStringCat(&parentDirectoryFullPath, &(fileNameInfo->ParentDir));
InitializeObjectAttributes(&targetFileParentDirAttributes, &parentDirectoryFullPath, OBJ_KERNEL_HANDLE, NULL, NULL);
status = FltCreateFile(gFilterHandle, FltObjects->Instance, &targetFileParentDirHandle, FILE_TRAVERSE | FILE_LIST_DIRECTORY, &targetFileParentDirAttributes, &targetFileParentDirStatusBlock, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_DIRECTORY_FILE, NULL, 0, IO_IGNORE_SHARE_ACCESS_CHECK);
if (NT_SUCCESS(status)) {
ExFreePoolWithTag(parentDirectoryFullPath.Buffer, 'pdir');
LARGE_INTEGER replacementFileAllocationSize;
replacementFileAllocationSize.QuadPart = snapshotObject->Size;
//Create new file to copy snapshot to
HANDLE replacementFileHandle;
PFILE_OBJECT replacementFileObject;
OBJECT_ATTRIBUTES replacementFileObjectAttributes;
UNICODE_STRING snapshotPrefix;
RtlInitUnicodeString(&snapshotPrefix, L"Snapshot-");
UNICODE_STRING snapshotExtension;
RtlInitUnicodeString(&snapshotExtension, L".lrs");
UNICODE_STRING snapshotFileNameFinalComponent;
status = FltParseFileName(&(snapshotObject->FileName), NULL, NULL, &snapshotFileNameFinalComponent);
// check for successful parse of file name
if (NT_SUCCESS(status)) {
UNICODE_STRING snapshotFileNameComplete;
snapshotFileNameComplete.Buffer = ExAllocatePoolWithTag(PagedPool, snapshotPrefix.Length + snapshotFileNameFinalComponent.Length + snapshotExtension.Length, 'name');
snapshotFileNameComplete.Length = 0;
snapshotFileNameComplete.MaximumLength = snapshotPrefix.Length + snapshotFileNameFinalComponent.Length + snapshotExtension.Length;
RtlCopyUnicodeString(&snapshotFileNameComplete, &snapshotPrefix);
RtlUnicodeStringCat(&snapshotFileNameComplete, &snapshotFileNameFinalComponent);
RtlUnicodeStringCat(&snapshotFileNameComplete, &snapshotExtension);
InitializeObjectAttributes(&replacementFileObjectAttributes, &(snapshotFileNameComplete), OBJ_KERNEL_HANDLE, targetFileParentDirHandle, NULL);
IO_STATUS_BLOCK replacementFileStatusBlock;
// query for snapshot basic info to retrieve file attributes
FILE_BASIC_INFORMATION snapshotBasicInfo;
status = FltQueryInformationFile(FltObjects->Instance, snapshotObject, &snapshotBasicInfo, sizeof(snapshotBasicInfo), FileBasicInformation, NULL);
// check successful query
if (NT_SUCCESS(status)) {
//create replacement file
status = FltCreateFileEx(gFilterHandle, FltObjects->Instance, &replacementFileHandle, &replacementFileObject, GENERIC_WRITE, &replacementFileObjectAttributes, &replacementFileStatusBlock, &replacementFileAllocationSize, fileBasicInfo.FileAttributes, 0, FILE_CREATE, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_ALERT, NULL, 0, IO_IGNORE_SHARE_ACCESS_CHECK);
ExFreePoolWithTag(snapshotFileNameComplete.Buffer, 'name');
if (NT_SUCCESS(status)) {
LARGE_INTEGER byteOffset = { 0 };
PVOID buffer = ExAllocatePoolWithTag(PagedPool, sectorSize, 'PCCP');
if (buffer != NULL) {
BOOLEAN successfulCopy = TRUE;
// read snapshot and write to replacement file
while (TRUE) {
ULONG bytesRead;
status = FltReadFile(FltObjects->Instance, snapshotObject, &byteOffset, sectorSize, buffer, FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET, &bytesRead, NULL, NULL);
// unsuccessful read -> check for expected error, otherwise conservatively exit copy
if (!NT_SUCCESS(status)) {
if (status == STATUS_END_OF_FILE) {
break;
}
// unexpected error code
else {
successfulCopy = FALSE;
break;
}
}
// successful read -> write to replacement file
else {
ULONG bytesWritten;
status = FltWriteFile(FltObjects->Instance, replacementFileObject, &byteOffset, bytesRead, buffer, FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET, &bytesWritten, NULL, NULL);
if (!NT_SUCCESS(status)) {
successfulCopy = FALSE;
break;
}
}
// extra error check
if (bytesRead < sectorSize) {
break;
}
// update read offset
byteOffset.QuadPart += bytesRead;
}
if (buffer != NULL) {
ExFreePoolWithTag(buffer, 'PCCP');
buffer = NULL;
}
}
FltClose(replacementFileHandle);
}
}
}
FltClose(targetFileParentDirHandle);
}
}
FltReleaseFileNameInformation(fileNameInfo);
}
}
}
}
status = FltClose(snapshotHandle);
if (!NT_SUCCESS(status)) {
DbgPrint("%s", "Unable to delete snapshot.\n");
}
}
}
}
}
}
}
// always allow file cleanup to proceed - we've set the target file to be deleted, so this should complete the task.
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
FLT_PREOP_CALLBACK_STATUS
LRSSPreRename(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
This routine is a pre-rename dispatch routine for this miniFilter.
The purpose of this routine is to update the active files list to be resilient to file renames,
which is a common aspect of ransomware behaviour. Most variants do not preserve the name of the file.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The context for the completion routine for this
operation.
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(CompletionContext);
// first check whether we have any snapshots - nothing to do if not.
if (activeFilesHead != NULL && !IsListEmpty(activeFilesHead)) {
// only need to act if this operation is a file rename
if (Data->Iopb->Parameters.SetFileInformation.FileInformationClass == FileRenameInformation) {
// retrieve file index number to use as key
FILE_INTERNAL_INFORMATION fileInfo;
ULONG bytesReturned;
NTSTATUS status = FltQueryInformationFile(FltObjects->Instance, Data->Iopb->TargetFileObject, &fileInfo, sizeof(FILE_INTERNAL_INFORMATION), FileInternalInformation, &bytesReturned);
// if key successfully obtained, compare to keys of snapshots
if (NT_SUCCESS(status) && bytesReturned > 0) {
HANDLE fileHandle = getFile(activeFilesHead, fileInfo.IndexNumber);
// if we find a matching snapshot, update global variable to be checked
// by post-rename routine
if (fileHandle != NULL) {
renameIndexNumber = fileInfo.IndexNumber;
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
}
}
}
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
FLT_POSTOP_CALLBACK_STATUS
LRSSPostRename(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
)
/*++
Routine Description:
This routine is a post-rename dispatch routine for this miniFilter.
This is non-pageable because it could be called on the paging path
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The context for the completion routine for this
operation.
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(CompletionContext);
UNREFERENCED_PARAMETER(Flags);
// if the renameIndexNumber variable was set by the pre-rename routine,
// we need to update the key of a snapshot.
if (renameIndexNumber.QuadPart != 0) {
// query for key value
FILE_INTERNAL_INFORMATION fileInfo;
ULONG bytesReturned;
NTSTATUS status = FltQueryInformationFile(FltObjects->Instance, Data->Iopb->TargetFileObject, &fileInfo, sizeof(FILE_INTERNAL_INFORMATION), FileInternalInformation, &bytesReturned);
// if query successful, update the key of the renamed file's snapshot
if (NT_SUCCESS(status) && bytesReturned > 0) {
updateKey(activeFilesHead, renameIndexNumber, fileInfo.IndexNumber);
}
// reset variable to 0
renameIndexNumber.QuadPart = 0;
renameIndexNumber.LowPart = 0;
renameIndexNumber.HighPart = 0;
}
return FLT_POSTOP_FINISHED_PROCESSING;
}
VOID
LRSSOperationStatusCallback(
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PFLT_IO_PARAMETER_BLOCK ParameterSnapshot,
_In_ NTSTATUS OperationStatus,
_In_ PVOID RequesterContext
)
/*++
Routine Description:
This routine is called when the given operation returns from the call
to IoCallDriver. This is useful for operations where STATUS_PENDING
means the operation was successfully queued. This is useful for OpLocks
and directory change notification operations.
This callback is called in the context of the originating thread and will
never be called at DPC level. The file object has been correctly
referenced so that you can access it. It will be automatically
dereferenced upon return.
This is non-pageable because it could be called on the paging path
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
RequesterContext - The context for the completion routine for this
operation.
OperationStatus -
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(FltObjects);
PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
("LRSS!LRSSOperationStatusCallback: Entered\n"));
PT_DBG_PRINT(PTDBG_TRACE_OPERATION_STATUS,
("LRSS!LRSSOperationStatusCallback: Status=%08x ctx=%p IrpMj=%02x.%02x \"%s\"\n",
OperationStatus,
RequesterContext,
ParameterSnapshot->MajorFunction,
ParameterSnapshot->MinorFunction,
FltGetIrpName(ParameterSnapshot->MajorFunction)));
}
FLT_PREOP_CALLBACK_STATUS
LRSSPreOperationNoPostOperation(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
This routine is a pre-operation dispatch routine for this miniFilter.
This is non-pageable because it could be called on the paging path
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The context for the completion routine for this
operation.
Return Value:
The return value is the status of the operation.
--*/
{
UNREFERENCED_PARAMETER(Data);
UNREFERENCED_PARAMETER(FltObjects);
UNREFERENCED_PARAMETER(CompletionContext);
PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
("LRSS!LRSSPreOperationNoPostOperation: Entered\n"));
// This template code does not do anything with the callbackData, but
// rather returns FLT_PREOP_SUCCESS_NO_CALLBACK.
// This passes the request down to the next miniFilter in the chain.
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
BOOLEAN
LRSSDoRequestOperationStatus(
_In_ PFLT_CALLBACK_DATA Data
)
/*++
Routine Description:
This identifies those operations we want the operation status for. These
are typically operations that return STATUS_PENDING as a normal completion
status.
Arguments:
Return Value:
TRUE - If we want the operation status
FALSE - If we don't
--*/
{
PFLT_IO_PARAMETER_BLOCK iopb = Data->Iopb;
//
// return boolean state based on which operations we are interested in
//
return (BOOLEAN)
//
// Check for oplock operations
//
(((iopb->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) &&
((iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_FILTER_OPLOCK) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_BATCH_OPLOCK) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_1) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_2)))
||
//
// Check for directy change notification
//
((iopb->MajorFunction == IRP_MJ_DIRECTORY_CONTROL) &&
(iopb->MinorFunction == IRP_MN_NOTIFY_CHANGE_DIRECTORY))
);
}
| 31.809217 | 374 | 0.675137 |