text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
//************************************************************************
// Rust CHIP-8 emulator, created by David Garcia
// Distributed under the MIT license
//
// CHIP-8 emulator
//************************************************************************
use std::time::{SystemTime, Duration};
pub use crate::chip8::display::Display;
pub use crate::chip8::input::KeyInput;
use crate::chip8::constants::*;
use crate::chip8::timer::Timer;
use crate::chip8::types::{Address, OpCode};
use std::thread::sleep;
mod constants;
mod display;
mod input;
mod memory;
mod opcodes;
mod timer;
mod types;
// CHIP-8 structure
pub struct Chip8<Screen, Input> where Screen: Display, Input: KeyInput {
// CPU
registers : [u8; CHIP8_REGISTER_COUNT],
addr_register : Address,
program_counter : Address,
clock_speed : u16,
last_instruction_time: Option<SystemTime>,
// Memory
memory: [u8; CHIP8_MEMORY_SIZE],
// Stack
stack : [Address; CHIP8_STACK_COUNT],
stack_ptr: usize,
// Screen
gfx : [u8; CHIP8_PIXEL_COUNT],
pub screen: Screen,
// Timers
delay_timer: Timer,
sound_timer: Timer,
// Input
pub key_input: Input
}
impl<Screen, Input> Chip8<Screen, Input> where Screen: Display, Input: KeyInput {
// Initialize the emulator
pub fn new(screen: Screen, key_input: Input) -> Self {
Chip8 {
// CPU
registers : [0; CHIP8_REGISTER_COUNT],
addr_register : 0,
program_counter: 0,
clock_speed : CHIP8_CPU_CLOCK_SPEED,
last_instruction_time: None,
// Memory
memory: [0; CHIP8_MEMORY_SIZE],
// Stack
stack : [0; CHIP8_STACK_COUNT],
stack_ptr: 0,
// Screen
gfx: [0; CHIP8_PIXEL_COUNT],
screen,
// Timers
delay_timer: Timer::new(),
sound_timer: Timer::new(),
// Input
key_input
}
}
// Init the emulator
pub fn init(&mut self) -> Result<(), String> {
// Load the fontset
self.load_fontset();
// Check if the program is loaded
if self.memory[0x0200] == 0 {
return Err(format!("No rom loaded!"));
}
// Set the PC at 0x200
self.program_counter = 0x0200;
Ok(())
}
// Make a step
pub fn step(&mut self) -> Result<(), String> {
// Check if the program is loaded
if self.memory[0x0200] == 0 {
return Err(format!("No rom loaded!"));
}
// Get the opcode
let op_code: OpCode = ((self.memory[self.program_counter as usize] as OpCode) << 8) +
(self.memory[self.program_counter as usize + 1] as OpCode);
// Execute the opcode
self.execute_opcode(op_code);
// Emulate CPU speed
self.emulate_cpu_speed();
// Update timers
self.delay_timer.update();
self.sound_timer.update();
Ok(())
}
// Main loop
pub fn init_and_loop(&mut self) -> Result<(), String> {
// Init
self.init()?;
// Loop
loop {
self.step()?;
}
}
// Emulate clock speed, should be call after each instruction
fn emulate_cpu_speed(&mut self) {
// Get the current system time
let time_now = SystemTime::now();
// If there is an instruction before, simulate latency
if self.last_instruction_time.is_some() {
let duration = self.last_instruction_time.unwrap().elapsed().unwrap();
// We have to sleep
if duration < Duration::from_micros(1_000_000 / self.clock_speed as u64) {
sleep(Duration::from_micros(1_000_000 / self.clock_speed as u64) - duration);
}
}
// Set the new last instruction time
self.last_instruction_time = Some(time_now);
}
}
|
b46d5ef064a5912329c0495b6f61955b731e28e7
|
{
"blob_id": "b46d5ef064a5912329c0495b6f61955b731e28e7",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-21T08:11:04",
"content_id": "435d64f42f66df6f7be5e92395657af509a1e71b",
"detected_licenses": [
"MIT"
],
"directory_id": "30e4ee8982468ac0832213d1391098f2c7d3947f",
"extension": "rs",
"filename": "mod.rs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 255568246,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 3992,
"license": "MIT",
"license_type": "permissive",
"path": "/src/chip8/mod.rs",
"provenance": "stack-edu-0068.json.gz:191716",
"repo_name": "le-dragon-dev/rust-chip-8",
"revision_date": "2020-04-21T08:11:04",
"revision_id": "f72ebdf401db847b50e58ed1a8961d0c60fb7a2f",
"snapshot_id": "acda2d0ac53da3decfd4dcc3aeb7be802b97eaa2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/le-dragon-dev/rust-chip-8/f72ebdf401db847b50e58ed1a8961d0c60fb7a2f/src/chip8/mod.rs",
"visit_date": "2022-04-23T08:33:16.639383",
"added": "2024-11-18T20:54:50.863053+00:00",
"created": "2020-04-21T08:11:04",
"int_score": 3,
"score": 2.953125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
@author: Raven
@contact: [email protected]
@site: https://github.com/aducode
@file: invoker.py
@time: 2016/2/1 23:05
"""
from socket import socket, AF_INET, SOCK_STREAM
from gaea.core.protocol.protocol import MsgType, Platform
from gaea.core.protocol.protocol import Protocol, RequestProtocol, KeyValuePair, Out
from gaea.core.exception import InternalServerException
def recv_data(conn, buf_size=1024):
_data = ''
while True:
_in_buf = conn.recv(buf_size)
_data += _in_buf if _in_buf else ''
if (len(_in_buf) if _in_buf else 0) < buf_size:
break
conn.close()
return _data
def invoker(proxy, func):
def _func(*args):
type_and_values = zip(func.__args__, args)
params = list()
out_params = list()
for t, v in type_and_values:
if isinstance(t, Out):
if not isinstance(v, Out):
raise RuntimeError('Value must be Out instance!')
else:
out_params.append(v)
params.append((t.value, v.value, ))
else:
params.append((t, v, ))
request = RequestProtocol()
request.lookup = proxy.implement.__class__.__service_name__
request.methodName = func.__method_name__
request.paraKVList = [KeyValuePair(_type.__simple_name__, value)
for _type, value in params]
send_protocol = Protocol(msg=request,
msg_type=MsgType.Request,
compress_type=proxy.compress,
serialize_type=proxy.serialize,
platform=Platform.Java)
serialized = send_protocol.to_bytes()
conn = socket(AF_INET, SOCK_STREAM)
conn.connect(proxy.address)
conn.send(serialized)
data = recv_data(conn)
receive_protocol = Protocol.from_bytes(data)
if receive_protocol.msg_type == MsgType.Response:
response = receive_protocol.msg
response_out_params = response.outpara if response.outpara is not None else list()
if len(response_out_params) != len(out_params):
raise RuntimeError('Out parameter num not equal!')
for i in xrange(len(out_params)):
out_params[i].value = response_out_params[i]
return response.result
elif receive_protocol.msg_type == MsgType.Exception:
exception = receive_protocol.msg
exp = InternalServerException(exception.errorCode, exception.toIP, exception.fromIP, exception.errorMsg)
raise exp
return _func
|
c8432ae8b0ee2c71c3614f7da4746be0251adc04
|
{
"blob_id": "c8432ae8b0ee2c71c3614f7da4746be0251adc04",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-21T11:54:12",
"content_id": "d3cd7e932f559b56bf71e130f9ea3cd6ede8455e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fcdbf9c061feca71d73790b7cdd28dca56e35a56",
"extension": "py",
"filename": "invoker.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50784956,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2736,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/gaea/client/invoker.py",
"provenance": "stack-edu-0062.json.gz:147628",
"repo_name": "aducode/Gaeapy",
"revision_date": "2016-02-21T11:54:12",
"revision_id": "166c78d9074ae82d768fd1a0861834281d77f7e7",
"snapshot_id": "5523914be30471cabb0f0ec7b1d122fa1f7dc824",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aducode/Gaeapy/166c78d9074ae82d768fd1a0861834281d77f7e7/gaea/client/invoker.py",
"visit_date": "2021-01-10T14:55:38.068192",
"added": "2024-11-18T23:37:09.407531+00:00",
"created": "2016-02-21T11:54:12",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
protected $fillable=['abbr','local','name','direction','active'];
public function getActive(){
return $this->active == 1 ? 'مفعل':'غير مفعل' ;
}
public function scopeSelection($q){
return $q->select('id','abbr','name','direction','active');
}
}
|
843a3be59b9085c5a713d5437a50de7bcb2e7bb4
|
{
"blob_id": "843a3be59b9085c5a713d5437a50de7bcb2e7bb4",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-07T15:28:00",
"content_id": "c93b2c49d341d2a574fb9c7f9ef6aa89acbef107",
"detected_licenses": [
"MIT"
],
"directory_id": "26c5e087a130627e6d6a2315b3cfcb0d047be49e",
"extension": "php",
"filename": "Language.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 285860366,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 398,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Models/Language.php",
"provenance": "stack-edu-0052.json.gz:571403",
"repo_name": "KhalidAbeed/E-Commerce",
"revision_date": "2020-08-07T15:28:00",
"revision_id": "1c4974e7234ddc2188f1b477c5d5d5804eeb077f",
"snapshot_id": "1cfe76b7681bb137e1bad8c7669001afbe5faaae",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KhalidAbeed/E-Commerce/1c4974e7234ddc2188f1b477c5d5d5804eeb077f/app/Models/Language.php",
"visit_date": "2022-11-25T11:53:59.387676",
"added": "2024-11-18T19:43:59.992864+00:00",
"created": "2020-08-07T15:28:00",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
package io.alapierre.jdbc.api;
import io.alapierre.jdbc.model.ColumnMetadata;
import io.alapierre.jdbc.model.TableMetadata;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* @author Adrian Lapierre {@literal [email protected]}
* Copyrights by original author 2021.12.13
*/
@RequiredArgsConstructor
@Slf4j
public class JdbcMetadataExplorer {
private final DataSource dataSource;
@SuppressWarnings("unused")
public Set<TableMetadata> processTablesMetadata(@NotNull String schemaPattern) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
val meta = connection.getMetaData();
val res = new LinkedHashSet<TableMetadata>();
try (val rs = meta.getTables(null, schemaPattern, "%", new String[]{"TABLE"})) {
while (rs.next()) {
val catalog = rs.getString("TABLE_CAT");
val schema = rs.getString("TABLE_SCHEM");
val tableName = rs.getString("TABLE_NAME");
val foreignKeys = meta.getImportedKeys(catalog, schema, tableName);
val relatedTables = new LinkedHashSet<String>();
while (foreignKeys.next()) {
val fkTableName = foreignKeys.getString("PKTABLE_NAME");
if (!tableName.equals(fkTableName)) {
relatedTables.add(fkTableName);
}
}
res.add(new TableMetadata(tableName, schema, catalog, relatedTables));
}
}
return res;
}
}
@SuppressWarnings("unused")
public Set<ColumnMetadata> procesTableColumnsMetadata(@NotNull String tableName) throws SQLException {
val result = new LinkedHashSet<ColumnMetadata>();
try (Connection connection = dataSource.getConnection()) {
val meta = connection.getMetaData();
try (val rs = meta.getColumns(null, null, tableName, "%")) {
while (rs.next()) {
result.add(procesColumnMetadata(rs));
}
}
}
return result;
}
@Contract("_ -> new")
private @NotNull ColumnMetadata procesColumnMetadata(@NotNull ResultSet rs) throws SQLException {
// See: https://docs.oracle.com/javase/8/docs/api/java/sql/DatabaseMetaData.html#getColumns-java.lang.String-java.lang.String-java.lang.String-java.lang.String-
return new ColumnMetadata(
rs.getString("COLUMN_NAME"),
rs.getString("TABLE_NAME"),
rs.getInt("ORDINAL_POSITION"),
rs.getInt("DATA_TYPE"),
rs.getString("TYPE_NAME"),
getValue(rs, "COLUMN_SIZE", Integer.class),
"YES".equals(rs.getString("IS_NULLABLE")),
"YES".equals(rs.getString("IS_AUTOINCREMENT")),
getValue(rs, "NUMERIC_SCALE", Integer.class),
getValue(rs, "DECIMAL_DIGITS", Integer.class));
}
private <T> @Nullable T getValue(@NotNull ResultSet rs, @NotNull String name, @SuppressWarnings("SameParameterValue") @NotNull Class<T> clazz) {
try {
return rs.getObject(name, clazz);
} catch (SQLException ex) {
log.debug("can't get value for column {} cause by {}", name, ex.getMessage());
return null;
}
}
}
|
0b48fe7b408563ff1187c11b280c16d601437779
|
{
"blob_id": "0b48fe7b408563ff1187c11b280c16d601437779",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-23T09:57:49",
"content_id": "be22dc2ea695d8b29458a29288aa7a61640d003b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ce10494663309af6cda52237f2a261da9ee6d816",
"extension": "java",
"filename": "JdbcMetadataExplorer.java",
"fork_events_count": 1,
"gha_created_at": "2020-03-07T07:13:35",
"gha_event_created_at": "2023-09-01T10:23:00",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 245586016,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3753,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/jdbc-util/src/main/java/io/alapierre/jdbc/api/JdbcMetadataExplorer.java",
"provenance": "stack-edu-0028.json.gz:481376",
"repo_name": "alapierre/java-commons",
"revision_date": "2022-12-23T09:57:49",
"revision_id": "32dee0fe884827bd12399ad52c6476f1915a053b",
"snapshot_id": "569825c7d72e15f4b9bb914735d15321192cb88a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alapierre/java-commons/32dee0fe884827bd12399ad52c6476f1915a053b/jdbc-util/src/main/java/io/alapierre/jdbc/api/JdbcMetadataExplorer.java",
"visit_date": "2023-08-16T19:28:26.746125",
"added": "2024-11-18T23:26:41.481475+00:00",
"created": "2022-12-23T09:57:49",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
import * as utility from './utility.js'
/**
* Convert HTML table to data table with desired configurations.
* @param {string} table: A HTML formatted table.
* @returns {void}.
*/
function convertToDataTable (table) {
const hideColumns =
$('#vizMethod').val() === '3DScatter' ? [2, 3, 4] : [2, 3]
table.DataTable({
// Do not paging.
paging: false,
// Set the Scroll Height.
scrollY: 300,
// If not enough height, shrink the table height.
scrollCollapse: true,
// Specify where the button is.
dom: `<'row'<'col-sm-12 text-right'f>>
<'row'<'col-sm-12 'tr>>
<'row k-means-result-download-button'<'col-sm-12'B>>`,
// Specify all the download buttons that are displayed on the page.
buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5'],
columnDefs: [
{ // Truncate long documentation names.
targets: 1,
render: $.fn.dataTable.render.ellipsis(15, true)
},
{ // Hide columns which hold the coordinates.
targets: hideColumns,
visible: false,
searchable: false
}
]
})
}
/**
* Display the K-Means clustering result as a table on web though an Ajax call.
* @returns {void}.
*/
function generateKMeansResult () {
$('#status-analyze').css({'visibility': 'visible'})
// Convert form into an object map string to string
const form = utility.jsonifyForm()
// Send the ajax request
utility.sendAjaxRequest('/KMeansResult', form)
.done(
function (response) {
// Insert the table result.
const tableDiv = $('#KMeans-table')
tableDiv.html(response['table'])
// Change the HTML table to a data table.
convertToDataTable(tableDiv.children())
// Insert the plot result.
$('#KMeans-plot').html(response['plot'])
})
.fail(
function (jqXHR, textStatus, errorThrown) {
// If fail hide the loading icon.
$('#status-analyze').css({'visibility': 'hidden'})
console.log(`textStatus: ${textStatus}`)
console.log(`errorThrown: ${errorThrown}`)
utility.runModal('Error encountered while generating the K-Means result.')
})
.always(
function () {
// Always hide the loading icon.
$('#status-analyze').css({'visibility': 'hidden'})
})
}
$(function () {
// Hide the K-Means result div when first get to the page.
$('#KMeans-result').css({'display': 'none'})
// The event handler when generate K-Means result is clicked.
$('#get-k-means-result').click(function () {
// Catch the possible error during submission.
const error = utility.submissionError(2)
// Get K-Means result selector.
const KMeansResult = $('#KMeans-result')
if (error === null) {
// If there is no error, get the result.
KMeansResult.css({'display': 'block'})
generateKMeansResult()
// Scroll to the result.
utility.scrollToDiv(KMeansResult)
} else {
utility.runModal(error)
}
})
})
|
b0a9e74558d4893a9366d27ce5013f669a6862fd
|
{
"blob_id": "b0a9e74558d4893a9366d27ce5013f669a6862fd",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-02T19:48:08",
"content_id": "6ae0c31f64d3cf69e3b7a3b6806f531d3436d5f4",
"detected_licenses": [
"MIT"
],
"directory_id": "09eda169394f68ca3a76c2aa5ee83c6ef277761a",
"extension": "js",
"filename": "scripts_kmeans.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3022,
"license": "MIT",
"license_type": "permissive",
"path": "/lexos/static/js/scripts_kmeans.js",
"provenance": "stack-edu-0044.json.gz:645176",
"repo_name": "ashleychampagne/Lexos",
"revision_date": "2019-05-02T19:48:08",
"revision_id": "27a56d8f769af7dc477eb90c8ffbef684a941bbb",
"snapshot_id": "8f449f4354ff516f8bed0de44c3901f5dffbd60d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ashleychampagne/Lexos/27a56d8f769af7dc477eb90c8ffbef684a941bbb/lexos/static/js/scripts_kmeans.js",
"visit_date": "2020-05-23T09:00:42.247219",
"added": "2024-11-19T00:12:28.815046+00:00",
"created": "2019-05-02T19:48:08",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
# @cosmjs/launchpad-ledger
[](https://www.npmjs.com/package/@cosmjs/launchpad-ledger)
## Supported platforms
This library works with Node.js as well as certain browsers. We use the
[@ledgerhq/hw-transport-webusb](https://github.com/LedgerHQ/ledgerjs/tree/master/packages/hw-transport-webusb)
library to connect to Ledger devices from the browser via USB. You can check the
support status of this library
[here](https://github.com/LedgerHQ/ledgerjs/tree/master/packages/hw-transport-webusb#support-status).
Note the optional dependencies:
```json
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid": "^5.23.2",
"@ledgerhq/hw-transport-webusb": "^5.23.0"
}
```
If you are using this library with Node.js you must install
`@ledgerhq/hw-transport-node-hid`. You’ll need `@ledgerhq/hw-transport-webusb`
for the browser.
## Running the demo
### Node.js
Connect the Ledger device via USB, open the Cosmos app, then run the demo (this
will also build the package):
```sh
yarn demo-node
```
### Browser
Build the package for web:
```sh
yarn pack-web
```
Host the `launchpad-ledger` package directory, for example using Python 3:
```sh
python3 -m http.server
```
Visit the demo page in a browser, for example if using the Python 3 option:
http://localhost:8000/demo.
Then follow the instructions on that page.
## License
This package is part of the cosmjs repository, licensed under the Apache License
2.0 (see [NOTICE](https://github.com/CosmWasm/cosmjs/blob/master/NOTICE) and
[LICENSE](https://github.com/CosmWasm/cosmjs/blob/master/LICENSE)).
|
d969435429bcb6dfe42853695f5b763ff6ce0aac
|
{
"blob_id": "d969435429bcb6dfe42853695f5b763ff6ce0aac",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-24T16:02:38",
"content_id": "671258cfa11fb675aae21f9c0722d612ca543e39",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bc52e09ca9a254b3bc767d7effbcb2e8ffdd234c",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1643,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/packages/launchpad-ledger/README.md",
"provenance": "stack-edu-markdown-0010.json.gz:258991",
"repo_name": "heystraightedge/cosmjs",
"revision_date": "2020-09-24T16:02:38",
"revision_id": "5e79100fe341f7f745d28d8d4616912e2122e1ed",
"snapshot_id": "8987d2d098a5b4d4508d713945dfce5065534c7b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/heystraightedge/cosmjs/5e79100fe341f7f745d28d8d4616912e2122e1ed/packages/launchpad-ledger/README.md",
"visit_date": "2022-12-21T13:05:28.165523",
"added": "2024-11-18T22:04:52.493742+00:00",
"created": "2020-09-24T16:02:38",
"int_score": 4,
"score": 3.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
#!/opt/rh/python33/root/usr/bin/python3
###version 1.0.5
###Author: Feroz Omar
###Organisation: CTRAD, CSI Singapore, NUS
version = '1.0.5'
import sys
try:
filein=sys.argv[1]
fileout=sys.argv[2]
proceed = True
print('\nProgram: VAS Formatter (VF)\nVersion: {}\n\n'.format(version))
except:
print('\nProgram: VAS Formatter (VF)\nVersion: {}\nVF formats the existing variants and amino acid columns of the VAS output \nusage:\npython3 divideExistingVarsIntoColumnsxx.py <input_txt_file> <output_txt_file>\n\n\n\n'.format(version))
proceed = False
annoColumn = None
aapositionColumn = None
aaChangeColumn = None
if proceed == True:
openfile = open(filein)
savefile = open(fileout,'w')
scount=1
for line in openfile:
if '##' in line:
savefile.write(line)
if '. Format:' in line:
headerRegion=line[line.find('Format: ')+8:line.find('">')]
colheads = headerRegion.split('|')
annoColumn = colheads.index('Existing_variation')
aapositionColumn = colheads.index('Protein_position')
aaChangeColumn = colheads.index('Amino_acids')
easmaf = colheads.index('EAS_MAF')
sasmaf = colheads.index('SAS_MAF')
allelleCol = colheads.index('Allele')
headerRegion=headerRegion.replace('|','\t')
elif '#' in line and '##' not in line:
HeaderText=line.replace('\n','\t') #'\tDetails\n'
#HeaderText.replace('\tBR','\t')
existingCols = HeaderText.count('\t')##+1 or -1?
annoColumn += existingCols
aapositionColumn += existingCols
aaChangeColumn += existingCols
easmaf += existingCols
sasmaf += existingCols
allelleCol += existingCols
savefile.write(HeaderText+headerRegion+'\tAminoAcidChange\tcosmic\tdbSNP\thgmds\tNRASbase\tothers\tEAS\tSAS\n')
else:
if scount % 10000==0:print(scount,'variants have been formatted')
annos=line.strip('\n').split('\t')[annoColumn].split('&')#
try:
aaposition = line.strip('\n').split('\t')[aapositionColumn].split('/')[0]
except:
aaposition = ''
try:
aaRef = line.strip('\n').split('\t')[aaChangeColumn].split('/')[0]
except:
aaRef = ''
try:
aaChg = line.strip('\n').split('\t')[aaChangeColumn].split('/')[1]
except:
aaChg = ''
#if line.strip('\n').split('\t')[aaChangeColumn] == ''
#pass
#else:
aminochangeCombined = aaRef+aaposition+aaChg
savefile.write(line.strip('\n')+'\t'+aminochangeCombined) # write data to the file
cosList=[]
dbList=[]
hgmds=[]
NRASbase=[]
othersList=[]
for entry in annos:
if 'COSM' in entry:cosList.append(entry)
elif 'rs' in entry:dbList.append(entry)
elif 'CM' in entry:hgmds.append(entry)
elif 'NRASbase' in entry:NRASbase.append(entry)
else: othersList.append(entry)
savefile.write('\t')
if len(cosList) > 0:
for i in range(len(cosList)):
savefile.write(cosList[i])
if i !=len(cosList)-1:savefile.write('&')
savefile.write('\t')
if len(dbList) > 0:
for i in range(len(dbList)):
savefile.write(dbList[i])
if i !=len(dbList)-1:savefile.write('&')
savefile.write('\t')
#hgmds
if len(hgmds) > 0:
for i in range(len(hgmds)):
savefile.write(hgmds[i])
if i !=len(hgmds)-1:savefile.write('&')
savefile.write('\t')
#NRASbase
if len(NRASbase) > 0:
for i in range(len(NRASbase)):
savefile.write(NRASbase[i])
if i !=len(NRASbase)-1:savefile.write('&')
savefile.write('\t')
if len(othersList) > 0:
for i in range(len(othersList)):
savefile.write(othersList[i])
if i !=len(othersList)-1:savefile.write('&')
##EAS and SAS formatting
EAS = '0'
if line.strip('\n').split('\t')[easmaf] != '':
for entry in line.strip('\n').split('\t')[easmaf].split('&'):
if entry.split(':')[0] == line.strip('\n').split('\t')[allelleCol]:
EAS = entry.split(':')[1]
SAS = '0'
if line.strip('\n').split('\t')[sasmaf] != '':
for entry in line.strip('\n').split('\t')[sasmaf].split('&'):
if entry.split(':')[0] == line.strip('\n').split('\t')[allelleCol]:
SAS = entry.split(':')[1]
savefile.write('\t'+EAS+'\t'+SAS)
savefile.write('\n')
scount += 1
print(scount-1,'variants have been formatted')
openfile.close()
savefile.close()
|
59e6e2bb1548c0827acec30982b543eee76a017e
|
{
"blob_id": "59e6e2bb1548c0827acec30982b543eee76a017e",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-28T10:03:48",
"content_id": "7b2215bd2d48879d5a2ccde8c71f5a17a876b128",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "031cb869cfbba404dcd39a30622b275e2395c2e9",
"extension": "py",
"filename": "VAS_Formatter_1.0.5.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 48150886,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4262,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/projects/xenograft/oldxeno_pipelines/py_scripts/VAS_Formatter_1.0.5.py",
"provenance": "stack-edu-0061.json.gz:86335",
"repo_name": "tri-CSI/Bioinfo",
"revision_date": "2016-04-28T10:03:48",
"revision_id": "9a5dc39068af9ae9286e4b24458cd48656788cd6",
"snapshot_id": "395101f2a72a45afd06268d0f863d391f420b93e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tri-CSI/Bioinfo/9a5dc39068af9ae9286e4b24458cd48656788cd6/projects/xenograft/oldxeno_pipelines/py_scripts/VAS_Formatter_1.0.5.py",
"visit_date": "2021-01-21T13:07:40.778510",
"added": "2024-11-18T21:07:48.904678+00:00",
"created": "2016-04-28T10:03:48",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
# Python-for-Everybody-Iteration
Repeated execution of a set of statements using either a function that
calls itself or a loop.
Exercises
Exercise 1: Write a program which repeatedly reads numbers until the
user enters “done”. Once “done” is entered, print out the total, count,
and average of the numbers. If the user enters anything other than a
number, detect their mistake using try and except and print an error
message and skip to the next number.
5.9. EXERCISES 65
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333
Exercise 2: Write another program that prompts for a list of numbers
as above and at the end prints out both the maximum and minimum of
the numbers instead of the average.
|
568c8b5a4a56b2ccd850a5e43f980496f5684c34
|
{
"blob_id": "568c8b5a4a56b2ccd850a5e43f980496f5684c34",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-14T07:44:36",
"content_id": "59098793c4ff0933aa0e06bc70d84867d8fd170e",
"detected_licenses": [
"MIT"
],
"directory_id": "c87dcdde6563fa81dfcf53ea20512115dfe71b6e",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 312769331,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 792,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:38004",
"repo_name": "dishashetty5/Python-for-Everybody-Iteration",
"revision_date": "2020-11-14T07:44:36",
"revision_id": "804061616ff572bd90149ae5b78e85a5cd5989c6",
"snapshot_id": "78b69a342fa50495f218f6df2a3751b90860f514",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dishashetty5/Python-for-Everybody-Iteration/804061616ff572bd90149ae5b78e85a5cd5989c6/README.md",
"visit_date": "2023-01-12T01:28:04.033456",
"added": "2024-11-19T01:02:57.618324+00:00",
"created": "2020-11-14T07:44:36",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
package edu.stanford.nlp.parser.lexparser;
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.io.NumberRangesFileFilter;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.stats.*;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.trees.international.pennchinese.RadicalMap;
import edu.stanford.nlp.util.HashIndex;
import edu.stanford.nlp.util.Index;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.util.Timing;
import edu.stanford.nlp.process.WordSegmenter;
/**
* @author Galen Andrew
*/
public class ChineseCharacterBasedLexicon implements Lexicon {
private final double lengthPenalty;
// penaltyType should be set as follows:
// 0: no length penalty
// 1: quadratic length penalty
// 2: penalty for continuation chars only
private final int penaltyType;
private Map<List,Distribution> charDistributions;
private Set<Symbol> knownChars;
private Distribution<String> POSDistribution;
private final boolean useUnknownCharacterModel;
private static final int CONTEXT_LENGTH = 2;
private final Index<String> wordIndex;
private final Index<String> tagIndex;
public ChineseCharacterBasedLexicon(ChineseTreebankParserParams params,
Index<String> wordIndex,
Index<String> tagIndex) {
this.wordIndex = wordIndex;
this.tagIndex = tagIndex;
this.lengthPenalty = params.lengthPenalty;
this.penaltyType = params.penaltyType;
this.useUnknownCharacterModel = params.useUnknownCharacterModel;
}
public static void printStats(Collection<Tree> trees, PrintWriter pw) {
ClassicCounter<Integer> wordLengthCounter = new ClassicCounter<Integer>();
ClassicCounter<TaggedWord> wordCounter = new ClassicCounter<TaggedWord>();
ClassicCounter<Symbol> charCounter = new ClassicCounter<Symbol>();
int counter = 0;
for (Tree tree : trees) {
counter++;
List taggedWords = tree.taggedYield(new ArrayList());
for (int i = 0, size = taggedWords.size(); i < size; i++) {
TaggedWord taggedWord = (TaggedWord) taggedWords.get(i);
String word = taggedWord.word();
if (word.equals(BOUNDARY)) {
continue;
}
wordCounter.incrementCount(taggedWord);
wordLengthCounter.incrementCount(Integer.valueOf(word.length()));
for (int j = 0, length = word.length(); j < length; j++) {
Symbol sym = Symbol.cannonicalSymbol(word.charAt(j));
charCounter.incrementCount(sym);
}
charCounter.incrementCount(Symbol.END_WORD);
}
}
Set<Symbol> singletonChars = Counters.keysBelow(charCounter, 1.5);
Set<TaggedWord> singletonWords = Counters.keysBelow(wordCounter, 1.5);
ClassicCounter<String> singletonWordPOSes = new ClassicCounter<String>();
for (TaggedWord taggedWord : singletonWords) {
singletonWordPOSes.incrementCount(taggedWord.tag());
}
Distribution<String> singletonWordPOSDist = Distribution.getDistribution(singletonWordPOSes);
ClassicCounter<Character> singletonCharRads = new ClassicCounter<Character>();
for (Symbol s : singletonChars) {
singletonCharRads.incrementCount(Character.valueOf(RadicalMap.getRadical(s.getCh())));
}
Distribution<Character> singletonCharRadDist = Distribution.getDistribution(singletonCharRads);
Distribution<Integer> wordLengthDist = Distribution.getDistribution(wordLengthCounter);
NumberFormat percent = new DecimalFormat("##.##%");
pw.println("There are " + singletonChars.size() + " singleton chars out of " + (int) charCounter.totalCount() + " tokens and " + charCounter.size() + " types found in " + counter + " trees.");
pw.println("Thus singletonChars comprise " + percent.format(singletonChars.size() / charCounter.totalCount()) + " of tokens and " + percent.format((double) singletonChars.size() / charCounter.size()) + " of types.");
pw.println();
pw.println("There are " + singletonWords.size() + " singleton words out of " + (int) wordCounter.totalCount() + " tokens and " + wordCounter.size() + " types.");
pw.println("Thus singletonWords comprise " + percent.format(singletonWords.size() / wordCounter.totalCount()) + " of tokens and " + percent.format((double) singletonWords.size() / wordCounter.size()) + " of types.");
pw.println();
pw.println("Distribution over singleton word POS:");
pw.println(singletonWordPOSDist.toString());
pw.println();
pw.println("Distribution over singleton char radicals:");
pw.println(singletonCharRadDist.toString());
pw.println();
pw.println("Distribution over word length:");
pw.println(wordLengthDist);
}
// We need to make two passes over the data, whereas the calling
// routines only pass in the sentences or trees once, so we keep all
// the sentences and then process them at the end
transient private List<List<TaggedWord>> trainingSentences;
@Override
public void initializeTraining(double numTrees) {
trainingSentences = new ArrayList<List<TaggedWord>>();
}
/**
* Train this lexicon on the given set of trees.
*/
@Override
public void train(Collection<Tree> trees) {
for (Tree tree : trees) {
train(tree, 1.0);
}
}
/**
* Train this lexicon on the given set of trees.
*/
@Override
public void train(Collection<Tree> trees, double weight) {
for (Tree tree : trees) {
train(tree, weight);
}
}
/**
* TODO: make this method do something with the weight
*/
@Override
public void train(Tree tree, double weight) {
trainingSentences.add(tree.taggedYield());
}
@Override
public void trainUnannotated(List<TaggedWord> sentence, double weight) {
// TODO: for now we just punt on these
throw new UnsupportedOperationException("This version of the parser does not support non-tree training data");
}
@Override
public void train(TaggedWord tw, int loc, double weight) {
throw new UnsupportedOperationException();
}
@Override
public void train(List<TaggedWord> sentence, double weight) {
trainingSentences.add(sentence);
}
@Override
public void finishTraining() {
Timing.tick("Counting characters...");
ClassicCounter<Symbol> charCounter = new ClassicCounter<Symbol>();
// first find all chars that occur only once
for (List<TaggedWord> labels : trainingSentences) {
for (int i = 0, size = labels.size(); i < size; i++) {
String word = labels.get(i).word();
if (word.equals(BOUNDARY)) {
continue;
}
for (int j = 0, length = word.length(); j < length; j++) {
Symbol sym = Symbol.cannonicalSymbol(word.charAt(j));
charCounter.incrementCount(sym);
}
charCounter.incrementCount(Symbol.END_WORD);
}
}
Set<Symbol> singletons = Counters.keysBelow(charCounter, 1.5);
knownChars = new HashSet<Symbol>(charCounter.keySet());
Timing.tick("Counting nGrams...");
GeneralizedCounter[] POSspecificCharNGrams = new GeneralizedCounter[CONTEXT_LENGTH + 1];
for (int i = 0; i <= CONTEXT_LENGTH; i++) {
POSspecificCharNGrams[i] = new GeneralizedCounter(i + 2);
}
ClassicCounter<String> POSCounter = new ClassicCounter<String>();
List<Serializable> context = new ArrayList<Serializable>(CONTEXT_LENGTH + 1);
for (List<TaggedWord> words : trainingSentences) {
for (TaggedWord taggedWord : words) {
String word = taggedWord.word();
String tag = taggedWord.tag();
tagIndex.add(tag);
if (word.equals(BOUNDARY)) {
continue;
}
POSCounter.incrementCount(tag);
for (int i = 0, size = word.length(); i <= size; i++) {
Symbol sym;
Symbol unknownCharClass = null;
context.clear();
context.add(tag);
if (i < size) {
char thisCh = word.charAt(i);
sym = Symbol.cannonicalSymbol(thisCh);
if (singletons.contains(sym)) {
unknownCharClass = unknownCharClass(sym);
charCounter.incrementCount(unknownCharClass);
}
} else {
sym = Symbol.END_WORD;
}
POSspecificCharNGrams[0].incrementCount(context, sym); // POS-specific 1-gram
if (unknownCharClass != null) {
POSspecificCharNGrams[0].incrementCount(context, unknownCharClass); // for unknown ch model
}
// context is constructed incrementally:
// tag prevChar prevPrevChar
// this could be made faster using .sublist like in score
for (int j = 1; j <= CONTEXT_LENGTH; j++) { // poly grams
if (i - j < 0) {
context.add(Symbol.BEGIN_WORD);
POSspecificCharNGrams[j].incrementCount(context, sym);
if (unknownCharClass != null) {
POSspecificCharNGrams[j].incrementCount(context, unknownCharClass); // for unknown ch model
}
break;
} else {
Symbol prev = Symbol.cannonicalSymbol(word.charAt(i - j));
if (singletons.contains(prev)) {
context.add(unknownCharClass(prev));
} else {
context.add(prev);
}
POSspecificCharNGrams[j].incrementCount(context, sym);
if (unknownCharClass != null) {
POSspecificCharNGrams[j].incrementCount(context, unknownCharClass); // for unknown ch model
}
}
}
}
}
}
POSDistribution = Distribution.getDistribution(POSCounter);
Timing.tick("Creating character prior distribution...");
charDistributions = new HashMap<List, Distribution>();
// charDistributions = new HashMap<List, Distribution>(); // 1.5
// charCounter.incrementCount(Symbol.UNKNOWN, singletons.size());
int numberOfKeys = charCounter.size() + singletons.size();
Distribution<Symbol> prior = Distribution.goodTuringSmoothedCounter(charCounter, numberOfKeys);
charDistributions.put(Collections.EMPTY_LIST, prior);
for (int i = 0; i <= CONTEXT_LENGTH; i++) {
Set counterEntries = POSspecificCharNGrams[i].lowestLevelCounterEntrySet();
Timing.tick("Creating " + counterEntries.size() + " character " + (i + 1) + "-gram distributions...");
for (Iterator it = counterEntries.iterator(); it.hasNext();) {
Map.Entry<List,ClassicCounter> entry = (Map.Entry<List,ClassicCounter>) it.next();
context = entry.getKey();
ClassicCounter<Symbol> c = entry.getValue();
Distribution<Symbol> thisPrior = charDistributions.get(context.subList(0, context.size() - 1));
double priorWeight = thisPrior.getNumberOfKeys() / 200.0;
Distribution<Symbol> newDist = Distribution.dynamicCounterWithDirichletPrior(c, thisPrior, priorWeight);
charDistributions.put(context, newDist);
}
}
}
public Distribution<String> getPOSDistribution() {
return POSDistribution;
}
public static boolean isForeign(String s) {
for (int i = 0; i < s.length(); i++) {
int num = Character.getNumericValue(s.charAt(i));
if (num < 10 || num > 35) {
return false;
}
}
return true;
}
private Symbol unknownCharClass(Symbol ch) {
if (useUnknownCharacterModel) {
return new Symbol(Character.toString(RadicalMap.getRadical(ch.getCh()))).intern();
} else {
return Symbol.UNKNOWN;
}
}
protected static final NumberFormat formatter = new DecimalFormat("0.000");
public float score(IntTaggedWord iTW, int loc, String word, String featureSpec) {
String tag = tagIndex.get(iTW.tag);
assert !word.equals(BOUNDARY);
char[] chars = word.toCharArray();
List<Serializable> charList = new ArrayList<Serializable>(chars.length + CONTEXT_LENGTH + 1); // this starts of storing Symbol's and then starts storing String's. Clean this up someday!
// charList is constructed backward
// END_WORD char[length-1] char[length-2] ... char[0] BEGIN_WORD BEGIN_WORD
charList.add(Symbol.END_WORD);
for (int i = chars.length - 1; i >= 0; i--) {
Symbol ch = Symbol.cannonicalSymbol(chars[i]);
if (knownChars.contains(ch)) {
charList.add(ch);
} else {
charList.add(unknownCharClass(ch));
}
}
for (int i = 0; i < CONTEXT_LENGTH; i++) {
charList.add(Symbol.BEGIN_WORD);
}
double score = 0.0;
for (int i = 0, size = charList.size(); i < size - CONTEXT_LENGTH; i++) {
Symbol nextChar = (Symbol) charList.get(i);
charList.set(i, tag);
double charScore = getBackedOffDist(charList.subList(i, i + CONTEXT_LENGTH + 1)).probabilityOf(nextChar);
score += Math.log(charScore);
}
switch (penaltyType) {
case 0:
break;
case 1:
score -= (chars.length * (chars.length + 1)) * (lengthPenalty / 2);
break;
case 2:
score -= (chars.length - 1) * lengthPenalty;
break;
}
return (float) score;
}
// this is where we do backing off for unseen contexts
// (backing off for rarely seen contexts is done implicitly
// because the distributions are smoothed)
private Distribution<Symbol> getBackedOffDist(List<Serializable> context) {
// context contains [tag prevChar prevPrevChar]
for (int i = CONTEXT_LENGTH + 1; i >= 0; i--) {
List<Serializable> l = context.subList(0, i);
if (charDistributions.containsKey(l)) {
return charDistributions.get(l);
}
}
throw new RuntimeException("OOPS... no prior distribution...?");
}
/**
* Samples from the distribution over words with this POS according to the lexicon.
*
* @param tag the POS of the word to sample
* @return a sampled word
*/
public String sampleFrom(String tag) {
StringBuilder buf = new StringBuilder();
List<Serializable> context = new ArrayList<Serializable>(CONTEXT_LENGTH + 1);
// context must contain [tag prevChar prevPrevChar]
context.add(tag);
for (int i = 0; i < CONTEXT_LENGTH; i++) {
context.add(Symbol.BEGIN_WORD);
}
Distribution<Symbol> d = getBackedOffDist(context);
Symbol gen = d.sampleFrom();
genLoop:
while (gen != Symbol.END_WORD) {
buf.append(gen.getCh());
switch (penaltyType) {
case 1:
if (Math.random() > Math.pow(lengthPenalty, buf.length())) {
break genLoop;
}
break;
case 2:
if (Math.random() > lengthPenalty) {
break genLoop;
}
break;
}
for (int i = 1; i < CONTEXT_LENGTH; i++) {
context.set(i + 1, context.get(i));
}
context.set(1, gen);
d = getBackedOffDist(context);
gen = d.sampleFrom();
}
return buf.toString();
}
/**
* Samples over words regardless of POS: first samples POS, then samples
* word according to that POS
*
* @return a sampled word
*/
public String sampleFrom() {
String POS = POSDistribution.sampleFrom();
return sampleFrom(POS);
}
// don't think this should be used, but just in case...
public Iterator<IntTaggedWord> ruleIteratorByWord(int word, int loc, String featureSpec) {
throw new UnsupportedOperationException("ChineseCharacterBasedLexicon has no rule iterator!");
}
// don't think this should be used, but just in case...
public Iterator<IntTaggedWord> ruleIteratorByWord(String word, int loc, String featureSpec) {
throw new UnsupportedOperationException("ChineseCharacterBasedLexicon has no rule iterator!");
}
/** Returns the number of rules (tag rewrites as word) in the Lexicon.
* This method isn't yet implemented in this class.
* It currently just returns 0, which may or may not be helpful.
*/
public int numRules() {
return 0;
}
private Distribution<Integer> getWordLengthDistribution() {
int samples = 0;
ClassicCounter<Integer> c = new ClassicCounter<Integer>();
while (samples++ < 10000) {
String s = sampleFrom();
c.incrementCount(Integer.valueOf(s.length()));
if (samples % 1000 == 0) {
System.out.print(".");
}
}
System.out.println();
Distribution<Integer> genWordLengthDist = Distribution.getDistribution(c);
return genWordLengthDist;
}
public static void main(String[] args) throws IOException {
Map<String,Integer> flagsToNumArgs = new HashMap<String, Integer>();
flagsToNumArgs.put("-parser", Integer.valueOf(3));
flagsToNumArgs.put("-lex", Integer.valueOf(3));
flagsToNumArgs.put("-test", Integer.valueOf(2));
flagsToNumArgs.put("-out", Integer.valueOf(1));
flagsToNumArgs.put("-lengthPenalty", Integer.valueOf(1));
flagsToNumArgs.put("-penaltyType", Integer.valueOf(1));
flagsToNumArgs.put("-maxLength", Integer.valueOf(1));
flagsToNumArgs.put("-stats", Integer.valueOf(2));
Map<String,String[]> argMap = StringUtils.argsToMap(args, flagsToNumArgs);
boolean eval = argMap.containsKey("-eval");
PrintWriter pw = null;
if (argMap.containsKey("-out")) {
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream((argMap.get("-out"))[0]), "GB18030"), true);
}
System.err.println("ChineseCharacterBasedLexicon called with args:");
ChineseTreebankParserParams ctpp = new ChineseTreebankParserParams();
for (int i = 0; i < args.length; i++) {
ctpp.setOptionFlag(args, i);
System.err.print(" " + args[i]);
}
System.err.println();
Options op = new Options(ctpp);
if (argMap.containsKey("-stats")) {
String[] statArgs = (argMap.get("-stats"));
MemoryTreebank rawTrainTreebank = op.tlpParams.memoryTreebank();
FileFilter trainFilt = new NumberRangesFileFilter(statArgs[1], false);
rawTrainTreebank.loadPath(new File(statArgs[0]), trainFilt);
System.err.println("Done reading trees.");
MemoryTreebank trainTreebank;
if (argMap.containsKey("-annotate")) {
trainTreebank = new MemoryTreebank();
TreeAnnotator annotator = new TreeAnnotator(ctpp.headFinder(), ctpp, op);
for (Tree tree : rawTrainTreebank) {
trainTreebank.add(annotator.transformTree(tree));
}
System.err.println("Done annotating trees.");
} else {
trainTreebank = rawTrainTreebank;
}
printStats(trainTreebank, pw);
System.exit(0);
}
int maxLength = 1000000;
// Test.verbose = true;
if (argMap.containsKey("-norm")) {
op.testOptions.lengthNormalization = true;
}
if (argMap.containsKey("-maxLength")) {
maxLength = Integer.parseInt((argMap.get("-maxLength"))[0]);
}
op.testOptions.maxLength = 120;
boolean combo = argMap.containsKey("-combo");
if (combo) {
ctpp.useCharacterBasedLexicon = true;
op.testOptions.maxSpanForTags = 10;
op.doDep = false;
op.dcTags = false;
}
LexicalizedParser lp = null;
Lexicon lex = null;
if (argMap.containsKey("-parser")) {
String[] parserArgs = (argMap.get("-parser"));
if (parserArgs.length > 1) {
FileFilter trainFilt = new NumberRangesFileFilter(parserArgs[1], false);
lp = LexicalizedParser.trainFromTreebank(parserArgs[0], trainFilt, op);
if (parserArgs.length == 3) {
String filename = parserArgs[2];
System.err.println("Writing parser in serialized format to file " + filename + " ");
System.err.flush();
ObjectOutputStream out = IOUtils.writeStreamFromString(filename);
out.writeObject(lp);
out.close();
System.err.println("done.");
}
} else {
String parserFile = parserArgs[0];
lp = LexicalizedParser.loadModel(parserFile, op);
}
lex = lp.getLexicon();
op = lp.getOp();
ctpp = (ChineseTreebankParserParams) op.tlpParams;
}
if (argMap.containsKey("-rad")) {
ctpp.useUnknownCharacterModel = true;
}
if (argMap.containsKey("-lengthPenalty")) {
ctpp.lengthPenalty = Double.parseDouble((argMap.get("-lengthPenalty"))[0]);
}
if (argMap.containsKey("-penaltyType")) {
ctpp.penaltyType = Integer.parseInt((argMap.get("-penaltyType"))[0]);
}
if (argMap.containsKey("-lex")) {
String[] lexArgs = (argMap.get("-lex"));
if (lexArgs.length > 1) {
Index<String> wordIndex = new HashIndex<String>();
Index<String> tagIndex = new HashIndex<String>();
lex = ctpp.lex(op, wordIndex, tagIndex);
MemoryTreebank rawTrainTreebank = op.tlpParams.memoryTreebank();
FileFilter trainFilt = new NumberRangesFileFilter(lexArgs[1], false);
rawTrainTreebank.loadPath(new File(lexArgs[0]), trainFilt);
System.err.println("Done reading trees.");
MemoryTreebank trainTreebank;
if (argMap.containsKey("-annotate")) {
trainTreebank = new MemoryTreebank();
TreeAnnotator annotator = new TreeAnnotator(ctpp.headFinder(), ctpp, op);
for (Iterator iter = rawTrainTreebank.iterator(); iter.hasNext();) {
Tree tree = (Tree) iter.next();
tree = annotator.transformTree(tree);
trainTreebank.add(tree);
}
System.err.println("Done annotating trees.");
} else {
trainTreebank = rawTrainTreebank;
}
lex.initializeTraining(trainTreebank.size());
lex.train(trainTreebank);
lex.finishTraining();
System.err.println("Done training lexicon.");
if (lexArgs.length == 3) {
String filename = lexArgs.length == 3 ? lexArgs[2] : "parsers/chineseCharLex.ser.gz";
System.err.println("Writing lexicon in serialized format to file " + filename + " ");
System.err.flush();
ObjectOutputStream out = IOUtils.writeStreamFromString(filename);
out.writeObject(lex);
out.close();
System.err.println("done.");
}
} else {
String lexFile = lexArgs.length == 1 ? lexArgs[0] : "parsers/chineseCharLex.ser.gz";
System.err.println("Reading Lexicon from file " + lexFile);
ObjectInputStream in = IOUtils.readStreamFromString(lexFile);
try {
lex = (Lexicon) in.readObject();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Bad serialized file: " + lexFile);
}
in.close();
}
}
if (argMap.containsKey("-test")) {
boolean segmentWords = ctpp.segment;
boolean parse = lp != null;
assert (parse || segmentWords);
// WordCatConstituent.collinizeWords = argMap.containsKey("-collinizeWords");
// WordCatConstituent.collinizeTags = argMap.containsKey("-collinizeTags");
WordSegmenter seg = null;
if (segmentWords) {
seg = (WordSegmenter) lex;
}
String[] testArgs = (argMap.get("-test"));
MemoryTreebank testTreebank = op.tlpParams.memoryTreebank();
FileFilter testFilt = new NumberRangesFileFilter(testArgs[1], false);
testTreebank.loadPath(new File(testArgs[0]), testFilt);
TreeTransformer subcategoryStripper = op.tlpParams.subcategoryStripper();
TreeTransformer collinizer = ctpp.collinizer();
WordCatEquivalenceClasser eqclass = new WordCatEquivalenceClasser();
WordCatEqualityChecker eqcheck = new WordCatEqualityChecker();
EquivalenceClassEval basicEval = new EquivalenceClassEval(eqclass, eqcheck, "basic");
EquivalenceClassEval collinsEval = new EquivalenceClassEval(eqclass, eqcheck, "collinized");
List<String> evalTypes = new ArrayList<String>(3);
boolean goodPOS = false;
if (segmentWords) {
evalTypes.add(WordCatConstituent.wordType);
if (ctpp.segmentMarkov && !parse) {
evalTypes.add(WordCatConstituent.tagType);
goodPOS = true;
}
}
if (parse) {
evalTypes.add(WordCatConstituent.tagType);
evalTypes.add(WordCatConstituent.catType);
if (combo) {
evalTypes.add(WordCatConstituent.wordType);
goodPOS = true;
}
}
TreeToBracketProcessor proc = new TreeToBracketProcessor(evalTypes);
System.err.println("Testing...");
for (Tree goldTop : testTreebank) {
Tree gold = goldTop.firstChild();
List<HasWord> goldSentence = gold.yieldHasWord();
if (goldSentence.size() > maxLength) {
System.err.println("Skipping sentence; too long: " + goldSentence.size());
continue;
} else {
System.err.println("Processing sentence; length: " + goldSentence.size());
}
List<HasWord> s;
if (segmentWords) {
StringBuilder goldCharBuf = new StringBuilder();
for (Iterator<HasWord> wordIter = goldSentence.iterator(); wordIter.hasNext();) {
StringLabel word = (StringLabel) wordIter.next();
goldCharBuf.append(word.value());
}
String goldChars = goldCharBuf.toString();
s = seg.segment(goldChars);
} else {
s = goldSentence;
}
Tree tree;
if (parse) {
tree = lp.parseTree(s);
if (tree == null) {
throw new RuntimeException("PARSER RETURNED NULL!!!");
}
} else {
tree = Trees.toFlatTree(s);
tree = subcategoryStripper.transformTree(tree);
}
if (pw != null) {
if (parse) {
tree.pennPrint(pw);
} else {
Iterator sentIter = s.iterator();
for (; ;) {
Word word = (Word) sentIter.next();
pw.print(word.word());
if (sentIter.hasNext()) {
pw.print(" ");
} else {
break;
}
}
}
pw.println();
}
if (eval) {
Collection ourBrackets, goldBrackets;
ourBrackets = proc.allBrackets(tree);
goldBrackets = proc.allBrackets(gold);
if (goodPOS) {
ourBrackets.addAll(proc.commonWordTagTypeBrackets(tree, gold));
goldBrackets.addAll(proc.commonWordTagTypeBrackets(gold, tree));
}
basicEval.eval(ourBrackets, goldBrackets);
System.out.println("\nScores:");
basicEval.displayLast();
Tree collinsTree = collinizer.transformTree(tree);
Tree collinsGold = collinizer.transformTree(gold);
ourBrackets = proc.allBrackets(collinsTree);
goldBrackets = proc.allBrackets(collinsGold);
if (goodPOS) {
ourBrackets.addAll(proc.commonWordTagTypeBrackets(collinsTree, collinsGold));
goldBrackets.addAll(proc.commonWordTagTypeBrackets(collinsGold, collinsTree));
}
collinsEval.eval(ourBrackets, goldBrackets);
System.out.println("\nCollinized scores:");
collinsEval.displayLast();
System.out.println();
}
}
if (eval) {
basicEval.display();
System.out.println();
collinsEval.display();
}
}
}
public void readData(BufferedReader in) throws IOException {
throw new UnsupportedOperationException();
}
public void writeData(Writer w) throws IOException {
throw new UnsupportedOperationException();
}
public boolean isKnown(int word) {
throw new UnsupportedOperationException();
}
public boolean isKnown(String word) {
throw new UnsupportedOperationException();
}
private static class Symbol implements Serializable {
private static final int UNKNOWN_TYPE = 0;
private static final int DIGIT_TYPE = 1;
private static final int LETTER_TYPE = 2;
private static final int BEGIN_WORD_TYPE = 3;
private static final int END_WORD_TYPE = 4;
private static final int CHAR_TYPE = 5;
private static final int UNK_CLASS_TYPE = 6;
private char ch;
private String unkClass;
int type;
public static final Symbol UNKNOWN = new Symbol(UNKNOWN_TYPE);
public static final Symbol DIGIT = new Symbol(DIGIT_TYPE);
public static final Symbol LETTER = new Symbol(LETTER_TYPE);
public static final Symbol BEGIN_WORD = new Symbol(BEGIN_WORD_TYPE);
public static final Symbol END_WORD = new Symbol(END_WORD_TYPE);
public static final Interner<Symbol> interner = new Interner<Symbol>();
public Symbol(char ch) {
type = CHAR_TYPE;
this.ch = ch;
}
public Symbol(String unkClass) {
type = UNK_CLASS_TYPE;
this.unkClass = unkClass;
}
public Symbol(int type) {
assert type != CHAR_TYPE;
this.type = type;
}
public static Symbol cannonicalSymbol(char ch) {
if (Character.isDigit(ch)) {
return DIGIT; //{ Digits.add(new Character(ch)); return DIGIT; }
}
if (Character.getNumericValue(ch) >= 10 && Character.getNumericValue(ch) <= 35) {
return LETTER; //{ Letters.add(new Character(ch)); return LETTER; }
}
return new Symbol(ch);
}
public char getCh() {
if (type == CHAR_TYPE) {
return ch;
} else {
return '*';
}
}
public Symbol intern() {
return interner.intern(this);
}
@Override
public String toString() {
if (type == CHAR_TYPE) {
return "[u" + (int) ch + "]";
} else if (type == UNK_CLASS_TYPE) {
return "UNK:" + unkClass;
} else {
return Integer.toString(type);
}
}
private Object readResolve() throws ObjectStreamException {
switch (type) {
case CHAR_TYPE:
return intern();
case UNK_CLASS_TYPE:
return intern();
case UNKNOWN_TYPE:
return UNKNOWN;
case DIGIT_TYPE:
return DIGIT;
case LETTER_TYPE:
return LETTER;
case BEGIN_WORD_TYPE:
return BEGIN_WORD;
case END_WORD_TYPE:
return END_WORD;
default: // impossible...
throw new InvalidObjectException("ILLEGAL VALUE IN SERIALIZED SYMBOL");
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Symbol)) {
return false;
}
final Symbol symbol = (Symbol) o;
if (ch != symbol.ch) {
return false;
}
if (type != symbol.type) {
return false;
}
if (unkClass != null ? !unkClass.equals(symbol.unkClass) : symbol.unkClass != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = ch;
result = 29 * result + (unkClass != null ? unkClass.hashCode() : 0);
result = 29 * result + type;
return result;
}
private static final long serialVersionUID = 8925032621317022510L;
} // end class Symbol
private static final long serialVersionUID = -5357655683145854069L;
public UnknownWordModel getUnknownWordModel() {
// TODO Auto-generated method stub
return null;
}
public void setUnknownWordModel(UnknownWordModel uwm) {
// TODO Auto-generated method stub
}
@Override
public void train(Collection<Tree> trees, Collection<Tree> rawTrees) {
train(trees);
}
} // end class ChineseCharacterBasedLexicon
|
be50600c1a5166e266aa5d32ac8063f5060b013d
|
{
"blob_id": "be50600c1a5166e266aa5d32ac8063f5060b013d",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-25T09:43:52",
"content_id": "0cb242995170e1de295993fc127480eae9e97421",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "1641b82c9f7f7cf8f741256a1b4eaf0b0a80ee32",
"extension": "java",
"filename": "ChineseCharacterBasedLexicon.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 27590938,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 31552,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/build_dataset/politeness/edu/stanford/nlp/parser/lexparser/ChineseCharacterBasedLexicon.java",
"provenance": "stack-edu-0023.json.gz:259681",
"repo_name": "etta87/emotions-online-qa",
"revision_date": "2015-03-25T09:43:52",
"revision_id": "9cbdb497cf6f50053a0e33e276b1d24d3debb271",
"snapshot_id": "ddce3ef6f127044f028a880205b84f359a99c074",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/etta87/emotions-online-qa/9cbdb497cf6f50053a0e33e276b1d24d3debb271/build_dataset/politeness/edu/stanford/nlp/parser/lexparser/ChineseCharacterBasedLexicon.java",
"visit_date": "2020-12-02T16:32:21.485537",
"added": "2024-11-19T01:32:07.685611+00:00",
"created": "2015-03-25T09:43:52",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
namespace Maverick.WebSockets.Compression
{
/// <summary>
/// This class provides declaration for constants and PInvokes as well as some basic tools for exposing the
/// native CLRCompression.dll (effectively, ZLib) library to managed code.
/// </summary>
internal static partial class ZLibNative
{
// This is the NULL pointer for using with ZLib pointers;
// we prefer it to IntPtr.Zero to mimic the definition of Z_NULL in zlib.h:
internal static readonly IntPtr ZNullPtr = IntPtr.Zero;
public enum FlushCode : Int32
{
NoFlush = 0,
SyncFlush = 2,
Finish = 4,
}
public enum ErrorCode : Int32
{
Ok = 0,
StreamEnd = 1,
StreamError = -2,
DataError = -3,
MemError = -4,
BufError = -5,
VersionError = -6
}
public enum CompressionLevel : Int32
{
NoCompression = 0,
BestSpeed = 1,
DefaultCompression = -1
}
public enum CompressionStrategy : Int32
{
DefaultStrategy = 0
}
public enum CompressionMethod : Int32
{
Deflated = 8
}
/// <summary>
/// ZLib stream descriptor data structure
/// Do not construct instances of <code>ZStream</code> explicitly.
/// Always use <code>ZLibNative.DeflateInit2_</code> or <code>ZLibNative.InflateInit2_</code> instead.
/// Those methods will wrap this structure into a <code>SafeHandle</code> and thus make sure that it is always disposed correctly.
/// </summary>
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Ansi )]
internal struct ZStream
{
internal void Init()
{
zalloc = ZNullPtr;
zfree = ZNullPtr;
opaque = ZNullPtr;
}
internal IntPtr nextIn; //Bytef *next_in; /* next input byte */
internal UInt32 availIn; //uInt avail_in; /* number of bytes available at next_in */
internal UInt32 totalIn; //uLong total_in; /* total nb of input bytes read so far */
internal IntPtr nextOut; //Bytef *next_out; /* next output byte should be put there */
internal UInt32 availOut; //uInt avail_out; /* remaining free space at next_out */
internal UInt32 totalOut; //uLong total_out; /* total nb of bytes output so far */
internal IntPtr msg; //char *msg; /* last error message, NULL if no error */
internal IntPtr state; //struct internal_state FAR *state; /* not visible by applications */
internal IntPtr zalloc; //alloc_func zalloc; /* used to allocate the internal state */
internal IntPtr zfree; //free_func zfree; /* used to free the internal state */
internal IntPtr opaque; //voidpf opaque; /* private data object passed to zalloc and zfree */
internal Int32 dataType; //Int32 data_type; /* best guess about the data type: binary or text */
internal UInt32 adler; //uLong adler; /* adler32 value of the uncompressed data */
internal UInt32 reserved; //uLong reserved; /* reserved for future use */
}
// Legal values are 8..15 and -8..-15. 15 is the window size, negative val causes deflate to produce raw deflate data (no zlib header).
public const Int32 Deflate_DefaultWindowBits = -15;
/// <summary>
/// <p><strong>From the ZLib manual:</strong></p>
/// <p>The <code>memLevel</code> parameter specifies how much memory should be allocated for the internal compression state.
/// <code>memLevel</code> = 1 uses minimum memory but is slow and reduces compression ratio; <code>memLevel</code> = 9 uses maximum
/// memory for optimal speed. The default value is 8.</p>
/// <p>See also: How to choose a compression level (in comments to <code>CompressionLevel</code>.</p>
/// </summary>
public const Int32 Deflate_DefaultMemLevel = 8; // Memory usage by deflate. Legal range: [1..9]. 8 is ZLib default.
// More is faster and better compression with more memory usage.
public const Int32 Deflate_NoCompressionMemLevel = 7;
/**
* Do not remove the nested typing of types inside of <code>System.IO.Compression.ZLibNative</code>.
* This was done on purpose to:
*
* - Achieve the right encapsulation in a situation where <code>ZLibNative</code> may be compiled division-wide
* into different assemblies that wish to consume <code>CLRCompression</code>. Since <code>internal</code>
* scope is effectively like <code>public</code> scope when compiling <code>ZLibNative</code> into a higher
* level assembly, we need a combination of inner types and <code>private</code>-scope members to achieve
* the right encapsulation.
*
* - Achieve late dynamic loading of <code>CLRCompression.dll</code> at the right time.
* The native assembly will not be loaded unless it is actually used since the loading is performed by a static
* constructor of an inner type that is not directly referenced by user code.
*
* In Dev12 we would like to create a proper feature for loading native assemblies from user-specified
* directories in order to PInvoke into them. This would preferably happen in the native interop/PInvoke
* layer; if not we can add a Framework level feature.
*/
/// <summary>
/// The <code>ZLibStreamHandle</code> could be a <code>CriticalFinalizerObject</code> rather than a
/// <code>SafeHandleMinusOneIsInvalid</code>. This would save an <code>IntPtr</code> field since
/// <code>ZLibStreamHandle</code> does not actually use its <code>handle</code> field.
/// Instead it uses a <code>private ZStream zStream</code> field which is the actual handle data
/// structure requiring critical finalization.
/// However, we would like to take advantage if the better debugability offered by the fact that a
/// <em>releaseHandleFailed MDA</em> is raised if the <code>ReleaseHandle</code> method returns
/// <code>false</code>, which can for instance happen if the underlying ZLib <code>XxxxEnd</code>
/// routines return an failure error code.
/// </summary>
[SecurityCritical]
public sealed class ZLibStreamHandle : SafeHandle
{
public enum State { NotInitialized, InitializedForDeflate, InitializedForInflate, Disposed }
private ZStream _zStream;
[SecurityCritical]
private volatile State _initializationState;
public ZLibStreamHandle()
: base( new IntPtr( -1 ), true )
{
_zStream = new ZStream();
_zStream.Init();
_initializationState = State.NotInitialized;
SetHandle( IntPtr.Zero );
}
public override Boolean IsInvalid
{
[SecurityCritical]
get { return handle == new IntPtr( -1 ); }
}
public State InitializationState
{
[Pure]
[SecurityCritical]
get { return _initializationState; }
}
[SecurityCritical]
protected override Boolean ReleaseHandle()
{
switch ( InitializationState )
{
case State.NotInitialized: return true;
case State.InitializedForDeflate: return ( DeflateEnd() == ErrorCode.Ok );
case State.InitializedForInflate: return ( InflateEnd() == ErrorCode.Ok );
case State.Disposed: return true;
default: return false; // This should never happen. Did we forget one of the State enum values in the switch?
}
}
public IntPtr NextIn
{
[SecurityCritical]
get { return _zStream.nextIn; }
[SecurityCritical]
set { _zStream.nextIn = value; }
}
public UInt32 AvailIn
{
[SecurityCritical]
get { return _zStream.availIn; }
[SecurityCritical]
set { _zStream.availIn = value; }
}
public IntPtr NextOut
{
[SecurityCritical]
get { return _zStream.nextOut; }
[SecurityCritical]
set { _zStream.nextOut = value; }
}
public UInt32 AvailOut
{
[SecurityCritical]
get { return _zStream.availOut; }
[SecurityCritical]
set { _zStream.availOut = value; }
}
[Pure]
[SecurityCritical]
private void EnsureNotDisposed()
{
if ( InitializationState == State.Disposed )
throw new ObjectDisposedException( GetType().ToString() );
}
[Pure]
[SecurityCritical]
private void EnsureState( State requiredState )
{
if ( InitializationState != requiredState )
throw new InvalidOperationException( "InitializationState != " + requiredState.ToString() );
}
[SecurityCritical]
public ErrorCode DeflateInit2_( CompressionLevel level, Int32 windowBits, Int32 memLevel, CompressionStrategy strategy )
{
EnsureNotDisposed();
EnsureState( State.NotInitialized );
ErrorCode errC = ZLibInterop.DeflateInit2_( ref _zStream, level, CompressionMethod.Deflated, windowBits, memLevel, strategy );
_initializationState = State.InitializedForDeflate;
return errC;
}
[SecurityCritical]
public ErrorCode Deflate( FlushCode flush )
{
EnsureNotDisposed();
EnsureState( State.InitializedForDeflate );
return ZLibInterop.Deflate( ref _zStream, flush );
}
[SecurityCritical]
public ErrorCode DeflateEnd()
{
EnsureNotDisposed();
EnsureState( State.InitializedForDeflate );
ErrorCode errC = ZLibInterop.DeflateEnd( ref _zStream );
_initializationState = State.Disposed;
return errC;
}
[SecurityCritical]
public ErrorCode InflateInit2_( Int32 windowBits )
{
EnsureNotDisposed();
EnsureState( State.NotInitialized );
ErrorCode errC = ZLibInterop.InflateInit2_( ref _zStream, windowBits );
_initializationState = State.InitializedForInflate;
return errC;
}
[SecurityCritical]
public ErrorCode Inflate( FlushCode flush )
{
EnsureNotDisposed();
EnsureState( State.InitializedForInflate );
return ZLibInterop.Inflate( ref _zStream, flush );
}
[SecurityCritical]
public ErrorCode InflateEnd()
{
EnsureNotDisposed();
EnsureState( State.InitializedForInflate );
ErrorCode errC = ZLibInterop.InflateEnd( ref _zStream );
_initializationState = State.Disposed;
return errC;
}
/// <summary>
/// This function is equivalent to inflateEnd followed by inflateInit.
/// The stream will keep attributes that may have been set by inflateInit2.
/// </summary>
[SecurityCritical]
public ErrorCode InflateReset( Int32 windowBits )
{
EnsureNotDisposed();
EnsureState( State.InitializedForInflate );
ErrorCode errC = ZLibInterop.InflateEnd( ref _zStream );
if ( errC != ErrorCode.Ok )
{
_initializationState = State.Disposed;
return errC;
}
errC = ZLibInterop.InflateInit2_( ref _zStream, windowBits );
_initializationState = State.InitializedForInflate;
return errC;
}
// This can work even after XxflateEnd().
[SecurityCritical]
public String GetErrorMessage() => _zStream.msg != ZNullPtr ? Marshal.PtrToStringAnsi( _zStream.msg ) : String.Empty;
}
[SecurityCritical]
public static ErrorCode CreateZLibStreamForDeflate( out ZLibStreamHandle zLibStreamHandle, CompressionLevel level,
Int32 windowBits, Int32 memLevel, CompressionStrategy strategy )
{
zLibStreamHandle = new ZLibStreamHandle();
return zLibStreamHandle.DeflateInit2_( level, windowBits, memLevel, strategy );
}
[SecurityCritical]
public static ErrorCode CreateZLibStreamForInflate( out ZLibStreamHandle zLibStreamHandle, Int32 windowBits )
{
zLibStreamHandle = new ZLibStreamHandle();
return zLibStreamHandle.InflateInit2_( windowBits );
}
}
}
|
7c67b85dbea559a8831a850e91a7c3423616f57d
|
{
"blob_id": "7c67b85dbea559a8831a850e91a7c3423616f57d",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-09T08:03:42",
"content_id": "09d76a6d3e7744417c6efd80020775b5a6e06ec8",
"detected_licenses": [
"MIT"
],
"directory_id": "85c05d35f398897bf559c292511615cda757b24e",
"extension": "cs",
"filename": "ZLibNative.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 169167207,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 13949,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Maverick.WebSockets/Compression/ZLibNative.cs",
"provenance": "stack-edu-0014.json.gz:572566",
"repo_name": "zlatanov/websockets",
"revision_date": "2019-02-09T08:03:42",
"revision_id": "4d0c4e43e278d3bc6c0e185bb09b828160af2db8",
"snapshot_id": "5d1a5d027aa5b36168b492332aab6952efcbbf4c",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/zlatanov/websockets/4d0c4e43e278d3bc6c0e185bb09b828160af2db8/src/Maverick.WebSockets/Compression/ZLibNative.cs",
"visit_date": "2020-04-20T23:24:38.619698",
"added": "2024-11-19T01:36:31.565187+00:00",
"created": "2019-02-09T08:03:42",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
import json
import re
import string
import scipy
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm_notebook as tqdm
from nltk import wordpunct_tokenize
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from sklearn.linear_model import LinearRegression,SGDClassifier,ElasticNet,LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier,VotingClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score,f1_score,mean_squared_error,confusion_matrix
from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer
train_path = 'data/train.json'
dev_path = 'data/dev.json'
translator = str.maketrans("","", string.punctuation)
stemmer = SnowballStemmer("english", ignore_stopwords=True)
def read_file(path):
data_X = []
data_Y = []
with open(path, 'r') as data_file:
line = data_file.readline()
while line:
data = json.loads(line)
data_X.append(data['review'])
data_Y.append(data['ratings'])
line = data_file.readline()
return data_X,data_Y
def get_metrics_from_pred(y_pred,y_true):
mse = mean_squared_error(y_pred,y_true)
try:
f1_scor = f1_score(y_true, y_pred, average='weighted')
acc = accuracy_score(y_true, y_pred)
conf_matrix = confusion_matrix(y_true,y_pred)
except:
y_pred = np.round(y_pred)
f1_scor = f1_score(y_true, y_pred, average='weighted')
acc = accuracy_score(y_true, y_pred)
conf_matrix = confusion_matrix(y_true,y_pred)
print("MSE = ",mse," F1 = ",f1_scor," Accuracy = ",acc)
plt.matshow(conf_matrix)
plt.colorbar()
def get_metrics(model,X,y_true):
y_pred = model.predict(X)
get_metrics_from_pred(y_pred,y_true)
def get_metrics_using_probs(model,X,y_true):
y_pred = model.predict_proba(X)
y_pred = np.average(y_pred,axis=1, weights=[1,2,3,4,5])*15
get_metrics_from_pred(y_pred,y_true)
def remove_repeats(sentence):
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1", sentence)
def tokenizer1(sentence):
sentence = sentence.translate(translator) # Remove punctuations
sentence = sentence.lower() # Convert to lowercase
sentence = re.sub(r'\d+', '', sentence) # Remove Numbers
sentence = remove_repeats(sentence) # Remove repeated characters
# sentence = sentence.strip() # Remove Whitespaces
tokens = wordpunct_tokenize(sentence) # Tokenize
# tokens = word_tokenize(sentence) # Tokenize
# for i in range(len(tokens)): # Stem word
# tokens[i] = stemmer.stem(tokens[i])
return tokens
tokenize = tokenizer1
X_train,Y_train = read_file(train_path)
X_dev,Y_dev = read_file(dev_path)
# X_train = X_train[0:100]
# Y_train = Y_train[0:100]
# X_dev = X_dev[0:100]
# Y_dev = Y_dev[0:100]
processed_stopwords = []
for word in stopwords.words('english'):
processed_stopwords += tokenize(word)
# vectorizer = TfidfVectorizer(strip_accents='ascii',
# lowercase=True,
# tokenizer=tokenize,
# stop_words=processed_stopwords,
# ngram_range=(1,1),
# binary=True,
# norm='l2',
# analyzer='word')
# vectorizer = TfidfVectorizer(binary=True,tokenizer=tokenize)
# vectorizer = TfidfVectorizer(tokenizer=tokenize)
# vectorizer = TfidfVectorizer(tokenizer=tokenize,ngram_range=(1,2),binary=True)
vectorizer = CountVectorizer(tokenizer=tokenize,ngram_range=(1,2))
X_train_counts = vectorizer.fit_transform(X_train)
X_dev_counts = vectorizer.transform(X_dev)
print("vectorizer done")
indices = np.where(list(map(lambda x: x<=3,Y_train)))[0]
X_train_counts_12_3 = X_train_counts[indices]
Y_train_12_3 = [1 if Y_train[j]==3 else 0 for j in indices]
indices = np.where(list(map(lambda x:x>3,Y_train)))[0]
X_train_counts_4_5 = X_train_counts[indices]
Y_train_4_5 = [Y_train[j] for j in indices]
indices = np.where(list(map(lambda x:x<3,Y_train)))[0]
X_train_counts_1_2 = X_train_counts[indices]
Y_train_1_2 = [Y_train[j] for j in indices]
def modif(x):
if (x>3):
return 1
else:
return 0
Y_modified = list(map(lambda x: modif(x),Y_train))
model_123_45 = LogisticRegression(verbose=1,solver='sag')
model_123_45.fit(X_train_counts,Y_modified)
model_4_5 = LogisticRegression(verbose=1,solver='sag')
model_4_5.fit(X_train_counts_4_5,Y_train_4_5)
model_12_3 = LogisticRegression(verbose=1,solver='sag')
model_12_3.fit(X_train_counts_12_3,Y_train_12_3)
model_1_2 = LogisticRegression(verbose=1,solver='sag')
model_1_2.fit(X_train_counts_1_2,Y_train_1_2)
pred_123_45 = model_123_45.predict_proba(X_dev_counts)
pred_12_3 = model_12_3.predict_proba(X_dev_counts)
pred_1_2 = model_1_2.predict_proba(X_dev_counts)
pred_4_5 = model_4_5.predict_proba(X_dev_counts)
pred = []
for i in tqdm(range(len(pred_123_45))):
pred.append(pred_123_45[i][0]*pred_12_3[i][0]*pred_1_2[i][0]*1.0+
pred_123_45[i][0]*pred_12_3[i][0]*pred_1_2[i][1]*2.0+
pred_123_45[i][0]*pred_12_3[i][1]*3.0+
pred_123_45[i][1]*pred_4_5[i][0]*4.0+
pred_123_45[i][1]*pred_4_5[i][1]*5.0)
get_metrics_from_pred(pred,Y_dev)
|
7df8296fff8a043492b55956de747fb85a23d985
|
{
"blob_id": "7df8296fff8a043492b55956de747fb85a23d985",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-21T04:21:24",
"content_id": "cdd0a617b25bd48b42bcc6ced9d902bae1be0317",
"detected_licenses": [
"MIT"
],
"directory_id": "f43aff054b472dbe4c5f11ad89381e5e9ab3baed",
"extension": "py",
"filename": "Non Pipelined Tester.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 167846897,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5541,
"license": "MIT",
"license_type": "permissive",
"path": "/A1_part_1/Non Pipelined Tester.py",
"provenance": "stack-edu-0056.json.gz:20425",
"repo_name": "ankurshaswat/COL772",
"revision_date": "2019-03-21T04:21:24",
"revision_id": "503425e89290a8ac710cf053dae3c23aadf49ca7",
"snapshot_id": "a6f9990974f27ffb46fd7f7bdae60840a0d6c50a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ankurshaswat/COL772/503425e89290a8ac710cf053dae3c23aadf49ca7/A1_part_1/Non Pipelined Tester.py",
"visit_date": "2020-04-19T00:27:06.502092",
"added": "2024-11-18T22:02:41.713669+00:00",
"created": "2019-03-21T04:21:24",
"int_score": 3,
"score": 2.671875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
module Fog
module Compute
class RackspaceV2
class Real
# Deletes a specified server instance from the system.
# @param [String] server_id the id of the server to delete
# @return [Excon::Response] response
# @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404
# @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400
# @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500
# @raise [Fog::Compute::RackspaceV2::ServiceError]
# @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Server-d1e2883.html
def delete_server(server_id)
request(
:expects => [204],
:method => 'DELETE',
:path => "servers/#{server_id}"
)
end
end
class Mock
def delete_server(server_id)
self.data[:servers].delete(server_id)
volumes = self.data[:volumes].values
volumes.each do |v|
v["attachments"].delete_if { |a| a["serverId"] == server_id }
v["status"] = "available" if v["attachments"].empty?
end
response(:status => 204)
end
end
end
end
end
|
039c8e805468e02c78ace82936f4166b455efae8
|
{
"blob_id": "039c8e805468e02c78ace82936f4166b455efae8",
"branch_name": "refs/heads/master",
"committer_date": "2013-08-30T19:11:20",
"content_id": "3eca0ed35b6b790736438a68c144fb896dbb5902",
"detected_licenses": [
"MIT"
],
"directory_id": "e7ff4c3c73822921be56473808b88e4a94445d42",
"extension": "rb",
"filename": "delete_server.rb",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 12491878,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1230,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/fog/rackspace/requests/compute_v2/delete_server.rb",
"provenance": "stack-edu-0067.json.gz:677910",
"repo_name": "Instagram/fog",
"revision_date": "2013-08-30T19:11:20",
"revision_id": "46a43ff78e751aac09340eff16ef1151920368db",
"snapshot_id": "fba6652082dcef72d85fc76862cf699f9c09d56f",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/Instagram/fog/46a43ff78e751aac09340eff16ef1151920368db/lib/fog/rackspace/requests/compute_v2/delete_server.rb",
"visit_date": "2020-12-25T11:58:13.936801",
"added": "2024-11-18T22:39:43.196815+00:00",
"created": "2013-08-30T19:11:20",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
import Character from 'objects/Character';
import PlayerAnimation from 'objects/animations/PlayerAnimation';
import Interactive from 'objects/behaviours/Interactive';
class Player extends Character {
constructor(game,x,y){
super(game,x,y);
this.animation = new PlayerAnimation(game,x,y,1);
this.behaviour = new Interactive(game, x,100);
this.agility = .5;
}
}
export default Player;
|
84df88a9ae7ee6ddf9599f34f9dacfaf16b3c371
|
{
"blob_id": "84df88a9ae7ee6ddf9599f34f9dacfaf16b3c371",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-30T16:19:35",
"content_id": "c962cb4faa3ce922e3e87c4fb73e6e71b7efb9f8",
"detected_licenses": [
"MIT"
],
"directory_id": "0eda95ae5ab088e1c77682622ca2730a73c96225",
"extension": "js",
"filename": "Player.js",
"fork_events_count": 0,
"gha_created_at": "2016-01-29T13:46:08",
"gha_event_created_at": "2016-01-30T15:24:16",
"gha_language": "JavaScript",
"gha_license_id": null,
"github_id": 50664896,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 419,
"license": "MIT",
"license_type": "permissive",
"path": "/src/objects/Player.js",
"provenance": "stack-edu-0039.json.gz:536021",
"repo_name": "digitalapesjam/ggj2016",
"revision_date": "2016-01-30T16:19:35",
"revision_id": "bb7eb1b11dae60d0a689fe4d3859151aae4f9c80",
"snapshot_id": "3a2698bad0f0f7e3238484deffdf2daa585a22e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/digitalapesjam/ggj2016/bb7eb1b11dae60d0a689fe4d3859151aae4f9c80/src/objects/Player.js",
"visit_date": "2021-01-10T12:06:38.479306",
"added": "2024-11-18T22:41:47.628919+00:00",
"created": "2016-01-30T16:19:35",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz"
}
|
# Secure DNS
> A simple DNS server written in Go using DNS over HTTPS along with some graceful fallback options
## Features
- [x] DNS over HTTPS
- [x] Fallback over UDP
- [x] Systemd Daemon
## Installation
```bash
go get github.com/rameezk/secure-dns
```
## Usage
### Classic Mode (AKA running from cli)
If your `$GOPATH` is set correctly, you can simply invoke with:
```bash
secure-dns <args>
```
For a full list of configuration options, use:
```bash
secure-dns --help
```
NOTE If you're using the default listening address and port (e.g. <IP_ADDRESS>:53), you'll need to run as root
```bash
sudo secure-dns <args>
```
### Daemon (via systemd)
The systemd daemon can be installed by running:
```bash
./install-systemd-service.sh
```
The configuration file can be found at `/etc/secure-dns.conf`
|
c9ecaae317389017e86870c54573c57f22d21037
|
{
"blob_id": "c9ecaae317389017e86870c54573c57f22d21037",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-30T11:48:40",
"content_id": "a9510a3f3da2ce1f5300010a6f84f41ef751595c",
"detected_licenses": [
"MIT"
],
"directory_id": "7586e31c3065753165018c3750305c3d9b98297b",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189244958,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 804,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0009.json.gz:124720",
"repo_name": "rameezk/secure-dns",
"revision_date": "2019-05-30T11:48:40",
"revision_id": "2855d86f439c607c9c78473a74277bbfd677bedd",
"snapshot_id": "0aeb8ab3c5568fe2b7decdf722445726f83cec79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rameezk/secure-dns/2855d86f439c607c9c78473a74277bbfd677bedd/README.md",
"visit_date": "2020-05-29T16:17:52.795654",
"added": "2024-11-18T23:04:59.992376+00:00",
"created": "2019-05-30T11:48:40",
"int_score": 4,
"score": 3.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz"
}
|
#!/usr/bin/env python3
from netcdfTools import *
import sys
import argparse
import numpy as np
'''
Description:
'''
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
def checkVariables(vnames, vDict):
# Check that variables are found
for vi in vnames:
if( vi not in vDict.keys() ):
sys.exit(' Variable {} not found from variable list: {}'.format(vi, vDict.keys()))
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
def unaryOpr( v, opStr ):
if( opStr is None ):
return v
if( opStr == '^2'):
np.power(v, 2, out=v)
elif( opStr == 'abs' ):
np.abs(v, out=v)
elif( opStr == 'sqrt'):
np.sqrt(v, out=v)
return v
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
def binaryOpr( v1, v2, opStr ):
if( opStr == '+' ):
return v1+v2
elif( opStr == '-' ):
return v1-v2
elif( opStr == '/' ):
return v1/(v2+1.e-6)
elif( opStr == '*' ):
return v1*v2
else:
sys.exit('Unrecognized binary operator {}: Exiting ...'.format(opStr))
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
def unaryOprUnit( unit1 , opStr ):
if( opStr is None ):
return unit1
if( opStr == '^2'):
unitout = '({})^2'.format(unit1)
elif( opStr == 'abs' ):
unitout = unit1
elif( opStr == 'sqrt'):
unitout = '({})^(1/2)'.format(unit1)
return unitout
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
def binaryOprUnit( unit1, unit2, opStr ):
if( opStr == '+' ):
return unit1
elif( opStr == '-' ):
return unit1
elif( opStr == '/' ):
return '{}({})^-1'.format(unit1,unit2)
elif( opStr == '*' ):
if( unit1 == unit2 ): unitout = '({})^2'.format(unit1)
else: unitout = '{} {}'.format(unit1,unit2)
return unitout
#==========================================================#
parser = argparse.ArgumentParser(prog='binaryOperateNetCdf.py')
parser.add_argument("-f1", "--filename1", metavar='FILE1', type=str,
help="First NetCDF file.")
parser.add_argument("-f2", "--filename2", metavar='FILE2', type=str,
help="Second NetCDF file.")
parser.add_argument("-fo", "--fileout", type=str, required=True,
help="Name of the output netCDF file.")
parser.add_argument("-vn1", "--varNames1", metavar='VN1', type=str, nargs='+',\
help="Names of variables from f1 dataset.")
parser.add_argument("-vn2", "--varNames2", metavar='VN2', type=str, nargs='+',\
help="Names of variables from f2 dataset.")
parser.add_argument("-vno", "--varOutNames", metavar='VNO', type=str, nargs='+',\
help="Names of output variables. Their number must match with VN1.")
parser.add_argument("-dn", "--derivNames",type=str, nargs='+', metavar='DN', default=None,\
help="(Optional) Names of derived coordinates to output to same file.")
parser.add_argument("-s1", "--scale1", type=float, default=1.0,
help="Scale factor for file 1 dataset.")
parser.add_argument("-s2", "--scale2", type=float, default=1.0,
help="Scale factor for file 2 dataset.")
parser.add_argument("-op", "--binaryOperator", type=str, choices=['+','-','/','*'],
help="Binary operator: v1 <op> v2.")
parser.add_argument("-uop1", "--unaryOperator1", type=str, choices=['^2','abs','sqrt'], default=None,
help="Unary operator for file 1 dataset.")
parser.add_argument("-uop2", "--unaryOperator2", type=str, choices=['^2','abs','sqrt'], default=None,
help="Unary operator for file 2 dataset.")
args = parser.parse_args()
#==========================================================#
fn1 = args.filename1
fn2 = args.filename2
fileout = args.fileout
vn1 = args.varNames1
vn2 = args.varNames2
vno = args.varOutNames
dn = args.derivNames
s1 = args.scale1
s2 = args.scale2
uop1 = args.unaryOperator1
uop2 = args.unaryOperator2
biop = args.binaryOperator
'''
Establish two boolean variables which indicate whether the created variable is an
independent or dependent variable in function createNetcdfVariable().
'''
parameter = True; variable = False
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
N1 = len(vn1); N2 = len(vn2); NO = len(vno)
if( N1 == N2 ):
pass
elif( (N1 > N2) and (N2 == 1) ):
pass
else:
sys.exit(' Incompatible number of variables: N1={} & N2={}. If N1 > N2, then N2 == 1 is required.'.format(N1,N2))
if( N1 != NO ):
sys.exit(' The number of output variable names NO={} must match N1={}. Exiting ...'.format(NO,N1))
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
ds1, v1D, u1D = netcdfDataset2(fn1) # vD: variableDict, uD: unitDict
ds2, v2D, u2D = netcdfDataset2(fn2)
checkVariables( vn1, v1D )
checkVariables( vn2, v2D )
vstr = vn1[0] # We can use the first variable as the coords should match.
tn = v1D[vstr][0]; zn = v1D[vstr][1]; yn = v1D[vstr][2]; xn = v1D[vstr][3]
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
# Create a NETCDF output dataset (dso) for writing out the data.
dso = netcdfOutputDataset( fileout )
# Read
dD1 = dict()
dD2 = dict()
time, time_dims = read1DVariableFromDataset(tn, vstr , ds1, 0, 0, 1 ) # All values.
tv = createNetcdfVariable( dso, time, tn, len(time), u1D[tn],'f4', (tn,), parameter )
x, x_dims = read1DVariableFromDataset( xn, vstr, ds1, 0, 0, 1 )
xv = createNetcdfVariable( dso, x , xn , len(x) , u1D[xn],'f4', (xn,), parameter )
y, y_dims = read1DVariableFromDataset( yn, vstr, ds1, 0, 0, 1 )
yv = createNetcdfVariable( dso, y , yn , len(y) , u1D[yn],'f4', (yn,), parameter )
z, z_dims = read1DVariableFromDataset( zn, vstr, ds1, 0, 0, 1 )
zv = createNetcdfVariable( dso, z , zn , len(z) , u1D[zn],'f4', (zn,), parameter )
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
# Include additional (derived) coordinates into the output file.
if( dn ):
for di in dn:
if( di in v1D.keys() ):
dc = ds1.variables[di][:]
uD = u1D[di]
vD = v1D[di]
elif( di in v2D.keys() ):
dc = ds2.variables[di][:]
uD = u2D[di]
vD = v2D[di]
else:
sys.exit('Error: {} not found variable lists. Exiting ...'.format(di))
dc_dims = np.shape( dc )
dv = createNetcdfVariable( dso, dc, di, None, uD, 'f4', vD, variable )
dc = None
time = None; x = None; y = None; z = None
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
for vi in vn1:
vt , _ = read3DVariableFromDataset( vi, ds1, 0, 0, 0, 1 ) # All values.
if( s1 != 1.0 ): vt *= s1
vt = unaryOpr( vt, uop1 )
dD1[vi] = vt
for vi in vn2:
vt , _ = read3DVariableFromDataset( vi, ds2, 0, 0, 0, 1 ) # All values.
if( s2 != 1.0 ): vt *= s2
vt = unaryOpr( vt, uop2 )
dD2[vi] = vt
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
for i in range( N1 ):
if( N2 != 1 ):
j = i
vo = binaryOpr( dD1.pop(vn1[i]), dD2.pop(vn2[j]) , biop )
else:
j = 0
vo = binaryOpr( dD1.pop(vn1[i]), dD2[vn2[0]] , biop )
unit12 = binaryOprUnit( u1D[vn1[i]] , u2D[vn2[0]] , biop )
vv = createNetcdfVariable( dso, vo, vno[i], None, unit12, 'f4',(tn,zn,yn,xn,) , variable )
vo = None
netcdfWriteAndClose(dso)
|
cd13df4c13729a1e306700d226a4fd8084a647ee
|
{
"blob_id": "cd13df4c13729a1e306700d226a4fd8084a647ee",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-17T10:28:49",
"content_id": "a5eca6fcce71f90f1f76ca701f36a168109afd8b",
"detected_licenses": [
"MIT"
],
"directory_id": "f7b24ad49181041e4b3dc914dbb975bb4ee8c818",
"extension": "py",
"filename": "binaryOperateNetCdf.py",
"fork_events_count": 7,
"gha_created_at": "2017-01-27T12:44:17",
"gha_event_created_at": "2023-08-21T12:48:57",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 80206554,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7087,
"license": "MIT",
"license_type": "permissive",
"path": "/pyNetCDF/binaryOperateNetCdf.py",
"provenance": "stack-edu-0056.json.gz:614319",
"repo_name": "mjsauvinen/P4UL",
"revision_date": "2023-08-17T10:20:19",
"revision_id": "bc5c2080bca01f682e8c3e110e651f7136b9f572",
"snapshot_id": "649b6446c36decc64c560458d8db682938ebe956",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/mjsauvinen/P4UL/bc5c2080bca01f682e8c3e110e651f7136b9f572/pyNetCDF/binaryOperateNetCdf.py",
"visit_date": "2023-09-01T18:32:47.116945",
"added": "2024-11-18T21:33:33.560083+00:00",
"created": "2023-08-17T10:20:19",
"int_score": 3,
"score": 2.859375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ScreenDevService {
private api = "http://localhost:3000";
constructor(private http: HttpClient) {
}
getScreenDef() {
return this.http.post(this.api + 'visible/screen/qryScreenInfo', {})
.map((val: any) => JSON.parse(val.data.content));
}
updateScreenDef(newDef) {
return this.http.post(this.api + 'visible/screen/updateScreenInfo', {content: newDef});
}
// 获取自定义的图表类型
getSelfDefCharts() {
return this.http.get('assets/json/alters.json')
.map(val => val['retList']);
}
// 根据id获取图表详细信息
getOptionAndDataById(id) {
return this.http.get('assets/json/chartModel.json'/* + id */)
.map(data => data[0]);
}
}
|
e69bdd341eafe4ea294d5157ce6622b5b3d1a5ba
|
{
"blob_id": "e69bdd341eafe4ea294d5157ce6622b5b3d1a5ba",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-13T07:14:12",
"content_id": "68ac98ad7cd215f109544df463b7a99654d8b2d2",
"detected_licenses": [
"MIT"
],
"directory_id": "b2c463c6acd5cda8ae287641a0d29da3c3990dc7",
"extension": "ts",
"filename": "screen-dev.service.ts",
"fork_events_count": 3,
"gha_created_at": "2018-01-18T01:29:30",
"gha_event_created_at": "2018-10-31T09:54:55",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 117914794,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 919,
"license": "MIT",
"license_type": "permissive",
"path": "/src/app/routes/developer/screen-dev.service.ts",
"provenance": "stack-edu-0075.json.gz:892475",
"repo_name": "sincisco/delon",
"revision_date": "2019-02-13T07:14:12",
"revision_id": "6a96564cc88b32792ebb0c1980a5a7a16cebbc2f",
"snapshot_id": "4c40ff3d638f1fb102fa6ccab5bd9ad149d0378b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/sincisco/delon/6a96564cc88b32792ebb0c1980a5a7a16cebbc2f/src/app/routes/developer/screen-dev.service.ts",
"visit_date": "2021-05-16T14:00:24.585144",
"added": "2024-11-19T02:20:12.418712+00:00",
"created": "2019-02-13T07:14:12",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
import React from 'react'
import {Timeline} from 'antd';
import DocContent from '../../site/template/doc_content'
import desc from './desc'
class Changelog extends React.Component {
constructor() {
super();
this.state = {
title: '',
contentArray: []
}
this.itemMap = new Map()
this.timeArray = []
}
componentDidMount() {
for (let i = 0; i < desc.change_log.length; i++) {
const item = desc.change_log[i]
this.itemMap.set(item.version, {
"time": item.time,
"version": item.version,
"content": item.content
});
this.timeArray.push({
key: item.version,
value: `${item.version} ${item.time}`
})
}
this.setState({
title: this.timeArray[0].key,
contentArray: this.itemMap.get(this.timeArray[0].key).content
})
}
clickVersion = (e) => {
const item = this.itemMap.get(e.target.parentNode.getAttribute("data-value"));
if (item) {
this.setState({
title: item.version,
contentArray: item.content
})
}
}
render() {
const {title, contentArray} = this.state;
return (
<DocContent>
<div className="gis-change-log">
<div className="gis-change-time">
<Timeline>
{this.timeArray.map(value => {
return <Timeline.Item onClick={this.clickVersion} data-value={value.key}
key={value.key}>{value.value}</Timeline.Item>
})}
</Timeline>
</div>
<div className="gis-change-content">
<h1>{title}</h1>
<ol>
{contentArray.map((value, index) => {
// eslint-disable-next-line react/no-array-index-key
return <li key={index}>{value}</li>
})}
</ol>
</div>
</div>
</DocContent>
)
}
}
export default Changelog
|
7208f377fde349f770a6098793fa743969a6f44d
|
{
"blob_id": "7208f377fde349f770a6098793fa743969a6f44d",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-14T09:09:15",
"content_id": "a1db19a19c20f8df6c3f666744e6aca0b16e1cb3",
"detected_licenses": [
"MIT"
],
"directory_id": "0522b7b0a6da89243d330ea9412af10c126be4d8",
"extension": "jsx",
"filename": "index.jsx",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1954,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components_gis/change_log/index.jsx",
"provenance": "stack-edu-0043.json.gz:18453",
"repo_name": "YangJianFei/htht-design",
"revision_date": "2020-02-14T09:09:15",
"revision_id": "5dedc1243f8f3c968af95cc69ba7a760f2f42330",
"snapshot_id": "346cf6ae6edafdc0e58e0ac17221f89ffcb7fb69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/YangJianFei/htht-design/5dedc1243f8f3c968af95cc69ba7a760f2f42330/src/components_gis/change_log/index.jsx",
"visit_date": "2022-04-07T00:24:58.638614",
"added": "2024-11-18T23:46:18.392242+00:00",
"created": "2020-02-14T09:09:15",
"int_score": 3,
"score": 2.515625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
use App\Model\Companysetting;
use App\Model\Themesetting;
use App\Model\StsTimesheet;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use \Illuminate\Filesystem\FilesystemManager;
use Illuminate\Contracts\Filesystem\Factory as Filesystem;
use Carbon\Carbon;
use Illuminate\Http\File;
use App\Helpers\CommonHelper;
use App\User;
use PDF;
class ReportController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
function __construct()
{
$this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','store']]);
$this->middleware('permission:role-create', ['only' => ['create','store']]);
$this->middleware('permission:role-edit', ['only' => ['edit','update']]);
$this->middleware('permission:role-delete', ['only' => ['destroy']]);
$this->Companysetting = new Companysetting;
$this->Themesetting = new Themesetting;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
/* company setting */
public function index(Request $request)
{
//dd($request->input());
// $select = array();
$where = array();
$or_where = array();
$join =array();
$or_where_in = '';
$data = $request->all();
if(!empty($data)){
if ((isset($data['name_moor']) && !empty($data['name_moor'])) || ((isset($data['fromdate']) && !empty($data['fromdate'])) && (isset($data['todate']) && !empty($data['todate'])))) {
$user_name = $data['name_moor'];
$fromdate = $data['fromdate'];
$todate = $data['todate'];
//dd($fromdate);
if(!empty($user_name)){
$usid = User::where('name','LIKE',"%{$user_name}%")->get();
if(!empty($usid)){
$uname=array();
foreach($usid as $usingle){
$uname[] = $usingle->id;
}
$or_where_in = array("user_id", $uname);
}
}
if((!empty($fromdate)) && (!empty($todate))){
$fdate = CommonHelper::convert_databaseformat($fromdate);
$tdate = CommonHelper::convert_databaseformat($todate);
$todt = date('Y-m-d', strtotime($tdate . ' +1 day'));
$or_where1 = array("sts.created_at", ">=", "{$fdate}");
$or_where2 = array("sts.created_at", "<", "{$todt}' +1 day");
$where = array($or_where1, $or_where2);
}
}
}
//$or_where1 = array("sts.created_at", ">=", "{$fdate}");
// $where = array($or_where1, $or_where2);
$join["sts_ts_additional as sts_add"] =array("sts.t_id","sts_add.ts_id");
$join["sts_mr_addition as sts_mradd"] =array("sts.t_id","sts_mradd.ts_id");
$join["sts_ts_oper_timings as sts_oprtiming"] =array("sts.t_id","sts_oprtiming.ts_id");
$join["sts_unmr_addition as sts_unmraddition"] =array("sts.t_id","sts_unmraddition.ts_id");
// $join["ts_mooring_tugs as ts_m_tugs"] =array("sts.t_id","ts_m_tugs.ts_id");
// $join["ts_unmooring_tugs as ts_um_tugs"] =array("sts.t_id","ts_um_tugs.ts_id");
$select = array('sts.*');
//$selectall = $select1.",".$select2.",".$select3.",".$select4.",".$select5.",".$select6;
//$select1 = array();
$summarylist = new StsTimesheet();
$overallsummarylist = $summarylist->getTimesheet_data($select="", $where, $or_where,$or_where_in, $join);
// $overallsummarylist;
//$overallsummaryhead = ;
//dd($overallsummarylist);
return view('reports.summaryreport', compact('overallsummarylist'));
}
public function sts_approvedstatusUpdate($id)
{
/* $sts_data = StsTimesheet::where('t_id','=',$id)->first();
$moor_master_id = User::where('id','=',$sts_data->user_id)->pluck('id');
$ts_id = $sts_data->t_id;
$client_id = $sts_data->client_id;
$datatime = date("Y-m-d h:m:i"); */
$updateData = StsTimesheet::where('t_id', $id)->update([
'status' => 1
]);
if($updateData == true)
{
return redirect('/reports')->with('type', 'Success!')->with('message', 'STS timesheet approved successfully!')->with('alertClass', 'alert alert-success');
}
}
public function sts_rejectedstatusUpdate($id)
{
$updateData = StsTimesheet::where('t_id', $id)->update([
'status' => 2
]);
if($updateData == true)
{
return redirect('/reports')->with('type', 'Danger!')->with('message', 'STS timesheet details rejected!')->with('alertClass', 'alert alert-danger');
}
}
public function pilotage_summary()
{
return view('reports.pilotage_summaryreport');
}
public function store_refno(Request $request)
{
$id = $request->input('timesheet_id');
if($request->input('submit_ref_number'))
{
$updateData = StsTimesheet::where('t_id', $id)->update([
'work_ref_no' => $request->input('reference_no'),
'status' => 3
]);
if($updateData == true)
{
return redirect('/reports')->with('type', 'Success!')->with('message', 'STS timesheet reference number created!')->with('alertClass', 'alert alert-success');
}
}
//echo $request->input('reference_no');
}
public function findReferenceNumberExists(Request $request)
{
$reference_no = $request->input('reference_no');
$timesheet_id = $request->input('timesheet_id');
if(!empty($timesheet_id))
{
$data_exists = StsTimesheet::where([
['job_ref_id','=',$reference_no],
['t_id','!=',$timesheet_id]
])->count();
}
else
{
$data_exists = StsTimesheet::where([
['job_ref_id','=',$reference_no]
])->count();
}
if($data_exists > 0)
{
return "false";
}
else{
return "true";
}
}
/* end theme */
public function show(){
}
public function store(){
}
public function destroy(){
}
}
|
157c5f876fc361ac938ced41dbdf808cd1963ed9
|
{
"blob_id": "157c5f876fc361ac938ced41dbdf808cd1963ed9",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-07T07:34:52",
"content_id": "bbae63c32e3e2683b4b2bca48cf986b9dfb56fa7",
"detected_licenses": [
"MIT"
],
"directory_id": "7c8cea4e1af5065daadcc296b7b4e2831ed2ca12",
"extension": "php",
"filename": "ReportController.php",
"fork_events_count": 0,
"gha_created_at": "2019-08-06T05:35:54",
"gha_event_created_at": "2023-02-02T07:23:00",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 200783274,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 6575,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/ReportController.php",
"provenance": "stack-edu-0051.json.gz:502138",
"repo_name": "denariusoft-com/CME",
"revision_date": "2019-09-07T07:34:52",
"revision_id": "b520537e4c4e564139803a715b12fe908a2bff27",
"snapshot_id": "38cfd675330e46c55eb2ae5895daddbc93915978",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/denariusoft-com/CME/b520537e4c4e564139803a715b12fe908a2bff27/app/Http/Controllers/ReportController.php",
"visit_date": "2023-02-09T05:40:10.916088",
"added": "2024-11-19T03:21:41.954164+00:00",
"created": "2019-09-07T07:34:52",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
using UnityEngine;
using System.Collections;
//assumes its all local
public class primitiveLine : MonoBehaviour {
public Transform p1, p2;
Vector3 lastPos1, lastPos2;
void Awake() {
lastPos1 = Vector3.zero;
lastPos2 = Vector3.zero;
}
void Update() {
if (lastPos1 != p1.localPosition || lastPos2 != p2.localPosition) {
lastPos1 = p1.localPosition;
lastPos2 = p2.localPosition;
UpdateLine();
}
}
void UpdateLine() {
transform.position = Vector3.Lerp(p1.position, p2.position, .5f);
float dist = Vector3.Distance(p1.localPosition, p2.localPosition);
transform.localScale = new Vector3(.0025f, dist, 1);
float rot = Mathf.Atan2(p1.transform.localPosition.x - p2.transform.localPosition.x, p2.transform.localPosition.y - p1.transform.localPosition.y) * Mathf.Rad2Deg;
transform.localRotation = Quaternion.Euler(0, 0, rot);
}
}
|
1e9d6a4c0c0384434250d2cf5c9c355e9c2e39a0
|
{
"blob_id": "1e9d6a4c0c0384434250d2cf5c9c355e9c2e39a0",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-22T00:56:53",
"content_id": "d9404ba85822936e10f9d134c05de04d5ab07ac6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3fa004a09974f78b965e55268be3c5c6b7f6653d",
"extension": "cs",
"filename": "primitiveLine.cs",
"fork_events_count": 12,
"gha_created_at": "2019-11-10T17:04:03",
"gha_event_created_at": "2020-05-30T18:52:47",
"gha_language": "C#",
"gha_license_id": "Apache-2.0",
"github_id": 220821487,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1486,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Assets/Scripts/Unorganized/primitiveLine.cs",
"provenance": "stack-edu-0015.json.gz:244200",
"repo_name": "plaidpants/soundstagevr",
"revision_date": "2022-04-22T00:56:53",
"revision_id": "0253ffa0e377fe97b017a1ab6b2609173185f947",
"snapshot_id": "10ba05f6743070b45de66b59039c7285951b2833",
"src_encoding": "UTF-8",
"star_events_count": 44,
"url": "https://raw.githubusercontent.com/plaidpants/soundstagevr/0253ffa0e377fe97b017a1ab6b2609173185f947/Assets/Scripts/Unorganized/primitiveLine.cs",
"visit_date": "2022-04-30T20:06:25.408524",
"added": "2024-11-19T00:51:12.874185+00:00",
"created": "2022-04-22T00:56:53",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
// --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------
namespace Microsoft.Research.Malmo.HumanAction
{
using System;
using SlimDX;
using SlimDX.XInput;
/// <summary>
/// Wrapper around SlimDX Gamepad state and XInput.
/// </summary>
public class GamepadState
{
/// <summary>
/// The user index of this gamepad
/// </summary>
public readonly UserIndex UserIndex;
/// <summary>
/// The underlying XInput controller object for this gamepad
/// </summary>
public readonly Controller Controller;
/// <summary>
/// The number of the most recent packet.
/// </summary>
private uint lastPacket;
/// <summary>
/// Initializes a new instance of the <see cref="GamepadState"/> class.
/// </summary>
/// <param name="userIndex">The index of the user whose gamepad this object should model</param>
public GamepadState(UserIndex userIndex)
{
this.UserIndex = userIndex;
this.Controller = new Controller(userIndex);
}
/// <summary>
/// Gets the state of the DPad.
/// </summary>
public DPadState DPad { get; private set; }
/// <summary>
/// Gets the state of the left stick.
/// </summary>
public ThumbstickState LeftStick { get; private set; }
/// <summary>
/// Gets the state of the right stick.
/// </summary>
public ThumbstickState RightStick { get; private set; }
/// <summary>
/// Gets a value indicating whether the A button is pressed.
/// </summary>
public bool A { get; private set; }
/// <summary>
/// Gets a value indicating whether the B button is pressed.
/// </summary>
public bool B { get; private set; }
/// <summary>
/// Gets a value indicating whether the X button is pressed.
/// </summary>
public bool X { get; private set; }
/// <summary>
/// Gets a value indicating whether the Y button is pressed.
/// </summary>
public bool Y { get; private set; }
/// <summary>
/// Gets a value indicating whether the right shoulder button is pressed.
/// </summary>
public bool RightShoulder { get; private set; }
/// <summary>
/// Gets a value indicating whether the left shoulder button is pressed.
/// </summary>
public bool LeftShoulder { get; private set; }
/// <summary>
/// Gets a value indicating whether the start button is pressed.
/// </summary>
public bool Start { get; private set; }
/// <summary>
/// Gets a value indicating whether the back button is pressed.
/// </summary>
public bool Back { get; private set; }
/// <summary>
/// Gets a value indicating whether the right trigger is pulled.
/// </summary>
public bool RightTrigger { get; private set; }
/// <summary>
/// Gets a value indicating whether the left trigger is pulled.
/// </summary>
public bool LeftTrigger { get; private set; }
/// <summary>
/// Gets a value indicating whether the desired gamepad is connected.
/// </summary>
public bool IsConnected
{
// If get a crash here then maybe need to install the SlimDX Developer SDK:
// http://slimdx.org/download.php
get { return this.Controller.IsConnected; }
}
/// <summary>
/// Vibrates the gamepad.
/// </summary>
/// <param name="leftMotor">The amount to vibrate the left motor</param>
/// <param name="rightMotor">The amount to vibrate the right motor</param>
public void Vibrate(float leftMotor, float rightMotor)
{
this.Controller.SetVibration(new Vibration
{
LeftMotorSpeed = (ushort)(this.Saturate(leftMotor) * ushort.MaxValue),
RightMotorSpeed = (ushort)(this.Saturate(rightMotor) * ushort.MaxValue)
});
}
/// <summary>
/// Updates the state of the gamepad.
/// </summary>
public void Update()
{
// If not connected, nothing to update
if (!this.IsConnected)
{
return;
}
State state = this.Controller.GetState();
if (this.lastPacket == state.PacketNumber)
{
return;
}
this.lastPacket = state.PacketNumber;
var gamepadState = state.Gamepad;
// Shoulders
this.LeftShoulder = (gamepadState.Buttons & GamepadButtonFlags.LeftShoulder) != 0;
this.RightShoulder = (gamepadState.Buttons & GamepadButtonFlags.RightShoulder) != 0;
// Triggers
this.LeftTrigger = gamepadState.LeftTrigger > Gamepad.GamepadTriggerThreshold;
this.RightTrigger = gamepadState.RightTrigger > Gamepad.GamepadTriggerThreshold;
// Buttons
this.Start = (gamepadState.Buttons & GamepadButtonFlags.Start) != 0;
this.Back = (gamepadState.Buttons & GamepadButtonFlags.Back) != 0;
this.A = (gamepadState.Buttons & GamepadButtonFlags.A) != 0;
this.B = (gamepadState.Buttons & GamepadButtonFlags.B) != 0;
this.X = (gamepadState.Buttons & GamepadButtonFlags.X) != 0;
this.Y = (gamepadState.Buttons & GamepadButtonFlags.Y) != 0;
// D-Pad
this.DPad = new DPadState(
(gamepadState.Buttons & GamepadButtonFlags.DPadUp) != 0,
(gamepadState.Buttons & GamepadButtonFlags.DPadDown) != 0,
(gamepadState.Buttons & GamepadButtonFlags.DPadLeft) != 0,
(gamepadState.Buttons & GamepadButtonFlags.DPadRight) != 0);
// Thumbsticks
this.LeftStick = new ThumbstickState(
this.Normalize(gamepadState.LeftThumbX, gamepadState.LeftThumbY, Gamepad.GamepadLeftThumbDeadZone),
(gamepadState.Buttons & GamepadButtonFlags.LeftThumb) != 0);
this.RightStick = new ThumbstickState(
this.Normalize(gamepadState.RightThumbX, gamepadState.RightThumbY, Gamepad.GamepadRightThumbDeadZone),
(gamepadState.Buttons & GamepadButtonFlags.RightThumb) != 0);
}
/// <summary>
/// Normalizes the input, providing dead zone handling.
/// </summary>
/// <param name="rawX">The raw X value</param>
/// <param name="rawY">The raw Y value</param>
/// <param name="threshold">The dead zone threshold</param>
/// <returns>The normalized vector</returns>
private Vector2 Normalize(short rawX, short rawY, short threshold)
{
var value = new Vector2(rawX, rawY);
var magnitude = value.Length();
var direction = value / (magnitude == 0 ? 1 : magnitude);
var normalizedMagnitude = 0.0f;
if (magnitude - threshold > 0)
{
normalizedMagnitude = Math.Min((magnitude - threshold) / (short.MaxValue - threshold), 1);
}
return direction * normalizedMagnitude;
}
/// <summary>
/// Bounds the value to be within 0 and 1.
/// </summary>
/// <param name="value">The value</param>
/// <returns>A value between 0 and 1</returns>
private float Saturate(float value)
{
return value < 0 ? 0 : value > 1 ? 1 : value;
}
/// <summary>
/// Value type representing the state of the Directional Pad.
/// </summary>
public struct DPadState
{
/// <summary>
/// Value indicating whether the Up direction is pressed.
/// </summary>
public readonly bool Up;
/// <summary>
/// Value indicating whether the Down direction is pressed.
/// </summary>
public readonly bool Down;
/// <summary>
/// Value indicating whether the Left direction is pressed.
/// </summary>
public readonly bool Left;
/// <summary>
/// Value indicating whether the Right direction is pressed.
/// </summary>
public readonly bool Right;
/// <summary>
/// Initializes a new instance of the <see cref="DPadState"/> struct.
/// </summary>
/// <param name="up">Whether the up button is pressed</param>
/// <param name="down">Whether the down button is pressed</param>
/// <param name="left">Whether the left button is pressed</param>
/// <param name="right">Whether the right button is pressed</param>
public DPadState(bool up, bool down, bool left, bool right)
{
this.Up = up;
this.Down = down;
this.Left = left;
this.Right = right;
}
}
/// <summary>
/// Value type representing the state of a thumbstick.
/// </summary>
public struct ThumbstickState
{
/// <summary>
/// The position of the thumbstick.
/// </summary>
public readonly Vector2 Position;
/// <summary>
/// Value indicating whether the thumbstick has been clicked.
/// </summary>
public readonly bool Clicked;
/// <summary>
/// Initializes a new instance of the <see cref="ThumbstickState"/> struct.
/// </summary>
/// <param name="position">The position of the thumbstick</param>
/// <param name="clicked">Whether the thumbstick has been clicked</param>
public ThumbstickState(Vector2 position, bool clicked)
{
this.Clicked = clicked;
this.Position = position;
}
}
}
}
|
9b1be45f9524f9a1a7208b8dc5f7cb33622e377a
|
{
"blob_id": "9b1be45f9524f9a1a7208b8dc5f7cb33622e377a",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-28T14:54:15",
"content_id": "5c3c478e59ff1d7bb2fbe3d267dd167ede8939db",
"detected_licenses": [
"MIT"
],
"directory_id": "2535e26700d4a631fcf38aab34ec0dd3069aa76c",
"extension": "cs",
"filename": "GamepadState.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 11553,
"license": "MIT",
"license_type": "permissive",
"path": "/Malmo/humanAction/GamepadState.cs",
"provenance": "stack-edu-0012.json.gz:599644",
"repo_name": "Tibdem/malmo",
"revision_date": "2021-05-28T14:54:15",
"revision_id": "0b54e8c5aa89795207592f6e0de22224b3ead09e",
"snapshot_id": "5d4a7dd1bc67e564aa01f218080f3a306078c661",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tibdem/malmo/0b54e8c5aa89795207592f6e0de22224b3ead09e/Malmo/humanAction/GamepadState.cs",
"visit_date": "2021-06-09T11:52:06.357910",
"added": "2024-11-19T00:27:42.023195+00:00",
"created": "2021-05-28T14:54:15",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
// -*- mode: go; coding: utf-8 -*-
// vi: set syntax=go :
// cSpell.language:en-GB
// cSpell:disable
package what3words
// Coordinates struct with latitude and longitude.
// Tags are used to map from the JSON response.
type Coordinates struct {
Latitude float64 `json:"lat"`
Longitude float64 `json:"lng"`
}
// CoordinatesInterface interface definition
type CoordinatesInterface interface {
SetLat(lat float64) error
SetLon(lon float64) error
String() string
}
// Verify this object implement the necessary interfaces
var _ CoordinatesInterface = &Coordinates{}
|
198a5e5609417fafc7cfd99641d44cfbc9fb7d7c
|
{
"blob_id": "198a5e5609417fafc7cfd99641d44cfbc9fb7d7c",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-12T21:01:39",
"content_id": "6d03d83fc3eb0feeb352d1fa97a930119f8b22fc",
"detected_licenses": [
"MIT"
],
"directory_id": "6363bbf6e4fcedb7fffcb75c613c3d711d8efe73",
"extension": "go",
"filename": "coordinates_interface.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 204079757,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 572,
"license": "MIT",
"license_type": "permissive",
"path": "/coordinates_interface.go",
"provenance": "stack-edu-0016.json.gz:381072",
"repo_name": "jcmurray/what3words",
"revision_date": "2023-02-12T21:01:39",
"revision_id": "b1c8b59ddf3205d85a9c536d062eda5a369aed74",
"snapshot_id": "6e40d9526b6b560cccdd6dec02d52f372ab1222f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jcmurray/what3words/b1c8b59ddf3205d85a9c536d062eda5a369aed74/coordinates_interface.go",
"visit_date": "2023-02-16T18:49:22.247611",
"added": "2024-11-19T02:09:53.661115+00:00",
"created": "2023-02-12T21:01:39",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
/**
* Copyright (C) 2018 Jeebiz (http://jeebiz.net).
* All Rights Reserved.
*/
package net.jeebiz.admin.extras.monitor.web.mvc;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.jeebiz.admin.extras.monitor.service.IOnlineSessionService;
import net.jeebiz.admin.extras.monitor.setup.Constants;
import net.jeebiz.admin.extras.monitor.web.dto.OnlineSessionDTO;
import net.jeebiz.boot.api.annotation.BusinessLog;
import net.jeebiz.boot.api.annotation.BusinessType;
import net.jeebiz.boot.api.web.BaseApiController;
import net.jeebiz.boot.api.web.Result;
/**
* http://jinnianshilongnian.iteye.com/blog/2047643
*/
@Api(tags = "会话管理:在线会话管理")
@Validated
@RestController
@RequestMapping("/sessions/")
@RequiresPermissions("session:*")
public class SessionStatusController extends BaseApiController {
@Autowired
private IOnlineSessionService onlineSessionService;
@ApiOperation(value = "会话列表", notes = "分页查询已维护的应用基本信息、订阅服务量")
@BusinessLog(module = Constants.EXTRAS_SESSIONS, business = "分页查询数据源信息", opt = BusinessType.SELECT)
@PostMapping("list")
@ResponseBody
public Object list() throws Exception {
List<OnlineSessionDTO> sessions = getOnlineSessionService().getActiveSessions();
return new Result<OnlineSessionDTO>(sessions);
}
@ApiOperation(value = "创建我的应用", notes = "增加我的应用信息: 应用名称、开发语言、部署地址等")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "body", name = "appDTO", value = "应用信息传输对象", dataType = "MyApplicationDTO")
})
@BusinessLog(module = Constants.EXTRAS_SESSIONS, business = "创建新数据源", opt = BusinessType.INSERT)
@PatchMapping("/{sessionId}/kickout")
public String kickout(@PathVariable("sessionId") String sessionId,
RedirectAttributes redirectAttributes) {
getOnlineSessionService().kickout(sessionId);
redirectAttributes.addFlashAttribute("msg", "强制退出成功!");
return "redirect:/sessions";
}
public IOnlineSessionService getOnlineSessionService() {
return onlineSessionService;
}
public void setOnlineSessionService(IOnlineSessionService onlineSessionService) {
this.onlineSessionService = onlineSessionService;
}
}
|
5d155c573ed6e37695474863f8de5cd7bcd6d699
|
{
"blob_id": "5d155c573ed6e37695474863f8de5cd7bcd6d699",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-06T17:45:12",
"content_id": "d967c22e3a550423d2b7c58ef49f06a35391fe1a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8ca6c6d9d304a176bde7a10ef77c5301d4991708",
"extension": "java",
"filename": "SessionStatusController.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3101,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/jeebiz-admin-extras/jeebiz-admin-extras-sessions/src/main/java/net/jeebiz/admin/extras/monitor/web/mvc/SessionStatusController.java",
"provenance": "stack-edu-0022.json.gz:842234",
"repo_name": "gong1989313/jeebiz-admin",
"revision_date": "2021-07-06T17:45:12",
"revision_id": "518fbeb6ee0e927d8f6cc2f9de5f80c1ed4b92e3",
"snapshot_id": "ac1dd3c192cad6ebc17d47d6c0a6a2a3bdedfd8e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gong1989313/jeebiz-admin/518fbeb6ee0e927d8f6cc2f9de5f80c1ed4b92e3/jeebiz-admin-extras/jeebiz-admin-extras-sessions/src/main/java/net/jeebiz/admin/extras/monitor/web/mvc/SessionStatusController.java",
"visit_date": "2023-06-12T00:58:09.310868",
"added": "2024-11-19T00:13:19.602888+00:00",
"created": "2021-07-06T17:45:12",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
<?php
/*
* This file is part of the Tiny package.
*
* (c) Alex Ermashev <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tiny\Http;
class Request
{
const METHOD_CONSOLE = 'CONSOLE';
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
/**
* @var array
*/
public $allowedMethods
= [
self::METHOD_CONSOLE,
self::METHOD_POST,
self::METHOD_GET,
self::METHOD_PUT,
self::METHOD_DELETE,
];
/**
* @var RequestSystemParamsInterface
*/
private $requestSystemParams;
/**
* @var array
*/
private $params = [];
/**
* Request constructor.
*
* @param RequestSystemParamsInterface $requestSystemParams
*/
public function __construct(
RequestSystemParamsInterface $requestSystemParams
) {
$this->requestSystemParams = $requestSystemParams;
}
/**
* @return string
*/
public function getMethod(): string
{
return $this->requestSystemParams->getMethod();
}
/**
* @return string
*/
public function getRequest(): string
{
return $this->requestSystemParams->getRequest();
}
/**
* @param array $params
*
* @return $this
*/
public function setParams(array $params): self
{
$this->params = $params;
return $this;
}
/**
* @return array
*/
public function getParams(): array
{
return $this->params;
}
/**
* @param string $name
* @param mixed $defaultValue
*
* @return mixed
*/
public function getParam(string $name, $defaultValue = null)
{
if (isset($this->params[$name])) {
return $this->params[$name];
}
if (null !== $defaultValue) {
return $defaultValue;
}
throw new Exception\InvalidArgumentException(
sprintf(
'Request param "%s" not found',
$name
)
);
}
}
|
a975091138eb6efa8a7d18ddc46e901f808883f2
|
{
"blob_id": "a975091138eb6efa8a7d18ddc46e901f808883f2",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-06T07:34:10",
"content_id": "b0339998a7182062f7fb46f9d2bd77a622fd34eb",
"detected_licenses": [
"MIT"
],
"directory_id": "b016d096416b3e175788c3fbb7c123bcafe98797",
"extension": "php",
"filename": "Request.php",
"fork_events_count": 0,
"gha_created_at": "2020-08-06T09:40:48",
"gha_event_created_at": "2020-08-06T09:40:49",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 285532012,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2271,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Request.php",
"provenance": "stack-edu-0052.json.gz:702405",
"repo_name": "aa675465418/tiny-http",
"revision_date": "2020-08-06T07:34:10",
"revision_id": "dd36d66d414664f2ee4c73414e1599e654b84166",
"snapshot_id": "3d5b842f3d8559065ed694dbc8abf7968b31bc88",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aa675465418/tiny-http/dd36d66d414664f2ee4c73414e1599e654b84166/src/Request.php",
"visit_date": "2022-11-29T00:23:00.279242",
"added": "2024-11-18T20:52:32.192630+00:00",
"created": "2020-08-06T07:34:10",
"int_score": 3,
"score": 2.96875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
//jshint esversion:6
const mariadb = require('mariadb');
const dotenv = require('dotenv').config();
const sql = require('./sql');
// creating mariadb connection pool
const pool = mariadb.createPool({
host: "127.0.0.1",
user: process.env.MARIADB_USER,
password: process.env.MARIADB_PASSWORD,
database: process.env.MARIADB_DATABASE,
multipleStatements: true
})
const handler = {
"runQueries": async function(code) {
// takes in SQL queries and runs them on the database in the connection pool above
const conn = await pool.getConnection();
const results = await Promise.all(code.map((item) => {
return conn.query(item);
}));
conn.release();
return results;
},
"queryBuilder": async function(data, type, id) {
// Builds a type of query based on the desired type. Used for building inserts, deletes, and updates
let query = "";
data[type].forEach(item => {
const s1 = item["id"] != 0 ? 1 : 0;
const s2 = item[type] != '' ? 1 : 0;
switch (s1 + "|" + s2) {
case "1|1":
// update
if (type !== "sprint"){
query = query.concat(sql.updateProjDetails(id, item["id"], type, item[type], ''));
} else {
const check = item["checked"] ? 1 : 0;
const where = ', sprint_num = ' + item["sprint_num"] + ', is_checked = ' + check;
query = query.concat(sql.updateProjDetails(id, item["id"], type, item[type], where));
}
break;
case "1|0":
// delete
query = query.concat(sql.deleteProjDetails(item["id"], type));
break;
case "0|1":
// insert
if (type !== "sprint"){
query = query.concat(sql.insertProjDetails(id, type, item[type], ''));
} else {
const check = item["checked"] ? 1 : 0;
const where = ', sprint_num = ' + item["sprint_num"] + ', is_checked = ' + check;
query = query.concat(sql.insertProjDetails(id, type, item[type], where));
}
break;
}
});
if (query != "") {
return await this.runQueries([query]);
}
},
"getDateTime": () => {
let today = new Date();
let date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
let dateTime = date + ' ' + time;
return dateTime;
},
"deetFunction": (deet, type, ifCall) => {
// Takes the details of a project and maps it to convert it into an object that can be split into features, languages, and sprints. Used primarily to pull data out for projects
const x = [];
Object.keys(deet).forEach((item) => {
if (item !== "meta"){
if (deet[item][type] != null) {
let objCreator = {};
objCreator.id = deet[item].id;
objCreator[type] = deet[item][type];
if (ifCall) {
objCreator.sprint_num = deet[item].sprint_num;
objCreator.is_checked = deet[item].is_checked;
}
if (objCreator !== {}) {
x.push(objCreator);
}
}
}
}
);
return x;
// return x.slice(0, -1);
}
};
module.exports = handler ;
|
193997834ac346907588dee678a72e03c77dcc52
|
{
"blob_id": "193997834ac346907588dee678a72e03c77dcc52",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-18T17:18:07",
"content_id": "46e01254f627a488f88fbeeeadf8efbfa246d61e",
"detected_licenses": [
"MIT"
],
"directory_id": "e89563d219dd52194bd4c328b8e006c7d7a3a871",
"extension": "js",
"filename": "main.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 296966332,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3264,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/main.js",
"provenance": "stack-edu-0033.json.gz:81896",
"repo_name": "dkbearsong/Bug-Tracker",
"revision_date": "2020-10-18T17:18:07",
"revision_id": "eb8d5c516a45f712dd76a25b45d1d67a14c5761e",
"snapshot_id": "c528cf9af885d8ed6374dbe4a7221854f07d45fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dkbearsong/Bug-Tracker/eb8d5c516a45f712dd76a25b45d1d67a14c5761e/lib/main.js",
"visit_date": "2023-01-01T20:00:21.424145",
"added": "2024-11-19T02:30:48.387899+00:00",
"created": "2020-10-18T17:18:07",
"int_score": 3,
"score": 2.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
package org.marketcetera.photon.internal.strategy.ui;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.marketcetera.photon.PhotonPlugin;
import org.marketcetera.photon.internal.strategy.TradeSuggestion;
import org.marketcetera.photon.internal.strategy.TradeSuggestionManager;
import org.marketcetera.photon.strategy.StrategyUI;
import org.marketcetera.trade.OrderSingle;
import org.marketcetera.util.log.SLF4JLoggerProxy;
import org.marketcetera.util.misc.ClassVersion;
/* $License$ */
/**
* Opens the trade suggestion in the ticket view to be modified.
*
* @author <a href="mailto:[email protected]">Will Horn</a>
* @version $Id: OpenSuggestionHandler.java 16154 2012-07-14 16:34:05Z colin $
* @since 1.0.0
*/
@ClassVersion("$Id: OpenSuggestionHandler.java 16154 2012-07-14 16:34:05Z colin $")
public class OpenSuggestionHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IStructuredSelection selection = (IStructuredSelection) HandlerUtil
.getCurrentSelectionChecked(event);
TradeSuggestion suggestion = (TradeSuggestion) selection
.getFirstElement();
OrderSingle order = suggestion.getOrder();
try {
PhotonPlugin.getDefault().showOrderInTicket(order);
TradeSuggestionManager.getCurrent().removeSuggestion(suggestion);
} catch (WorkbenchException e) {
SLF4JLoggerProxy.error(this, e);
Shell shell = HandlerUtil.getActiveShellChecked(event);
ErrorDialog.openError(shell, null, null, new Status(IStatus.ERROR,
StrategyUI.PLUGIN_ID, e.getLocalizedMessage()));
}
return null;
}
}
|
34e4dd914a123d5e038478d9524bd82d81523b80
|
{
"blob_id": "34e4dd914a123d5e038478d9524bd82d81523b80",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-25T08:37:53",
"content_id": "99d649062ebacd5c7b1b7c70440f9c1d4e665a3a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "236b2da5d748ef26a90d66316b1ad80f3319d01e",
"extension": "java",
"filename": "OpenSuggestionHandler.java",
"fork_events_count": 2,
"gha_created_at": "2014-05-07T10:22:59",
"gha_event_created_at": "2023-07-25T08:37:54",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 19530179,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2211,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/photon/photon/plugins/org.marketcetera.photon.strategy/src/main/java/org/marketcetera/photon/internal/strategy/ui/OpenSuggestionHandler.java",
"provenance": "stack-edu-0021.json.gz:335642",
"repo_name": "nagyist/marketcetera",
"revision_date": "2023-07-25T08:37:53",
"revision_id": "4f3cc0d4755ee3730518709412e7d6ec6c1e89bd",
"snapshot_id": "a5bd70a0369ce06feab89cd8c62c63d9406b42fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nagyist/marketcetera/4f3cc0d4755ee3730518709412e7d6ec6c1e89bd/photon/photon/plugins/org.marketcetera.photon.strategy/src/main/java/org/marketcetera/photon/internal/strategy/ui/OpenSuggestionHandler.java",
"visit_date": "2023-08-03T10:57:43.504365",
"added": "2024-11-19T02:17:09.642717+00:00",
"created": "2023-07-25T08:37:53",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
class AddNewColumnInHomeContent3 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'show_key_feature')) {
$table->boolean('show_key_feature')->default(true);
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_title1')) {
$table->string('key_feature_title1')->default('50K+ Online Courses');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_subtitle1')) {
$table->string('key_feature_subtitle1')->default('Enjoy lifetime access to courses');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_logo1')) {
$table->string('key_feature_logo1')->default('public/frontend/infixlmstheme/img/svg/course_1.svg');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_link1')) {
$table->string('key_feature_link1')->nullable();
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_title2')) {
$table->string('key_feature_title2')->default('Teacher directory');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_subtitle2')) {
$table->string('key_feature_subtitle2')->default('Learn from industry experts');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_logo2')) {
$table->string('key_feature_logo2')->default('public/frontend/infixlmstheme/img/svg/course_2.svg');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_link2')) {
$table->string('key_feature_link2')->nullable();
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_title3')) {
$table->string('key_feature_title3')->default('Unlimited access');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_subtitle3')) {
$table->string('key_feature_subtitle3')->default('Learn on your schedule');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_logo3')) {
$table->string('key_feature_logo3')->default('public/frontend/infixlmstheme/img/svg/course_3.svg');
}
});
Schema::table('home_contents', function ($table) {
if (!Schema::hasColumn('home_contents', 'key_feature_link3')) {
$table->string('key_feature_link3')->nullable();
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
|
730733d318216f26815affc95037d9e85bc29855
|
{
"blob_id": "730733d318216f26815affc95037d9e85bc29855",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-07T03:25:37",
"content_id": "0230d59cdb04f5979c474fe0aef4c5f3b5cbeaba",
"detected_licenses": [
"MIT"
],
"directory_id": "1f680f14379be60db90f92f6c8bb8ebef45ed9b2",
"extension": "php",
"filename": "2021_03_16_161609_AddNewColumnInHomeContent3.php",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 365097743,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3660,
"license": "MIT",
"license_type": "permissive",
"path": "/Modules/FrontendManage/Database/Migrations/2021_03_16_161609_AddNewColumnInHomeContent3.php",
"provenance": "stack-edu-0050.json.gz:906203",
"repo_name": "redheet/coursesite",
"revision_date": "2021-05-07T03:25:37",
"revision_id": "d5a3a77dd9a1ae1568f6c704c2b3d3f362c35792",
"snapshot_id": "30f2f52eb5fbf9ab76b317371aa7392e399626a9",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/redheet/coursesite/d5a3a77dd9a1ae1568f6c704c2b3d3f362c35792/Modules/FrontendManage/Database/Migrations/2021_03_16_161609_AddNewColumnInHomeContent3.php",
"visit_date": "2023-04-19T07:19:27.458021",
"added": "2024-11-18T23:10:01.179909+00:00",
"created": "2021-05-07T03:25:37",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
# AIDA-server
Server to control all requests directed to my IoT devices in home
For my use case, I found using paho library for browser which uses websockets better
## Build Setup
```bash
# install dependencies
yarn install
# Transpile Typescript and run server at localhost:3000
yarn dev
# Transpile files
yarn build
```
|
a1fc0cbf742c678eaaeb2512b3e1a7f01eceffc5
|
{
"blob_id": "a1fc0cbf742c678eaaeb2512b3e1a7f01eceffc5",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-02T04:08:52",
"content_id": "2902f4936f06e1cfabb79d27096dd8ad599b911c",
"detected_licenses": [
"MIT"
],
"directory_id": "651b878224085050b7ea7565524d02f06fd79131",
"extension": "md",
"filename": "README.md",
"fork_events_count": 2,
"gha_created_at": "2018-01-26T14:16:48",
"gha_event_created_at": "2021-08-10T22:15:35",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 119059620,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 328,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0009.json.gz:36833",
"repo_name": "nickdex/AIDA-Server",
"revision_date": "2019-03-02T04:08:52",
"revision_id": "6558b68701c8596aded08057578a78af7a430b7e",
"snapshot_id": "4ff638429dd4aa1001e0bb2a705b385e3d07f8bd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nickdex/AIDA-Server/6558b68701c8596aded08057578a78af7a430b7e/README.md",
"visit_date": "2021-08-29T14:09:47.634270",
"added": "2024-11-18T23:33:10.084463+00:00",
"created": "2019-03-02T04:08:52",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz"
}
|
# Deep Learning with PyTorch [Video]
This is the code repository for [Deep Learning with PyTorch [Video]](https://www.packtpub.com/big-data-and-business-intelligence/deep-learning-pytorch-video?utm_source=github&utm_medium=repository&utm_campaign=9781788475266), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the video course from start to finish.
## About the Video Course
This video course will get you up-and-running with one of the most cutting-edge deep learning libraries: PyTorch. Written in Python, PyTorch is grabbing the attention of all data science professionals due to its ease of use over other libraries and its use of dynamic computation graphs.
In this course, you will learn how to accomplish useful tasks using Convolutional Neural Networks to process spatial data such as images and using Recurrent Neural Networks to process sequential data such as texts. You will explore how you can make use of unlabeled data using Auto Encoders. You will also be training a neural network to learn how to balance a pole all by itself, using Reinforcement Learning. Throughout this journey, you will implement various mechanisms of the PyTorch framework to do these tasks.
By the end of the video course, you will have developed a good understanding of, and feeling for, the algorithms and techniques used. You'll have a good knowledge of how PyTorch works and how you can use it in to solve your daily machine learning problems.
<H2>What You Will Learn</H2>
<DIV class=book-info-will-learn-text>
<UL>
<LI>Discover how to organize new features and bugs with Issue Board
<LI>Use groups to control access to each project
<LI>Time each phase in your development cycle with Cycle Analytics
<LI>Implement Continuous Integration, and Continuous Deployment
<LI>Use GitLab Pages to create a site and publicize your project </LI></UL></DIV>
## Instructions and Navigation
### Assumed Knowledge
To fully benefit from the coverage included in this course, you will need:<br/>
This course is for Python programmers who have some knowledge of machine learning and want to build Deep Learning systems with PyTorch. Python programming knowledge and minimal math skills (matrix/vector manipulation, simple probabilities) is assumed.
### Technical Requirements
### Minimum Hardware Requirements
<UL>
<LI>OS: GNU/Linux Distribution (ex: Ubuntu, Debian, Fedora, etc.), Mac OS, Microsoft Windows</LI>
<LI>Processor: Relatively modern CPU (Intel Core iX series 4th gen, AMD equivalent)</LI>
<LI>Memory: 4GB</LI></UL>
## Related Products
* [Practical Ansible Solutions [Video]](https://www.packtpub.com/networking-and-servers/practical-ansible-solutions-video?utm_source=github&utm_medium=repository&utm_campaign=9781788476904)
* [Responsive Web Development with Bootstrap 4 and Angular 7 [Video]](https://www.packtpub.com/web-development/responsive-web-development-bootstrap-4-and-angular-7-video?utm_source=github&utm_medium=repository&utm_campaign=9781789615272)
* [Learning GitLab [Video]](https://www.packtpub.com/application-development/learning-gitlab-video?utm_source=github&utm_medium=repository&utm_campaign=9781789809169)
|
1d596507b1e82d3e85863441733aecfba10de3b2
|
{
"blob_id": "1d596507b1e82d3e85863441733aecfba10de3b2",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-30T09:58:54",
"content_id": "8ee797c68da4ca1551f6bfd963031db85b728456",
"detected_licenses": [
"MIT"
],
"directory_id": "4fa5a61821323fabf0b218b4a47b6e576ef3a4ec",
"extension": "md",
"filename": "README.md",
"fork_events_count": 59,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125961637,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3268,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0010.json.gz:231534",
"repo_name": "PacktPublishing/Deep-learning-with-PyTorch-video",
"revision_date": "2023-01-30T09:58:54",
"revision_id": "4114bb143ca30475a14b37f247c770abe92ad0f4",
"snapshot_id": "f04806451ae590847867ec70f02c8f85fd5e6b01",
"src_encoding": "UTF-8",
"star_events_count": 64,
"url": "https://raw.githubusercontent.com/PacktPublishing/Deep-learning-with-PyTorch-video/4114bb143ca30475a14b37f247c770abe92ad0f4/README.md",
"visit_date": "2023-02-06T16:53:02.531303",
"added": "2024-11-19T00:55:02.585255+00:00",
"created": "2023-01-30T09:58:54",
"int_score": 3,
"score": 3.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
use crate::construction::heuristics::*;
use crate::models::problem::Job;
use crate::solver::search::LocalOperator;
use crate::solver::RefinementContext;
use crate::utils::Noise;
use rand::prelude::SliceRandom;
use rosomaxa::HeuristicSolution;
/// A local search operator which tries to exchange jobs in random way inside one route.
pub struct ExchangeIntraRouteRandom {
probability: f64,
noise_range: (f64, f64),
}
impl ExchangeIntraRouteRandom {
/// Creates a new instance of `ExchangeIntraRouteRandom`.
pub fn new(probability: f64, min: f64, max: f64) -> Self {
Self { probability, noise_range: (min, max) }
}
}
impl Default for ExchangeIntraRouteRandom {
fn default() -> Self {
Self::new(0.05, -0.25, 0.25)
}
}
impl LocalOperator for ExchangeIntraRouteRandom {
fn explore(&self, _: &RefinementContext, insertion_ctx: &InsertionContext) -> Option<InsertionContext> {
if let Some(route_idx) = get_random_route_idx(insertion_ctx) {
let random = insertion_ctx.environment.random.clone();
let route_ctx = insertion_ctx.solution.routes.get(route_idx).unwrap();
if let Some(job) = get_shuffled_jobs(insertion_ctx, route_ctx).into_iter().next() {
let mut new_insertion_ctx = insertion_ctx.deep_copy();
let new_route_ctx = new_insertion_ctx.solution.routes.get_mut(route_idx).unwrap();
assert!(new_route_ctx.route_mut().tour.remove(&job));
new_insertion_ctx.solution.required.push(job.clone());
new_insertion_ctx.problem.goal.accept_route_state(new_route_ctx);
let leg_selection = LegSelection::Stochastic(random.clone());
let result_selector = NoiseResultSelector::new(Noise::new_with_addition(
self.probability,
self.noise_range,
random.clone(),
));
let eval_ctx = EvaluationContext {
goal: &insertion_ctx.problem.goal,
job: &job,
leg_selection: &leg_selection,
result_selector: &result_selector,
};
let new_route_ctx = new_insertion_ctx.solution.routes.get(route_idx).unwrap();
let insertion = eval_job_insertion_in_route(
&new_insertion_ctx,
&eval_ctx,
new_route_ctx,
InsertionPosition::Any,
InsertionResult::make_failure(),
);
return match insertion {
InsertionResult::Success(success) => {
apply_insertion_success(&mut new_insertion_ctx, success);
finalize_insertion_ctx(&mut new_insertion_ctx);
Some(new_insertion_ctx)
}
_ => None,
};
}
}
None
}
}
fn get_shuffled_jobs(insertion_ctx: &InsertionContext, route_ctx: &RouteContext) -> Vec<Job> {
let mut jobs = route_ctx
.route()
.tour
.jobs()
.filter(|job| !insertion_ctx.solution.locked.contains(*job))
.cloned()
.collect::<Vec<_>>();
jobs.shuffle(&mut insertion_ctx.environment.random.get_rng());
jobs
}
fn get_random_route_idx(insertion_ctx: &InsertionContext) -> Option<usize> {
let routes = insertion_ctx
.solution
.routes
.iter()
.enumerate()
.filter_map(|(idx, route_ctx)| if route_ctx.route().tour.job_count() > 1 { Some(idx) } else { None })
.collect::<Vec<_>>();
if routes.is_empty() {
None
} else {
Some(routes[insertion_ctx.environment.random.uniform_int(0, (routes.len() - 1) as i32) as usize])
}
}
|
5d6a82bfb230baae21b3431f952658c42df13cdb
|
{
"blob_id": "5d6a82bfb230baae21b3431f952658c42df13cdb",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-26T11:44:28",
"content_id": "48f05d649244f7eefd260abc163b11934710931a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f2d3aebf59c8be546747b9a73839589ddba9a3d5",
"extension": "rs",
"filename": "exchange_intra_route.rs",
"fork_events_count": 54,
"gha_created_at": "2020-02-05T11:38:10",
"gha_event_created_at": "2023-07-26T17:33:14",
"gha_language": "Rust",
"gha_license_id": "Apache-2.0",
"github_id": 238436117,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 3851,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vrp-core/src/solver/search/local/exchange_intra_route.rs",
"provenance": "stack-edu-0068.json.gz:339564",
"repo_name": "reinterpretcat/vrp",
"revision_date": "2023-08-26T11:44:28",
"revision_id": "dfb76e9d985b08aea88f588ba43f5e8f8ad649b6",
"snapshot_id": "53ace786e3b157bc24bd9fe4548e64d00c084b06",
"src_encoding": "UTF-8",
"star_events_count": 279,
"url": "https://raw.githubusercontent.com/reinterpretcat/vrp/dfb76e9d985b08aea88f588ba43f5e8f8ad649b6/vrp-core/src/solver/search/local/exchange_intra_route.rs",
"visit_date": "2023-09-01T12:34:37.659239",
"added": "2024-11-18T23:48:46.708708+00:00",
"created": "2023-08-26T11:44:28",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
package edu.ucar.rap.maw;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
public class DataLoginTask extends AsyncTask<String, Integer, Long> {
Activity _mainActivity;
Controller _controller;
boolean _isLogin = true;
protected Long doInBackground(String... urls) {
try {
// String loginUrl = "http://www.ral.ucar.edu/projects/rdwx_mdss/AK_mdss/proxy.php?path=/maw_login.json&user=pad&password=padpass&action=login";
// String logoutUrl = "http://www.ral.ucar.edu/projects/rdwx_mdss/AK_mdss/proxy.php?path=/maw_login.json&session_id=1234asdf1234&action=logout";
String url = urls[0];
String paramString = urls[1];
Log.i(getClass().getSimpleName(), "send task - start");
// Add params.
url += "?" + paramString;
// Login or logout?
if ( paramString.contains("logout") ) {
_isLogin = false;
}
Log.i(getClass().getSimpleName(), "Requesting url: " + url);
// Toast.makeText(_mainActivity, url, Toast.LENGTH_LONG).show();
// Get the response...
HttpGet httpget = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String jsonResponse = null;
if ( entity == null) {
Log.i(getClass().getSimpleName(), "Could not get HttpEntity from response...");
// Toast.makeText(_mainActivity, "Could not get HttpEntity from response...", Toast.LENGTH_LONG).show();
}
else {
InputStream instream = entity.getContent();
try {
StringWriter writer = new StringWriter();
IOUtils.copy(instream, writer, "UTF-8");
jsonResponse = writer.toString();
Log.i(getClass().getSimpleName(), "Received: " + jsonResponse);
// Toast.makeText(_mainActivity, theString, Toast.LENGTH_LONG).show();
} catch (IOException ioe) {
ioe.printStackTrace();
// Toast.makeText(_mainActivity, "IOException: " + ioe, Toast.LENGTH_LONG).show();
} finally {
instream.close();
}
}
// Parse
if ( jsonResponse == null ) {
_controller.handleAlertError("Got null JSON response from login request.");
}
else {
JSONObject jsonO = new JSONObject(jsonResponse);
// Check for error string in response
try {
String login_error = jsonO.getString("error_string");
_controller.handleAlertError(login_error);
return null;
} catch (JSONException err_ex) {
Log.i(getClass().getSimpleName(), "Login response contained no error string...");
}
String sessionId = jsonO.getString("session_id");
String sequenceNo = jsonO.getString("sequence_no");
_controller.setSessionId(sessionId);
int parsedInt = -9999;
try {
parsedInt = Integer.parseInt(sequenceNo);
} catch ( NumberFormatException e ) {
Log.e(getClass().getSimpleName(), "Error. Sequence number from server does not contain a parsable integer: " + sequenceNo);
}
_controller.setSequenceNo(parsedInt);
/*
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
*/
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (Throwable t) {
t.printStackTrace();
// Toast.makeText(_mainActivity, "Request failed: " + t.toString(),
// Toast.LENGTH_LONG).show();
return null;
}
return null;
}
public void setMainActivity(Activity act) {
_mainActivity = act;
}
public void setController(Controller controller) {
_controller = controller;
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
// showDialog("Downloaded " + result + " bytes");
if ( _isLogin )
_controller.loginComplete(result);
else
_controller.logoutComplete(result);
}
}
|
2cb8c5ce09883a8f1721eb653187587ca10e4cb8
|
{
"blob_id": "2cb8c5ce09883a8f1721eb653187587ca10e4cb8",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-03T16:09:38",
"content_id": "551727349451e1fb0f8e2cc56af2a8058bed5f45",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "032a59902e47f6843ac9c76f6e27eb1d4a78c27d",
"extension": "java",
"filename": "DataLoginTask.java",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25056408,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5981,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/apps/maw_phone/src/edu/ucar/rap/maw/DataLoginTask.java",
"provenance": "stack-edu-0028.json.gz:35621",
"repo_name": "OSADP/Pikalert-Vehicle-Data-Translator-",
"revision_date": "2017-04-03T16:09:38",
"revision_id": "295da604408f6f13af0301b55476a81311459386",
"snapshot_id": "17411c602879eb4fb080201973b4a966f9405a4b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/OSADP/Pikalert-Vehicle-Data-Translator-/295da604408f6f13af0301b55476a81311459386/apps/maw_phone/src/edu/ucar/rap/maw/DataLoginTask.java",
"visit_date": "2021-03-27T12:02:18.535636",
"added": "2024-11-18T23:36:28.633788+00:00",
"created": "2017-04-03T16:09:38",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
<?php namespace unittest\assert;
class NotPossible extends Condition {
protected $message;
public function __construct($message) {
$this->message= $message;
}
public function matches($value) {
return false;
}
public function describe($value, $positive) {
return sprintf(self::stringOf($value).' '.$this->message);
}
}
|
945e38ef7800dd866eeae566bce426730737ee96
|
{
"blob_id": "945e38ef7800dd866eeae566bce426730737ee96",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-27T08:51:15",
"content_id": "288fb07161ef83437d34fdcea4a0467deb3125ff",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2e427a0230a9c9b06404aad1b8e4f97eeb2371a0",
"extension": "php",
"filename": "NotPossible.class.php",
"fork_events_count": 0,
"gha_created_at": "2014-09-06T17:14:18",
"gha_event_created_at": "2017-06-04T11:48:35",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 23740161,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 348,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/main/php/unittest/assert/NotPossible.class.php",
"provenance": "stack-edu-0047.json.gz:319125",
"repo_name": "xp-forge/assert",
"revision_date": "2022-02-27T08:51:15",
"revision_id": "8018243f0e0c0706d59c1604efb4fc7e512fb55d",
"snapshot_id": "35b3388d5ca4d34934d9d17cce042dfc928bf29a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xp-forge/assert/8018243f0e0c0706d59c1604efb4fc7e512fb55d/src/main/php/unittest/assert/NotPossible.class.php",
"visit_date": "2022-03-09T23:45:30.096607",
"added": "2024-11-18T20:31:38.034854+00:00",
"created": "2022-02-27T08:51:15",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
/*
* Copyright (c) Microsoft Corporation and Dapr Contributors.
* Licensed under the MIT License.
*/
package io.dapr.examples.actors;
import io.dapr.actors.ActorMethod;
import io.dapr.actors.ActorType;
import reactor.core.publisher.Mono;
/**
* Example of implementation of an Actor.
*/
@ActorType(name = "DemoActor")
public interface DemoActor {
void registerReminder();
@ActorMethod(name = "echo_message")
String say(String something);
void clock(String message);
@ActorMethod(returns = Integer.class)
Mono<Integer> incrementAndGet(int delta);
}
|
0fb711dc1d28104a4c601410d27d6661ed77ec3f
|
{
"blob_id": "0fb711dc1d28104a4c601410d27d6661ed77ec3f",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-27T03:34:59",
"content_id": "99f352a87c45da074965a03d21af9ec4e3ea0da9",
"detected_licenses": [
"MIT"
],
"directory_id": "adfe30c4e1b0dd53c320f2e6969a79925f13de16",
"extension": "java",
"filename": "DemoActor.java",
"fork_events_count": 0,
"gha_created_at": "2021-06-03T01:59:04",
"gha_event_created_at": "2021-06-03T01:59:05",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 373352957,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 598,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/src/main/java/io/dapr/examples/actors/DemoActor.java",
"provenance": "stack-edu-0023.json.gz:405454",
"repo_name": "pinxiong/java-sdk",
"revision_date": "2021-05-27T03:34:59",
"revision_id": "b1e54384c1067d68360640bd9ea6a4c3b0253f9a",
"snapshot_id": "ad310210d9880a315a7bdb2a002bbe8bdf25ea0a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pinxiong/java-sdk/b1e54384c1067d68360640bd9ea6a4c3b0253f9a/examples/src/main/java/io/dapr/examples/actors/DemoActor.java",
"visit_date": "2023-05-06T17:09:07.691597",
"added": "2024-11-19T00:26:39.085761+00:00",
"created": "2021-05-27T03:34:59",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
<?php
namespace TinyPixel\ActionNetwork\Services;
use \TinyPixel\ActionNetwork\Services\ActionNetwork;
class Utility extends ActionNetwork
{
/**
* Add Person
*
* @param Person
* @return void
*/
public function addPerson($person)
{
// At minimum a person should have an email
$this->validate($person);
// #todo validation & formatting
return $this::getInstance()->call('people', 'POST', [
'person' => collect($person)->toArray(),
]);
}
/**
* Validate
*
* @param object $person
* @return true
*/
public function validate($person)
{
!isset($person->email_addresses[0]['address']) ??
ActionNetwork::error('No email address supplied');
!self::checkEmail($person->email_addresses[0]['address']) ??
ActionNetwork::error('Invalid email address supplied');
if (isset($person->postal_code)) {
!is_string($person->postal_code) ??
ActionNetwork::error('Postal code must be of type string');
}
if (isset($person->family_name)) {
!is_string($person->family_name) ??
ActionNetwork::error('Family name must be of type string');
}
if (isset($person->given_name)) {
!is_string($person->given_name) ??
ActionNetwork::error('Given name must be of type string');
}
return true;
}
/**
* Check Email
*
* @param string $email
* @return void
*/
public static function checkEmail($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL) ? true : false;
}
}
|
26ef011f5e522a95cac51792a620e0e00a46a40e
|
{
"blob_id": "26ef011f5e522a95cac51792a620e0e00a46a40e",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-06T10:27:26",
"content_id": "ad277f8922623abd0f1456c4668fdbe7801fb7f7",
"detected_licenses": [
"MIT"
],
"directory_id": "6cb575af8aa3fa6ebbb8c70cd398d001bd7e2a92",
"extension": "php",
"filename": "Utility.php",
"fork_events_count": 0,
"gha_created_at": "2019-04-23T15:58:40",
"gha_event_created_at": "2023-01-04T03:41:49",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 183049682,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1695,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Services/Utility.php",
"provenance": "stack-edu-0050.json.gz:914678",
"repo_name": "pixelcollective/action-network-wordpress-powertools",
"revision_date": "2019-11-06T10:27:26",
"revision_id": "cf02c78183b131cce08467769711d2866e529f50",
"snapshot_id": "e768bef32d0f3a7d91fafc07016311b3a160107b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/pixelcollective/action-network-wordpress-powertools/cf02c78183b131cce08467769711d2866e529f50/app/Services/Utility.php",
"visit_date": "2023-01-07T14:12:20.668995",
"added": "2024-11-18T21:32:30.586894+00:00",
"created": "2019-11-06T10:27:26",
"int_score": 3,
"score": 2.984375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
<?php
/**
* Created by PhpStorm.
* User: VILDERR
* Date: 03.04.17
* Time: 19:37
*/
namespace app\assets\distribution;
use yii\web\AssetBundle;
/**
* Class DistributionAsset
* @package app\assets\distribution
*/
class DistributionAsset extends AssetBundle
{
public $sourcePath = 'app/media';
public $js = [
'js/distribution/script.js',
];
public $css = [
'css/distribution/styles.css',
];
public $depends = [
'yii\web\YiiAsset',
'yii\web\JqueryAsset',
];
}
|
0a4e7f76c13b8dccc6e456afb0b779df8e17b082
|
{
"blob_id": "0a4e7f76c13b8dccc6e456afb0b779df8e17b082",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-07T11:21:59",
"content_id": "9e28538bc42de354a138046eb49d23fcab25e236",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "080bb87e96e2275d6b44c2a4bf697961eff24f55",
"extension": "php",
"filename": "DistributionAsset.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87640315,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 530,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/app/assets/distribution/DistributionAsset.php",
"provenance": "stack-edu-0051.json.gz:92467",
"repo_name": "vilderr/baseproducts",
"revision_date": "2017-04-07T11:21:59",
"revision_id": "befb5864035ae7ffe9a499bc81bf502070f848b6",
"snapshot_id": "84790dcbc88c1149a9a9ec73568232dae9693bb6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vilderr/baseproducts/befb5864035ae7ffe9a499bc81bf502070f848b6/app/assets/distribution/DistributionAsset.php",
"visit_date": "2021-01-19T08:30:53.128330",
"added": "2024-11-18T21:32:02.164932+00:00",
"created": "2017-04-07T11:21:59",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
package com.lqb.leetcode.mark;
import org.junit.Test;
import java.util.LinkedList;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
* <p>
* 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出: 6
*/
public class TrapWater {
@Test
public void test1() {
//6
System.out.println(trap5(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
//3
System.out.println(trap5(new int[]{2,1,0,2}));
}
/**
* 官方解法1:暴力法。对于数组中的每个元素,我们找出下雨后水能达到的最高位置,等于两边最大高度的较小值减去当前高度的值。
* 时间复杂度:O(n²),空间复杂度:O(1)
*/
int trap(int[] height) {
int ans = 0;
int size = height.length;
for (int i = 0; i < size - 1; i++) {
int max_left = 0, max_right = 0;
for (int j = i; j >= 0; j--) { //Search the left part for max bar size
max_left = max(max_left, height[j]);
}
for (int j = i; j < size; j++) { //Search the right part for max bar size
max_right = max(max_right, height[j]);
}
ans += min(max_left, max_right) - height[i];
}
return ans;
}
/**
* 官方解法2:
* 时间复杂度:O(n),空间复杂度:O(n)
* 在暴力方法中,我们仅仅为了找到最大值每次都要向左和向右扫描一次。
* 但是我们可以提前存储这个值。因此,可以通过动态编程解决
*/
int trap2(int[] height) {
if (height == null) {
return 0;
}
int ans = 0;
int size = height.length;
int[] left_max = new int[size];
int[] right_max = new int[size];
left_max[0] = height[0];
for (int i = 1; i < size; i++) {
left_max[i] = max(height[i], left_max[i - 1]);
}
right_max[size - 1] = height[size - 1];
for (int i = size - 2; i >= 0; i--) {
right_max[i] = max(height[i], right_max[i + 1]);
}
for (int i = 1; i < size - 1; i++) {
ans += min(left_max[i], right_max[i]) - height[i];
}
return ans;
}
/**
* 官方解法3:
* 时间复杂度:O(n),因为每个bar访问两次(压栈和出栈)。空间复杂度:O(n)
* 我们可以不用像方法 2 那样存储最大高度,而是用栈来跟踪可能储水的最长的条形块。
* 使用栈就可以在一次遍历内完成计算。
* 我们在遍历数组时维护一个栈。
* 如果当前的条形块小于或等于栈顶的条形块,我们将条形块的索引入栈,意思是当前的条形块被栈中的前一个条形块界定。
* 如果我们发现一个条形块长于栈顶,我们可以确定栈顶的条形块被当前条形块和栈的前一个条形块界定,
* 因此我们可以弹出栈顶元素并且累加答案到 ans
*/
int trap3(int[] height) {
int ans = 0, cur = 0;
LinkedList<Integer> st = new LinkedList<>();
while (cur < height.length) {
//注意这个循环条件,只有当前bar大于最近的bar才有意义,表示可以计算雨水
//注意:当出现一个较长bar,遍历栈,比当前bar小的都要出栈。
//只需要保留当前bar和往左比它长的bar就可以了,因为较短bar在下面的循环中已经计算完毕
//后面的计算不需要用到他们
while (!st.isEmpty() && height[cur] > height[st.peekFirst()]) {
int top = st.pop();
//后面需要访问栈顶元素,也就是最近的靠左的一个bar,如果为空后面没办法计算了,直接退出
if (st.isEmpty()) {
break;
}
int distance = cur - st.peekFirst() - 1;
int bounded_height = min(height[cur], height[st.peekFirst()]) - height[top];
ans += distance * bounded_height;
}
st.push(cur++);
}
return ans;
}
/**
* 官方解法4:
* 和方法 2 相比,我们不从左和从右分开计算,我们想办法一次完成遍历。
* 从动态编程方法的示意图中我们注意到,只要 right_max[i] > left_max[i](元素 0 到元素 6),
* 积水高度将由 left_max 决定,类似地 left_max[i] > right_max[i](元素 8 到元素 11)。
* 所以我们可以认为如果一端有更高的条形块(例如右端),积水的高度依赖于当前方向的高度(从左到右)。
* 当我们发现另一侧(右侧)的条形块高度不是最高的,我们则开始从相反的方向遍历(从右到左)。
* 我们必须在遍历时维护 left_max 和 right_max,但是我们现在可以使用两个指针交替进行,
* 实现 1 次遍历即可完成。
*/
int trap4(int[] height) {
if (height == null || height.length <= 2) {
return 0;
}
int leftMax = 0;
int rightMax = 0;
int left = 0;
int right = height.length - 1;
int count = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] > leftMax) {
leftMax = height[left];
} else {
count += leftMax - height[left];
}
left++;
} else {
if (height[right] > rightMax) {
rightMax = height[right];
} else {
count += rightMax - height[right];
}
right--;
}
}
return count;
}
/**
* @author liqibo
* @date 2019/10/10 14:40
* @description
*/
public int trap5(int[] height) {
int i = 0;
int ans = 0;
LinkedList<Integer> stack = new LinkedList<>();
while (i < height.length) {
while (!stack.isEmpty() && height[i] > height[stack.peekFirst()]) {
Integer top = stack.pop();
if (stack.isEmpty()) {
break;
}
int w = i - stack.peekFirst() - 1;
int h = Math.min(height[i], height[stack.peekFirst()]) - height[top];
ans += w * h;
}
stack.push(i++);
}
return ans;
}
}
|
974b1db5c899aed71d622236940032a7ddc1d40a
|
{
"blob_id": "974b1db5c899aed71d622236940032a7ddc1d40a",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-24T06:29:33",
"content_id": "de13b9de7d37581c02611ff3429d209dcf9be888",
"detected_licenses": [
"MIT"
],
"directory_id": "a3e5112f3fe0c3be3aa8c79db2790380e1cc4a9b",
"extension": "java",
"filename": "TrapWater.java",
"fork_events_count": 0,
"gha_created_at": "2016-07-27T01:35:38",
"gha_event_created_at": "2023-06-14T22:23:18",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 64267198,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 6706,
"license": "MIT",
"license_type": "permissive",
"path": "/src/com/lqb/leetcode/mark/TrapWater.java",
"provenance": "stack-edu-0024.json.gz:501934",
"repo_name": "cable5881/algorithm",
"revision_date": "2022-03-24T06:29:33",
"revision_id": "bcf20dfb467376dfa4d53c96f1236901fae69a5c",
"snapshot_id": "36828d04a05e489417126dbbe33b055c56094684",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cable5881/algorithm/bcf20dfb467376dfa4d53c96f1236901fae69a5c/src/com/lqb/leetcode/mark/TrapWater.java",
"visit_date": "2023-06-26T06:45:19.807479",
"added": "2024-11-19T00:25:57.049433+00:00",
"created": "2022-03-24T06:29:33",
"int_score": 4,
"score": 3.875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package com.example.hongzebin.schedule.greendao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.example.hongzebin.schedule.bean.Course;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "COURSE".
*/
public class CourseDao extends AbstractDao<Course, Long> {
public static final String TABLENAME = "COURSE";
/**
* Properties of entity Course.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Number = new Property(2, String.class, "number", false, "NUMBER");
public final static Property Major = new Property(3, String.class, "major", false, "MAJOR");
public final static Property FigureNumber = new Property(4, String.class, "figureNumber", false, "FIGURENUMBER");
public final static Property Time = new Property(5, String.class, "time", false, "TIME");
public final static Property Week = new Property(6, String.class, "week", false, "WEEK");
public final static Property Weekday = new Property(7, String.class, "weekday", false, "WEEKDAY");
public final static Property Place = new Property(8, String.class, "place", false, "PLACE");
public final static Property Teacher = new Property(9, String.class, "teacher", false, "TEACHER");
}
public CourseDao(DaoConfig config) {
super(config);
}
public CourseDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"COURSE\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"NAME\" TEXT," + // 1: name
"\"NUMBER\" TEXT," + // 2: number
"\"MAJOR\" TEXT," + // 3: major
"\"FIGURENUMBER\" TEXT," + // 4: figureNumber
"\"TIME\" TEXT," + // 5: time
"\"WEEK\" TEXT," + // 6: week
"\"WEEKDAY\" TEXT," + // 7: weekday
"\"PLACE\" TEXT," + // 8: place
"\"TEACHER\" TEXT);"); // 9: teacher
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"COURSE\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, Course entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String number = entity.getNumber();
if (number != null) {
stmt.bindString(3, number);
}
String major = entity.getMajor();
if (major != null) {
stmt.bindString(4, major);
}
String figureNumber = entity.getFigureNumber();
if (figureNumber != null) {
stmt.bindString(5, figureNumber);
}
String time = entity.getTime();
if (time != null) {
stmt.bindString(6, time);
}
String week = entity.getWeek();
if (week != null) {
stmt.bindString(7, week);
}
String weekday = entity.getWeekday();
if (weekday != null) {
stmt.bindString(8, weekday);
}
String place = entity.getPlace();
if (place != null) {
stmt.bindString(9, place);
}
String teacher = entity.getTeacher();
if (teacher != null) {
stmt.bindString(10, teacher);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, Course entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String number = entity.getNumber();
if (number != null) {
stmt.bindString(3, number);
}
String major = entity.getMajor();
if (major != null) {
stmt.bindString(4, major);
}
String figureNumber = entity.getFigureNumber();
if (figureNumber != null) {
stmt.bindString(5, figureNumber);
}
String time = entity.getTime();
if (time != null) {
stmt.bindString(6, time);
}
String week = entity.getWeek();
if (week != null) {
stmt.bindString(7, week);
}
String weekday = entity.getWeekday();
if (weekday != null) {
stmt.bindString(8, weekday);
}
String place = entity.getPlace();
if (place != null) {
stmt.bindString(9, place);
}
String teacher = entity.getTeacher();
if (teacher != null) {
stmt.bindString(10, teacher);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public Course readEntity(Cursor cursor, int offset) {
Course entity = new Course( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // number
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // major
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // figureNumber
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // time
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // week
cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // weekday
cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // place
cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9) // teacher
);
return entity;
}
@Override
public void readEntity(Cursor cursor, Course entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setNumber(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setMajor(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setFigureNumber(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setTime(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setWeek(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setWeekday(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7));
entity.setPlace(cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8));
entity.setTeacher(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9));
}
@Override
protected final Long updateKeyAfterInsert(Course entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(Course entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(Course entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
|
3179f88f583b7c176efafb6ead8ad3e43dbf0618
|
{
"blob_id": "3179f88f583b7c176efafb6ead8ad3e43dbf0618",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-04T13:07:36",
"content_id": "9644e773c2ff8c2a897e5ad235a777eb96fa41c0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3410b32fb773974c957cdc46d3990bfbcaf0a88b",
"extension": "java",
"filename": "CourseDao.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 144951964,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8453,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/com/example/hongzebin/schedule/greendao/CourseDao.java",
"provenance": "stack-edu-0024.json.gz:8126",
"repo_name": "HongZeBin98/Schedule",
"revision_date": "2018-09-04T13:07:36",
"revision_id": "f1fe01e14b7cdb5b398e806da124cc8adb4e2429",
"snapshot_id": "6b294fe7788af3b34555f6180c40001975bc21ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HongZeBin98/Schedule/f1fe01e14b7cdb5b398e806da124cc8adb4e2429/app/src/main/java/com/example/hongzebin/schedule/greendao/CourseDao.java",
"visit_date": "2020-03-26T13:41:35.983579",
"added": "2024-11-18T22:53:23.378661+00:00",
"created": "2018-09-04T13:07:36",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
# Calculate the mode Pairing Challenge
# I worked on this challenge [by myself, with: Chris Shahin ]
# I spent [1] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# What is the input?
# Array of numbers and/or strings
# What is the output? (i.e. What should the code return?)
# Array of the most frequent elements
# What are the steps needed to solve the problem?
# Convert array to a hash whose elements are the keys
# The value += each time a key is hit
# Return the key(s) with the highest value
# 1. Initial Solution
# def mode (array)
# frequencies = {}
# frequencies.default = 0
# array.each do |x|
# frequencies[x] += 1
# end
# new_array = []
# frequencies.each { |k,v| new_array.push(k) if v == frequencies.values.max}
# new_array
# end
# 3. Refactored Solution
def mode (array)
frequencies = {}
frequencies.default = 0
array.each {|x|frequencies[x] +=1}
new_array = []
frequencies.each { |k, v| new_array.push(k) if v == frequencies.values.max }
new_array
end
print mode([1,1,1,1,2,3,4, 'Bob','Bob','Bob'])
print mode([1,2,3,4])
print mode([1,1,2,3,4,4,4,4,4,4,4])
# 4. Reflection
# Which data structure did you and your pair decide to implement and why?
#We decided to implement both arrays and hashes. We used a hash to contain the elements passed through as keys and the frequencies as the values. We did this because we thought it would be easier to access and sort the frequencies. Then we had to push the highest frenquency keys to an array since that what was in the instructions.
# Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?
# I'd say we were just as succesful. We found both of these problems to be fairly simple and straightforward.
# What issues/successes did you run into when translating your pseudocode to code?
# We had a little issue iterating through the hash. We each just didn't have as much experience working with hashes and weren't as familiar with hash methods.
# What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?
# We used the .each to iterate through the keys and values of our hash. Then we used .values.max on the hash which was able for us to find the keys with the highest values.
|
dd11b75eb4e65875292e06a47e01f0c9788da169
|
{
"blob_id": "dd11b75eb4e65875292e06a47e01f0c9788da169",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-21T07:13:26",
"content_id": "422f9cd166b847035007b025ac7ae053bdf17c80",
"detected_licenses": [
"MIT"
],
"directory_id": "11694ff638c8658f100af0964a8806981918cc0e",
"extension": "rb",
"filename": "my_solution.rb",
"fork_events_count": 0,
"gha_created_at": "2015-10-23T21:32:25",
"gha_event_created_at": "2015-12-06T21:00:54",
"gha_language": "Ruby",
"gha_license_id": null,
"github_id": 44839666,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2501,
"license": "MIT",
"license_type": "permissive",
"path": "/week-5/calculate-mode/my_solution.rb",
"provenance": "stack-edu-0067.json.gz:650479",
"repo_name": "amitzman/phase-0",
"revision_date": "2015-12-21T07:13:26",
"revision_id": "bff4a78b4db0a2b2480bef0f4af19b2374157f8c",
"snapshot_id": "bcf0f0ddfd1827e2e32ba9b83bac3811d7acecd3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/amitzman/phase-0/bff4a78b4db0a2b2480bef0f4af19b2374157f8c/week-5/calculate-mode/my_solution.rb",
"visit_date": "2016-08-12T05:43:02.214865",
"added": "2024-11-19T02:21:40.488579+00:00",
"created": "2015-12-21T07:13:26",
"int_score": 3,
"score": 3.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
/*
* Copyright (C) 2014 Google Inc.
* Copyright (C) 2015 End Point Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.endpoint.lg.support.lua;
/**
* Methods for dealing with Lua regex syntax.
*
* @author Matt Vollrath <[email protected]>
*/
public class LuaRegex {
/**
* Escape Lua regex for the given string.
*
* @param in
* a string to be escaped
* @return the escaped string
*/
public static String escape(String in) {
String out = in;
out = out.replace("%", "%%");
out = out.replace("^", "%^");
out = out.replace("$", "%$");
out = out.replace("(", "%(");
out = out.replace(")", "%)");
out = out.replace("[", "%[");
out = out.replace("]", "%]");
out = out.replace(".", "%.");
out = out.replace("*", "%*");
out = out.replace("+", "%+");
out = out.replace("-", "%-");
out = out.replace("?", "%?");
out = out.replace("\0", "%z");
return out;
}
}
|
9cf5db3026331e6d45b6e08ed00099d75eb38f26
|
{
"blob_id": "9cf5db3026331e6d45b6e08ed00099d75eb38f26",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-26T13:46:42",
"content_id": "4dbbdc526640b5ca42584096f2d99ffcd860e5c8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e43506936698fd08ab40b33fd0c115caad363016",
"extension": "java",
"filename": "LuaRegex.java",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34342974,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1482,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/com/endpoint/lg/support/lua/LuaRegex.java",
"provenance": "stack-edu-0023.json.gz:590781",
"repo_name": "EndPointCorp/com.endpoint.lg.support",
"revision_date": "2015-05-26T13:46:42",
"revision_id": "4d26bd27822359660d3ab905eb3e4a45dd8d3a4c",
"snapshot_id": "8cb8a391903ffcf7a9d23da43d75bf728e49a46e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/EndPointCorp/com.endpoint.lg.support/4d26bd27822359660d3ab905eb3e4a45dd8d3a4c/src/main/java/com/endpoint/lg/support/lua/LuaRegex.java",
"visit_date": "2021-01-19T12:37:03.008972",
"added": "2024-11-19T01:53:01.962396+00:00",
"created": "2015-05-26T13:46:42",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
#include <other.h>
void f1_1_F();
void f1_2_F(int);
template <class T> void f1_1_T();
template <class T> void f1_2_T(int);
template <class T, template <class> class U> void f1_1_U(U<T>);
template <class T, template <class> class U> void f1_2_U(U<T>, int);
struct DefHF { struct ID { }; struct IC; };
struct DecHF;
typedef DefHF DefYHF;
typedef DecHF DecYHF;
template <class T> struct DefHTF { struct ID { }; struct IC; };
template <class T> struct DecHTF;
namespace {
struct DefHAN { struct ID { }; struct IC; };
struct DecHAN;
typedef DefHF DefYHF;
typedef DecHF DecYHF;
template <class T> struct DefHTAN { struct ID { }; struct IC; };
template <class T> struct DecHTAN;
}
namespace N {
struct DefHN { struct ID { }; struct IC; };
struct DecHN;
typedef DefHF DefYHF;
typedef DecHF DecYHF;
template <class T> struct DefHTN { struct ID { }; struct IC; };
template <class T> struct DecHTN;
}
#define fs(tplt, typn, prefix, name, type) \
tplt void prefix##_1_##name(typn type); \
tplt void prefix##_2_##name(const typn type *); \
tplt void prefix##_3_##name(volatile typn type &); \
tplt void prefix##_4_##name(int, typn type); \
tplt void prefix##_5_##name(int, const typn type *); \
tplt void prefix##_6_##name(int, volatile typn type &);
#define fu(tplt, typn, prefix, name, type) \
template <class T, template <class> class U> \
void prefix##_7_##name(U<typn type>); \
template <class T, template <class> class U> \
void prefix##_8_##name(U<const typn type *>); \
template <class T, template <class> class U> \
void prefix##_9_##name(U<volatile typn type &>);
#define fss(f, tplt, typn, prefix, name, type) \
f( tplt, , prefix, Dec##name, Dec##type) \
f( tplt, , prefix, Def##name, Def##type) \
f( tplt, typn, prefix, Def##name##Id, Def##type::ID) \
f( tplt, typn, prefix, Def##name##If, Def##type::IC)
#define allf(f,prefix) \
fss(f,,, prefix, HF, HF) \
fss(f,,, prefix, OHF, OHF) \
fss(f,,, prefix, HAN, HAN) \
fss(f,,, prefix, OHAN, OHAN) \
f(,, prefix, DefYHF, DefYHF) \
f(,, prefix, DecYHF, DecYHF) \
fss(f, template<class T>, typename, prefix, HTF, HTF<T>) \
fss(f, template<class T>, typename, prefix, OHTF, OHTF<T>) \
fss(f, template<class T>, typename, prefix, HTAN, HTAN<T>) \
fss(f, template<class T>, typename, prefix, OHTAN, OHTAN<T>)
#define all(prefix) allf(fs, prefix) allf(fu, prefix)
all(f1)
namespace N {
all(f1)
}
struct E {
all(f1)
};
extern "C++" {
all(f2)
}
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
|
ca1c6c4369b0957392bd303eae527dcb9b622758
|
{
"blob_id": "ca1c6c4369b0957392bd303eae527dcb9b622758",
"branch_name": "refs/heads/debian",
"committer_date": "2016-04-15T16:08:28",
"content_id": "0a11b9905f121a22c6e68fc7bbac14632dab07e1",
"detected_licenses": [
"MIT"
],
"directory_id": "ccf3d4ddf8355b4a8e20ef9ade6af7e22d6b6159",
"extension": "h",
"filename": "genfunc.h",
"fork_events_count": 3,
"gha_created_at": "2015-07-01T11:22:29",
"gha_event_created_at": "2015-09-16T12:36:28",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 38367232,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5098,
"license": "MIT",
"license_type": "permissive",
"path": "/checks/csaaq/free-functions-depend/genfunc.h",
"provenance": "stack-edu-0003.json.gz:41886",
"repo_name": "hmaldona/bde_verify",
"revision_date": "2016-04-15T16:08:28",
"revision_id": "6fb86bb21c387e829f77bbc9d25c86530c4d68d9",
"snapshot_id": "809442ecf0c36fd57d53f0251368baa5ae17247f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hmaldona/bde_verify/6fb86bb21c387e829f77bbc9d25c86530c4d68d9/checks/csaaq/free-functions-depend/genfunc.h",
"visit_date": "2020-05-02T08:49:06.504911",
"added": "2024-11-18T21:41:01.144334+00:00",
"created": "2016-04-15T16:08:28",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz"
}
|
'use strict'
var influx = require('influx')
var _ = require('lodash')
var bole = require('bole')
var through = require('through2')
var locals = {
plugin: 'vidi-influx-sink',
role: 'metrics',
enabled: true,
batch: {
max: 5,
timeout: 500,
},
influx: {
host: 'localhost',
port: '8086',
username: 'metrics',
password: 'metrics',
database: 'vidi_metrics'
}
}
module.exports = function (options) {
var seneca = this
var extend = seneca.util.deepextend
locals = extend(locals, options)
locals.log = bole(locals.plugin)
locals.client = influx(locals.influx)
locals.batch.list = {}
locals.batch.count = 0
locals.batch.stream = through.obj(on_write)
locals.batch.stream.on('error', on_stream_err)
locals.batch.next = Date.now() + locals.batch.timeout
seneca.add({role: locals.role, hook: 'sink'}, sink)
seneca.add({role: locals.role, enabled: '*'}, enable_disable)
locals.log.info(`batch size: ${locals.batch.max}`)
locals.log.info(`batch timeout: ${locals.batch.timeout}`)
return locals.plugin
}
function on_stream_err (err) {
locals.log.err('write stream error:')
locals.log.err(err)
}
function sink (msg, done) {
var stream = locals.batch.stream
var client = locals.client
if (locals.enabled && msg && msg.metric) {
stream.write(msg.metric)
}
done()
}
function enable_disable (msg, done) {
locals.enabled = msg.enabled
done()
}
// Called each time the stream is written to
function on_write (metric, enc, done) {
var name = metric.name
var values = metric.values
var tags = metric.tags
locals.batch.list[name] = locals.batch.list[name] || []
locals.batch.list[name].push([values, tags])
locals.batch.count = locals.batch.count + 1
var exceeded = locals.batch.count >= locals.batch.max
var expired = Date.now() > locals.batch.next
if (exceeded || expired) {
write_batch()
}
done()
}
function write_batch () {
var db = `${locals.influx.database}:${locals.influx.port}`
var written = locals.batch.count
var batches = locals.batch.list
locals.batch.list = {}
locals.batch.count = 0
reset_timeout()
function on_err (err) {
if (err) {
locals.log.error('error writing to influx:')
locals.log.error(err)
}
else {
locals.log.info(`${written} metric(s) written to ${db}`)
}
}
locals.client.writeSeries(batches, on_err)
}
function reset_timeout () {
var timeout = locals.batch.timeout
var next = locals.batch.next
if (timeout) {
clearTimeout(locals.batch.timer)
}
locals.batch.timer = setTimeout(() => {write_batch()}, timeout)
locals.batch.next = Date.now() + next
}
|
70b54e9391bfb687dfe94b128f9e886670cd6445
|
{
"blob_id": "70b54e9391bfb687dfe94b128f9e886670cd6445",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-15T14:00:07",
"content_id": "e2e46f20ddac3349678fec79fef1894184e4da16",
"detected_licenses": [
"MIT"
],
"directory_id": "141c773eba7fdd9a1deed2697fd6f1abf7402863",
"extension": "js",
"filename": "influx-sink.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2666,
"license": "MIT",
"license_type": "permissive",
"path": "/influx-sink.js",
"provenance": "stack-edu-0033.json.gz:46400",
"repo_name": "KristinaMatuleviciute/vidi-influx-sink",
"revision_date": "2016-02-15T14:00:07",
"revision_id": "613851b6f7372415e62384a8a09624d362887f0d",
"snapshot_id": "0560ed9b564545ccf874be66f4086fce28a9ca6c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KristinaMatuleviciute/vidi-influx-sink/613851b6f7372415e62384a8a09624d362887f0d/influx-sink.js",
"visit_date": "2020-12-26T10:02:28.931699",
"added": "2024-11-19T01:30:58.462619+00:00",
"created": "2016-02-15T14:00:07",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
---
layout: post
published: true
categories:
- Subscriptions
title: Bespoke Post June 2015 Selections + 25% off Coupon!
featured: false
comments: true
type: photo
imagefeature: BespokePostJune2015Selections.jpg
headline: Bespoke Post June 2015 Selections + 25% off Coupon!
tags: [Bespoke Post, Subscriptions]
date: 2015-06-01 08:27:39 -08:00
---
<h4>The June 2015 <a href="http://bespoke.evyy.net/c/164125/70438/1804">Bespoke Post</a> Selections are available and they look great!</h4>
<center><img src='/images/BespokePostJune2015Selections.jpg'></center>
<DT>FRONTIER:</DT>
1. Opinel - No. 8 Pocket Knife
2. Machine Era Co. - Bottle Opener
3. Kaweco - Black Sport Fountain Pen
4. Bespoke Post - Black Soft Cover Notebook
<br>
<DT>ROAST:</DT>
1. Bobble - Presse Coffee Maker
2. Bespoke Post- Ceramic Burr Grinder
3. Dapper & Wise - Coffee Beans
<br>
<DT>COPPER:</DT>
1. Line of Trade - Copper Mugs, Set of 2
2. Liber & Co - Fiery Ginger Syrup
3. Ice Mallet and Lewis Bag
<br>
<DT>ROAM:</DT>
1. Line of Trade - Tote Bag
2. TM1985 - Cord Wrap
3. Vapur - Water Bottle
<br>
<p><b>Subscription:</b> <a href="http://bespoke.evyy.net/c/164125/70438/1804">Bespoke Post</a></p>
<p><b>Cost:</b> $45 / month with Free Shipping</p>
<p><b>What's in the box:</b> Every month you'll get to choose a themed box curated by them with products that may include gadgets, sportswear, accessories and more.</p>
<p><b>Coupon:</b> Use coupon code <a href="http://bespoke.evyy.net/c/164125/70438/1804"><b>ALONE</b></a> to get 25% off your first box!</p>
|
f00d536e7689574b482d586606636b712fcfb66a
|
{
"blob_id": "f00d536e7689574b482d586606636b712fcfb66a",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-25T23:09:35",
"content_id": "1d35af93d947ab038d8ab390f7131644b65d7148",
"detected_licenses": [
"MIT"
],
"directory_id": "dd91edbb50b1f8ce73ea8b8d47fe70e9ef45846b",
"extension": "md",
"filename": "2015-06-01-Bespoke-Post-June-2015-Selections.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35123886,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1545,
"license": "MIT",
"license_type": "permissive",
"path": "/_posts/2015-06-01-Bespoke-Post-June-2015-Selections.md",
"provenance": "stack-edu-markdown-0013.json.gz:121525",
"repo_name": "whatsupmailbox/whatsupmailbox.github.io",
"revision_date": "2017-07-25T23:09:35",
"revision_id": "15445be0254ee725a323c74694861b918db549ae",
"snapshot_id": "06a77f093a795519c5849de454b43a2968dddbe5",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/whatsupmailbox/whatsupmailbox.github.io/15445be0254ee725a323c74694861b918db549ae/_posts/2015-06-01-Bespoke-Post-June-2015-Selections.md",
"visit_date": "2020-04-04T03:20:10.351298",
"added": "2024-11-18T22:43:25.932911+00:00",
"created": "2017-07-25T23:09:35",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz"
}
|
QUnit.module('"Arrays" category methods');
(function () {
var args = toArgs([
__num_top__,
null,
[__num_top__],
null,
__num_top__
]), sortedArgs = toArgs([
__num_top__,
[__num_top__],
__num_top__,
null,
null
]), array = [
__num_top__,
__num_top__,
__num_top__,
__num_top__,
__num_top__,
__num_top__
];
QUnit.test('should work with `arguments` objects', function (assert) {
assert.expect(30);
function message(methodName) {
return __str_top__ + methodName + __str_top__;
}
assert.deepEqual(_.difference(args, [null]), [
__num_top__,
[__num_top__],
__num_top__
], message(__str_top__));
assert.deepEqual(_.difference(array, args), [
__num_top__,
__num_top__,
__num_top__,
__num_top__
], __str_top__);
assert.deepEqual(_.union(args, [
null,
__num_top__
]), [
__num_top__,
null,
[__num_top__],
__num_top__,
__num_top__
], message(__str_top__));
assert.deepEqual(_.union(array, args), array.concat([
null,
[__num_top__]
]), __str_top__);
assert.deepEqual(_.compact(args), [
__num_top__,
[__num_top__],
__num_top__
], message(__str_top__));
assert.deepEqual(_.drop(args, __num_top__), [
null,
__num_top__
], message(__str_top__));
assert.deepEqual(_.dropRight(args, __num_top__), [
__num_top__,
null
], message(__str_top__));
assert.deepEqual(_.dropRightWhile(args, identity), [
__num_top__,
null,
[__num_top__],
null
], message(__str_top__));
assert.deepEqual(_.dropWhile(args, identity), [
null,
[__num_top__],
null,
__num_top__
], message(__str_top__));
assert.deepEqual(_.findIndex(args, identity), __num_top__, message(__str_top__));
assert.deepEqual(_.findLastIndex(args, identity), __num_top__, message(__str_top__));
assert.deepEqual(_.flatten(args), [
__num_top__,
null,
__num_top__,
null,
__num_top__
], message(__str_top__));
assert.deepEqual(_.head(args), __num_top__, message(__str_top__));
assert.deepEqual(_.indexOf(args, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.initial(args), [
__num_top__,
null,
[__num_top__],
null
], message(__str_top__));
assert.deepEqual(_.intersection(args, [__num_top__]), [__num_top__], message(__str_top__));
assert.deepEqual(_.last(args), __num_top__, message(__str_top__));
assert.deepEqual(_.lastIndexOf(args, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.sortedIndex(sortedArgs, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.sortedIndexOf(sortedArgs, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.sortedLastIndex(sortedArgs, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.sortedLastIndexOf(sortedArgs, __num_top__), __num_top__, message(__str_top__));
assert.deepEqual(_.tail(args, __num_top__), [
null,
[__num_top__],
null,
__num_top__
], message(__str_top__));
assert.deepEqual(_.take(args, __num_top__), [
__num_top__,
null
], message(__str_top__));
assert.deepEqual(_.takeRight(args, __num_top__), [__num_top__], message(__str_top__));
assert.deepEqual(_.takeRightWhile(args, identity), [__num_top__], message(__str_top__));
assert.deepEqual(_.takeWhile(args, identity), [__num_top__], message(__str_top__));
assert.deepEqual(_.uniq(args), [
__num_top__,
null,
[__num_top__],
__num_top__
], message(__str_top__));
assert.deepEqual(_.without(args, null), [
__num_top__,
[__num_top__],
__num_top__
], message(__str_top__));
assert.deepEqual(_.zip(args, args), [
[
__num_top__,
__num_top__
],
[
null,
null
],
[
[__num_top__],
[__num_top__]
],
[
null,
null
],
[
__num_top__,
__num_top__
]
], message(__str_top__));
});
QUnit.test('should accept falsey primary arguments', function (assert) {
assert.expect(4);
function message(methodName) {
return __str_top__ + methodName + __str_top__;
}
assert.deepEqual(_.difference(null, array), [], message(__str_top__));
assert.deepEqual(_.intersection(null, array), [], message(__str_top__));
assert.deepEqual(_.union(null, array), array, message(__str_top__));
assert.deepEqual(_.xor(null, array), array, message(__str_top__));
});
QUnit.test('should accept falsey secondary arguments', function (assert) {
assert.expect(3);
function message(methodName) {
return __str_top__ + methodName + __str_top__;
}
assert.deepEqual(_.difference(array, null), array, message(__str_top__));
assert.deepEqual(_.intersection(array, null), [], message(__str_top__));
assert.deepEqual(_.union(array, null), array, message(__str_top__));
});
}());
|
3e06017b2087df7c7bf8c46e5fb43917768145bf
|
{
"blob_id": "3e06017b2087df7c7bf8c46e5fb43917768145bf",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-04T06:49:03",
"content_id": "5f1c6330beabbe0031203985d2331ece1a5c3213",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "28f4ecd6d6a085d090108d89c6d0aa189130809e",
"extension": "js",
"filename": "test304.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 372735636,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 6032,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/tests/benchmarks/lodash4/tests-rewritten/test304.js",
"provenance": "stack-edu-0033.json.gz:723058",
"repo_name": "kaist-plrg/safe-ds",
"revision_date": "2021-06-04T06:49:03",
"revision_id": "c54a9481b297a75af4f8b2ff42464025a95ea792",
"snapshot_id": "8fb97d9901d20238685f24e82f8e43bad4982228",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/kaist-plrg/safe-ds/c54a9481b297a75af4f8b2ff42464025a95ea792/tests/benchmarks/lodash4/tests-rewritten/test304.js",
"visit_date": "2023-04-13T12:06:35.227921",
"added": "2024-11-19T01:21:51.061320+00:00",
"created": "2021-06-04T06:49:03",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
describe("scorecard with bowling frames", function() {
describe('when game starts', function(){
var game;
var bowlingFrame;
beforeEach(function() {
game = new Game();
game.start();
bowlingFrame = new BowlingFrame();
});
it("each Frame has a subframe with two values of 0 and current starts at 'one'", function() {
expect(bowlingFrame.subFrame.current).toEqual('first');
expect(bowlingFrame.subFrame.one).toEqual(0);
expect(bowlingFrame.subFrame.two).toEqual(0);
});
});
describe('calculating the score', function() {
var bowlingFrame;
beforeEach(function() {
bowlingFrame = new BowlingFrame();
});
it('adds up for each subframe', function() {
bowlingFrame.subFrame.one = 5;
bowlingFrame.subFrame.two = 3;
bowlingFrame.score();
expect(bowlingFrame.currentScore).toEqual(8);
});
it("throws an error when 'subFrame TWO' is out of range", function(){
bowlingFrame.subFrame.one = 5;
bowlingFrame.subFrame.two = 8;
expect(function(){ bowlingFrame.score();
}).toThrow();
});
it("throws an error when 'subFrame ONE' is out of range", function(){
bowlingFrame.subFrame.one = 12;
expect(function(){ bowlingFrame.score();
}).toThrow();
});
xit('if strike adds up 2 points in last frame', function(){
for(var i=0;i<18;i++){ updateScorecardList(4); }
expect(Scorecard.list[9].subFrame.current.toEqual('first'));
});
});
});
|
d78edbc45495d30cfe08fe127429f3c87f8881a4
|
{
"blob_id": "d78edbc45495d30cfe08fe127429f3c87f8881a4",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-07T18:07:59",
"content_id": "45256f411b4790b8d36a1b821499adcb7382cfa0",
"detected_licenses": [
"MIT"
],
"directory_id": "9bd9f2ebf5b019f511d202e976d947d4a85b9898",
"extension": "js",
"filename": "BowlingFramesSpec.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41479924,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1518,
"license": "MIT",
"license_type": "permissive",
"path": "/spec/BowlingFramesSpec.js",
"provenance": "stack-edu-0034.json.gz:482942",
"repo_name": "dregules/bowling_game",
"revision_date": "2015-09-07T18:07:59",
"revision_id": "15bdce65959cd13dbac96c99f1710cc4e02a0bed",
"snapshot_id": "695c9e6ef7a287f6a9b17de59066749cd2c81bb5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dregules/bowling_game/15bdce65959cd13dbac96c99f1710cc4e02a0bed/spec/BowlingFramesSpec.js",
"visit_date": "2021-01-21T19:35:16.690548",
"added": "2024-11-19T01:31:10.427456+00:00",
"created": "2015-09-07T18:07:59",
"int_score": 3,
"score": 2.515625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz"
}
|
// Copyright 2017 Julio. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"sync"
"syscall"
"github.com/hanwen/go-fuse/fuse"
"github.com/hanwen/go-fuse/fuse/nodefs"
"r3stfs/client/remote"
"r3stfs/client/log"
"time"
)
// LoopbackFile delegates all operations back to an underlying os.file.
func NewLoopbackFile(f *os.File, restPath string, client *remote.Client) nodefs.File {
return &loopback{
file: f,
restPath: restPath,
remote: client,
}
}
type loopback struct {
file *os.File
restPath string //path passed in urls
remote *remote.Client
// os.file is not threadsafe. Although fd themselves are
// constant during the lifetime of an open file, the OS may
// reuse the fd number after it is closed. When open races
// with another close, they may lead to confusion as which
// file gets written in the end.
lock sync.Mutex
}
func (f *loopback) InnerFile() nodefs.File {
return nil
}
func (f *loopback) SetInode(n *nodefs.Inode) {
}
func (f *loopback) String() string {
return fmt.Sprintf("loopback(%s)", f.file.Name())
}
func (f *loopback) Read(buf []byte, off int64) (res fuse.ReadResult, status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", res, status)
} else {
log.Return(res, status)
}
}()
f.lock.Lock()
// This is not racy by virtue of the kernel properly
// synchronizing the open/write/close.
r := fuse.ReadResultFd(f.file.Fd(), off, len(buf))
f.lock.Unlock()
return r, fuse.OK
}
func (f *loopback) Write(data []byte, off int64) (n uint32, status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", n, status)
} else {
log.Return(n, status)
}
}()
fmt.Println("writing: ", string(data))
f.lock.Lock()
nint, err := f.file.WriteAt(data, off)
if err != nil {
fmt.Println("ERROR WRITING: ", err)
}
f.lock.Unlock()
n, status = uint32(nint), fuse.ToStatus(err)
return
}
func (f *loopback) Release() {
status := fuse.OK
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR")
} else {
log.Return()
}
}()
//close file
f.lock.Lock()
f.file.Close()
f.lock.Unlock()
name := f.file.Name()
fileToSend, err := os.OpenFile(name, os.O_RDONLY, 0600)
if err != nil {
fmt.Println("err", err)
status = fuse.ToStatus(err)
return
}
fmt.Println("filename: ", f.restPath)
_, err = f.remote.Put(f.restPath, fileToSend)
if err != nil {
fmt.Println(err)
status = fuse.ToStatus(err)
}
}
func (f *loopback) Flush() (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
// Since Flush() may be called for each dup'd fd, we don't
// want to really close the file, we just want to flush. This
// is achieved by closing a dup'd fd.
newFd, err := syscall.Dup(int(f.file.Fd()))
f.lock.Unlock()
if err != nil {
return fuse.ToStatus(err)
}
err = syscall.Close(newFd)
return fuse.ToStatus(err)
}
func (f *loopback) Fsync(flags int) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
status = fuse.ToStatus(syscall.Fsync(int(f.file.Fd())))
f.lock.Unlock()
return
}
func (f *loopback) Flock(flags int) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
status = fuse.ToStatus(syscall.Flock(int(f.file.Fd()), flags))
f.lock.Unlock()
return
}
func (f *loopback) Truncate(size uint64) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
status = fuse.ToStatus(syscall.Ftruncate(int(f.file.Fd()), int64(size)))
f.lock.Unlock()
return
}
func (f *loopback) Chmod(mode uint32) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
status = fuse.ToStatus(f.file.Chmod(os.FileMode(mode)))
f.lock.Unlock()
return
}
func (f *loopback) Chown(uid uint32, gid uint32) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
f.lock.Lock()
status = fuse.ToStatus(f.file.Chown(int(uid), int(gid)))
f.lock.Unlock()
return
}
func (f *loopback) GetAttr(a *fuse.Attr) (status fuse.Status) {
log.Func(f.restPath)
defer func() {
if status != fuse.OK {
log.Return("ERROR", status)
} else {
log.Return(status)
}
}()
st := syscall.Stat_t{}
f.lock.Lock()
err := syscall.Fstat(int(f.file.Fd()), &st)
f.lock.Unlock()
if err != nil {
status = fuse.ToStatus(err)
return
}
a.FromStat(&st)
status = fuse.OK
return
}
// Utimens - file handle based version of loopbackFileSystem.Utimens()
func (f *loopback) Utimens(a *time.Time, m *time.Time) (status fuse.Status) {
//TODO implement server side attr changes
status = fuse.ToStatus(os.Chtimes(f.file.Name(), *a, *m))
return
}
// Allocate implemented in files_linux.go and files_darwin.go
|
2539c357c354d41dde86d9b44f89b9b1a10b481c
|
{
"blob_id": "2539c357c354d41dde86d9b44f89b9b1a10b481c",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-26T06:11:58",
"content_id": "4ab592ba3a30840248a5959164452e8c2fa6bf50",
"detected_licenses": [
"MIT"
],
"directory_id": "c7e45b3b5334ceeaf61df5c1e05c10853efeea00",
"extension": "go",
"filename": "files.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103901229,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 5418,
"license": "MIT",
"license_type": "permissive",
"path": "/client/files.go",
"provenance": "stack-edu-0017.json.gz:181577",
"repo_name": "ear7h/r3stfs",
"revision_date": "2018-03-26T06:11:58",
"revision_id": "aed8775c11fd3acdfcb4bc035efa9078e93b6668",
"snapshot_id": "d14d9236121b9483ca0c44bb20205335023f7424",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ear7h/r3stfs/aed8775c11fd3acdfcb4bc035efa9078e93b6668/client/files.go",
"visit_date": "2021-09-10T12:17:33.060830",
"added": "2024-11-18T21:56:09.748820+00:00",
"created": "2018-03-26T06:11:58",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
/*
This file belongs to Ashes.
See LICENSE file in root folder.
*/
#include "Core/D3D11DisplayMode.hpp"
#include "Core/D3D11Display.hpp"
#include "ashesd3d11_api.hpp"
namespace ashes::d3d11
{
DisplayModeKHR::DisplayModeKHR( VkDisplayKHR display
, VkDisplayModeCreateInfoKHR createInfo )
: m_display{ display }
, m_desc{ get( m_display )->getDesc( createInfo.parameters ) }
{
}
DisplayModeKHR::~DisplayModeKHR()
{
}
VkDisplayPlaneCapabilitiesKHR DisplayModeKHR::getDisplayPlaneCapabilities( uint32_t planeIndex )
{
VkExtent2D defaultExt{ get( m_display )->getExtent() };
VkOffset2D defaultMinPos{};
VkOffset2D defaultMaxPos{};
VkDisplayPlaneCapabilitiesKHR const result
{
VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
defaultMinPos,
defaultMaxPos,
defaultExt,
defaultExt,
defaultMinPos,
defaultMaxPos,
defaultExt,
defaultExt,
};
return result;
}
}
|
cbabb68ff1eca09f8f9da8bf0a89350b01643902
|
{
"blob_id": "cbabb68ff1eca09f8f9da8bf0a89350b01643902",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-20T16:42:55",
"content_id": "e0a593b3522a19bfc3cfd95af271594b4dbc273c",
"detected_licenses": [
"MIT"
],
"directory_id": "ce37a5b4208319a6e917447f89f4930224e88f42",
"extension": "cpp",
"filename": "D3D11DisplayMode.cpp",
"fork_events_count": 16,
"gha_created_at": "2018-01-06T11:40:03",
"gha_event_created_at": "2023-07-20T16:42:57",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 116478178,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 900,
"license": "MIT",
"license_type": "permissive",
"path": "/source/ashes/renderer/D3D11Renderer/Core/D3D11DisplayMode.cpp",
"provenance": "stack-edu-0004.json.gz:482121",
"repo_name": "DragonJoker/Ashes",
"revision_date": "2023-06-23T23:10:30",
"revision_id": "6ceaf2b452c9778cbeafc8fb52ad97f8a02d4997",
"snapshot_id": "916e63a759b2130d65ae40f3cfdd3d896774894b",
"src_encoding": "UTF-8",
"star_events_count": 284,
"url": "https://raw.githubusercontent.com/DragonJoker/Ashes/6ceaf2b452c9778cbeafc8fb52ad97f8a02d4997/source/ashes/renderer/D3D11Renderer/Core/D3D11DisplayMode.cpp",
"visit_date": "2023-08-03T07:04:25.952879",
"added": "2024-11-18T21:53:44.345689+00:00",
"created": "2023-06-23T23:10:30",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz"
}
|
//
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Curve_Polyline.h"
#include <assert.h>
#include "Polyline.h"
using namespace Urho3D;
String Curve_Polyline::iconTexture = "Textures/Icons/Curve_Polyline.png";
Curve_Polyline::Curve_Polyline(Context* context) :
IoComponentBase(context, 2, 1)
{
SetName("Polyline");
SetFullName("Construct Polyline");
SetDescription("Construct a polyline from a vertex list");
SetGroup(IoComponentGroup::MESH);
SetSubgroup("Primitive");
inputSlots_[0]->SetName("Vertices");
inputSlots_[0]->SetVariableName("V");
inputSlots_[0]->SetDescription("List of coordinates of vertices");
inputSlots_[0]->SetVariantType(VariantType::VAR_VECTOR3);
inputSlots_[0]->SetDataAccess(DataAccess::LIST);
inputSlots_[1]->SetName("Close");
inputSlots_[1]->SetVariableName("C");
inputSlots_[1]->SetDescription("Close the curve");
inputSlots_[1]->SetVariantType(VariantType::VAR_BOOL);
inputSlots_[1]->SetDataAccess(DataAccess::ITEM);
inputSlots_[1]->SetDefaultValue(false);
inputSlots_[1]->DefaultSet();
outputSlots_[0]->SetName("Polyline");
outputSlots_[0]->SetVariableName("P");
outputSlots_[0]->SetDescription("Constructed polyline");
outputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);
outputSlots_[0]->SetDataAccess(DataAccess::ITEM);
}
void Curve_Polyline::SolveInstance(
const Vector<Variant>& inSolveInstance,
Vector<Variant>& outSolveInstance
)
{
assert(inSolveInstance.Size() == inputSlots_.Size());
assert(outSolveInstance.Size() == outputSlots_.Size());
///////////////////
// VERIFY & EXTRACT
// Verify input slot 0
if (inSolveInstance[0].GetType() != VariantType::VAR_VARIANTVECTOR) {
URHO3D_LOGWARNING("V must be a list of points (Vector3).");
outSolveInstance[0] = Variant();
return;
}
VariantVector varVec = inSolveInstance[0].GetVariantVector();
if (varVec.Size() < 2) {
URHO3D_LOGWARNING("V must contain at least 2 points (Vector3).");
outSolveInstance[0] = Variant();
return;
}
for (unsigned i = 0; i < varVec.Size(); ++i) {
if (varVec[i].GetType() != VariantType::VAR_VECTOR3) {
URHO3D_LOGWARNING("V must list only points (Vector3).");
outSolveInstance[0] = Variant();
return;
}
}
// Verify input slot 1
if (inSolveInstance[1].GetType() != VariantType::VAR_BOOL) {
URHO3D_LOGWARNING("C must be a boolean.");
outSolveInstance[0] = Variant();
return;
}
bool close = inSolveInstance[1].GetBool();
VariantVector verts = inSolveInstance[0].GetVariantVector();
if (close)
{
/*
* Subtle bug alert!
* If we do
* verts.Push(verts[0]) that last Variant ends up not having
* type VAR_VECTOR3, even though verts[0] is a Variant that does have type VAR_VECTOR3.
* I don't know why this happens.
*/
Vector3 start = verts[0].GetVector3();
if (start != verts[verts.Size() - 1].GetVector3())
{
verts.Push(start);
}
}
outSolveInstance[0] = Polyline_Make(verts);
}
|
2c5a47d025fd8b41c25b20a090d9fd7edb865227
|
{
"blob_id": "2c5a47d025fd8b41c25b20a090d9fd7edb865227",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-31T20:09:08",
"content_id": "39a69dcaf260f7be7b7d63b72d30d51903fad29f",
"detected_licenses": [
"MIT"
],
"directory_id": "4f267de5c3abde3eaf3a7b89d71cd10d3abad87c",
"extension": "cpp",
"filename": "Curve_Polyline.cpp",
"fork_events_count": 17,
"gha_created_at": "2017-02-28T17:07:02",
"gha_event_created_at": "2022-02-01T13:45:33",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 83458576,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4120,
"license": "MIT",
"license_type": "permissive",
"path": "/Components/Curve_Polyline.cpp",
"provenance": "stack-edu-0002.json.gz:160431",
"repo_name": "MeshGeometry/IogramSource",
"revision_date": "2018-01-31T20:09:08",
"revision_id": "a82302ccf96177dde3358456c6dc8e597c30509c",
"snapshot_id": "5f627ca3102e85cd4f16801f5ee67557605eb506",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/MeshGeometry/IogramSource/a82302ccf96177dde3358456c6dc8e597c30509c/Components/Curve_Polyline.cpp",
"visit_date": "2022-02-10T19:19:18.984763",
"added": "2024-11-18T21:28:59.131696+00:00",
"created": "2018-01-31T20:09:08",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
<?php
use PHPUnit\Framework\TestCase;
use Roolith\Template\Engine\Interfaces\ViewInterface;
use Roolith\Template\Engine\View;
class ViewTest extends TestCase
{
protected $viewPath = __DIR__ . '/viewsForTest';
private function accessProtected($obj, $prop)
{
try {
$reflection = new ReflectionClass($obj);
$property = $reflection->getProperty($prop);
$property->setAccessible(true);
return $property->getValue($obj);
} catch (ReflectionException $e) {
return false;
}
}
private function getInstance()
{
return new View($this->viewPath);
}
public function testShouldSetViewFolder()
{
$viewInstance = new View($this->viewPath);
$this->assertInstanceOf(ViewInterface::class, $viewInstance);
$this->assertEquals($this->viewPath, $this->accessProtected($viewInstance, 'viewFolder'));
}
public function testShouldEscapeVariable()
{
$viewInstance = $this->getInstance();
$viewInstance->setTemplateData(['test' => 'aaa']);
$this->assertEquals('aaa', $viewInstance->escape('test'));
$this->expectException(\Roolith\Template\Engine\Exceptions\Exception::class);
$viewInstance->escape('not');
}
public function testShouldAddSlashBeforeUrl()
{
$viewInstance = $this->getInstance();
$url = 'assets/something.txt';
$this->assertEquals('/' . $url, $viewInstance->url($url));
}
public function testShouldCompileViewFile()
{
$viewInstance = $this->getInstance();
$data = [
'content' => 'home content',
'title' => 'home page',
];
$result = $viewInstance->compile('home', $data);
$this->assertNotEmpty($result);
$this->assertStringContainsString('home page', $result);
$this->assertStringContainsString('home content', $result);
$this->expectException(\Roolith\Template\Engine\Exceptions\Exception::class);
$viewInstance->compile('file-doesnt-exists');
}
}
|
d77e8f89c8a6d7db751543160ffab0e94cf32dc4
|
{
"blob_id": "d77e8f89c8a6d7db751543160ffab0e94cf32dc4",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-01T09:26:14",
"content_id": "c14d66271c4680b3769f1d3f3581bb536aec35b4",
"detected_licenses": [
"MIT"
],
"directory_id": "934e2c8274e56b3a0997efeee37947369b78defe",
"extension": "php",
"filename": "ViewTest.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 289756344,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2101,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/ViewTest.php",
"provenance": "stack-edu-0050.json.gz:401503",
"repo_name": "im4aLL/roolith-template-engine",
"revision_date": "2020-09-01T09:26:14",
"revision_id": "3097a1e65f83522039d4eac788c603674db02a9a",
"snapshot_id": "68e31f10945dbabbf1151a181b95d7afbaebd70b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/im4aLL/roolith-template-engine/3097a1e65f83522039d4eac788c603674db02a9a/tests/ViewTest.php",
"visit_date": "2022-12-10T02:45:35.667492",
"added": "2024-11-18T23:23:10.664758+00:00",
"created": "2020-09-01T09:26:14",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
+++
title = "Research Software Seminar Series"
description = "Nordic RSE – Research Software Engineers in the Nordics - Research Software Seminar Series"
template = "seminar-series.html"
[extra]
subtitle = ""
+++
Are you developing software or tools that are driven by research/engineering in
either academia or industry? Do you need to network, share knowledge and
experiences with your peers? Then you came to the right page: Nordic-RSE
invites everyone interested to participate in Research Software Seminar Series:
## Timing
We aim at having a talk every month.
The time for each seminar will be set by the speaker.
We are inviting everyone to suggest topics and/or speakers for this series [here](https://github.com/nordic-rse/nordic-rse.github.io/issues).
## Format
As an example, events can be 60 min (40+20 discussion) or 30 min (15+15
discussion). Events could be talks, demos, discussion, debates, and so on.
Events are hosted with HackMD for public asynchronous discussion. We will
provide mentoring for speakers.
We would like this series to be an informal space also for exchanging ideas and
experiences, learning something new, and networking with people of the same
interest group. You do not have to be a Research Software Engineer or a
Researcher or a Software Engineer nor do you have to be in or be related to the
Nordics. Everyone interested in RSE activities is welcome and encouraged to
participate!
The Nordic-RSE team will provide support and infrastructure.
---
## Upcoming seminars
We will publish upcoming seminar topics and abstracts here as soon as they are confirmed.
You can see topics in planning and add your own suggestions on our [Issues page](https://github.com/nordic-rse/nordic-rse.github.io/issues).
## Past seminars
We will publish past seminar topics and their recordings here as soon as they are available.
### May 2023: AI Regulation in the EU – challenges and latest developments
- Speaker: Béatrice Schütte ([Faculty of Law, University of Helsinki](https://researchportal.helsinki.fi/en/persons/b%C3%A9atrice-sch%C3%BCtte), University of Lapland, [Ethics board of the Finnish Center for Artificial Intelligence](https://fcai.fi/ethics-advisory-board))
- 2023-05-24, 13:00 CEST [convert to your time zome](https://arewemeetingyet.com/Helsinki/2023-05-24/14:00) | [add to your calendar](https://link.webropolsurveys.com/EP/3757A49B24DBED6D)
- Collaborative document (contains zoom connection details): <https://hackmd.io/@nordic-rse/seminar-May-2023>
- Abstract: The EU institutions are currently preparing a regulation on Artificial Intelligence (AI). It is a complex process: The continuous and rapid technological development makes it difficult to stay on track – the law is always behind the technology.
This presentation will outline the latest developments on the path to regulating AI and point out critical aspects.
The event will be online and include a 20-30 minute talk, followed by informal discussion.
### April 2023: What a Research Software Engineering group at a Nordic university looks like
- Speaker: Richard Darst, [Aalto Scicomp](https://scicomp.aalto.fi/)
- 2023-04-05, 13:00 CET [convert to your time zome](https://arewemeetingyet.com/Helsinki/2023-04-05/14:00)
- Hackmd (contains connection details): <https://hackmd.io/@nordic-rse/seminar-march-2023>
- Abstract: What does a Research Software Engineering (RSE) group at a Nordic university look like? Aalto RSE supports the whole university, and Richard Darst and other Aalto RSE members will discuss the history behind their team, the way it works, future prospects, and lessons for others. This talk will focus on the administrative side of things, and discussion will focus on what one should know to reproduce this work at other universities.
Aalto University is the leading technical university in Finland. Started in 2020, Aalto RSE now serves the entire university in computing, data, and software problems. They work as part of Science-IT, which is effectively the local "HPC team". They have good connections to the local IT Services, Data Agents, and other research services.
### November 2022: Chapel: Making Parallel Programming Productive, from laptops to supercomputers
- Speaker: [Brad Chamberlain](https://homes.cs.washington.edu/~bradc/), HPE
- 2022-11-30, 16:00 CET [convert to your time zome](https://arewemeetingyet.com/Helsinki/2022-11-30/17:00)
- Hackmd (contains connection details): <https://hackmd.io/@nordic-rse/seminar-november-2022>
- Abstract:
Over the past few decades, a gulf has existed between 'mainstream' programming languages—like Python, Java, C++, Rust, or Swift—and technologies used in practice for programming supercomputers—like MPI, OpenSHMEM, OpenMP, CUDA, OpenCL, or OpenACC.
This gulf results in making High Performance Computing something of a specialized skill that may not be readily available to the general programmer or applied computational scientist.
In some ways, the problem has even gotten worse over time, as the end of Moore's law has led to building supercomputers using manycore processors and computational accelerators like GPUs.
In this talk, I will introduce [Chapel](https://chapel-lang.org/), an open-source language created to bridge this gulf.
Chapel strives to support code that is similarly readable/writeable as Python, yet without sacrificing the portability and scalable performance required to utilize supercomputers effectively.
Specifically, I will provide motivation for Chapel, present some of its unique features and themes, introduce flagship applications of Chapel, and give a glimpse into our team's current priorities.
#### April 2022: Journal of Open Source Software – Developing a Software Review Community
- Speaker: [Arfon Smith](https://www.arfon.org/)
- 2022-04-27, 13 -- 14 CEST [convert to your time zone](https://arewemeetingyet.com/Helsinki/2022-04-27/14:00)
- [recording](https://youtu.be/Dvmi9tq550Q)
- Hackmd (contains connection details): <https://hackmd.io/@nordic-rse/joss-talk>
- Abstract: In this presentation, I'll introduce the Journal of Open Source Software, a community-run diamond open access journal for publishing open source software packages. I'll share some of the motivations behind the journal, how it works, and how the journal has evolved over the last six years of operations.
#### April 2022: Motivating specialist services in universities (or, "Starting a RSE group")
- Speaker: Richard Darst, [Aalto Scientific Computing](https://scicomp.aalto.fi/)
- 2022-04-06, 14 -- 15 CEST [convert to your time zone](https://arewemeetingyet.com/Helsinki/2022-04-06/15:00)
- Hackmd: <https://hackmd.io/@nordic-rse/starting-rse-group>
- Summary: I've gotten several requests about "what is your advice for
starting a RSE service", and I will lead a discussion on this in the
seminar series.
#### February 2022: The importance and role of community in open source
- Speaker: [Logan Kilpatrick](https://twitter.com/officiallogank), JuliaLang
- 2022-02-16, 17-18 CET [convert to your time zone](https://arewemeetingyet.com/Stockholm/2022-02-16/17:00)
- Hackmd (contains connection details): <https://hackmd.io/@nordic-rse/community_oss>
- [recording](https://youtu.be/R4-M1YGm6z8)
Open Source is more than code. In order for an Open Source project to thrive, it must put in place mechanism to attract and reward non-code contributions. In this talk, we will go over how the Julia community attracts and rewards these contributions as well as how other projects can learn from our experience.
#### January 2022: Developing and distributing in-house R-packages
- Speaker: [Athanasia Monika Mowinckel](https://drmowinckels.io/about/), University of Oslo
- 2022-01-20, 13-14 CET [convert to your timezone](https://arewemeetingyet.com/Stockholm/2022-01-20/13:00)
- Hackmd notes: <https://hackmd.io/@nordic-rse/R_packaging>
- [slides](https://athanasiamo.github.io/talks/slides/2022.01.20-rse-pgk/#1)
- [recording](https://youtu.be/i2fnLtED86E)
R is mainly a statistical programming language than has been around for more than 20 years. In recent years, it has seen a large resurge in popularity, especially amongst researchers, for its powerful statistical backbone and open source practice. But R can be unfamiliar and intimidating for researchers used to a purely GUI based statistical tool. This talk will center around how I have developed in-house R tools to clean and handle in-house data, and how I have distributed these to work on multiple platforms.
#### November: Blurring the lines: Singularity containerisation of SLURM orchestrators
- Speaker: Frankie Robertson, University of Jyväskylä
- 2021-11-23, 13-15 CET [convert to your timezone](https://arewemeetingyet.com/Stockholm/2021-11-23/13:00)
- Hackmd notes: <https://hackmd.io/@nordic-rse/singularity_containerization>
- [Recording](https://youtu.be/revklPtujtE)
While [SLURM](https://slurm.schedmd.com) itself provides tools for job
orchestration like job arrays, high level tools like
[Snakemake](https://snakemake.github.io/) and [Ray](https://www.ray.io/) are
cluster agnostic and can either make use of SLURM or run on a laptop. To make
Snakemake and Ray to run within Singularity, I present
[singreqrun](https://github.com/frankier/singreqrun), which works by requesting
the host runs programs on behalf of the container.
The talk doubles as an introduction to Snakemake and Ray. After some brief
background on the main tools (Singularity, SLURM, Snakemake and Ray), we
proceed to shell code-along to run the following examples:
* Snakemake for heterogeneous (mixture of CPU and GPU nodes) video corpus
processing + quick porting across HPC clusters
* Snakemake for text corpus processing including using extra Singularity
containers for utilities
* Ray for hyperparameter search
I end the talk by opening for discussion. Is this a good approach? Can we
improve upon it?
#### October 2021: I/O profiling and optimization.
- Speaker: Simo Tuomisto, [Aalto Scientific
Computing](https://scicomp.aalto.fi)
- Abstract: In computing, I/O bandwidth is just as much of a
consumable resource as CPU and memory. While on an individual scale
on one's own computer, this is often not the most pressing
consideration, on a cluster with shared storage (or very intensive
individual projects) it is actually very important to consider.
This talk presented lessons and tools that RSEs should have in
their toolbox, as we have learned at Aalto Scientific Computing over
the years.
- HackMD notes: <https://hackmd.io/@nordic-rse/io-monitoring-optimization>
* [Recording](https://youtu.be/mtKZbDtZ7PE)
#### September 2021: Combining Rust and Python: Why and How?
- Speaker: [Radovan Bast](https://bast.fr/), UiT The Arctic University of Norway
- 2021-09-14, 13-14 CEST [convert to your timezone](https://arewemeetingyet.com/Stockholm/2021-09-14/13:00)
- HackMD notes: <https://hackmd.io/@nordic-rse/rust-python>
* Blogpost: coming soon
* [Recording](https://youtu.be/UQF2Ez8GyL8)
#### August 2021: Package development in Julia
- Speaker: [Luca Ferranti](https://lucaferranti.github.io), University of Vaasa, Finland.
- 2021-08-18, 13-16 CEST [convert to your timezone](https://arewemeetingyet.com/Stockholm/2021-08-18/13:00).
- HackMD notes: <https://hackmd.io/@nordic-rse/package-development-julia>
[Julia](https://julialang.org/) is constantly gaining popularity both in academia and industry and it is thus an appealing programming language for research software engineers. This session will be a hands-on tutorial, which will cover the typical package development workflow in Julia. Topics covered include
- Creating a package from scratch
- Contributing to existing packages
- Tools to test and debug your packages
- Tools to document your packages
Moreover, Luca will share tips and tricks that have helped him making his workflow more efficient and hopefully will help you too.
The workshop will involve a lot of live coding and you are encouraged to follow along, check the setup instructions [here](https://hackmd.io/@nordic-rse/package-development-julia).
* [Blogpost](https://nordic-rse.org/blog/seminar-report-julia-package/)
* [Recording](https://www.youtube.com/watch?v=oHsLmaHSHd8)
|
060cd85c7fa2cd2b1ac75881ef2e5cf1c0b57fc0
|
{
"blob_id": "060cd85c7fa2cd2b1ac75881ef2e5cf1c0b57fc0",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-08T13:02:44",
"content_id": "ed1da448eab56d35efc7c34ecc796f2dc5275b6a",
"detected_licenses": [
"MIT"
],
"directory_id": "cc4063e964f0adef72a733a7f0c3addfb2203461",
"extension": "md",
"filename": "_index.md",
"fork_events_count": 24,
"gha_created_at": "2018-04-07T16:09:10",
"gha_event_created_at": "2023-08-08T13:02:46",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 128545485,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 12291,
"license": "MIT",
"license_type": "permissive",
"path": "/content/events/seminar-series/_index.md",
"provenance": "stack-edu-markdown-0000.json.gz:156359",
"repo_name": "nordic-rse/nordic-rse.github.io",
"revision_date": "2023-08-08T13:02:44",
"revision_id": "c87bf8a75af4525265527ab15cafe4cbe0dc943b",
"snapshot_id": "62a29f34ef937a9ff5a0294076a2749bcf830fd9",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/nordic-rse/nordic-rse.github.io/c87bf8a75af4525265527ab15cafe4cbe0dc943b/content/events/seminar-series/_index.md",
"visit_date": "2023-08-08T22:01:00.530062",
"added": "2024-11-18T23:09:18.187260+00:00",
"created": "2023-08-08T13:02:44",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz"
}
|
/**
* Created by nijk on 14/03/2016.
*/
export enum SearchFilterFieldNames {
'contactInformation/emailAddress',
'contactInformation/telephoneNumber',
'displayName',
'name/givenName',
'name/familyName',
'userName'
}
export enum SearchFilterOperators {
sw,
co,
eq,
and,
or
}
|
0b0a09a48087ad55ef37028632eba3564076bf61
|
{
"blob_id": "0b0a09a48087ad55ef37028632eba3564076bf61",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-14T11:26:35",
"content_id": "0d36fc5f274d1f96ab592c3527acda777954ccfa",
"detected_licenses": [
"MIT"
],
"directory_id": "da703a9e98d7ce7c0068c05de159331e0e8cd261",
"extension": "ts",
"filename": "search.enums.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 53519836,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 321,
"license": "MIT",
"license_type": "permissive",
"path": "/src/app/search/search.enums.ts",
"provenance": "stack-edu-0073.json.gz:898914",
"repo_name": "nijk/forge-rock-exercise",
"revision_date": "2016-03-14T11:26:35",
"revision_id": "c7f85f294d414d048c9607d9a0a7f8c1dc2a803c",
"snapshot_id": "a5b24747d047ca8f69f1f337b8340fde55d4b83a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nijk/forge-rock-exercise/c7f85f294d414d048c9607d9a0a7f8c1dc2a803c/src/app/search/search.enums.ts",
"visit_date": "2021-01-10T06:25:48.914839",
"added": "2024-11-18T21:19:37.481274+00:00",
"created": "2016-03-14T11:26:35",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
// Copyright (c) 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMECAST_GRAPHICS_ACCESSIBILITY_PARTIAL_MAGNIFICATION_CONTROLLER_H_
#define CHROMECAST_GRAPHICS_ACCESSIBILITY_PARTIAL_MAGNIFICATION_CONTROLLER_H_
#include <memory>
#include "base/macros.h"
#include "chromecast/graphics/accessibility/magnification_controller.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/events/event_handler.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/widget/widget_observer.h"
namespace ui {
class Layer;
} // namespace ui
namespace chromecast {
// Controls the chromecast screen magnifier, which is a small area of the screen
// which is zoomed in. The zoomed area follows the mouse cursor when enabled.
class PartialMagnificationController : public MagnificationController,
public ui::EventHandler,
public aura::WindowObserver,
public views::WidgetObserver {
public:
explicit PartialMagnificationController(aura::Window* root_window);
~PartialMagnificationController() override;
// Turns the partial screen magnifier feature on or off.
// Note that the magnifier itself is displayed when it is both enabled
// and active. Magnification becomes active on a finger press.
void SetEnabled(bool enabled) override;
bool IsEnabled() const override;
// Adjust the scale of magnification.
void SetMagnificationScale(float magnification_scale) override;
// Switch PartialMagnified RootWindow to |new_root_window|. This does
// following:
// - Remove the magnifier from the current root window.
// - Create a magnifier in the new root_window |new_root_window|.
// - Switch the target window from current window to |new_root_window|.
void SwitchTargetRootWindowIfNeeded(aura::Window* new_root_window);
private:
friend class PartialMagnificationControllerTestApi;
class BorderRenderer;
class ContentMask;
// ui::EventHandler:
void OnTouchEvent(ui::TouchEvent* event) override;
// WindowObserver:
void OnWindowDestroying(aura::Window* window) override;
// WidgetObserver:
void OnWidgetDestroying(views::Widget* widget) override;
// Enables or disables the actual magnifier window.
void SetActive(bool active);
// Create or close the magnifier window.
void CreateMagnifierWindow(aura::Window* root_window);
void CloseMagnifierWindow();
// Removes this as an observer of the zoom widget and the root window.
void RemoveZoomWidgetObservers();
float magnification_scale_;
bool is_enabled_ = false;
bool is_active_ = false;
aura::Window* root_window_;
// The host widget is the root parent for all of the layers. The widget's
// location follows the mouse, which causes the layers to also move.
views::Widget* host_widget_ = nullptr;
// Draws the background with a zoom filter applied.
std::unique_ptr<ui::Layer> zoom_layer_;
// Draws an outline that is overlayed on top of |zoom_layer_|.
std::unique_ptr<ui::Layer> border_layer_;
// Draws a multicolored black/white/black border on top of |border_layer_|.
// Also draws a shadow around the border. This must be ordered after
// |border_layer_| so that it gets destroyed after |border_layer_|, otherwise
// |border_layer_| will have a pointer to a deleted delegate.
std::unique_ptr<BorderRenderer> border_renderer_;
// Masks the content of |zoom_layer_| so that only a circle is magnified.
std::unique_ptr<ContentMask> zoom_mask_;
// Masks the content of |border_layer_| so that only a circle outline is
// drawn.
std::unique_ptr<ContentMask> border_mask_;
DISALLOW_COPY_AND_ASSIGN(PartialMagnificationController);
};
} // namespace chromecast
#endif // CHROMECAST_GRAPHICS_ACCESSIBILITY_PARTIAL_MAGNIFICATION_CONTROLLER_H_
|
39cc04f9b8cab93a18e7ba665c3b267cf41ada9d
|
{
"blob_id": "39cc04f9b8cab93a18e7ba665c3b267cf41ada9d",
"branch_name": "refs/heads/castanets_76_dev",
"committer_date": "2021-08-11T05:45:21",
"content_id": "356e7eaaa99c168cda4b867d5fe21d6a0eea0e75",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "04b1803adb6653ecb7cb827c4f4aa616afacf629",
"extension": "h",
"filename": "partial_magnification_controller.h",
"fork_events_count": 49,
"gha_created_at": "2018-03-16T08:07:37",
"gha_event_created_at": "2022-10-16T19:31:26",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 125484161,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3994,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/chromecast/graphics/accessibility/partial_magnification_controller.h",
"provenance": "stack-edu-0004.json.gz:395749",
"repo_name": "Samsung/Castanets",
"revision_date": "2021-07-30T04:56:25",
"revision_id": "4896f732fc747dfdcfcbac3d442f2d2d42df264a",
"snapshot_id": "240d9338e097b75b3f669604315b06f7cf129d64",
"src_encoding": "UTF-8",
"star_events_count": 58,
"url": "https://raw.githubusercontent.com/Samsung/Castanets/4896f732fc747dfdcfcbac3d442f2d2d42df264a/chromecast/graphics/accessibility/partial_magnification_controller.h",
"visit_date": "2023-08-31T09:01:04.744346",
"added": "2024-11-18T21:19:17.728898+00:00",
"created": "2021-07-30T04:56:25",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz"
}
|
#include "Task.h"
#include "../Structure.h"
namespace v1
{
namespace TaskSystem
{
void Task::SetUID(uint in_uid)
{
uid = in_uid;
}
uint Task::GetUID() const
{
return uid;
}
uint Task::GetPriority() const
{
return priority;
}
TYPE Task::GetType() const
{
return type;
}
Structure * Task::From() const
{
return from;
}
Structure * Task::To() const
{
return to;
}
int Task::Fufill(int amount)
{
return fufilled += amount;
}
int Task::HasLeft()
{
return amount - fufilled;
}
ResourceName Task::GetResource() const
{
return resource;
}
int Task::GetAmount() const
{
return amount;
}
int Task::GetIndex() const
{
return index;
}
Task::Task(): type(TASK_TYPE::NONE), to(nullptr)
{
}
Task::Task(TYPE t) : type(t)
{
}
Task::Task(TYPE t, uint p, Structure * from, Structure * to) :
type(t), priority(p), from(from), to(to), index(0)
{
}
Task::Task(TYPE t, uint p, Structure * from, Structure * to, ResourceName resource, int amount) :
type(t), priority(p), from(from), to(to),
resource(resource), amount(amount), index(0)
{
}
Task::Task(TYPE t, uint p, Structure * from, Structure * to, ResourceName resource, int amount, int index) : type(t), priority(p), from(from), to(to),
resource(resource), amount(amount), index(index)
{
}
Task::Task(const Task & task) :
type(task.type), priority(task.priority), uid(task.uid),
from(task.from), to(task.to), resource(task.resource), amount(task.amount), index(task.index)
{
}
}
}
|
c687941ec64c8dc054d999ed192eb98e8b024223
|
{
"blob_id": "c687941ec64c8dc054d999ed192eb98e8b024223",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-12T20:49:13",
"content_id": "bcf3ce62d4c8e54a5f78037444c9e0d47c3aff0e",
"detected_licenses": [
"MIT"
],
"directory_id": "2b5fb4af4abcfa8c03c62c162534aadfa2802d6b",
"extension": "cpp",
"filename": "Task.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 118777372,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1585,
"license": "MIT",
"license_type": "permissive",
"path": "/Game/Scripts/task_system/Task.cpp",
"provenance": "stack-edu-0006.json.gz:354059",
"repo_name": "JohnHonkanen/ProjectM",
"revision_date": "2018-04-12T20:49:13",
"revision_id": "881171ad749e8fe7db6188ee9486239a37256569",
"snapshot_id": "08691b0c350268f1f7e74d1d03ae456188dfe0de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JohnHonkanen/ProjectM/881171ad749e8fe7db6188ee9486239a37256569/Game/Scripts/task_system/Task.cpp",
"visit_date": "2021-03-27T11:14:14.264184",
"added": "2024-11-19T00:23:02.709031+00:00",
"created": "2018-04-12T20:49:13",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
package scienceWork.objects.machineLearning.mlSettings;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.TermCriteria;
import org.opencv.ml.ANN_MLP;
import org.opencv.ml.SVM;
import scienceWork.objects.constants.Settings;
import scienceWork.objects.data.BOWVocabulary;
public class SettingsANNMLP {
public static void setSettings(ANN_MLP annMlp) {
Mat layers = new Mat(1,4, CvType.CV_32S);
layers.put(0,0, Settings.getCountBOWClusters());
layers.put(0,1, BOWVocabulary.vocabularies.size()*2);
layers.put(0,2, BOWVocabulary.vocabularies.size()*2);
layers.put(0,3, BOWVocabulary.vocabularies.size());
// layers.put(0,4, BOWVocabulary.vocabularies.size());
annMlp.setLayerSizes(layers);
annMlp.setActivationFunction(ANN_MLP.GAUSSIAN, 1, 1);
annMlp.setTrainMethod(ANN_MLP.BACKPROP, 0.01, 0.01);
annMlp.setTermCriteria(new TermCriteria(TermCriteria.EPS, 100000, 0.00001));
}
// enum ActivationFunctions {
// IDENTITY = 0,
// SIGMOID_SYM = 1,
// GAUSSIAN = 2
// }
// possible activation functions More...
//
// enum Flags {
// UPDATE_MODEL = 1,
// RAW_OUTPUT =1,
// COMPRESSED_INPUT =2,
// PREPROCESSED_INPUT =4
// }
// Predict options. More...
//
// enum TrainFlags {
// UPDATE_WEIGHTS = 1,
// NO_INPUT_SCALE = 2,
// NO_OUTPUT_SCALE = 4
// }
// Train options. More...
//
// enum TrainingMethods {
// BACKPROP =0,
// RPROP =1
// }
// Available training methods. More...
}
|
2d9c57573fc0a4fdcbe63d22b26cad11b1a3b46b
|
{
"blob_id": "2d9c57573fc0a4fdcbe63d22b26cad11b1a3b46b",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-14T14:20:05",
"content_id": "9d3a6e1abdf17cbc84978c416d591628162b116f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "647caba1dfc9d144ebb3d42d5028d8c21fdf5e52",
"extension": "java",
"filename": "SettingsANNMLP.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83908203,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1624,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/scienceWork/objects/machineLearning/mlSettings/SettingsANNMLP.java",
"provenance": "stack-edu-0023.json.gz:266457",
"repo_name": "fev0ks/MyProject",
"revision_date": "2018-06-14T14:20:05",
"revision_id": "8d4d3ddee06eff9666f23053e6bfce0025073853",
"snapshot_id": "47cc77781b084fd5c1ca812229a5a8b16e5c63b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fev0ks/MyProject/8d4d3ddee06eff9666f23053e6bfce0025073853/src/scienceWork/objects/machineLearning/mlSettings/SettingsANNMLP.java",
"visit_date": "2021-01-17T08:25:29.671452",
"added": "2024-11-18T22:43:43.106853+00:00",
"created": "2018-06-14T14:20:05",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
import * as themes from "../themes/index";
export type IGoogleMapsAPI = typeof google.maps;
export type IMap = google.maps.Map;
export type IMapOptions = google.maps.MapOptions;
export type ILatLng = google.maps.LatLng;
export type IControlPosition = keyof typeof google.maps.ControlPosition;
export type IScaleControlStyle = google.maps.ScaleControlStyle;
export type IMapTypeControlOptions = google.maps.MapTypeControlOptions;
export type IMapTypeId = google.maps.MapTypeId;
export type IMapRestriction = google.maps.MapRestriction;
export type IStreetViewPanorama = google.maps.StreetViewPanorama;
export type IMapTypeStyle = google.maps.MapTypeStyle;
export type IMarker = google.maps.Marker;
export type IPolyline = google.maps.Polyline;
export type IPolygon = google.maps.Polygon;
export type IRectangle = google.maps.Rectangle;
export type ICircle = google.maps.Circle;
export type IMarkerOptions = google.maps.MarkerOptions;
export type IPolylineOptions = google.maps.PolylineOptions;
export type IPolygonOptions = google.maps.PolygonOptions;
export type IRectangleOptions = google.maps.RectangleOptions;
export type ICircleOptions = google.maps.CircleOptions;
export type ITheme = keyof typeof themes;
|
1f253082f74b452b03addb50d8e0e3788332271b
|
{
"blob_id": "1f253082f74b452b03addb50d8e0e3788332271b",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-12T02:40:25",
"content_id": "c335075ea701ded42d435b0850faf685222d46e3",
"detected_licenses": [
"MIT"
],
"directory_id": "747cf3acdf1383dfe0590518388fc0b71576d476",
"extension": "ts",
"filename": "index.ts",
"fork_events_count": 0,
"gha_created_at": "2021-08-07T04:57:03",
"gha_event_created_at": "2021-08-07T04:57:04",
"gha_language": null,
"gha_license_id": null,
"github_id": 393582775,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1215,
"license": "MIT",
"license_type": "permissive",
"path": "/src/@types/index.ts",
"provenance": "stack-edu-0075.json.gz:505627",
"repo_name": "dblythy/vue3-google-map",
"revision_date": "2021-06-12T02:40:25",
"revision_id": "16191a819cabf578efd650cbc767220b83481c42",
"snapshot_id": "cd7b9342dcb62f4f7916db2948e533b892b68e64",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dblythy/vue3-google-map/16191a819cabf578efd650cbc767220b83481c42/src/@types/index.ts",
"visit_date": "2023-07-10T01:06:04.896848",
"added": "2024-11-18T20:59:29.485622+00:00",
"created": "2021-06-12T02:40:25",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
#!/bin/sh
# Check fault injection along with signal injection.
. "${srcdir=.}/scno_tampering.sh"
run_strace -a12 -echdir,exit_group -einject=chdir:error=ENOENT:signal=USR1 \
"../$NAME"
match_diff
|
69fa657c706a6d329eaf61a3d83f084e2f0484ee
|
{
"blob_id": "69fa657c706a6d329eaf61a3d83f084e2f0484ee",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-31T01:54:37",
"content_id": "1fe46126da237769fb6233829ebca721a6cf9dbd",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "473fc28d466ddbe9758ca49c7d4fb42e7d82586e",
"extension": "test",
"filename": "qual_inject-error-signal.test",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237205127,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 199,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/app/src/main/java/com/syd/source/aosp/external/strace/tests/qual_inject-error-signal.test",
"provenance": "stack-edu-0068.json.gz:633909",
"repo_name": "lz-purple/Source",
"revision_date": "2020-01-31T01:54:37",
"revision_id": "e2745b756317aac3c7a27a4c10bdfe0921a82a1c",
"snapshot_id": "a7788070623f2965a8caa3264778f48d17372bab",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/lz-purple/Source/e2745b756317aac3c7a27a4c10bdfe0921a82a1c/app/src/main/java/com/syd/source/aosp/external/strace/tests/qual_inject-error-signal.test",
"visit_date": "2020-12-23T17:03:12.412572",
"added": "2024-11-19T00:41:30.434932+00:00",
"created": "2020-01-31T01:54:37",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
<?php
namespace App\Twig;
use App\Entity\User;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
class TruncateTextExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
// If your filter generates SAFE HTML, you should add a third
// parameter: ['is_safe' => ['html']]
// Reference: https://twig.symfony.com/doc/2.x/advanced.html#automatic-escaping
new TwigFilter('truncateText', [$this, 'truncateText']),
];
}
public function truncateText($text, $words = 30, $end = '...')
{
$array = explode(' ', $text);
$result = '';
if (count($array)<$words) {
return implode(' ', $array);
} else {
for ($i=0; $i<$words; $i++) {
$result = $result . ' ' . $array[$i];
}
return $result . $end;
}
}
}
|
5ce09998907492a2aa59166a0307ffc45973aaac
|
{
"blob_id": "5ce09998907492a2aa59166a0307ffc45973aaac",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-30T16:06:24",
"content_id": "4bc5a94db7f0846e942405f36310205074ee74c0",
"detected_licenses": [
"MIT"
],
"directory_id": "67af33f62f066062fd8e878f0ae5e372e046c881",
"extension": "php",
"filename": "TruncateTextExtension.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 944,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Twig/TruncateTextExtension.php",
"provenance": "stack-edu-0052.json.gz:862645",
"repo_name": "Philippe-Naveilhan/Coach-Peter",
"revision_date": "2020-10-30T16:06:24",
"revision_id": "dcf28136252e4e1aa7bfe2ce6ac615fb560f690b",
"snapshot_id": "b24d02673de1021a65a09b082c92b661df6a08da",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Philippe-Naveilhan/Coach-Peter/dcf28136252e4e1aa7bfe2ce6ac615fb560f690b/src/Twig/TruncateTextExtension.php",
"visit_date": "2023-01-02T22:11:26.786629",
"added": "2024-11-19T01:02:25.399352+00:00",
"created": "2020-10-30T16:06:24",
"int_score": 3,
"score": 2.84375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push(
[
[266,],
{
/***/ 3158: /***/ function (
module
) {
// shim for using process in browser
var process = (module.exports = {
});
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout(
) {
throw new Error(
"setTimeout has not been defined"
);
}
function defaultClearTimeout(
) {
throw new Error(
"clearTimeout has not been defined"
);
}
(function (
) {
try {
if (typeof setTimeout === "function") {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === "function") {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})(
);
function runTimeout(
fun
) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(
fun,
0
);
}
// if setTimeout wasn't available but was latter defined
if (
(cachedSetTimeout === defaultSetTimout ||
!cachedSetTimeout) &&
setTimeout
) {
cachedSetTimeout = setTimeout;
return setTimeout(
fun,
0
);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(
fun,
0
);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(
null,
fun,
0
);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(
this,
fun,
0
);
}
}
}
function runClearTimeout(
marker
) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(
marker
);
}
// if clearTimeout wasn't available but was latter defined
if (
(cachedClearTimeout === defaultClearTimeout ||
!cachedClearTimeout) &&
clearTimeout
) {
cachedClearTimeout = clearTimeout;
return clearTimeout(
marker
);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(
marker
);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(
null,
marker
);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(
this,
marker
);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick(
) {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(
queue
);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue(
);
}
}
function drainQueue(
) {
if (draining) {
return;
}
var timeout = runTimeout(
cleanUpNextTick
);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run(
);
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(
timeout
);
}
process.nextTick = function (
fun
) {
var args = new Array(
arguments.length - 1
);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(
new Item(
fun,
args
)
);
if (queue.length === 1 && !draining) {
runTimeout(
drainQueue
);
}
};
// v8 likes predictible objects
function Item(
fun, array
) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function (
) {
this.fun.apply(
null,
this.array
);
};
process.title = "browser";
process.browser = true;
process.env = {
};
process.argv = [];
process.version = ""; // empty string to avoid regexp issues
process.versions = {
};
function noop(
) {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (
name
) {
return [];
};
process.binding = function (
name
) {
throw new Error(
"process.binding is not supported"
);
};
process.cwd = function (
) {
return "/";
};
process.chdir = function (
dir
) {
throw new Error(
"process.chdir is not supported"
);
};
process.umask = function (
) {
return 0;
};
/***/
},
/***/ 8182: /***/ function (
module
) {
"use strict";
function hash(
str
) {
var hash = 5381,
i = str.length;
while (i) {
hash = (hash * 33) ^ str.charCodeAt(
--i
);
}
/* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
* integers. Since we want the results to be always positive, convert the
* signed int to an unsigned by doing an unsigned bitshift. */
return hash >>> 0;
}
module.exports = hash;
/***/
},
/***/ 9261: /***/ function (
__unused_webpack_module,
exports,
__webpack_require__
) {
"use strict";
/* provided dependency */ var process = __webpack_require__(
3158
);
exports.__esModule = true;
exports.default = void 0;
function _defineProperties(
target, props
) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(
target,
descriptor.key,
descriptor
);
}
}
function _createClass(
Constructor, protoProps, staticProps
) {
if (protoProps)
_defineProperties(
Constructor.prototype,
protoProps
);
if (staticProps) _defineProperties(
Constructor,
staticProps
);
return Constructor;
}
/*
Based on Glamor's sheet
https://github.com/threepointone/glamor/blob/667b480d31b3721a905021b26e1290ce92ca2879/src/sheet.js
*/
var isProd =
typeof process !== "undefined" &&
process.env &&
"production" === "production";
var isString = function isString(
o
) {
return Object.prototype.toString.call(
o
) === "[object String]";
};
var StyleSheet = /*#__PURE__*/ (function (
) {
function StyleSheet(
_temp
) {
var _ref = _temp === void 0
? {
}
: _temp,
_ref$name = _ref.name,
name = _ref$name === void 0 ? "stylesheet" : _ref$name,
_ref$optimizeForSpeed = _ref.optimizeForSpeed,
optimizeForSpeed =
_ref$optimizeForSpeed === void 0
? isProd
: _ref$optimizeForSpeed,
_ref$isBrowser = _ref.isBrowser,
isBrowser =
_ref$isBrowser === void 0
? typeof window !== "undefined"
: _ref$isBrowser;
invariant(
isString(
name
),
"`name` must be a string"
);
this._name = name;
this._deletedRulePlaceholder =
"#" + name + "-deleted-rule____{}";
invariant(
typeof optimizeForSpeed === "boolean",
"`optimizeForSpeed` must be a boolean"
);
this._optimizeForSpeed = optimizeForSpeed;
this._isBrowser = isBrowser;
this._serverSheet = undefined;
this._tags = [];
this._injected = false;
this._rulesCount = 0;
var node =
this._isBrowser &&
document.querySelector(
'meta[property="csp-nonce"]'
);
this._nonce = node
? node.getAttribute(
"content"
)
: null;
}
var _proto = StyleSheet.prototype;
_proto.setOptimizeForSpeed = function setOptimizeForSpeed(
bool
) {
invariant(
typeof bool === "boolean",
"`setOptimizeForSpeed` accepts a boolean"
);
invariant(
this._rulesCount === 0,
"optimizeForSpeed cannot be when rules have already been inserted"
);
this.flush(
);
this._optimizeForSpeed = bool;
this.inject(
);
};
_proto.isOptimizeForSpeed = function isOptimizeForSpeed(
) {
return this._optimizeForSpeed;
};
_proto.inject = function inject(
) {
var _this = this;
invariant(
!this._injected,
"sheet already injected"
);
this._injected = true;
if (this._isBrowser && this._optimizeForSpeed) {
this._tags[0] = this.makeStyleTag(
this._name
);
this._optimizeForSpeed =
"insertRule" in this.getSheet(
);
if (!this._optimizeForSpeed) {
if (!isProd) {
console.warn(
"StyleSheet: optimizeForSpeed mode not supported falling back to standard mode."
);
}
this.flush(
);
this._injected = true;
}
return;
}
this._serverSheet = {
cssRules: [],
insertRule: function insertRule(
rule, index
) {
if (typeof index === "number") {
_this._serverSheet.cssRules[index] = {
cssText: rule,
};
} else {
_this._serverSheet.cssRules.push(
{
cssText: rule,
}
);
}
return index;
},
deleteRule: function deleteRule(
index
) {
_this._serverSheet.cssRules[index] = null;
},
};
};
_proto.getSheetForTag = function getSheetForTag(
tag
) {
if (tag.sheet) {
return tag.sheet;
} // this weirdness brought to you by firefox
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
return document.styleSheets[i];
}
}
};
_proto.getSheet = function getSheet(
) {
return this.getSheetForTag(
this._tags[this._tags.length - 1]
);
};
_proto.insertRule = function insertRule(
rule, index
) {
invariant(
isString(
rule
),
"`insertRule` accepts only strings"
);
if (!this._isBrowser) {
if (typeof index !== "number") {
index = this._serverSheet.cssRules.length;
}
this._serverSheet.insertRule(
rule,
index
);
return this._rulesCount++;
}
if (this._optimizeForSpeed) {
var sheet = this.getSheet(
);
if (typeof index !== "number") {
index = sheet.cssRules.length;
} // this weirdness for perf, and chrome's weird bug
// https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule
try {
sheet.insertRule(
rule,
index
);
} catch (error) {
if (!isProd) {
console.warn(
"StyleSheet: illegal rule: \n\n" +
rule +
"\n\nSee https://stackoverflow.com/q/20007992 for more info"
);
}
return -1;
}
} else {
var insertionPoint = this._tags[index];
this._tags.push(
this.makeStyleTag(
this._name,
rule,
insertionPoint
)
);
}
return this._rulesCount++;
};
_proto.replaceRule = function replaceRule(
index, rule
) {
if (this._optimizeForSpeed || !this._isBrowser) {
var sheet = this._isBrowser
? this.getSheet(
)
: this._serverSheet;
if (!rule.trim(
)) {
rule = this._deletedRulePlaceholder;
}
if (!sheet.cssRules[index]) {
// @TBD Should we throw an error?
return index;
}
sheet.deleteRule(
index
);
try {
sheet.insertRule(
rule,
index
);
} catch (error) {
if (!isProd) {
console.warn(
"StyleSheet: illegal rule: \n\n" +
rule +
"\n\nSee https://stackoverflow.com/q/20007992 for more info"
);
} // In order to preserve the indices we insert a deleteRulePlaceholder
sheet.insertRule(
this._deletedRulePlaceholder,
index
);
}
} else {
var tag = this._tags[index];
invariant(
tag,
"old rule at index `" + index + "` not found"
);
tag.textContent = rule;
}
return index;
};
_proto.deleteRule = function deleteRule(
index
) {
if (!this._isBrowser) {
this._serverSheet.deleteRule(
index
);
return;
}
if (this._optimizeForSpeed) {
this.replaceRule(
index,
""
);
} else {
var tag = this._tags[index];
invariant(
tag,
"rule at index `" + index + "` not found"
);
tag.parentNode.removeChild(
tag
);
this._tags[index] = null;
}
};
_proto.flush = function flush(
) {
this._injected = false;
this._rulesCount = 0;
if (this._isBrowser) {
this._tags.forEach(
function (
tag
) {
return tag && tag.parentNode.removeChild(
tag
);
}
);
this._tags = [];
} else {
// simpler on server
this._serverSheet.cssRules = [];
}
};
_proto.cssRules = function cssRules(
) {
var _this2 = this;
if (!this._isBrowser) {
return this._serverSheet.cssRules;
}
return this._tags.reduce(
function (
rules, tag
) {
if (tag) {
rules = rules.concat(
Array.prototype.map.call(
_this2.getSheetForTag(
tag
).cssRules,
function (
rule
) {
return rule.cssText ===
_this2._deletedRulePlaceholder
? null
: rule;
}
)
);
} else {
rules.push(
null
);
}
return rules;
},
[]
);
};
_proto.makeStyleTag = function makeStyleTag(
name,
cssString,
relativeToTag
) {
if (cssString) {
invariant(
isString(
cssString
),
"makeStyleTag acceps only strings as second parameter"
);
}
var tag = document.createElement(
"style"
);
if (this._nonce) tag.setAttribute(
"nonce",
this._nonce
);
tag.type = "text/css";
tag.setAttribute(
"data-" + name,
""
);
if (cssString) {
tag.appendChild(
document.createTextNode(
cssString
)
);
}
var head =
document.head ||
document.getElementsByTagName(
"head"
)[0];
if (relativeToTag) {
head.insertBefore(
tag,
relativeToTag
);
} else {
head.appendChild(
tag
);
}
return tag;
};
_createClass(
StyleSheet,
[
{
key: "length",
get: function get(
) {
return this._rulesCount;
},
},
]
);
return StyleSheet;
})(
);
exports.default = StyleSheet;
function invariant(
condition, message
) {
if (!condition) {
throw new Error(
"StyleSheet: " + message + "."
);
}
}
/***/
},
/***/ 8672: /***/ function (
__unused_webpack_module,
exports,
__webpack_require__
) {
"use strict";
var __webpack_unused_export__;
__webpack_unused_export__ = true;
__webpack_unused_export__ = flush;
exports.default = void 0;
var _react = __webpack_require__(
2735
);
var _stylesheetRegistry = _interopRequireDefault(
__webpack_require__(
7805
)
);
function _interopRequireDefault(
obj
) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
function _inheritsLoose(
subClass, superClass
) {
subClass.prototype = Object.create(
superClass.prototype
);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var styleSheetRegistry = new _stylesheetRegistry["default"](
);
var JSXStyle = /*#__PURE__*/ (function (
_Component
) {
_inheritsLoose(
JSXStyle,
_Component
);
function JSXStyle(
props
) {
var _this;
_this = _Component.call(
this,
props
) || this;
_this.prevProps = {
};
return _this;
}
JSXStyle.dynamic = function dynamic(
info
) {
return info
.map(
function (
tagInfo
) {
var baseId = tagInfo[0];
var props = tagInfo[1];
return styleSheetRegistry.computeId(
baseId,
props
);
}
)
.join(
" "
);
}; // probably faster than PureComponent (shallowEqual)
var _proto = JSXStyle.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate(
otherProps
) {
return (
this.props.id !== otherProps.id || // We do this check because `dynamic` is an array of strings or undefined.
// These are the computed values for dynamic styles.
String(
this.props.dynamic
) !==
String(
otherProps.dynamic
)
);
};
_proto.componentWillUnmount = function componentWillUnmount(
) {
styleSheetRegistry.remove(
this.props
);
};
_proto.render = function render(
) {
// This is a workaround to make the side effect async safe in the "render" phase.
// See https://github.com/zeit/styled-jsx/pull/484
if (this.shouldComponentUpdate(
this.prevProps
)) {
// Updates
if (this.prevProps.id) {
styleSheetRegistry.remove(
this.prevProps
);
}
styleSheetRegistry.add(
this.props
);
this.prevProps = this.props;
}
return null;
};
return JSXStyle;
})(
_react.Component
);
exports.default = JSXStyle;
function flush(
) {
var cssRules = styleSheetRegistry.cssRules(
);
styleSheetRegistry.flush(
);
return cssRules;
}
/***/
},
/***/ 7805: /***/ function (
__unused_webpack_module,
exports,
__webpack_require__
) {
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _stringHash = _interopRequireDefault(
__webpack_require__(
8182
)
);
var _stylesheet = _interopRequireDefault(
__webpack_require__(
9261
)
);
function _interopRequireDefault(
obj
) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
var sanitize = function sanitize(
rule
) {
return rule.replace(
/\/style/gi,
"\\/style"
);
};
var StyleSheetRegistry = /*#__PURE__*/ (function (
) {
function StyleSheetRegistry(
_temp
) {
var _ref = _temp === void 0
? {
}
: _temp,
_ref$styleSheet = _ref.styleSheet,
styleSheet =
_ref$styleSheet === void 0 ? null : _ref$styleSheet,
_ref$optimizeForSpeed = _ref.optimizeForSpeed,
optimizeForSpeed =
_ref$optimizeForSpeed === void 0
? false
: _ref$optimizeForSpeed,
_ref$isBrowser = _ref.isBrowser,
isBrowser =
_ref$isBrowser === void 0
? typeof window !== "undefined"
: _ref$isBrowser;
this._sheet =
styleSheet ||
new _stylesheet["default"](
{
name: "styled-jsx",
optimizeForSpeed: optimizeForSpeed,
}
);
this._sheet.inject(
);
if (styleSheet && typeof optimizeForSpeed === "boolean") {
this._sheet.setOptimizeForSpeed(
optimizeForSpeed
);
this._optimizeForSpeed =
this._sheet.isOptimizeForSpeed(
);
}
this._isBrowser = isBrowser;
this._fromServer = undefined;
this._indices = {
};
this._instancesCounts = {
};
this.computeId = this.createComputeId(
);
this.computeSelector = this.createComputeSelector(
);
}
var _proto = StyleSheetRegistry.prototype;
_proto.add = function add(
props
) {
var _this = this;
if (undefined === this._optimizeForSpeed) {
this._optimizeForSpeed = Array.isArray(
props.children
);
this._sheet.setOptimizeForSpeed(
this._optimizeForSpeed
);
this._optimizeForSpeed =
this._sheet.isOptimizeForSpeed(
);
}
if (this._isBrowser && !this._fromServer) {
this._fromServer = this.selectFromServer(
);
this._instancesCounts = Object.keys(
this._fromServer
).reduce(
function (
acc, tagName
) {
acc[tagName] = 0;
return acc;
},
{
}
);
}
var _this$getIdAndRules = this.getIdAndRules(
props
),
styleId = _this$getIdAndRules.styleId,
rules = _this$getIdAndRules.rules; // Deduping: just increase the instances count.
if (styleId in this._instancesCounts) {
this._instancesCounts[styleId] += 1;
return;
}
var indices = rules
.map(
function (
rule
) {
return _this._sheet.insertRule(
rule
);
}
) // Filter out invalid rules
.filter(
function (
index
) {
return index !== -1;
}
);
this._indices[styleId] = indices;
this._instancesCounts[styleId] = 1;
};
_proto.remove = function remove(
props
) {
var _this2 = this;
var _this$getIdAndRules2 = this.getIdAndRules(
props
),
styleId = _this$getIdAndRules2.styleId;
invariant(
styleId in this._instancesCounts,
"styleId: `" + styleId + "` not found"
);
this._instancesCounts[styleId] -= 1;
if (this._instancesCounts[styleId] < 1) {
var tagFromServer =
this._fromServer && this._fromServer[styleId];
if (tagFromServer) {
tagFromServer.parentNode.removeChild(
tagFromServer
);
delete this._fromServer[styleId];
} else {
this._indices[styleId].forEach(
function (
index
) {
return _this2._sheet.deleteRule(
index
);
}
);
delete this._indices[styleId];
}
delete this._instancesCounts[styleId];
}
};
_proto.update = function update(
props, nextProps
) {
this.add(
nextProps
);
this.remove(
props
);
};
_proto.flush = function flush(
) {
this._sheet.flush(
);
this._sheet.inject(
);
this._fromServer = undefined;
this._indices = {
};
this._instancesCounts = {
};
this.computeId = this.createComputeId(
);
this.computeSelector = this.createComputeSelector(
);
};
_proto.cssRules = function cssRules(
) {
var _this3 = this;
var fromServer = this._fromServer
? Object.keys(
this._fromServer
).map(
function (
styleId
) {
return [styleId, _this3._fromServer[styleId],];
}
)
: [];
var cssRules = this._sheet.cssRules(
);
return fromServer.concat(
Object.keys(
this._indices
)
.map(
function (
styleId
) {
return [
styleId,
_this3._indices[styleId]
.map(
function (
index
) {
return cssRules[index].cssText;
}
)
.join(
_this3._optimizeForSpeed ? "" : "\n"
),
];
}
) // filter out empty rules
.filter(
function (
rule
) {
return Boolean(
rule[1]
);
}
)
);
};
/**
* createComputeId
*
* Creates a function to compute and memoize a jsx id from a basedId and optionally props.
*/
_proto.createComputeId = function createComputeId(
) {
var cache = {
};
return function (
baseId, props
) {
if (!props) {
return "jsx-" + baseId;
}
var propsToString = String(
props
);
var key = baseId + propsToString; // return `jsx-${hashString(`${baseId}-${propsToString}`)}`
if (!cache[key]) {
cache[key] =
"jsx-" +
(0, _stringHash["default"])(
baseId + "-" + propsToString
);
}
return cache[key];
};
};
/**
* createComputeSelector
*
* Creates a function to compute and memoize dynamic selectors.
*/
_proto.createComputeSelector = function createComputeSelector(
selectoPlaceholderRegexp
) {
if (selectoPlaceholderRegexp === void 0) {
selectoPlaceholderRegexp =
/__jsx-style-dynamic-selector/g;
}
var cache = {
};
return function (
id, css
) {
// Sanitize SSR-ed CSS.
// Client side code doesn't need to be sanitized since we use
// document.createTextNode (dev) and the CSSOM api sheet.insertRule (prod).
if (!this._isBrowser) {
css = sanitize(
css
);
}
var idcss = id + css;
if (!cache[idcss]) {
cache[idcss] = css.replace(
selectoPlaceholderRegexp,
id
);
}
return cache[idcss];
};
};
_proto.getIdAndRules = function getIdAndRules(
props
) {
var _this4 = this;
var css = props.children,
dynamic = props.dynamic,
id = props.id;
if (dynamic) {
var styleId = this.computeId(
id,
dynamic
);
return {
styleId: styleId,
rules: Array.isArray(
css
)
? css.map(
function (
rule
) {
return _this4.computeSelector(
styleId,
rule
);
}
)
: [this.computeSelector(
styleId,
css
),],
};
}
return {
styleId: this.computeId(
id
),
rules: Array.isArray(
css
)
? css
: [css,],
};
};
/**
* selectFromServer
*
* Collects style tags from the document with id __jsx-XXX
*/
_proto.selectFromServer = function selectFromServer(
) {
var elements = Array.prototype.slice.call(
document.querySelectorAll(
'[id^="__jsx-"]'
)
);
return elements.reduce(
function (
acc, element
) {
var id = element.id.slice(
2
);
acc[id] = element;
return acc;
},
{
}
);
};
return StyleSheetRegistry;
})(
);
exports.default = StyleSheetRegistry;
function invariant(
condition, message
) {
if (!condition) {
throw new Error(
"StyleSheetRegistry: " + message + "."
);
}
}
/***/
},
/***/ 266: /***/ function (
module,
__unused_webpack_exports,
__webpack_require__
) {
module.exports = __webpack_require__(
8672
);
/***/
},
},
]
);
|
c37babc85fff306f8aaa4b7203c327918d65d952
|
{
"blob_id": "c37babc85fff306f8aaa4b7203c327918d65d952",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-19T15:00:48",
"content_id": "7fc87edeb9a0f290482b43904896d96512678c5f",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "3720499fff550f5e243255b50abd0ab1e677d896",
"extension": "js",
"filename": "input.js",
"fork_events_count": 1,
"gha_created_at": "2019-12-14T18:32:11",
"gha_event_created_at": "2019-12-14T18:32:12",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 228070317,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 54562,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/ecmascript/minifier/tests/compress/fixture/projects/next/.archive-4/266-aee26c928109d49d6151/input.js",
"provenance": "stack-edu-0039.json.gz:464044",
"repo_name": "dsherret/swc",
"revision_date": "2021-10-19T15:00:48",
"revision_id": "bf886bac73ad348ab7bc333e6eae824c96e9abde",
"snapshot_id": "9f780682844595b1722f10e777dfc8915ad39372",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dsherret/swc/bf886bac73ad348ab7bc333e6eae824c96e9abde/ecmascript/minifier/tests/compress/fixture/projects/next/.archive-4/266-aee26c928109d49d6151/input.js",
"visit_date": "2023-09-03T16:59:11.250540",
"added": "2024-11-19T01:09:53.667638+00:00",
"created": "2021-10-19T15:00:48",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz"
}
|
#!/bin/bash
set -eo pipefail
declare -r DIR=$(dirname ${BASH_SOURCE[0]})
declare rule_stage='login_success'
declare rule_order=1
function usage() {
cat <<END >&2
USAGE: $0 [-e env] [-a access_token] [-f file] [-n name] [-o order] [-s stage] [-v|-h]
-e file # .env file location (default cwd)
-a token # access_token. default from environment variable
-f file # Rule script file
-n name # Name
-o order # Execution order (default to "${rule_order}")
-s stage # stage of: login_success, login_failure, pre_authorize (defaults to "${rule_stage}")
-h|? # usage
-v # verbose
eg,
$0 -n test -f test.js -o 10
END
exit $1
}
declare script_file=''
declare opt_verbose=''
declare rule_name=''
while getopts "e:a:f:n:o:s:hv?" opt
do
case ${opt} in
e) source ${OPTARG};;
a) access_token=${OPTARG};;
f) script_file=${OPTARG};;
n) rule_name=${OPTARG};;
o) rule_order=${OPTARG};;
s) rule_stage=${OPTARG};;
v) opt_verbose='-v';; #set -x;;
h|?) usage 0;;
*) usage 1;;
esac
done
[[ -z "${access_token}" ]] && { echo >&2 "ERROR: access_token undefined. export access_token='PASTE' "; usage 1; }
[[ -z "${rule_name}" ]] && { echo >&2 "ERROR: rule_name undefined."; usage 1; }
[[ -z "${script_file}" ]] && { echo >&2 "ERROR: script_file undefined."; usage 1; }
[[ -f "${script_file}" ]] || { echo >&2 "ERROR: script_file missing: ${json_file}"; usage 1; }
declare -r AUTH0_DOMAIN_URL=$(echo ${access_token} | awk -F. '{print $2}' | base64 -di 2>/dev/null | jq -r '.iss')
declare script_single_line=`sed 's/$/\\\\n/' ${script_file} | tr -d '\n'`
declare BODY=$(cat <<EOL
{
"name": "${rule_name}",
"script": "${script_single_line}",
"order": ${rule_order},
"stage": "${rule_stage}",
"enabled": true
}
EOL
)
curl ${opt_verbose} -H "Authorization: Bearer ${access_token}" \
--url ${AUTH0_DOMAIN_URL}api/v2/rules \
--header 'content-type: application/json' \
--data "${BODY}"
|
9f11c6f4729fa52ade5424d05dc2326ff8d2f2f3
|
{
"blob_id": "9f11c6f4729fa52ade5424d05dc2326ff8d2f2f3",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-28T04:12:05",
"content_id": "3f6d99a0c6926a08ebebad697d1f8e9ed47eaa26",
"detected_licenses": [
"MIT"
],
"directory_id": "5aa92e4349efb0dcae61ed3e0febe10e86c34170",
"extension": "sh",
"filename": "create-rule.sh",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2073,
"license": "MIT",
"license_type": "permissive",
"path": "/rules/create-rule.sh",
"provenance": "stack-edu-0069.json.gz:569293",
"repo_name": "tomauth0/auth0-bash",
"revision_date": "2020-10-28T04:12:05",
"revision_id": "99bb21c3da0575b0ac692f32cd7d3bd6737000dc",
"snapshot_id": "c38d3a47f075d05a0fc323c818869dc8a22297a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tomauth0/auth0-bash/99bb21c3da0575b0ac692f32cd7d3bd6737000dc/rules/create-rule.sh",
"visit_date": "2023-01-01T07:10:19.297305",
"added": "2024-11-18T20:10:58.602127+00:00",
"created": "2020-10-28T04:12:05",
"int_score": 4,
"score": 3.8125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
/*
* Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode
*
* 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.
*/
using org.javarosa.core.model.data;
using org.javarosa.core.model.instance.utils;
using org.javarosa.core.model.util.restorable;
using org.javarosa.core.model.utils;
using org.javarosa.core.services.storage;
using org.javarosa.core.util.externalizable;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace org.javarosa.core.model.instance
{
/**
* This class represents the xform model instance
*/
public class FormInstance : Persistable, Restorable
{
public const String STORAGE_KEY = "FORMDATA";
/** The root of this tree */
private TreeElement root = new TreeElement();
// represents '/'; always has one and only one child -- the top-level
// instance data node
// this node is never returned or manipulated directly
/** The name for this data model */
private String name;
/** The integer Id of the model */
private int id;
/** The ID of the form that this is a model for */
private int formId;
/** The date that this model was taken and recorded */
private DateTime dateSaved;
public String schema;
public String formVersion;
public String uiVersion;
private Hashtable namespaces = new Hashtable();
public FormInstance()
{
}
/**
* Creates a new data model using the root given.
*
* @param root
* The root of the tree for this data model.
*/
public FormInstance(TreeElement root)
{
ID = -1;
setFormId(-1);
setRoot(root);
}
/**
* Sets the root element of this Model's tree
*
* @param root
* The root of the tree for this data model.
*/
public void setRoot(TreeElement topLevel)
{
root = new TreeElement();
if (topLevel != null)
root.addChild(topLevel);
}
/**
* TODO: confusion between root and its first child?
*
* @return This model's root tree element
*/
public TreeElement getRoot()
{
if (root.getNumChildren() == 0)
throw new SystemException("root node has no children");
return root.getChildAt(0);
}
// throws classcastexception if not using XPathReference
public static TreeReference unpackReference(IDataReference ref_)
{
return (TreeReference)ref_.Reference;
}
public TreeReference unpackReference2(IDataReference ref_)
{
return (TreeReference)ref_.Reference;
}
public TreeReference copyNode(TreeReference from, TreeReference to)
{
if (!from.isAbsolute())
{
throw new InvalidReferenceException("Source reference must be absolute for copying", from);
}
TreeElement src = resolveReference(from);
if (src == null)
{
throw new InvalidReferenceException("Null Source reference while attempting to copy node", from);
}
return copyNode(src, to).getRef();
}
// for making new repeat instances; 'from' and 'to' must be unambiguous
// references EXCEPT 'to' may be ambiguous at its final step
// return true is successfully copied, false otherwise
public TreeElement copyNode(TreeElement src, TreeReference to)
{
if (!to.isAbsolute())
throw new InvalidReferenceException("Destination reference must be absolute for copying", to);
// strip out dest node info and get dest parent
String dstName = to.getNameLast();
int dstMult = to.getMultLast();
TreeReference toParent = to.getParentRef();
TreeElement parent = resolveReference(toParent);
if (parent == null)
{
throw new InvalidReferenceException("Null parent reference whle attempting to copy", toParent);
}
if (!parent.isChildable())
{
throw new InvalidReferenceException("Invalid Parent Node: cannot accept children.", toParent);
}
if (dstMult == TreeReference.INDEX_UNBOUND)
{
dstMult = parent.getChildMultiplicity(dstName);
}
else if (parent.getChild(dstName, dstMult) != null)
{
throw new InvalidReferenceException("Destination already exists!", to);
}
TreeElement dest = src.deepCopy(false);
dest.setName(dstName);
dest.multiplicity = dstMult;
parent.addChild(dest);
return dest;
}
public void copyItemsetNode(TreeElement copyNode, TreeReference destRef, FormDef f)
{
TreeElement templateNode = getTemplate(destRef);
TreeElement newNode = this.copyNode(templateNode, destRef);
newNode.populateTemplate(copyNode, f);
}
// don't think this is used anymore
public IAnswerData getDataValue(IDataReference questionReference)
{
TreeElement element = resolveReference(questionReference);
if (element != null)
{
return element.getValue();
}
else
{
return null;
}
}
// take a ref that unambiguously refers to a single node and return that node
// return null if ref is ambiguous, node does not exist, ref is relative, or ref is '/'
// can be used to retrieve template nodes
public TreeElement resolveReference(TreeReference ref_)
{
if (!ref_.isAbsolute())
{
return null;
}
TreeElement node = root;
for (int i = 0; i < ref_.size(); i++)
{
String name = ref_.getName(i);
int mult = ref_.getMultiplicity(i);
if (mult == TreeReference.INDEX_ATTRIBUTE)
{
//Should we possibly just return here?
//I guess technically we could step back...
node = node.getAttribute(null, name);
continue;
}
if (mult == TreeReference.INDEX_UNBOUND)
{
if (node.getChildMultiplicity(name) == 1)
{
mult = 0;
}
else
{
// reference is not unambiguous
node = null;
break;
}
}
node = node.getChild(name, mult);
if (node == null)
break;
}
return (node == root ? null : node); // never return a reference to '/'
}
// same as resolveReference but return a vector containing all interstitial
// nodes: top-level instance data node first, and target node last
// returns null in all the same situations as resolveReference EXCEPT ref
// '/' will instead return empty vector
public ArrayList explodeReference(TreeReference ref_)
{
if (!ref_.isAbsolute())
return null;
ArrayList nodes = new ArrayList();
TreeElement cur = root;
for (int i = 0; i < ref_.size(); i++)
{
String name = ref_.getName(i);
int mult = ref_.getMultiplicity(i);
//If the next node down the line is an attribute
if (mult == TreeReference.INDEX_ATTRIBUTE)
{
//This is not the attribute we're testing
if (cur != root)
{
//Add the current node
nodes.Add(cur);
}
cur = cur.getAttribute(null, name);
}
//Otherwise, it's another child element
else
{
if (mult == TreeReference.INDEX_UNBOUND)
{
if (cur.getChildMultiplicity(name) == 1)
{
mult = 0;
}
else
{
// reference is not unambiguous
return null;
}
}
if (cur != root)
{
nodes.Add(cur);
}
cur = cur.getChild(name, mult);
if (cur == null)
{
return null;
}
}
}
return nodes;
}
public List<TreeReference> expandReference(TreeReference ref_)
{
return expandReference(ref_, false);
}
// take in a potentially-ambiguous ref, and return a vector of refs for all nodes that match the passed-in ref
// meaning, search out all repeated nodes that match the pattern of the passed-in ref
// every ref in the returned vector will be unambiguous (no index will ever be INDEX_UNBOUND)
// does not return template nodes when matching INDEX_UNBOUND, but will match templates when INDEX_TEMPLATE is explicitly set
// return null if ref is relative, otherwise return vector of refs (but vector will be empty is no refs match)
// '/' returns {'/'}
// can handle sub-repetitions (e.g., {/a[1]/b[1], /a[1]/b[2], /a[2]/b[1]})
public List<TreeReference> expandReference(TreeReference ref_, Boolean includeTemplates)
{
if (!ref_.isAbsolute())
return null;
List<TreeReference> v = new List<TreeReference>();
expandReference(ref_, root, v, includeTemplates);
return v;
}
// recursive helper function for expandReference
// sourceRef: original path we're matching against
// node: current node that has matched the sourceRef thus far
// templateRef: explicit path that refers to the current node
// refs: Vector to collect matching paths; if 'node' is a target node that
// matches sourceRef, templateRef is added to refs
private void expandReference(TreeReference sourceRef, TreeElement node, List<TreeReference> refs, Boolean includeTemplates)
{
int depth = node.getDepth();
if (depth == sourceRef.size())
{
refs.Add(node.getRef());
}
else
{
String name = sourceRef.getName(depth);
int mult = sourceRef.getMultiplicity(depth);
List<TreeElement> set = new List<TreeElement>();
if (node.getNumChildren() > 0)
{
if (mult == TreeReference.INDEX_UNBOUND)
{
int count = node.getChildMultiplicity(name);
for (int i = 0; i < count; i++)
{
TreeElement child = node.getChild(name, i);
if (child != null)
{
set.Add(child);
}
else
{
throw new InvalidOperationException(); // missing/non-sequential
// nodes
}
}
if (includeTemplates)
{
TreeElement template = node.getChild(name, TreeReference.INDEX_TEMPLATE);
if (template != null)
{
set.Add(template);
}
}
}
else if (mult != TreeReference.INDEX_ATTRIBUTE)
{
//TODO: Make this test mult >= 0?
//If the multiplicity is a simple integer, just get
//the appropriate child
TreeElement child = node.getChild(name, mult);
if (child != null)
{
set.Add(child);
}
}
}
if (mult == TreeReference.INDEX_ATTRIBUTE)
{
TreeElement attribute = node.getAttribute(null, name);
set.Add(attribute);
}
for (IEnumerator e = set.GetEnumerator(); e.MoveNext(); )
{
expandReference(sourceRef, (TreeElement)e.Current, refs, includeTemplates);
}
}
}
// retrieve the template node for a given repeated node ref may be ambiguous
// return null if node is not repeatable
// assumes templates are built correctly and obey all data model validity rules
public TreeElement getTemplate(TreeReference ref_)
{
TreeElement node = getTemplatePath(ref_);
return (node == null ? null : node.repeatable ? node : null);
}
public TreeElement getTemplatePath(TreeReference ref_)
{
if (!ref_.isAbsolute())
return null;
TreeElement node = root;
for (int i = 0; i < ref_.size(); i++)
{
String name = ref_.getName(i);
if (ref_.getMultiplicity(i) == TreeReference.INDEX_ATTRIBUTE)
{
node = node.getAttribute(null, name);
}
else
{
TreeElement newNode = node.getChild(name, TreeReference.INDEX_TEMPLATE);
if (newNode == null)
{
newNode = node.getChild(name, 0);
}
if (newNode == null)
{
return null;
}
node = newNode;
}
}
return node;
}
// determine if nodes are homogeneous, meaning their descendant structure is 'identical' for repeat purposes
// identical means all children match, and the children's children match, and so on
// repeatable children are ignored; as they do not have to exist in the same quantity for nodes to be homogeneous
// however, the child repeatable nodes MUST be verified amongst themselves for homogeneity later
// this function ignores the names of the two nodes
public static Boolean isHomogeneous(TreeElement a, TreeElement b)
{
if (a.isLeaf() && b.isLeaf())
{
return true;
}
else if (a.isChildable() && b.isChildable())
{
// verify that every (non-repeatable) node in a exists in b and vice
// versa
for (int k = 0; k < 2; k++)
{
TreeElement n1 = (k == 0 ? a : b);
TreeElement n2 = (k == 0 ? b : a);
for (int i = 0; i < n1.getNumChildren(); i++)
{
TreeElement child1 = n1.getChildAt(i);
if (child1.repeatable)
continue;
TreeElement child2 = n2.getChild(child1.getName(), 0);
if (child2 == null)
return false;
if (child2.repeatable)
throw new SystemException("shouldn't happen");
}
}
// compare children
for (int i = 0; i < a.getNumChildren(); i++)
{
TreeElement childA = a.getChildAt(i);
if (childA.repeatable)
continue;
TreeElement childB = b.getChild(childA.getName(), 0);
if (!isHomogeneous(childA, childB))
return false;
}
return true;
}
else
{
return false;
}
}
/**
* Resolves a binding to a particular question data element
*
* @param binding
* The binding representing a particular question
* @return A QuestionDataElement corresponding to the binding provided. Null
* if none exists in this tree.
*/
public TreeElement resolveReference(IDataReference binding)
{
return resolveReference(unpackReference(binding));
}
public void accept(IInstanceVisitor visitor)
{
visitor.visit(this);
if (visitor is ITreeVisitor)
{
root.accept((ITreeVisitor)visitor);
}
}
public void setDateSaved(DateTime dateSaved)
{
this.dateSaved = dateSaved;
}
public void setFormId(int formId)
{
this.formId = formId;
}
public DateTime getDateSaved()
{
return this.dateSaved;
}
public int getFormId()
{
return this.formId;
}
/*
* (non-Javadoc)
*
* @see
* org.javarosa.core.services.storage.utilities.Externalizable#readExternal
* (java.io.DataInputStream)
*/
public void readExternal(BinaryReader in_, PrototypeFactory pf)
{
id = ExtUtil.readInt(in_);
formId = ExtUtil.readInt(in_);
name = (String)ExtUtil.read(in_, new ExtWrapNullable(typeof(String)), pf);
schema = (String)ExtUtil.read(in_, new ExtWrapNullable(typeof(String)), pf);
dateSaved = (DateTime)ExtUtil.read(in_, new ExtWrapNullable(typeof(DateTime)), pf);
namespaces = (Hashtable)ExtUtil.read(in_, new ExtWrapMap(typeof(String), typeof(String)));
setRoot((TreeElement)ExtUtil.read(in_, typeof(TreeElement), pf));
}
/*
* (non-Javadoc)
*
* @see
* org.javarosa.core.services.storage.utilities.Externalizable#writeExternal
* (java.io.DataOutputStream)
*/
public void writeExternal(BinaryWriter out_)
{
ExtUtil.writeNumeric(out_, id);
ExtUtil.writeNumeric(out_, formId);
ExtUtil.write(out_, new ExtWrapNullable(name));
ExtUtil.write(out_, new ExtWrapNullable(schema));
ExtUtil.write(out_, new ExtWrapNullable(dateSaved));
ExtUtil.write(out_, new ExtWrapMap(namespaces));
ExtUtil.write(out_, getRoot());
}
public String getName()
{
return name;
}
/**
* Sets the name of this datamodel instance
*
* @param name
* The name to be used
*/
public void setName(String name)
{
this.name = name;
}
public int ID
{
get { return id; }
set {
this.id = value;
}
}
public TreeReference addNode(TreeReference ambigRef)
{
TreeReference ref_ = ambigRef.clone();
if (createNode(ref_) != null)
{
return ref_;
}
else
{
return null;
}
}
public TreeReference addNode(TreeReference ambigRef, IAnswerData data, int dataType)
{
TreeReference ref_ = ambigRef.clone();
TreeElement node = createNode(ref_);
if (node != null)
{
if (dataType >= 0)
{
node.dataType = dataType;
}
node.setValue(data);
return ref_;
}
else
{
return null;
}
}
/*
* create the specified node in the tree, creating all intermediary nodes at
* each step, if necessary. if specified node already exists, return null
*
* creating a duplicate node is only allowed at the final step. it will be
* done if the multiplicity of the last step is ALL or equal to the count of
* nodes already there
*
* at intermediate steps, the specified existing node is used; if
* multiplicity is ALL: if no nodes exist, a new one is created; if one node
* exists, it is used; if multiple nodes exist, it's an error
*
* return the newly-created node; modify ref so that it's an unambiguous ref
* to the node
*/
private TreeElement createNode(TreeReference ref_)
{
TreeElement node = root;
for (int k = 0; k < ref_.size(); k++)
{
String name = ref_.getName(k);
int count = node.getChildMultiplicity(name);
int mult = ref_.getMultiplicity(k);
TreeElement child;
if (k < ref_.size() - 1)
{
if (mult == TreeReference.INDEX_UNBOUND)
{
if (count > 1)
{
return null; // don't know which node to use
}
else
{
// will use existing (if one and only one) or create new
mult = 0;
ref_.setMultiplicity(k, 0);
}
}
// fetch
child = node.getChild(name, mult);
if (child == null)
{
if (mult == 0)
{
// create
child = new TreeElement(name, count);
node.addChild(child);
ref_.setMultiplicity(k, count);
}
else
{
return null; // intermediate node does not exist
}
}
}
else
{
if (mult == TreeReference.INDEX_UNBOUND || mult == count)
{
if (k == 0 && root.getNumChildren() != 0)
{
return null; // can only be one top-level node, and it
// already exists
}
if (!node.isChildable())
{
return null; // current node can't have children
}
// create new
child = new TreeElement(name, count);
node.addChild(child);
ref_.setMultiplicity(k, count);
}
else
{
return null; // final node must be a newly-created node
}
}
node = child;
}
return node;
}
public void addNamespace(String prefix, String URI)
{
namespaces.Add(prefix, URI);
}
public String[] getNamespacePrefixes()
{
String[] prefixes = new String[namespaces.Count];
int i = 0;
for (IEnumerator en = namespaces.GetEnumerator(); en.MoveNext(); )
{
prefixes[i] = (String)en.Current;
++i;
}
return prefixes;
}
public String getNamespaceURI(String prefix)
{
return (String)namespaces[prefix];
}
public String RestorableType
{
get
{
return "form";
}
}
// TODO: include whether form was sent already (or restrict always to unsent
// forms)
public FormInstance exportData()
{
FormInstance dm = RestoreUtils.createDataModel(this);
RestoreUtils.addData(dm, "name", name);
RestoreUtils.addData(dm, "form-id", (int)(formId));
RestoreUtils.addData(dm, "saved-on", dateSaved,
Constants.DATATYPE_DATE_TIME);
RestoreUtils.addData(dm, "schema", schema);
/////////////
throw new SystemException("FormInstance.exportData(): must be updated to use new transport layer");
// ITransportManager tm = TransportManager._();
// boolean sent = (tm.getModelDeliveryStatus(id, true) == TransportMessage.STATUS_DELIVERED);
// RestoreUtils.addData(dm, "sent", new Boolean(sent));
/////////////
// for (Enumeration e = namespaces.keys(); e.hasMoreElements(); ) {
// String key = (String)e.nextElement();
// RestoreUtils.addData(dm, "namespace/" + key, namespaces.get(key));
// }
//
// RestoreUtils.mergeDataModel(dm, this, "data");
// return dm;
}
public void templateData(FormInstance dm, TreeReference parentRef)
{
RestoreUtils.applyDataType(dm, "name", parentRef, typeof(String));
RestoreUtils.applyDataType(dm, "form-id", parentRef, typeof(int));
RestoreUtils.applyDataType(dm, "saved-on", parentRef,
Constants.DATATYPE_DATE_TIME);
RestoreUtils.applyDataType(dm, "schema", parentRef, typeof(String));
RestoreUtils.applyDataType(dm, "sent", parentRef, typeof(Boolean));
// don't touch data for now
}
public void importData(FormInstance dm)
{
name = (String)RestoreUtils.getValue("name", dm);
formId = ((int)RestoreUtils.getValue("form-id", dm));
dateSaved = (DateTime)RestoreUtils.getValue("saved-on", dm);
schema = (String)RestoreUtils.getValue("schema", dm);
Boolean sent = RestoreUtils.getBoolean(RestoreUtils
.getValue("sent", dm));
TreeElement names = dm.resolveReference(RestoreUtils.absRef("namespace", dm));
if (names != null)
{
for (int i = 0; i < names.getNumChildren(); i++)
{
TreeElement child = names.getChildAt(i);
String name_ = child.getName();
Object value = RestoreUtils.getValue("namespace/" + name_, dm);
if (value != null)
{
namespaces.Add(name_, value);
}
}
}
/////////////
throw new SystemException("FormInstance.importData(): must be updated to use new transport layer");
// if (sent) {
// ITransportManager tm = TransportManager._();
// tm.markSent(id, false);
// }
/////////////
// IStorageUtility forms = StorageManager.getStorage(FormDef.STORAGE_KEY);
// FormDef f = (FormDef)forms.read(formId);
// setRoot(processSavedDataModel(dm.resolveReference(RestoreUtils.absRef("data", dm)), f.getDataModel(), f));
}
public TreeElement processSaved(FormInstance template, FormDef f)
{
TreeElement fixedInstanceRoot = template.getRoot().deepCopy(true);
TreeElement incomingRoot = root.getChildAt(0);
if (!fixedInstanceRoot.getName().Equals(incomingRoot.getName()) || incomingRoot.getMult() != 0)
{
throw new SystemException("Saved form instance to restore does not match form definition");
}
fixedInstanceRoot.populate(incomingRoot, f);
return fixedInstanceRoot;
}
public FormInstance clone()
{
FormInstance cloned = new FormInstance(this.getRoot().deepCopy(true));
cloned.ID = (this.ID);
cloned.setFormId(this.getFormId());
cloned.setName(this.getName());
cloned.setDateSaved(this.getDateSaved());
cloned.schema = this.schema;
cloned.formVersion = this.formVersion;
cloned.uiVersion = this.uiVersion;
cloned.namespaces = new Hashtable();
for (IEnumerator e = this.namespaces.GetEnumerator(); e.MoveNext(); )
{
Object key = e.Current;
cloned.namespaces.Add(key, this.namespaces[key]);
}
return cloned;
}
}
}
|
5ba5b86d7201175d5e050f391c3c1d94b1448a18
|
{
"blob_id": "5ba5b86d7201175d5e050f391c3c1d94b1448a18",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-26T15:43:28",
"content_id": "041cf1ec0f79a7110d23890c0f822fda502847c7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "94721666aa09e6c417d1959df37efdcb55d20a12",
"extension": "cs",
"filename": "FormInstance.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 30345,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/csrosa/core/src/org/javarosa/core/model/instance/FormInstance.cs",
"provenance": "stack-edu-0010.json.gz:551933",
"repo_name": "ryanbehr/csrosa",
"revision_date": "2014-11-26T15:43:28",
"revision_id": "7640004e97bcf0564bef108cfc71c2dc9beef870",
"snapshot_id": "15b750ed1bcd47f45be23d4992b3347cd586aa83",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ryanbehr/csrosa/7640004e97bcf0564bef108cfc71c2dc9beef870/csrosa/core/src/org/javarosa/core/model/instance/FormInstance.cs",
"visit_date": "2021-01-20T14:01:56.181490",
"added": "2024-11-18T23:09:58.128645+00:00",
"created": "2014-11-26T15:43:28",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
using GuiCookie.Attributes;
using LiruGameHelper.Reflection;
using System;
using System.Collections.Generic;
using System.Xml;
namespace GuiCookie.Styles
{
public class StyleVariant
{
#region Fields
/// <summary> The collection of style attributes keyed by a combination of the type and its name. </summary>
private readonly Dictionary<string, IStyleAttribute> styleAttributesByTypeAndName = new Dictionary<string, IStyleAttribute>();
private readonly Dictionary<Type, IStyleAttribute> unnamedStyleAttributesByType = new Dictionary<Type, IStyleAttribute>();
#endregion
#region Properties
/// <summary> The name of this variant, e.g. "Hovered". </summary>
public string Name { get; }
#endregion
#region Constructors
public StyleVariant(string name, IReadOnlyList<IStyleAttribute> styleAttributes)
{
// Set the name.
Name = !string.IsNullOrWhiteSpace(name) ? name : throw new ArgumentException("Variant name cannot be empty.", nameof(name));
// Ensure the attributes exist.
if (styleAttributes == null) throw new ArgumentNullException(nameof(styleAttributes));
// Add each style attribute.
foreach (IStyleAttribute styleAttribute in styleAttributes)
AddAttribute(styleAttribute);
}
public StyleVariant(XmlNode variantNode, ResourceManager resourceManager, ConstructorCache<IStyleAttribute> attributeCache)
{
// Set the name.
Name = variantNode.Name;
foreach (XmlNode childNode in variantNode)
{
// Create the attribute.
IStyleAttribute styleAttribute = attributeCache.CreateInstance(childNode.Name, resourceManager, new AttributeCollection(childNode));
// Try to add the attributes to the collection.
AddAttribute(styleAttribute);
}
}
private StyleVariant(StyleVariant original)
{
if (original == null) throw new ArgumentNullException(nameof(original));
Name = original.Name;
// Copy each attribute.
foreach (IStyleAttribute attribute in original.styleAttributesByTypeAndName.Values)
AddAttribute(attribute.CreateCopy());
}
#endregion
#region Collection Functions
public T GetUnnamedAttributeOfType<T>() where T : class, IStyleAttribute => unnamedStyleAttributesByType.TryGetValue(typeof(T), out IStyleAttribute styleAttribute) ? (T)styleAttribute : null;
public T GetNamedAttributeOfType<T>(string name) where T : class, IStyleAttribute
=> styleAttributesByTypeAndName.TryGetValue(calculateKey(typeof(T), name), out IStyleAttribute styleAttribute) ? styleAttribute as T : null;
/// <summary> Gets the first attribute of the type <typeparamref name="T"/>, prioritising unnamed attributes. </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetFirstAttributeOfType<T>() where T : class, IStyleAttribute
{
// Search the unnamed collection first.
if (GetUnnamedAttributeOfType<T>() is T attribute) return attribute;
// If the unnamed collection does not contain the type, return the first instance of the type within the main collection.
foreach (IStyleAttribute namedAttribute in styleAttributesByTypeAndName.Values)
if (namedAttribute is T typedAttribute) return typedAttribute;
// Otherwise; return null.
return null;
}
#endregion
#region Add Functions
public void AddAttribute(IStyleAttribute styleAttribute)
{
// Calculate the key.
Type type = styleAttribute.GetType();
string key = calculateKey(type, styleAttribute);
// Try to add the attribute to the collection.
if (!styleAttributesByTypeAndName.ContainsKey(key)) styleAttributesByTypeAndName.Add(key, styleAttribute);
else throw new Exception($"Style attribute with key {key} has already been added to style variant {Name}.");
// If the attribute has no name, add it to the typed collection. No two unnamed attributes of the same type can exist at this point, so no contains check is required.
if (string.IsNullOrWhiteSpace(styleAttribute.Name))
unnamedStyleAttributesByType.Add(type, styleAttribute);
}
private string calculateKey(Type type, IStyleAttribute styleAttribute) => calculateKey(type, styleAttribute?.Name);
private string calculateKey(Type type, string name) => $"{type.Name}:{name}";
#endregion
#region Copy Functions
public StyleVariant CreateCopy() => new StyleVariant(this);
#endregion
#region Combination Functions
public void CombineOverBase(StyleVariant baseVariant)
{
// Go over each attribute in the base.
foreach (IStyleAttribute baseAttribute in baseVariant.styleAttributesByTypeAndName.Values)
{
// If this variant does not have the attribute, take a copy of it as it is.
string key = calculateKey(baseAttribute.GetType(), baseAttribute);
if (!styleAttributesByTypeAndName.TryGetValue(key, out IStyleAttribute derivedAttribute)) AddAttribute(baseAttribute.CreateCopy());
// Otherwise; combine the derived attribute over the base attribute.
else derivedAttribute.OverrideBaseAttribute(baseAttribute);
}
}
#endregion
#region String Functions
public override string ToString() => Name;
#endregion
}
}
|
6958368e6c30cc75c4152321134dc76c4aec1b1b
|
{
"blob_id": "6958368e6c30cc75c4152321134dc76c4aec1b1b",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-18T17:37:38",
"content_id": "9ed951e6d348592bb58c68bc62151b873942e6c4",
"detected_licenses": [
"MIT"
],
"directory_id": "cfe7cdbffa967baf12904e528962765548cf7505",
"extension": "cs",
"filename": "StyleVariant.cs",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 68858405,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 5856,
"license": "MIT",
"license_type": "permissive",
"path": "/GuiCookie/Styles/StyleVariant.cs",
"provenance": "stack-edu-0010.json.gz:390285",
"repo_name": "LiruJ/GuiCookie",
"revision_date": "2021-10-18T17:37:38",
"revision_id": "707bd0446df995370f62ca4d5f288dbf2969517f",
"snapshot_id": "88027c52fa55d7c29fc4ec8320bd0972c35c1284",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/LiruJ/GuiCookie/707bd0446df995370f62ca4d5f288dbf2969517f/GuiCookie/Styles/StyleVariant.cs",
"visit_date": "2021-11-16T14:07:09.827946",
"added": "2024-11-19T01:31:58.784049+00:00",
"created": "2021-10-18T17:37:38",
"int_score": 3,
"score": 3.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
// Copyright (c) homuler & The Vignette Authors. Licensed under the MIT license.
// See the LICENSE file in the repository root for more details.
using Akihabara.Gpu;
using NUnit.Framework;
namespace Akihabara.Tests.Gpu
{
[TestFixture]
public class GlTextureTest
{
#region Constructor
[Test, GpuOnly]
public void Ctor_ShouldInstantiateGlTexture_When_CalledWithNoArguments()
{
var glTexture = new GlTexture();
Assert.AreEqual(glTexture.Width, 0);
Assert.AreEqual(glTexture.Height, 0);
}
[Test, GpuOnly]
public void Ctor_ShouldInstantiateGlTexture_When_CalledWithNameAndSize()
{
var glTexture = new GlTexture(1, 100, 100);
Assert.AreEqual(glTexture.Name, 1);
Assert.AreEqual(glTexture.Width, 100);
Assert.AreEqual(glTexture.Height, 100);
}
#endregion
#region IsDisposed
[Test, GpuOnly]
public void IsDisposed_ShouldReturnFalse_When_NotDisposedYet()
{
var glTexture = new GlTexture();
Assert.False(glTexture.IsDisposed);
}
[Test, GpuOnly]
public void IsDisposed_ShouldReturnTrue_When_AlreadyDisposed()
{
var glTexture = new GlTexture();
glTexture.Dispose();
Assert.True(glTexture.IsDisposed);
}
#endregion
#region Target
[Test, GpuOnly]
public void Target_ShouldReturnTarget()
{
var glTexture = new GlTexture();
Assert.AreEqual(glTexture.Target, Gl.glTexture2D);
}
#endregion
}
}
|
fc3d6171acb52c587222fcb58af3fb401e72313e
|
{
"blob_id": "fc3d6171acb52c587222fcb58af3fb401e72313e",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-02T00:20:37",
"content_id": "29e4504590de1326a39971ba0b335d83359bddac",
"detected_licenses": [
"MIT"
],
"directory_id": "03d3636f13b8ed7c83a9d2e4094464d24450c466",
"extension": "cs",
"filename": "GlTextureTest.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1680,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Akihabara.Tests/Gpu/GlTextureTest.cs",
"provenance": "stack-edu-0010.json.gz:171536",
"repo_name": "canaxx/Akihabara",
"revision_date": "2021-11-02T00:20:37",
"revision_id": "956662f742f9c0c557b90205caddc737836231c2",
"snapshot_id": "6e7082524df1504f80a3cc2e645eb7582c0162ee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/canaxx/Akihabara/956662f742f9c0c557b90205caddc737836231c2/src/Akihabara.Tests/Gpu/GlTextureTest.cs",
"visit_date": "2023-09-01T22:18:34.002536",
"added": "2024-11-19T02:15:29.745280+00:00",
"created": "2021-11-02T00:20:37",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
/* TCP/IP UNAPI implementations control program
By Konamiman 6/2019
Compilation command line:
sdcc --code-loc 0x180 --data-loc 0 -mz80 --disable-warning 196 --no-std-crt0 crt0msx_msxdos_advanced.rel printf_simple.rel putchar_msxdos.rel asm.lib tcpip.c
hex2bin -e com tcpip.ihx
The resulting file, eth.com, is a MSX-DOS executable.
Get the required extra files (asm.h, asm.lib, crt0msx_msxdos_advanced.rel, printf_simple.rel, putchar_msxdos.rel) here:
https://www.konamiman.com/msx/msx-e.html#sdcc
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "asm.h"
#define _TERM0 0
enum TcpipUnapiFunctions {
UNAPI_GET_INFO = 0,
TCPIP_GET_CAPAB = 1,
TCPIP_GET_IPINFO = 2,
TCPIP_NET_STATE = 3,
TCPIP_DNS_Q = 6,
TCPIP_CONFIG_AUTOIP = 25,
TCPIP_CONFIG_IP = 26,
TCPIP_CONFIG_TTL = 27,
TCPIP_CONFIG_PING = 28,
};
enum TcpipErrorCodes {
ERR_OK,
ERR_NOT_IMP,
ERR_NO_NETWORK,
ERR_NO_DATA,
ERR_INV_PARAM,
ERR_QUERY_EXISTS,
ERR_INV_IP,
ERR_NO_DNS,
ERR_DNS,
ERR_NO_FREE_CONN,
ERR_CONN_EXISTS,
ERR_NO_CONN,
ERR_CONN_STATE,
ERR_BUFFER,
ERR_LARGE_DGRAM,
ERR_INV_OPER
};
enum IpAddresses {
IP_LOCAL = 1,
IP_REMOTE = 2,
IP_MASK = 3,
IP_GATEWAY = 4,
IP_DNS1 = 5,
IP_DNS2 = 6
};
const char* strPresentation=
"TCP/IP UNAPI control program 1.1\r\n"
"By Konamiman, 6/2019\r\n"
"\r\n";
const char* strUsage=
"Usage: tcpip f | s\r\n"
" tcpip ip [l<address>] [r<address>] [m<address>] [g<address>]\r\n"
" [p<address>] [s<address>] [a(0|1|2|3)]]\r\n"
" tcpip set [p(0|1)] [ttl<TTL value>] [tos<TOS value>]\r\n"
"\r\n"
"f: Show implementation capabilities and features\r\n"
"s: Show current configuration and status information\r\n"
"ip l/r/m/g/p/s: Change the IP address (local, remote, subnet mask,\r\n"
" primary DNS server, secondary DNS server)\r\n"
"ip a: Configure IP addresses to retrieve automatically\r\n"
" (0=none, 1=local+subnet+gateway, 2=DNS servers, 3=all)\r\n"
"set p: Enable (1) or disable (0) reply to incoming PINGs\r\n"
"set ttl: Set TTL for outgoing deatagrams (0-255)\r\n"
"set tos: Set ToS for outgoing deatagrams (0-255)\r\n";
const char* strMissingParams = "Missing parameters";
const char* strInvParam = "Invalid parameter";
const char* strYES="YES";
const char* strNO="NO";
const char* strON="ON";
const char* strOFF="OFF";
Z80_registers regs;
int i;
int param;
unapi_code_block codeBlock;
byte mustChangeIP[6];
byte newIP[6*4];
byte mustChangeAutoIP = 0;
byte newAutoIP;
byte mustChangeTTL = 0;
byte newTTL;
byte mustChangeTOS = 0;
byte newTOS;
byte mustChangePingReply = 0;
byte newPingReply;
byte isSpec11;
// I know, these should be on a tcpip.h
void PrintUsageAndEnd();
void PrintImplementationName();
void DoShowInfo();
void Terminate(char* errorMessage);
int strcmpi(const char *a1, const char *a2);
int strncmpi(const char *a1, const char *a2, unsigned size);
void DoShowFeatures();
void DoShowStatus();
void ParseFlagParam(char* param, byte* flagAddress, byte* flagValue);
void ParseIP(char* IP, byte* flagAddress, byte* ipAddress);
void ParseAutoIP(char* param, byte* flagAddress, byte* flagValue);
void ParseByteParam(char* param, byte* flagAddress, byte* valueAddress);
void DoChangeIP(byte IPindex, byte* IPvalue);
void DoChangeAutoIP(byte autoIP);
void DoChangePingReply(byte newPingReply);
void DoChangeTtlTos(byte mustChangeTTL, byte newTTL, byte mustChangeTOS, byte newTOS);
void print(char* str);
#define print(x) printf(x)
/**********************
*** MAIN is here ***
**********************/
int main(char** argv, int argc)
{
memset(mustChangeIP, 0, 6);
print(strPresentation);
if(argc==0) {
PrintUsageAndEnd();
}
i = UnapiGetCount("TCP/IP");
if(i==0) {
print("*** No TCP/IP UNAPI implementations found");
return 0;
}
UnapiBuildCodeBlock(NULL, 1, &codeBlock);
if(strcmpi(argv[0], "f")==0) {
PrintImplementationName();
DoShowFeatures();
Terminate(NULL);
}
else if(strcmpi(argv[0], "s")==0) {
PrintImplementationName();
DoShowStatus();
Terminate(NULL);
}
else if(strcmpi(argv[0], "ip")==0) {
if(argc == 1) {
Terminate(strMissingParams);
}
for(param=1; param<argc; param++) {
if(tolower(argv[param][0]) == 'l') {
ParseIP(argv[param]+1, &mustChangeIP[IP_LOCAL-1], &newIP[(IP_LOCAL-1)*4]);
} else if(tolower(argv[param][0]) == 'r') {
ParseIP(argv[param]+1, &mustChangeIP[IP_REMOTE-1], &newIP[(IP_REMOTE-1)*4]);
} else if(tolower(argv[param][0]) == 'm') {
ParseIP(argv[param]+1, &mustChangeIP[IP_MASK-1], &newIP[(IP_MASK-1)*4]);
} else if(tolower(argv[param][0]) == 'g') {
ParseIP(argv[param]+1, &mustChangeIP[IP_GATEWAY-1], &newIP[(IP_GATEWAY-1)*4]);
} else if(tolower(argv[param][0]) == 'p') {
ParseIP(argv[param]+1, &mustChangeIP[IP_DNS1-1], &newIP[(IP_DNS1-1)*4]);
} else if(tolower(argv[param][0]) == 's') {
ParseIP(argv[param]+1, &mustChangeIP[IP_DNS2-1], &newIP[(IP_DNS2-1)*4]);
} else if(tolower(argv[param][0]) == 'a') {
ParseAutoIP(argv[param]+1, &mustChangeAutoIP, &newAutoIP);
} else {
Terminate(strInvParam);
}
}
}
else if(strcmpi(argv[0], "set")==0) {
if(argc == 1) {
Terminate(strMissingParams);
}
for(param=1; param<argc; param++) {
if(tolower(argv[param][0]) == 'p') {
ParseFlagParam(argv[param]+1, &mustChangePingReply, &newPingReply);
}
else if(strncmpi(argv[param], "ttl", 3)==0) {
ParseByteParam(argv[param]+3, &mustChangeTTL, &newTTL);
} else if(strncmpi(argv[param], "tos", 3)==0) {
ParseByteParam(argv[param]+3, &mustChangeTOS, &newTOS);
} else {
Terminate(strInvParam);
}
}
}
else {
Terminate(strInvParam);
}
PrintImplementationName();
for(i=IP_LOCAL-1; i<=IP_DNS2-1; i++) {
if(mustChangeIP[i]) {
DoChangeIP(i+1, &newIP[i*4]);
}
}
if(mustChangeAutoIP) {
DoChangeAutoIP(newAutoIP);
}
if(mustChangePingReply) {
DoChangePingReply(newPingReply);
}
if(mustChangeTTL || mustChangeTOS) {
DoChangeTtlTos(mustChangeTTL, newTTL, mustChangeTOS, newTOS);
}
printf("Done.");
return 0;
}
/****************************
*** FUNCTIONS are here ***
****************************/
void PrintUsageAndEnd()
{
print(strUsage);
DosCall(0, ®s, REGS_MAIN, REGS_NONE);
}
void PrintImplementationName()
{
byte readChar;
byte versionMain;
byte versionSec;
byte specVersionMain;
byte specVersionSec;
uint nameAddress;
print("Implementation name: ");
UnapiCall(&codeBlock, UNAPI_GET_INFO, ®s, REGS_NONE, REGS_MAIN);
versionMain = regs.Bytes.B;
versionSec = regs.Bytes.C;
specVersionMain = regs.Bytes.D;
specVersionSec = regs.Bytes.E;
nameAddress = regs.UWords.HL;
isSpec11 = regs.UWords.DE >= 0x0101;
while(1) {
readChar = UnapiRead(&codeBlock, nameAddress);
if(readChar == 0) {
break;
}
putchar(readChar);
nameAddress++;
}
printf(" v%u.%u\r\nTCP/IP UNAPI specification version: %u.%u\r\n\r\n", versionMain, versionSec, specVersionMain, specVersionSec);
}
void Terminate(const char* errorMessage)
{
if(errorMessage != NULL) {
printf("\r\n*** %s\r\n", errorMessage);
}
DosCall(_TERM0, ®s, REGS_NONE, REGS_NONE);
}
int strcmpi(const char *a1, const char *a2) {
char c1, c2;
/* Want both assignments to happen but a 0 in both to quit, so it's | not || */
while((c1=*a1) | (c2=*a2)) {
if (!c1 || !c2 || /* Unneccesary? */
(islower(c1) ? toupper(c1) : c1) != (islower(c2) ? toupper(c2) : c2))
return (c1 - c2);
a1++;
a2++;
}
return 0;
}
int strncmpi(const char *a1, const char *a2, unsigned size) {
char c1, c2;
/* Want both assignments to happen but a 0 in both to quit, so it's | not || */
while((size > 0) && (c1=*a1) | (c2=*a2)) {
if (!c1 || !c2 || /* Unneccesary? */
(islower(c1) ? toupper(c1) : c1) != (islower(c2) ? toupper(c2) : c2))
return (c1 - c2);
a1++;
a2++;
size--;
}
return 0;
}
void PrintYesNoBit(char* message, uint flags, int bitIndex)
{
printf("%s: %s\r\n", message, (flags & (1<<bitIndex)) ? strYES : strNO);
}
void DoShowFeatures()
{
uint features;
byte linkLevelProto;
regs.Bytes.B = 1;
UnapiCall(&codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
features = regs.UWords.DE;
linkLevelProto = regs.Bytes.B;
print("Capabilities:\r\n\r\n");
PrintYesNoBit("Send ICMP echo messages (PINGs) and retrieve the replies", regs.UWords.HL, 0);
PrintYesNoBit("Resolve host names by querying a local hosts file or database", regs.UWords.HL, 1);
PrintYesNoBit("Resolve host names by querying a DNS server", regs.UWords.HL, 2);
PrintYesNoBit("Open TCP connections in active mode", regs.UWords.HL, 3);
PrintYesNoBit("Open TCP connections in passive mode, with specified remote socket", regs.UWords.HL, 4);
PrintYesNoBit("Open TCP connections in passive mode, with unespecified remote socket", regs.UWords.HL, 5);
PrintYesNoBit("Send and receive TCP urgent data", regs.UWords.HL, 6);
PrintYesNoBit("Explicitly set the PUSH bit when sending TCP data", regs.UWords.HL, 7);
PrintYesNoBit("Send data to a TCP connection before the ESTABLISHED state is reached", regs.UWords.HL, 8);
PrintYesNoBit("Discard the output buffer of a TCP connection", regs.UWords.HL, 9);
PrintYesNoBit("Open UDP connections", regs.UWords.HL, 10);
PrintYesNoBit("Open raw IP connections", regs.UWords.HL, 11);
PrintYesNoBit("Explicitly set the TTL and ToS for outgoing datagrams", regs.UWords.HL, 12);
PrintYesNoBit("Explicitly set the automatic reply to PINGs on or off", regs.UWords.HL, 13);
if(!isSpec11) {
PrintYesNoBit("Automatically obtain the IP addresses", regs.UWords.HL, 14);
}
if(isSpec11) {
PrintYesNoBit("Get the TTL and ToS for outgoing datagrams", regs.UWords.HL, 15);
regs.Bytes.B = 4;
UnapiCall(&codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
PrintYesNoBit("Automatically obtain the local IP address, subnet mask and default gateway", regs.UWords.HL, 0);
PrintYesNoBit("Automatically obtain the IP addresses of the DNS servers", regs.UWords.HL, 1);
PrintYesNoBit("Manually set the local IP address", regs.UWords.HL, 2);
PrintYesNoBit("Manually set the peer IP address", regs.UWords.HL, 3);
PrintYesNoBit("Manually set the subnet mask IP address", regs.UWords.HL, 4);
PrintYesNoBit("Manually set the default gateway IP address", regs.UWords.HL, 5);
PrintYesNoBit("Manually set the primary DNS server IP address", regs.UWords.HL, 6);
PrintYesNoBit("Manually set the secondary DNS server IP address", regs.UWords.HL, 7);
PrintYesNoBit("Use TLS in active TCP connections", regs.UWords.HL, 8);
PrintYesNoBit("Use TLS in passve TCP connections", regs.UWords.HL, 9);
}
print("\r\nFeatures:\r\n\r\n");
PrintYesNoBit("Physical link is point to point", features, 0);
PrintYesNoBit("Physical link is wireless", features, 1);
PrintYesNoBit("Connection pool is shared by TCP, UDP and raw IP", features, 2);
PrintYesNoBit("Checking network state is time-expensive", features, 3);
PrintYesNoBit("The TCP/IP handling code is assisted by external hardware", features, 4);
PrintYesNoBit("The loopback address (127.x.x.x) is supported", features, 5);
PrintYesNoBit("A host name resolution cache is implemented", features, 6);
PrintYesNoBit("IP datagram fragmentation is supported", features, 7);
PrintYesNoBit("User timeout suggested when opening a TCP connection is actually applied", features, 8);
if(isSpec11) {
PrintYesNoBit("TTL can be specified for ICMP echo messages (PINgs)", features, 9);
PrintYesNoBit("Querying a DNS server is a blocking operation", features, 10);
PrintYesNoBit("Opening a TCP connection is a blocking operation", features, 11);
PrintYesNoBit("Support for veryfying the server certificate on active TCP connections", features, 12);
}
print("\r\nLink level protocol: ");
if(linkLevelProto == 0) {
print("Unespecified\r\n");
} else if(linkLevelProto == 1) {
print("SLIP\r\n");
} else if(linkLevelProto == 2) {
print("PPP\r\n");
} else if(linkLevelProto == 3) {
print("Ethernet\r\n");
} else if(linkLevelProto == 4) {
print("WiFi\r\n");
} else {
printf("Unknown (%i)\r\n", linkLevelProto);
}
regs.Bytes.B = 2;
UnapiCall(&codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.B != 0) {
printf("TCP connections (total / free): %i / %i\r\n", regs.Bytes.B, regs.Bytes.D);
}
if(regs.Bytes.C != 0) {
printf("UDP connections (total / free): %i / %i\r\n", regs.Bytes.C, regs.Bytes.E);
}
if(regs.Bytes.H != 0) {
printf("Raw IP connections (total / free): %i / %i\r\n", regs.Bytes.H, regs.Bytes.L);
}
regs.Bytes.B = 3;
UnapiCall(&codeBlock, TCPIP_GET_CAPAB, ®s, REGS_MAIN, REGS_MAIN);
printf("Maximum incoming datagram size supported: %i bytes\r\n", regs.UWords.HL);
printf("Maximum outgoing datagram size supported: %i bytes\r\n", regs.UWords.DE);
}
void DoShowStatus()
{
regs.Bytes.B = IP_LOCAL;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
printf("Local IP address: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
regs.Bytes.B = IP_REMOTE;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.A == 0) {
printf("Remote IP address: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
}
regs.Bytes.B = IP_MASK;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.A == 0) {
printf("Subnet mask: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
}
regs.Bytes.B = IP_GATEWAY;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.A == 0) {
printf("Default gateway address: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
}
regs.Bytes.B = IP_DNS1;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
printf("Primary DNS server address: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
regs.Bytes.B = IP_DNS2;
UnapiCall(&codeBlock, TCPIP_GET_IPINFO, ®s, REGS_MAIN, REGS_MAIN);
printf("Secondary DNS server address: %i.%i.%i.%i\r\n", regs.Bytes.L, regs.Bytes.H, regs.Bytes.E, regs.Bytes.D);
regs.Bytes.B = 0;
UnapiCall(&codeBlock, TCPIP_CONFIG_AUTOIP, ®s, REGS_MAIN, REGS_MAIN);
regs.Bytes.C &= 3;
print("\r\nAddresses configured for automatic retrieval: ");
if(regs.Bytes.C == 0) {
print("None\r\n");
} else if(regs.Bytes.C == 1) {
print("Local, mask and gateway\r\n");
} else if(regs.Bytes.C == 2) {
print("DNS servers\r\n");
} else {
print("All\r\n");
}
print("\r\n");
regs.Bytes.B = 0;
UnapiCall(&codeBlock, TCPIP_CONFIG_TTL, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.A == ERR_OK) {
printf("TTL for outgoing datagrams: %i\r\n", regs.Bytes.D);
printf("ToS for outgoing datagrams: %i\r\n", regs.Bytes.E);
}
regs.Bytes.B = 0;
UnapiCall(&codeBlock, TCPIP_CONFIG_PING, ®s, REGS_MAIN, REGS_MAIN);
printf("Reply incoming PING requests: %s\r\n", regs.Bytes.C ? strYES : strNO);
UnapiCall(&codeBlock, TCPIP_NET_STATE, ®s, REGS_MAIN, REGS_MAIN);
print("Network state: ");
if(regs.Bytes.B == 0) {
print("CLOSED\r\n");
} else if(regs.Bytes.B == 1) {
print("Opening\r\n");
} else if(regs.Bytes.B == 2) {
print("OPEN\r\n");
} else if(regs.Bytes.B == 3) {
print("Closing\r\n");
} else {
print("Unknown\r\n");
}
}
void ParseFlagParam(char* param, byte* flagAddress, byte* flagValue)
{
*flagAddress = 1;
if(param[0]=='0') {
*flagValue = 0;
} else if(param[0]=='1') {
*flagValue = 1;
} else {
Terminate(strInvParam);
}
}
void ParseIP(char* IP, byte* flagAddress, byte* ipAddress)
{
*flagAddress = 1;
regs.Words.HL = (int)IP;
regs.Bytes.B = 2; //Error if not an IP address
UnapiCall(&codeBlock, TCPIP_DNS_Q, ®s, REGS_MAIN, REGS_MAIN);
if(regs.Bytes.A != 0) {
Terminate(strInvParam);
}
*((int*)ipAddress) = regs.Words.HL;
*(((int*)ipAddress)+1) = regs.Words.DE;
}
void ParseAutoIP(char* param, byte* flagAddress, byte* flagValue)
{
*flagAddress = 1;
if(param[0] >= '0' && param[0] <= '3') {
*flagValue = (byte)param[0] - (byte)'0';
} else {
Terminate(strInvParam);
}
}
void DoChangeIP(byte IPindex, byte* IPvalue)
{
regs.Bytes.B = IPindex;
regs.Words.HL = *((int*)IPvalue);
regs.Words.DE = *(((int*)IPvalue)+1);
UnapiCall(&codeBlock, TCPIP_CONFIG_IP, ®s, REGS_MAIN, REGS_MAIN);
}
void DoChangeAutoIP(byte autoIP)
{
regs.Bytes.B = 1;
regs.Bytes.C = autoIP;
UnapiCall(&codeBlock, TCPIP_CONFIG_AUTOIP, ®s, REGS_MAIN, REGS_MAIN);
}
void ParseByteParam(char* param, byte* flagAddress, byte* valueAddress)
{
int value;
*flagAddress = 1;
value = atoi(param);
if(value>255 || (*valueAddress == 0 && (param[0]!='0' || param[1]!='\0'))) {
Terminate(strInvParam);
}
*valueAddress = (byte)value;
}
void DoChangePingReply(byte newPingReply)
{
regs.Bytes.B = 1;
regs.Bytes.C = newPingReply;
UnapiCall(&codeBlock, TCPIP_CONFIG_PING, ®s, REGS_MAIN, REGS_MAIN);
}
void DoChangeTtlTos(byte mustChangeTTL, byte newTTL, byte mustChangeTOS, byte newTOS)
{
regs.Bytes.B = 0;
UnapiCall(&codeBlock, TCPIP_CONFIG_TTL, ®s, REGS_MAIN, REGS_MAIN);
if(mustChangeTTL) {
regs.Bytes.D = newTTL;
}
if(mustChangeTOS) {
regs.Bytes.E = newTOS;
}
regs.Bytes.B = 1;
UnapiCall(&codeBlock, TCPIP_CONFIG_TTL, ®s, REGS_MAIN, REGS_MAIN);
}
|
9320e47d945b6df559dc21dfd42053e9befa6de7
|
{
"blob_id": "9320e47d945b6df559dc21dfd42053e9befa6de7",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-23T11:02:42",
"content_id": "04b8446b3d271545c59cae72506e8e179f86b0fa",
"detected_licenses": [
"MIT"
],
"directory_id": "b649650a7745314ce3afc0fee3ec2766d8e3dbfd",
"extension": "c",
"filename": "tcpip.c",
"fork_events_count": 4,
"gha_created_at": "2019-04-30T13:09:52",
"gha_event_created_at": "2019-07-20T02:20:53",
"gha_language": "Assembly",
"gha_license_id": "MIT",
"github_id": 184264184,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19523,
"license": "MIT",
"license_type": "permissive",
"path": "/tools/tcpip.c",
"provenance": "stack-edu-0000.json.gz:141084",
"repo_name": "Konamiman/MSX-UNAPI-specification",
"revision_date": "2023-01-23T11:02:42",
"revision_id": "b1f5f1853a4119170ac5cb4ae9a44390da79e34b",
"snapshot_id": "bc5cdaeb00e47f633a65caa50c94c3919976edb1",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/Konamiman/MSX-UNAPI-specification/b1f5f1853a4119170ac5cb4ae9a44390da79e34b/tools/tcpip.c",
"visit_date": "2023-02-06T11:28:43.898926",
"added": "2024-11-18T21:33:27.933726+00:00",
"created": "2023-01-23T11:02:42",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
<?php
namespace Modules\Profile\Entities;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function child()
{
return $this->hasOne('Modules\Birth\Entities\Children');
}
public function admin()
{
return $this->hasOne('Modules\Admin\Entities\Admin');
}
public function announcement()
{
return $this->hasMany(Announcement::class);
}
public function religion()
{
return $this->belongsTo(Religion::class);
}
public function event()
{
return $this->hasMany(Envet::class);
}
public function death()
{
return $this->hasOne('Modules\Death\Entities\Death');
}
public function attendEvent()
{
return $this->hasMany(AttendEvent::class);
}
public function userMessage()
{
return $this->hasMany(UserMessage::class);
}
public function family()
{
return $this->belongsTo('Modules\Family\Entities\Family');
}
public function leave()
{
return $this->hasOne('Modules\Address\Entities\LivesIn');
}
public function message()
{
return $this->hasMany(Message::class);
}
public function userImage()
{
return $this->hasOne(UserImage::class);
}
public function userVedio()
{
return $this->hasOne(UserVedio::class);
}
public function wife()
{
return $this->hasOne('Modules\Marriage\Entities\Wife');
}
public function husband()
{
return $this->hasOne('Modules\Marriage\Entities\Husband');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function businessUndergoes()
{
return $this->belongsToMany(BusinessUndergoes::class);
}
public function deseaseUndergoes()
{
return $this->belongsToMany(DeseaseUndergoes::class);
}
public function gender()
{
return $this->belongsTo(Gender::class);
}
public function image()
{
return $this->belongsTo(Image::class);
}
public function life()
{
return $this->belongsTo(LifeStatus::class);
}
public function maritalStatus()
{
return $this->belongsTo(MaritalStatus::class);
}
public function contacts()
{
return $this->hasMany(UserContact::class);
}
public function details()
{
return $this->hasMany(UserDetail::class);
}
public function health()
{
return $this->hasOne(Health::class);
}
public function workHistories()
{
return $this->hasMany(WorkHistory::class);
}
public function work()
{
return $this->hasOne('Modules\Address\Entities\WorkIn');
}
}
|
0c141575a1d7e877307a4465f04becd995c10327
|
{
"blob_id": "0c141575a1d7e877307a4465f04becd995c10327",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-27T00:17:48",
"content_id": "ae7fae23c48a36fd8213c91210b2be12bd526d74",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "8d973808d8ff16e5725983ec7fd10fa0a08d8658",
"extension": "php",
"filename": "Profile.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2754,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/Modules/Profile/Entities/Profile.php",
"provenance": "stack-edu-0051.json.gz:513265",
"repo_name": "adilimudassir/nifis",
"revision_date": "2019-01-27T00:17:48",
"revision_id": "9fb8bb8839cfac4c2fedadc90a62c61b9e09dcc4",
"snapshot_id": "ec031369e1d7e35de97fef0a2bcd978c8c596e21",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adilimudassir/nifis/9fb8bb8839cfac4c2fedadc90a62c61b9e09dcc4/Modules/Profile/Entities/Profile.php",
"visit_date": "2020-04-21T11:44:02.686297",
"added": "2024-11-18T21:31:38.759921+00:00",
"created": "2019-01-27T00:17:48",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
<?php
/**
* CollectionHandler.php.
*
* @author wangbing <[email protected]>
* @date 2017/8/19
*/
namespace pithyone\zhihu\crawler\Handler;
use pithyone\zhihu\crawler\Selector\CollectionSelector;
use Symfony\Component\DomCrawler\Crawler;
/**
* Class CollectionHandler.
*/
class CollectionHandler extends AbstractHandler
{
/**
* @var string 收藏夹ID
*/
protected $collectionId;
/**
* @var int 页数
*/
protected $page;
/**
* CollectionHandler constructor.
*
* @param string $collectionId
* @param int $page
*/
public function __construct($collectionId, $page = 1)
{
parent::__construct();
$this->collectionId ?: $this->collectionId = $collectionId;
$this->page ?: $this->page = $page;
}
/**
* {@inheritdoc}
*/
public function pick($callback = null)
{
$crawler = $this->client->request(
'GET',
self::BASE_URI."/collection/{$this->collectionId}?page={$this->page}"
);
return $crawler
->filter('div[class="zu-main-content"] div[class="zm-item"]')
->each(function (Crawler $node) use ($callback) {
$collectionSelector = new CollectionSelector($node);
$item = [
'title' => $collectionSelector->title,
'link' => $collectionSelector->link,
'vote' => $collectionSelector->vote,
'author' => $collectionSelector->author,
'author_link' => $collectionSelector->author_link,
'bio' => $collectionSelector->bio,
'summary' => $collectionSelector->summary,
'comment' => $collectionSelector->comment,
'created' => $collectionSelector->created,
];
return is_callable($callback) ? call_user_func($callback, $item) : $item;
});
}
}
|
4b511721e30730d9255a1a7603bbaf0f9d0487c0
|
{
"blob_id": "4b511721e30730d9255a1a7603bbaf0f9d0487c0",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-18T08:53:44",
"content_id": "068c6335acc88c7db05a6d14cd5191f9081bb20e",
"detected_licenses": [
"MIT"
],
"directory_id": "d7812ff94a19d34a191d6a7a6cf12145e6ace426",
"extension": "php",
"filename": "CollectionHandler.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2038,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Handler/CollectionHandler.php",
"provenance": "stack-edu-0052.json.gz:137905",
"repo_name": "hiandy168/zhihu-crawler",
"revision_date": "2017-09-18T08:53:44",
"revision_id": "4f394e27b5bbc94ce85adb1787ed3cd1bf52e4b3",
"snapshot_id": "a76aac60bac48c48956a16956c38153ea081b8f3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hiandy168/zhihu-crawler/4f394e27b5bbc94ce85adb1787ed3cd1bf52e4b3/src/Handler/CollectionHandler.php",
"visit_date": "2021-05-06T10:28:41.324691",
"added": "2024-11-18T22:55:10.217192+00:00",
"created": "2017-09-18T08:53:44",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
#include <catch2/catch.hpp>
#include <from_papers.hpp>
#include <simple.hpp>
#include <dump_dot.hpp>
#include <sstream>
#include <iostream>
TEST_CASE("Display BDD in a fancy way") {
Cudd mgr(2);
std::vector<std::string> names{"and", "xor with spaces"};
BDD and_bdd = abo::example_bdds::and_bdd(mgr, 2);
BDD xor_bdd = abo::example_bdds::xor_bdd(mgr, 12);
std::stringstream s1, s2, s3;
abo::util::dump_dot_readable(mgr, std::vector<BDD>{and_bdd,xor_bdd},s1, names);
abo::util::dump_dot_readable(mgr, std::vector<BDD>{and_bdd, xor_bdd},s2);
abo::util::dump_dot_readable(mgr, and_bdd,s3);
std::cout << s1.str() << "\n";
std::cout << s3.str();
// CHECK(s2.str() == s3.str());
}
|
5d0cd029d018cd679a8c5e31b6a7eba8036e843b
|
{
"blob_id": "5d0cd029d018cd679a8c5e31b6a7eba8036e843b",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-12T10:08:13",
"content_id": "5511f5d81694fd5fa768db0613279f2ff8dae777",
"detected_licenses": [
"MIT"
],
"directory_id": "14e26edef3b20eb1c5183ab3c189f5306114ca5f",
"extension": "cpp",
"filename": "dump_dot_test.cpp",
"fork_events_count": 0,
"gha_created_at": "2020-03-11T14:50:30",
"gha_event_created_at": "2020-03-11T14:50:31",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 246598957,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 709,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/dump_dot_test.cpp",
"provenance": "stack-edu-0002.json.gz:8929",
"repo_name": "andreaswendler/abo",
"revision_date": "2020-03-12T10:08:13",
"revision_id": "d5d31e0714365960fb9c02a6a5b240c07ac3a738",
"snapshot_id": "2ad085f00b7be95082861faadbce92213f96cef7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andreaswendler/abo/d5d31e0714365960fb9c02a6a5b240c07ac3a738/tests/dump_dot_test.cpp",
"visit_date": "2021-03-12T06:52:39.711080",
"added": "2024-11-18T22:10:44.596055+00:00",
"created": "2020-03-12T10:08:13",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
"""encyclopedia.py"""
import json
import random
from source.applications.application import Application
from source.window import (
Window,
WindowProperty,
DisplayWindow,
ScrollableWindow,
PromptWindow
)
# from source.models.models import Dictionary
import source.utils as utils
def open_data_file(datafile):
with open(datafile, 'r') as f:
data = json.loads(f.read())
return data
class Encyclopedia(Application):
CLI_NAMES = ('encyclopedia', 'spaceship', 'space')
def build_application(self, rebuild=False, reinsert=False, examples=False):
screen = self.screen
height, width = screen.getmaxyx()
self.data = open_data_file(".\data\spaceship.json")
exit()
|
c936a0703d52d3ab5b7e7939735bb9be2fa0fa12
|
{
"blob_id": "c936a0703d52d3ab5b7e7939735bb9be2fa0fa12",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-26T15:59:33",
"content_id": "f47490929c7d388f2d3229238faad87386e6b9f4",
"detected_licenses": [
"MIT"
],
"directory_id": "567a4a614727613160f64da1ddd20fbc9fdeb906",
"extension": "py",
"filename": "encyclopedia.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88906537,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 734,
"license": "MIT",
"license_type": "permissive",
"path": "/source/applications/encyclopedia.py",
"provenance": "stack-edu-0056.json.gz:312495",
"repo_name": "whitegreyblack/PyCurses",
"revision_date": "2019-06-26T15:59:33",
"revision_id": "78f3637b4c03c11d7f6ef15b20a1acf699d4be24",
"snapshot_id": "3790fd7561b02c984c8aee97cd1579c31866ab57",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/whitegreyblack/PyCurses/78f3637b4c03c11d7f6ef15b20a1acf699d4be24/source/applications/encyclopedia.py",
"visit_date": "2021-01-19T23:00:18.661002",
"added": "2024-11-18T21:52:06.124239+00:00",
"created": "2019-06-26T15:59:33",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
const functions = require("firebase-functions")
const { getFirestore } = require("firebase-admin/firestore")
const {
Scrapers: { AssociationService },
} = require("@amoschan/common-admin")
module.exports.updateAssociations = ({ app }) =>
functions.firestore
.document("/scrapers/{id}")
.onWrite(async (change, context) => {
const firestore = getFirestore(app)
const logger = console
const { id } = context.params
await logger.debug(`fetching accounts using scraper: ${id}`)
const accountsSnapshot = await firestore
.collection("accounts")
.where("scraper", "==", id)
.where("status", "==", "active")
.get()
for (const account of accountsSnapshot.docs) {
await new AssociationService(account.ref.path, {
firestore,
logger,
}).perform()
}
})
|
265afb7f251219cdcaeb657a9ec1f2c2dc54f2ec
|
{
"blob_id": "265afb7f251219cdcaeb657a9ec1f2c2dc54f2ec",
"branch_name": "refs/heads/main",
"committer_date": "2023-03-30T15:25:11",
"content_id": "b37b6cd87b530bdf5ef611f90ce6760d95f48f9d",
"detected_licenses": [
"MIT"
],
"directory_id": "344e4c13d3041f8fc292d8c83e5349cc0e221217",
"extension": "js",
"filename": "update-associations.js",
"fork_events_count": 0,
"gha_created_at": "2023-03-14T15:53:13",
"gha_event_created_at": "2023-04-13T16:29:22",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 613957797,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 871,
"license": "MIT",
"license_type": "permissive",
"path": "/web/apps/backend/functions/on-scraper-write/update-associations.js",
"provenance": "stack-edu-0041.json.gz:55524",
"repo_name": "achan/amoschan",
"revision_date": "2023-03-30T15:25:11",
"revision_id": "579aa932ced36f500823609460e0c9b084f97fe5",
"snapshot_id": "ac84600c60e90389902dde7face90d9ecc2160d4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/achan/amoschan/579aa932ced36f500823609460e0c9b084f97fe5/web/apps/backend/functions/on-scraper-write/update-associations.js",
"visit_date": "2023-05-27T06:48:46.029807",
"added": "2024-11-19T02:03:07.539640+00:00",
"created": "2023-03-30T15:25:11",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz"
}
|
use std::collections::HashMap;
use crate::utils;
pub enum BackendType {
Unknown,
Fs,
Erasure,
Gateway,
}
pub struct ObjectInfo {
// Name of the bucket.
pub bucket: String,
// Name of the object.
pub name: String,
// Date and time when the object was last modified.
pub mod_time: utils::DateTime,
// Total object size.
pub size: i64,
// IsDir indicates if the object is prefix.
pub is_dir: bool,
// Hex encoded unique entity tag of the object.
pub etag: String,
// The ETag stored in the gateway backend
pub inner_etag: String,
// Version ID of this object.
pub version_id: String,
// Indicates if this is the latest current version
// latest can be true for delete marker or a version.
pub is_latest: bool,
// Indicates if the versionId corresponds
// to a delete marker on an object.
pub delete_marker: bool,
// Indicates if transition is complete/pending
pub transition_status: String,
// Name of transitioned object on remote tier
transitioned_obj_name: String,
// VERSION_ID on the the remote tier
transition_version_id: String,
// Name of remote tier object has transitioned to
pub transition_tier: String,
// Indicates date a restored object expires
pub restore_expires: utils::DateTime,
// Indicates if a restore is in progress
pub restore_ongoing: bool,
// A standard MIME type describing the format of the object.
pub content_type: String,
// Specifies what content encodings have been applied to the object and thus
// what decoding mechanisms must be applied to obtain the object referenced
// by the Content-Type header field.
pub content_encoding: String,
// Date and time at which the object is no longer able to be cached
pub expires: utils::DateTime,
// Sets status of whether this is a cache hit/miss
pub cache_status: crate::objectcache::CacheStatus,
// Sets whether a cacheable response is present in the cache
pub cache_lookup_status: crate::objectcache::CacheStatus,
// Specify object storage class
pub storage_class: String,
pub replication_status: crate::bucket::replication::Status,
// User-Defined metadata
pub user_defined: HashMap<String, String>,
// User-Defined object tags
pub user_tags: String,
// List of individual parts, maximum size of upto 10,000
pub parts: Vec<crate::xl_storage::ObjectPartInfo>,
// Implements writer and reader used by CopyObject API
// pub Writer: io.WriteCloser,
// pub Reader: *hash.Reader,
// pub PutObjReader :*PutObjReader,
metadata_only: bool,
version_only: bool, // adds a new version, only used by CopyObject
key_rotation: bool,
// Date and time when the object was last accessed.
pub acc_time: utils::DateTime,
// Indicates object on disk is in legacy data format
pub legacy: bool,
// Indicates which backend filled this structure
backend_type: BackendType,
pub version_purge_status: crate::storage::VersionPurgeStatus,
// The total count of all versions of this object
pub num_versions: isize,
// The modtime of the successor object version if any
pub successor_mod_time: utils::DateTime,
}
pub struct ListObjectsInfo {
/// <p>A flag that indicates whether Amazon S3 returned all of the results that satisfied the search criteria.</p>
pub is_truncated: bool,
/// <p>When response is truncated (the IsTruncated element value in the response is true), you can use the key name in this field as marker in the subsequent request to get next set of objects. Amazon S3 lists objects in alphabetical order Note: This element is returned only if you have delimiter request parameter specified. If response does not include the NextMarker and it is truncated, you can use the value of the last Key in the response as the marker in the subsequent request to get the next set of object keys.</p>
pub next_marker: Option<String>,
pub objects: Vec<ObjectInfo>,
pub prefixes: Vec<String>,
}
pub struct ListObjectsV2Info {
/// <p> If ContinuationToken was sent with the request, it is included in the response.</p>
pub continuation_token: Option<String>,
/// <p>Set to false if all of the results were returned. Set to true if more keys are available to return. If the number of results exceeds that specified by MaxKeys, all of the results might not be returned.</p>
pub is_truncated: Option<bool>,
/// <p> <code>NextContinuationToken</code> is sent when <code>isTruncated</code> is true, which means there are more keys in the bucket that can be listed. The next list requests to Amazon S3 can be continued with this <code>NextContinuationToken</code>. <code>NextContinuationToken</code> is obfuscated and is not a real key</p>
pub next_continuation_token: Option<String>,
pub objects: Vec<ObjectInfo>,
pub prefixes: Vec<String>,
}
pub struct ObjectToDelete {}
pub struct DeletedObject {}
|
ff6ff797395c58b7744d486878d04a9ccef939f0
|
{
"blob_id": "ff6ff797395c58b7744d486878d04a9ccef939f0",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-11T13:34:40",
"content_id": "da2ae228dc8c54329c0f38e82c78b76f0ad1f8e6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bea187ec9bca1fe65b8a80abc0cf85c215d60f7d",
"extension": "rs",
"filename": "api_datatypes.rs",
"fork_events_count": 0,
"gha_created_at": "2021-06-03T10:17:41",
"gha_event_created_at": "2022-05-10T06:31:32",
"gha_language": "Rust",
"gha_license_id": "Apache-2.0",
"github_id": 373465796,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 5044,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/object/api_datatypes.rs",
"provenance": "stack-edu-0068.json.gz:307637",
"repo_name": "01intelligence/hulk",
"revision_date": "2021-10-11T13:34:40",
"revision_id": "29e4c98f686042e9290d3ad9e25df9e2e8c6f587",
"snapshot_id": "dfe50e875bd457df761a6a95f556b43896f02528",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/01intelligence/hulk/29e4c98f686042e9290d3ad9e25df9e2e8c6f587/src/object/api_datatypes.rs",
"visit_date": "2023-08-21T22:40:52.866057",
"added": "2024-11-19T00:33:38.104123+00:00",
"created": "2021-10-11T13:34:40",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
/* ----------------------------------------------------------------------
* Project: PULP DSP Library
* Title: plp_dwt_q32s_xpulpv2.c
* Description: 32bit Fixed-point Discret Wavelet Transform on real input data for XPULPV2
*
* $Date: 10. Juli 2021
* $Revision: V1
*
* Target Processor: PULP cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2021 ETH Zurich and University of Bologna. All rights reserved.
*
* Author: Jakub Mandula, ETH Zurich
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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 "plp_math.h"
#include "plp_const_structs.h"
/* HELPER FUNCTIONS */
#define HAAR_COEF ((int64_t) 0x5a82799a)
#define MAC_SHIFT 31U
#define MAC(Acc, A, B) Acc += (int64_t)((int64_t) A * (int64_t) B);
#define MSU(Acc, A, B) Acc -= (int64_t)((int64_t) A * (int64_t) B);
#include "plp_dwt_signal_ext.h"
/**
@ingroup dwt
*/
/**
@defgroup q32DWTKernels DWT kernels on Q31 input values
These kernels calculate the DWT transform on Q31 fixed point data.
*/
/**
@addtogroup q32DWTKernels
@{
*/
/**
@brief Q31 fixed-point DWT on real input data for XPULPV2 extension.
@param[in] pSrc points to the input buffer (real data)
@param[in] length length of input buffer
@param[in] wavelet wavelet structure for calculating DWT
@param[in] mode boundary extension mode
@param[out] pDstA points to ouput buffer with Approximate coefficients
@param[out] pDstD points to ouput buffer with Detailed coefficients
@return none
*/
void plp_dwt_q32s_xpulpv2(const int32_t *__restrict__ pSrc,
uint32_t length,
const plp_dwt_wavelet_q32 wavelet,
plp_dwt_extension_mode mode,
int32_t *__restrict__ pDstA,
int32_t *__restrict__ pDstD) {
int32_t *pCurrentA = pDstA;
int32_t *pCurrentD = pDstD;
static uint32_t step = 2;
int32_t offset;
/***
* The filter convolution is done in 4 steps handling cases where
* 1. Filter is hanging over the left side of the signal
* 2. Filter is same size, or totally enclosed in signal
* 3. Filter is larger than the enclosed signal and hangs over both edges
* 4. Filter hangs over the right side of the signal
*
* Each of the cases, where signal hangs over the boundary of the signal, values are computed
* on demand based on the edge extension mode.
*/
/* Step 1.
* Handle Left overhanging
*
* X() = x x[A B C D E F]
* H() = [d c b a]
* ^ ^
* | First compute the filter part overlapping with the signal
* Then extend the signal (x x) by computing the values based on the extension mode
*/
for(offset = step-1; offset < wavelet.length - 1 && offset < length; offset += step){
int64_t sum_lo = 0;
int64_t sum_hi = 0;
uint32_t filt_j = 0;
// Compute Filter overlapping with signal
for(; filt_j <= offset; filt_j++){
MAC(sum_lo, wavelet.dec_lo[filt_j], pSrc[offset - filt_j]);
MAC(sum_hi, wavelet.dec_hi[filt_j], pSrc[offset - filt_j]);
}
// Compute Left edge extension
switch(mode){
case PLP_DWT_MODE_CONSTANT:
CONSTANT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_SYMMETRIC:
SYMMETRIC_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_REFLECT:
REFLECT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTISYMMETRIC:
ANTISYMMETRIC_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTIREFLECT:
ANTIREFLECT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset, int64_t);
break;
case PLP_DWT_MODE_PERIODIC:
case PLP_DWT_MODE_ZERO:
default:
break;
}
*pCurrentA++ = sum_lo >> MAC_SHIFT;
*pCurrentD++ = sum_hi >> MAC_SHIFT;
}
/* Step 2.
* Compute center (length >= wavelet.length)
*
* X() = [A B C D E F]
* h() = [d c b a]
* ^
* Compute a full convolution of the filter with the signal
*/
for(;offset < length; offset += step){
int64_t sum_lo = 0;
int64_t sum_hi = 0;
const int32_t *pS = pSrc + offset;
const int32_t *dec_lo = wavelet.dec_lo;
const int32_t *dec_hi = wavelet.dec_hi;
uint32_t blkCnt = wavelet.length >> 1;
do{
int32_t S1 = *pS--;
int32_t S2 = *pS--;
MAC(sum_lo, *dec_lo++, S1);
MAC(sum_hi, *dec_hi++, S1);
MAC(sum_lo, *dec_lo++, S2);
MAC(sum_hi, *dec_hi++, S2);
}while(--blkCnt);
*pCurrentA++ = sum_lo >> MAC_SHIFT;
*pCurrentD++ = sum_hi >> MAC_SHIFT;
}
/* Step 3.
* Compute center (length < wavelet.length)
*
* X() = y y[A B C]x x x
* h() = [h g f e d c b a]
* ^ ^ ^
* | | Compute Right extension (x x x) based on extension mode
* | Compute a full convolution of the filter overlapping with the signal
* Compute Left extension (y y) based on extension mode
*/
for(;offset < wavelet.length - 1; offset += step){
int64_t sum_lo = 0;
int64_t sum_hi = 0;
uint32_t filt_j = 0;
// Filter Right extension
switch(mode){
case PLP_DWT_MODE_CONSTANT:
CONSTANT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_SYMMETRIC:
SYMMETRIC_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_REFLECT:
REFLECT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTISYMMETRIC:
ANTISYMMETRIC_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTIREFLECT:
ANTIREFLECT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset, int64_t);
break;
case PLP_DWT_MODE_PERIODIC:
case PLP_DWT_MODE_ZERO:
default:
filt_j = offset - length + 1;
break;
}
// Filter Center overlapp
for(; filt_j <= offset; filt_j++){
MAC(sum_lo, wavelet.dec_lo[filt_j], pSrc[offset - filt_j]);
MAC(sum_hi, wavelet.dec_hi[filt_j], pSrc[offset - filt_j]);
}
// Filter Left extension
switch(mode){
case PLP_DWT_MODE_CONSTANT:
CONSTANT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_SYMMETRIC:
SYMMETRIC_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_REFLECT:
REFLECT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTISYMMETRIC:
ANTISYMMETRIC_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTIREFLECT:
ANTIREFLECT_EDGE_LEFT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset, int64_t);
break;
case PLP_DWT_MODE_PERIODIC:
case PLP_DWT_MODE_ZERO:
default:
break;
}
*pCurrentA++ = sum_lo >> MAC_SHIFT;
*pCurrentD++ = sum_hi >> MAC_SHIFT;
}
/* Step 4.
* Handle Right overhanging
*
* X() = [A B C D E F]x x
* H() = [d c b a]
* ^ ^
* | First extend the signal (x x) by computing the values based on the extension mode
* Then compute the filter part overlapping with the signal
*/
for(; offset < length + wavelet.length - 1; offset += step){
int64_t sum_lo = 0;
int64_t sum_hi = 0;
uint32_t filt_j = 0;
// Compute Left edge extension
switch(mode){
case PLP_DWT_MODE_CONSTANT:
CONSTANT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_SYMMETRIC:
SYMMETRIC_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_REFLECT:
REFLECT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTISYMMETRIC:
ANTISYMMETRIC_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset);
break;
case PLP_DWT_MODE_ANTIREFLECT:
ANTIREFLECT_EDGE_RIGHT(sum_lo, sum_hi, pSrc, length, wavelet, filt_j, offset, int64_t);
break;
case PLP_DWT_MODE_PERIODIC:
case PLP_DWT_MODE_ZERO:
default:
filt_j = offset - length + 1;
break;
}
// Filter overlapping with signal
for(; filt_j < wavelet.length; filt_j++){
MAC(sum_lo, wavelet.dec_lo[filt_j], pSrc[offset - filt_j]);
MAC(sum_hi, wavelet.dec_hi[filt_j], pSrc[offset - filt_j]);
}
*pCurrentA++ = sum_lo >> MAC_SHIFT;
*pCurrentD++ = sum_hi >> MAC_SHIFT;
}
}
#define MAKE_HAAR(NAME, COEF, SHIFT) \
void NAME(const int32_t *__restrict__ pSrc, \
uint32_t length, \
plp_dwt_extension_mode mode, \
int32_t *__restrict__ pDstA, \
int32_t *__restrict__ pDstD) { \
int32_t *pCurrentA = pDstA; \
int32_t *pCurrentD = pDstD; \
\
\
/*** \
* The filter convolution is done in 2 steps handling cases where \
* 1. Filter is same size, or totally enclosed in signal center \
* 2. Filter hangs over the right side of the signal \
* \
* In of the cases, where signal hangs over the boundary of the signal, values are computed \
* on demand based on the edge extension mode. \
*/ \
\
\
/* Step 1. \
* Compute center (length >= wavelet.length) \
* \
* X() = [A B C D E F] \
* h() = [b a] \
* ^ \
* Compute a full convolution of the filter with the signal \
*/ \
uint32_t blkCnt = length >> 2; \
\
const int32_t *pS = pSrc; \
while(blkCnt--){ \
int32_t s0 = *pS++; \
int32_t s1 = *pS++; \
int32_t s2 = *pS++; \
int32_t s3 = *pS++; \
\
*pCurrentA++ = (COEF * (s0 + s1)) >> SHIFT; \
*pCurrentD++ = (COEF * (s0 - s1)) >> SHIFT; \
*pCurrentA++ = (COEF * (s2 + s3)) >> SHIFT; \
*pCurrentD++ = (COEF * (s2 - s3)) >> SHIFT; \
\
} \
\
if(length % 4 > 1){ \
int32_t s0 = *pS++; \
int32_t s1 = *pS++; \
\
*pCurrentA++ = (COEF * (s0 + s1)) >> SHIFT; \
*pCurrentD++ = (COEF * (s0 - s1)) >> SHIFT; \
} \
\
\
\
\
\
/* Step 2. \
* Handle Right overhanging (only for odd signal lengths) \
* \
* X() = [A B C D E F]x \
* H() = [b a] \
* ^ ^ \
* | Extend the signal (x) by computing the values based on the extension mode \
* Then compute the filter part overlapping with the signal \
*/ \
if(length % 2U){ \
int64_t sum_lo = 0; \
int64_t sum_hi = 0; \
\
uint32_t filt_j = 0; \
\
/* Compute Left edge extension */ \
switch(mode){ \
case PLP_DWT_MODE_CONSTANT: \
case PLP_DWT_MODE_SYMMETRIC: \
/* dec_lo[0] * src[N-1] + dec_lo[1] * src[N-1] */ \
sum_lo = 2 * COEF * pSrc[length - 1]; \
/* dec_hi[0] * src[N-1] + dec_hi[1] * src[N-1] == -dec_hi[1] * src[N-1] + dec_hi[1] * src[N-1]*/\
sum_hi = 0; \
break; \
case PLP_DWT_MODE_REFLECT: \
sum_lo = COEF * (pSrc[length - 1] + pSrc[length - 2]); \
sum_hi = COEF * (pSrc[length - 1] - pSrc[length - 2]); \
break; \
case PLP_DWT_MODE_ANTISYMMETRIC: \
sum_lo = COEF * (pSrc[length - 1] - pSrc[length - 1]); \
sum_hi = COEF * (pSrc[length - 1] + pSrc[length - 1]); \
break; \
case PLP_DWT_MODE_ANTIREFLECT: \
sum_lo = COEF * (3*pSrc[length - 1] - pSrc[length - 2]); \
sum_hi = COEF * ( -pSrc[length - 1] + pSrc[length - 2]); \
break; \
case PLP_DWT_MODE_PERIODIC: \
case PLP_DWT_MODE_ZERO: \
default: \
sum_lo = COEF * pSrc[length - 1]; \
sum_hi = COEF * pSrc[length - 1]; \
break; \
} \
\
*pCurrentA = sum_lo >> SHIFT; \
*pCurrentD = sum_hi >> SHIFT; \
} \
} \
/**
@brief Q31 Fixed-point DWT kernel optimized for Haar Wavelet for XPULPV2 extension.
@param[in] pSrc points to the input buffer (q31)
@param[in] length length of input buffer
@param[in] mode boundary extension mode
@param[out] pDstA points to ouput buffer with Approximate coefficients
@param[out] pDstD points to ouput buffer with Detailed coefficients
@return none
*/
MAKE_HAAR(plp_dwt_haar_q32s_xpulpv2, HAAR_COEF, MAC_SHIFT)
/**
@brief Q31 Fixed-point DWT kernel optimized for un-normalized Haar Wavelet for XPULPV2 extension.
@param[in] pSrc points to the input buffer (q31)
@param[in] length length of input buffer
@param[in] mode boundary extension mode
@param[out] pDstA points to ouput buffer with Approximate coefficients
@param[out] pDstD points to ouput buffer with Detailed coefficients
@return none
*/
MAKE_HAAR(plp_dwt_haar_u_q32s_xpulpv2, 1U, 0U)
|
6678019e390f2a092e6db448ea6e8713f319528d
|
{
"blob_id": "6678019e390f2a092e6db448ea6e8713f319528d",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-01T16:16:00",
"content_id": "d0d4052e21be717b61eaa3caf29b0ef16f461ee2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8295713f41e924bb8babf6b1bbedf9e9da962e8e",
"extension": "c",
"filename": "plp_dwt_q32s_xpulpv2.c",
"fork_events_count": 30,
"gha_created_at": "2019-12-20T14:42:51",
"gha_event_created_at": "2023-03-01T16:16:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 229281908,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 23348,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/TransformFunctions/kernels/plp_dwt_q32s_xpulpv2.c",
"provenance": "stack-edu-0000.json.gz:272733",
"repo_name": "pulp-platform/pulp-dsp",
"revision_date": "2023-03-01T16:16:00",
"revision_id": "cc5594b9998b4f243be02c3a7e853db9c936302b",
"snapshot_id": "2109b1ce91f92b54600d1e5c083c80885e751859",
"src_encoding": "UTF-8",
"star_events_count": 30,
"url": "https://raw.githubusercontent.com/pulp-platform/pulp-dsp/cc5594b9998b4f243be02c3a7e853db9c936302b/src/TransformFunctions/kernels/plp_dwt_q32s_xpulpv2.c",
"visit_date": "2023-03-15T18:43:02.575140",
"added": "2024-11-18T22:26:10.392728+00:00",
"created": "2023-03-01T16:16:00",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
package com.tensquare.article.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA
*
* @author Zjianru
* @version 1.0
* 2019/5/27
* com.tensquare.article.pojo
*/
@Entity
@Table(name="tb_article")
public class Article implements Serializable{
/**
* id
*/
@Id
private String id;
/**
* 专栏ID
*/
private String columnid;
/**
* 用户ID
*/
private String userid;
/**
* 标题
*/
private String title;
/**
* 文章正文
*/
private String content;
/**
* 文章封面
*/
private String image;
/**
* 发表日期
*/
private java.util.Date createtime;
/**
* 修改日期
*/
private java.util.Date updatetime;
/**
* 是否公开
*/
private String ispublic;
/**
* 是否置顶
*/
private String istop;
/**
* 浏览量
*/
private Integer visits;
/**
* 点赞数
*/
private Integer thumbup;
/**
* 评论数
*/
private Integer comment;
/**
* 审核状态
*/
private String state;
/**
* 所属频道
*/
private String channelid;
/**
* URL
*/
private String url;
/**
* 类型
*/
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getColumnid() {
return columnid;
}
public void setColumnid(String columnid) {
this.columnid = columnid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public java.util.Date getCreatetime() {
return createtime;
}
public void setCreatetime(java.util.Date createtime) {
this.createtime = createtime;
}
public java.util.Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(java.util.Date updatetime) {
this.updatetime = updatetime;
}
public String getIspublic() {
return ispublic;
}
public void setIspublic(String ispublic) {
this.ispublic = ispublic;
}
public String getIstop() {
return istop;
}
public void setIstop(String istop) {
this.istop = istop;
}
public Integer getVisits() {
return visits;
}
public void setVisits(Integer visits) {
this.visits = visits;
}
public Integer getThumbup() {
return thumbup;
}
public void setThumbup(Integer thumbup) {
this.thumbup = thumbup;
}
public Integer getComment() {
return comment;
}
public void setComment(Integer comment) {
this.comment = comment;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getChannelid() {
return channelid;
}
public void setChannelid(String channelid) {
this.channelid = channelid;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
035f3e17c2761136e02265b1c3edde04f14891cf
|
{
"blob_id": "035f3e17c2761136e02265b1c3edde04f14891cf",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-25T09:08:00",
"content_id": "175e0a4b251cf21bf4bf9fff17df7f8a7de64e9d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a1c01039585d26551024000b2871b7b059c05e13",
"extension": "java",
"filename": "Article.java",
"fork_events_count": 0,
"gha_created_at": "2019-05-25T08:44:28",
"gha_event_created_at": "2022-06-21T01:13:03",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 188542266,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3304,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tensquare_article/src/main/java/com/tensquare/article/pojo/Article.java",
"provenance": "stack-edu-0031.json.gz:71694",
"repo_name": "Zjianru/tensquare",
"revision_date": "2021-01-25T09:08:00",
"revision_id": "1095e8953c488e4c5f8a8e5789d7bb08628dd35b",
"snapshot_id": "c391207cedb1a748d021d80c9171a9ba1c149672",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/Zjianru/tensquare/1095e8953c488e4c5f8a8e5789d7bb08628dd35b/tensquare_article/src/main/java/com/tensquare/article/pojo/Article.java",
"visit_date": "2022-06-28T06:45:35.575535",
"added": "2024-11-19T00:06:27.176739+00:00",
"created": "2021-01-25T09:08:00",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
# Load the user configuration file.
#
# $1 - name of the config file to load
def load_config(config_file):
# Used in old config files, before "option ImageSize" was added.
MB = 1000 * 1000
GB = 1000 * MB
if os.path.isfile(config_file):
print(f"Loading configuration from {config_file}")
exec(open(config_file).read())
else:
print(f"Could not load {config_file}")
exit(1)
# Invoke an option, which might be in one of the board
# directories or in the top-level option directory.
def option(option_name, *args):
OPTION = option_name
for d in BOARDDIRS + [TOPDIR]:
OPTIONDIR = f"{d}/option/{OPTION}"
if os.path.exists(f"{OPTIONDIR}/setup.sh"):
print(f"Option: {OPTION} {' '.join(args)}")
exec(open(f"{OPTIONDIR}/setup.sh").read(), globals())
OPTION = None
OPTIONDIR = None
return 0
print(f"Cannot import option {OPTION}.")
print("No setup.sh found in either:")
for d in BOARDDIRS + [TOPDIR]:
print(f" * {d}/option")
exit(1)
|
e8a69a38857e8707dfffdc39d451d29e9ee9a7b1
|
{
"blob_id": "e8a69a38857e8707dfffdc39d451d29e9ee9a7b1",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-12T12:59:57",
"content_id": "71dbd66c27ac4087905b1601d7c9e0424299295f",
"detected_licenses": [
"MIT"
],
"directory_id": "dca1211d70b238aa4973ce15ad3045c4c65de375",
"extension": "py",
"filename": "config.py",
"fork_events_count": 0,
"gha_created_at": "2018-08-24T12:08:56",
"gha_event_created_at": "2023-02-28T20:24:00",
"gha_language": "Shell",
"gha_license_id": null,
"github_id": 145986853,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1088,
"license": "MIT",
"license_type": "permissive",
"path": "/src/libs/config.py",
"provenance": "stack-edu-0065.json.gz:12341",
"repo_name": "armbsd/kitchen",
"revision_date": "2023-08-12T12:59:57",
"revision_id": "ff8cabff112b071100c16bef566be90b2d7adfd4",
"snapshot_id": "3b43cf381d34e5f3097a1bd2cc5dcea62588a262",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/armbsd/kitchen/ff8cabff112b071100c16bef566be90b2d7adfd4/src/libs/config.py",
"visit_date": "2023-08-29T04:02:09.850653",
"added": "2024-11-18T20:10:19.119907+00:00",
"created": "2023-08-12T12:59:57",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
# Uses python3
import sys
def optimal_summands(n):
summands = []
#write your code here
if n==2:
return [2]
for i in range(n):
summands.append(i+1)
if n-i-1<=summands[-1]:
rem = n-i-1+summands[-1]
summands.pop()
summands.append(rem)
return summands
n-=i+1
return summands
if __name__ == '__main__':
#input = sys.stdin.read()
n = int(input())
summands = optimal_summands(n)
print(len(summands))
for x in summands:
print(x, end=' ')
|
fad4f25a9b7ed29e0e7b15a0862f79ff7507a22c
|
{
"blob_id": "fad4f25a9b7ed29e0e7b15a0862f79ff7507a22c",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-18T15:56:38",
"content_id": "24135c2e91a563700c243a34fc11b6c11f6142d2",
"detected_licenses": [
"MIT"
],
"directory_id": "0af9a1f12c2d8b6e085620be97771327448340b7",
"extension": "py",
"filename": "different_summands.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 359116789,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 560,
"license": "MIT",
"license_type": "permissive",
"path": "/greedy_algorithms/5_maximum_number_of_prizes/different_summands.py",
"provenance": "stack-edu-0061.json.gz:258587",
"repo_name": "Desaiakshata/Algorithms-problems",
"revision_date": "2021-04-18T15:56:38",
"revision_id": "90f4e40ba05e4bdfc783614bb70b9156b05eec0b",
"snapshot_id": "c46817a1303958d8f6e1d65285cbbdedb7071a24",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Desaiakshata/Algorithms-problems/90f4e40ba05e4bdfc783614bb70b9156b05eec0b/greedy_algorithms/5_maximum_number_of_prizes/different_summands.py",
"visit_date": "2023-04-29T00:09:31.118888",
"added": "2024-11-18T21:32:12.743007+00:00",
"created": "2021-04-18T15:56:38",
"int_score": 4,
"score": 3.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
// <autogenerated>
// This file was generated by T4 code generator Pluck.int.tt.
// Any changes made to this file manually will be lost next time the file is regenerated.
// </autogenerated>
using System;
using System.Linq;
using System.Dynamic;
using System.Collections;
using System.Threading.Tasks;
using static Ramda.NET.Currying;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Ramda.NET
{
public static partial class R
{
/// <summary>
/// Returns a new list by plucking the same named property off all objects inthe list supplied.
/// <para />
/// sig: k -> [{k: v}] -> [v]
/// </summary>
/// <param name="key">The key name to pluck off of each object.</param>
/// <param name="list">The array to consider.</param>
/// <returns>The list of values for the given key.</returns>
/// <see cref="R.Props"/>
public static dynamic Pluck<TSource>(int key, IEnumerable<TSource> list) {
return Currying.Pluck(key, list);
}
/// <summary>
/// Returns a new list by plucking the same named property off all objects inthe list supplied.
/// <para />
/// sig: k -> [{k: v}] -> [v]
/// </summary>
/// <param name="key">The key name to pluck off of each object.</param>
/// <param name="list">The array to consider.</param>
/// <returns>The list of values for the given key.</returns>
/// <see cref="R.Props"/>
public static dynamic Pluck<TSource>(RamdaPlaceholder key, IEnumerable<TSource> list) {
return Currying.Pluck(key, list);
}
/// <summary>
/// Returns a new list by plucking the same named property off all objects inthe list supplied.
/// <para />
/// sig: k -> [{k: v}] -> [v]
/// </summary>
/// <param name="key">The key name to pluck off of each object.</param>
/// <param name="list">The array to consider.</param>
/// <returns>The list of values for the given key.</returns>
/// <see cref="R.Props"/>
public static dynamic Pluck(int key, RamdaPlaceholder list = null) {
return Currying.Pluck(key, list);
}
/// <summary>
/// Returns a new list by plucking the same named property off all objects inthe list supplied.
/// <para />
/// sig: k -> [{k: v}] -> [v]
/// </summary>
/// <param name="key">The key name to pluck off of each object.</param>
/// <param name="list">The array to consider.</param>
/// <returns>The list of values for the given key.</returns>
/// <see cref="R.Props"/>
public static dynamic Pluck(RamdaPlaceholder key = null, RamdaPlaceholder list = null) {
return Currying.Pluck(key, list);
}
}
}
|
8197c16415b480fd1160cfa3aebb36e4951f5d06
|
{
"blob_id": "8197c16415b480fd1160cfa3aebb36e4951f5d06",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-04T18:17:26",
"content_id": "e2d90dc1b7113c9a047fea40aa184382bdb1d9b8",
"detected_licenses": [
"MIT"
],
"directory_id": "3620c1db83de6551c9ff5436b92d1bd5a58fb1dd",
"extension": "cs",
"filename": "Pluck.int.cs",
"fork_events_count": 7,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 66217128,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2569,
"license": "MIT",
"license_type": "permissive",
"path": "/Ramda/Pluck.int.cs",
"provenance": "stack-edu-0015.json.gz:106614",
"repo_name": "sagifogel/Ramda.NET",
"revision_date": "2018-04-04T18:17:26",
"revision_id": "8e84381751ad84118a4b868bc322bd26787608aa",
"snapshot_id": "467745be744af7b924c522dd3557fb1189fa0bfc",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/sagifogel/Ramda.NET/8e84381751ad84118a4b868bc322bd26787608aa/Ramda/Pluck.int.cs",
"visit_date": "2020-09-27T17:12:22.179518",
"added": "2024-11-18T22:47:03.736490+00:00",
"created": "2018-04-04T18:17:26",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
<?php declare(strict_types=1);
namespace kornrunner\Ethereum\Token;
use kornrunner\Ethereum\Contract;
/**
* Nexo
*
* @see https://etherscan.io/token/0xb62132e35a6c13ee1ee0f84dc5d40bad8d815206
*/
class NEXO extends Contract {
public const ADDRESS = '0xb62132e35a6c13ee1ee0f84dc5d40bad8d815206';
public const DECIMALS = 18;
}
|
8ce50269a0a7d9c0cc967135d238493a38034051
|
{
"blob_id": "8ce50269a0a7d9c0cc967135d238493a38034051",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-11T08:24:59",
"content_id": "23fc473a6a632277230987139019edc10375ddaf",
"detected_licenses": [
"MIT"
],
"directory_id": "e09e26d9fcb06e69fdfa91ebc3e610bc411994f9",
"extension": "php",
"filename": "NEXO.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 338,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Ethereum/Token/NEXO.php",
"provenance": "stack-edu-0052.json.gz:153543",
"repo_name": "selaz/php-ethereum-token",
"revision_date": "2021-08-11T08:24:59",
"revision_id": "32792c6c39f3681a2b308990ce85dca557803bbb",
"snapshot_id": "f43c6232e54982583250cab61f46a196b6aef2c4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/selaz/php-ethereum-token/32792c6c39f3681a2b308990ce85dca557803bbb/src/Ethereum/Token/NEXO.php",
"visit_date": "2023-07-02T06:45:05.863952",
"added": "2024-11-18T22:05:10.140470+00:00",
"created": "2021-08-11T08:24:59",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
peg_file! grammar("grammar.rustpeg");
use std::io;
use std::io::Read;
use std::fs::File;
use std::path::PathBuf;
use error::{Result, Error};
use translation_unit::TranslationUnit;
use ast::Expr;
pub type ParseError = grammar::ParseError;
pub fn parse_raw(code: &str) -> grammar::ParseResult<Expr> {
grammar::expr(code)
}
fn read_from(file: &PathBuf) -> io::Result<String> {
let mut f = try!(File::open(file.to_str().unwrap()));
let mut buf = String::new();
try!(f.read_to_string(&mut buf));
Ok(buf)
}
pub fn parse(file: &PathBuf) -> Result<TranslationUnit> {
let parsed = match read_from(file) {
Ok(code) => grammar::expr(code.as_str()),
Err(e) => return Err(Error::OnFileOpen(e)),
};
match parsed {
Ok(parsed) => Ok(TranslationUnit { file: file, ast: parsed }),
Err(err) => Err(Error::OnParse(err)),
}
}
|
8cde7baa6add6d3bd4fe7ce5686443722f230550
|
{
"blob_id": "8cde7baa6add6d3bd4fe7ce5686443722f230550",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-27T11:38:23",
"content_id": "1dbdf5bd1786c09e9b4f41e710521712a6717205",
"detected_licenses": [
"MIT"
],
"directory_id": "8ec99d048c0a7f322184f3af32367215a88ada95",
"extension": "rs",
"filename": "parser.rs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 66411493,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 879,
"license": "MIT",
"license_type": "permissive",
"path": "/src/parser.rs",
"provenance": "stack-edu-0068.json.gz:321244",
"repo_name": "rhysd/RustyML",
"revision_date": "2016-08-27T11:38:23",
"revision_id": "92d4f1a2e14b6b2a00d10a7ed4721a5a085fb9c1",
"snapshot_id": "6adf3fb7c129c4cdf39b04984ac9323f6dcf5273",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/rhysd/RustyML/92d4f1a2e14b6b2a00d10a7ed4721a5a085fb9c1/src/parser.rs",
"visit_date": "2020-07-03T17:39:00.620180",
"added": "2024-11-18T22:44:30.623812+00:00",
"created": "2016-08-27T11:38:23",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, Repository } from 'typeorm';
import { LoginUserDto } from './dtos/login-user.dto';
import { User } from './entities/user.entity';
import { JwtService } from 'src/jwt/jwt.service';
import { SearchUserFilters } from './interfaces/search-user-filters.interface';
import { PasswordHelper } from 'src/common/utils/PasswordHelper';
import { CreateUserDto } from './dtos/create-user.dto';
type QueryResult = [boolean, string?];
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly usersRepository: Repository<User>,
private readonly jwtService: JwtService,
private readonly connection: Connection,
) {}
async getAll(): Promise<User[]> {
return this.usersRepository.find({});
}
async getOne(filters: SearchUserFilters): Promise<User | undefined> {
return this.usersRepository.findOne({ ...filters });
}
async createUser(newUserDto: CreateUserDto): Promise<QueryResult> {
try {
const userInDb = await this.usersRepository.findOne({
email: newUserDto.email,
});
if (userInDb) throw new Error('Email already registered');
const newUser = this.usersRepository.create(newUserDto);
await this.usersRepository.save(newUser);
return [true];
} catch (e) {
return [false, e.message];
}
}
async loginUser({
email,
password,
}: LoginUserDto): Promise<[boolean, string?, string?]> {
try {
const userInDb = await this.usersRepository.findOneOrFail({ email });
const isPasswordMatch = await PasswordHelper.validatePassword(
password,
userInDb.password,
);
if (!isPasswordMatch) throw new Error('Invalid email/password');
return [true, undefined, await this.jwtService.sign({ id: userInDb.id })];
} catch (e) {
return [false, e.message];
}
}
}
|
4ee9883a3ee914911dda3c5d14d5b77b67d21521
|
{
"blob_id": "4ee9883a3ee914911dda3c5d14d5b77b67d21521",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-16T00:05:26",
"content_id": "034bb941ac81f11b16f95edf0e33e88f4a9ee1ed",
"detected_licenses": [
"MIT"
],
"directory_id": "0765154c85692f049e27978a94c8db8c6e366e46",
"extension": "ts",
"filename": "users.service.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 395266709,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1972,
"license": "MIT",
"license_type": "permissive",
"path": "/src/users/users.service.ts",
"provenance": "stack-edu-0074.json.gz:460577",
"repo_name": "xndong1020/nestjs-serverless",
"revision_date": "2021-08-16T00:05:26",
"revision_id": "b829892cf1e0b67212830b7c9efbcb81724219f0",
"snapshot_id": "5977a1aee4183e54d6ea32c52190b6961bd56738",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xndong1020/nestjs-serverless/b829892cf1e0b67212830b7c9efbcb81724219f0/src/users/users.service.ts",
"visit_date": "2023-07-07T10:27:44.156240",
"added": "2024-11-19T03:11:37.441424+00:00",
"created": "2021-08-16T00:05:26",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.util.Geometry;
public class SphericalDirectionCosines {
/**
* An object containing the direction cosines between the center of a sphere
* and a point on its surface
*/
public SphericalDirectionCosines() {
/** An empty constructor */
}
/**
* A constructor used to create a DirectionCosine object for a point at a
* given colatitude and longitude (in radians)
*/
public SphericalDirectionCosines(double colatitude, double longitude) {
getDirectionCosines(colatitude, longitude);
}
void getDirectionCosines(double colatitude, double longitude) {
/**
* Get direction cosines for a line joining a center point to a surface
* point at (colatitude, longitude)
*/
A = Math.sin(colatitude) * Math.cos(longitude);
B = Math.sin(colatitude) * Math.sin(longitude);
C = Math.cos(colatitude);
// direction cosines for the parallel of latitude through the point
D = Math.sin(longitude);
E = -1.0 * Math.cos(longitude);
// direction cosines for the meridian through the point
G = Math.cos(colatitude) * Math.cos(longitude);
H = Math.cos(colatitude) * Math.sin(longitude);
K = -1.0 * Math.sin(colatitude);
}
double A, B, C, D, E, G, H, K;
}
|
ac5ebff02beaea5a9e9a299ef4a8e71f050f7087
|
{
"blob_id": "ac5ebff02beaea5a9e9a299ef4a8e71f050f7087",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-23T20:44:10",
"content_id": "fd93e1379d4a1f9913cbbc70c276db5c40b94be8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "406757a1fd3624bdc64c97a905bfa6d31f48293f",
"extension": "java",
"filename": "SphericalDirectionCosines.java",
"fork_events_count": 1,
"gha_created_at": "2017-12-18T17:42:33",
"gha_event_created_at": "2023-02-20T10:09:05",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 114670393,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2305,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/externals/src/main/java/llnl/gnem/core/util/Geometry/SphericalDirectionCosines.java",
"provenance": "stack-edu-0024.json.gz:115772",
"repo_name": "LLNL/coda-calibration-tool",
"revision_date": "2023-08-23T20:44:10",
"revision_id": "f86cdc694ca7cc6a34b965321d5c87684afb9cf4",
"snapshot_id": "67e349f9c0653b5ab0804cc8a90e77c1817394a1",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/LLNL/coda-calibration-tool/f86cdc694ca7cc6a34b965321d5c87684afb9cf4/externals/src/main/java/llnl/gnem/core/util/Geometry/SphericalDirectionCosines.java",
"visit_date": "2023-08-30T05:03:58.686698",
"added": "2024-11-18T23:12:37.738047+00:00",
"created": "2023-08-23T20:44:10",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
<?php
/**
* Author: imsamurai <[email protected]>
* Date: 18.11.2012
* Time: 22:03:38
* Format: http://book.cakephp.org/2.0/en/development/testing.html
*/
App::uses('DiffbotModel', 'DiffbotSource.Model');
App::uses('DiffbotSource', 'DiffbotSource.Model/Datasource/Http');
App::uses('DiffbotTestSource', 'DiffbotSource.Model/Datasource/Http');
App::uses('HttpSourceConnection', 'HttpSource.Model/Datasource');
App::uses('DiffbotConnection', 'DiffbotSource.Model/Datasource');
App::uses('HttpSocketResponse', 'Network/Http');
/**
* DiffbotSourceTest
*
* @package DiffbotSourceTest
* @subpackage Model
*/
class DiffbotSourceTest extends CakeTestCase {
/**
* DiffbotSource Model
*
* @var AppModel
*/
public $Model = null;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->Model = new DiffbotModel(false, false, 'diffbotTest');
}
/**
* Test article
*
* @param array $request
* @param string $response
* @param float $result
*
* @dataProvider getArticleProvider
*/
public function testArticle(array $request, $response, $result) {
$this->_mockConnection($request, $response);
$this->Model->setSource('article');
$res = $this->Model->find('first',
array(
'conditions' =>
array(
'token' => 'token',
'url' => 'http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn',
'fields' => 'text'
)
)
);
$this->assertSame($result, $res[$this->Model->alias]['title']);
}
/**
* Test article2
*
* @param array $request
* @param string $response
* @param float $result
*
* @dataProvider getArticleErrorProvider
*/
public function testArticleError(array $request, $response, $result) {
$this->_mockConnection($request, $response);
$this->Model->setSource('article');
$res = $this->Model->find('first',
array('conditions' =>
array('token' => 'token',
'url' => 'http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn',
'fields' => 'text'
)
)
);
$this->assertSame($result, $res);
}
/**
* Data provider for testArticleError
*
* @return array
*/
public function getArticleProvider() {
return array(
//set #0
array(
//request
array(
'method' => 'GET',
'body' => array(),
'uri' => array(
'host' => 'api.diffbot.com',
'port' => 80,
'path' => '/v3/article',
'query' => array('token' => 'token',
'url' => 'http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn',
'fields' => 'text'
)
)
),
//response
'HTTP/1.1 200 OK' .
"\r\n" .
'Server: nginx/1.6.0' .
"\r\n" .
'Date: Wed, 12 Nov 2014 16:07:53 GMT' .
"\r\n" .
'Content-Type: application/json;charset=utf-8' .
"\r\n" .
'Content-Length: 4695' .
"\r\n" .
'Connection: keep-alive' .
"\r\n" .
'Vary: Accept-Encoding' .
"\r\n" .
'Access-Control-Allow-Origin: *' .
"\r\n" . "\r\n" .
'{"objects": [{"date": "Thu, 06 Nov 2014 00:00:00 GMT", "title": "Title for the example", "text": "Example description", "pageUrl": "http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn", "diffbotUri": "article|3|-1912116724", "images": [{"url": "http://amd.c.example.com/amd/20141106-00000032-rcdc-000-0-thumb.jpg", "naturalWidth": 200, "primary": true, "naturalHeight": 148, "diffbotUri": "image|3|1169107753"} ], "html": "<p><br>\n Example description</p>", "humanLanguage": "ja", "type": "article"} ], "request": {"fields": "title", "version": 3, "api": "article", "pageUrl": "http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn"} }',
//result
'Title for the example'
)
);
}
/**
* Data provider for testArticleError
*
* @return array
*/
public function getArticleErrorProvider() {
return array(
//set #0
array(
//request
array(
'method' => 'GET',
'body' => array(),
'uri' => array(
'host' => 'api.diffbot.com',
'port' => 80,
'path' => '/v3/article',
'query' => array('token' => 'token',
'url' => 'http://headlines.example.com/hl?a=20141106-00000032-rcdc-cn',
'fields' => 'text'
)
)
),
//response
'HTTP/1.1 200 OK' .
"\r\n" .
'Server: nginx/1.6.0' .
"\r\n" .
'Date: Wed, 12 Nov 2014 16:07:53 GMT' .
"\r\n" .
'Content-Type: application/json;charset=utf-8' .
"\r\n" .
'Content-Length: 4695' .
"\r\n" .
'Connection: keep-alive' .
"\r\n" .
'Vary: Accept-Encoding' .
"\r\n" .
'Access-Control-Allow-Origin: *' .
"\r\n" . "\r\n" .
'{"errorCode": 401,"error": "Not authorized API token."}',
//result
array()
)
);
}
/**
* Mock connection for test purposes
*
* @param array $request
* @param string $response
*/
protected function _mockConnection($request, $response) {
ConnectionManager::create('diffbotTest', array(
'datasource' => 'DiffbotSource.DiffbotTestSource',
'host' => 'api.diffbot.com',
'path' => '/v3/article',
'prefix' => '',
'port' => 80,
'timeout' => 5
));
$this->Model = new DiffbotModel(false, false, 'diffbotTest');
$DS = $this->Model->getDataSource();
$Connection = $this->getMock('DiffbotTestConnection', array(
'_request'
), array($DS->config));
$Connection->expects($this->once())->method('_request')->with($request)->will($this->returnValue(new HttpSocketResponse($response)));
$DS->setConnection($Connection);
}
}
/**
* Source class for tests
*/
class DiffbotTestSource extends DiffbotSource {
/**
* {@inheritdoc}
*
* @param array $config
* @param HttpSourceConnection $Connection
*/
public function __construct($config = array(), HttpSourceConnection $Connection = null) {
parent::__construct($config, $Connection);
}
/**
* Method for inject mocked connection
*
* @param HttpSourceConnection $Connection
*/
public function setConnection(HttpSourceConnection $Connection) {
parent::__construct($this->config, $Connection);
}
}
/**
* Connection class for tests
*/
class DiffbotTestConnection extends DiffbotConnection {
}
|
0fb9e0e17617d1535cf7c508fcdc05068849961a
|
{
"blob_id": "0fb9e0e17617d1535cf7c508fcdc05068849961a",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-11T14:14:01",
"content_id": "278972a8a85b2e627c752d1402e5bb7f7a58cbb5",
"detected_licenses": [
"MIT"
],
"directory_id": "718eac0ee774cc4c39f2f30a279745af2ebd64ba",
"extension": "php",
"filename": "DiffbotSourceTest.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 6126,
"license": "MIT",
"license_type": "permissive",
"path": "/Test/Case/Model/Datasource/DiffbotSourceTest.php",
"provenance": "stack-edu-0050.json.gz:646171",
"repo_name": "skalmi/CakePHP-DiffbotSource-Datasource",
"revision_date": "2014-12-11T14:14:01",
"revision_id": "1beae822d1c93dcd6ac2da75240f06cc22a0a0b4",
"snapshot_id": "5acb6c972ab363c5ffc0efd4c4bca34652aecdeb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skalmi/CakePHP-DiffbotSource-Datasource/1beae822d1c93dcd6ac2da75240f06cc22a0a0b4/Test/Case/Model/Datasource/DiffbotSourceTest.php",
"visit_date": "2021-01-13T01:23:25.039729",
"added": "2024-11-18T22:42:53.518445+00:00",
"created": "2014-12-11T14:14:01",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
namespace Printer
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.panel2);
this.panel1.ForeColor = System.Drawing.Color.White;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(734, 345);
this.panel1.TabIndex = 0;
this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
//
// panel2
//
this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(141)))), ((int)(((byte)(127)))), ((int)(((byte)(109)))));
this.panel2.Controls.Add(this.label4);
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.label2);
this.panel2.Controls.Add(this.label1);
this.panel2.Enabled = false;
this.panel2.ForeColor = System.Drawing.Color.White;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(734, 80);
this.panel2.TabIndex = 0;
//
// label4
//
this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("宋体", 19F);
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(632, 45);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(90, 26);
this.label4.TabIndex = 3;
this.label4.Text = "星期五";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("宋体", 19F);
this.label3.ForeColor = System.Drawing.Color.White;
this.label3.Location = new System.Drawing.Point(558, 45);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(77, 26);
this.label3.TabIndex = 2;
this.label3.Text = "12:30";
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("宋体", 19F);
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(541, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(181, 26);
this.label2.TabIndex = 1;
this.label2.Text = "2016年6月30日";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("华文彩云", 24.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(12, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(279, 34);
this.label1.TabIndex = 0;
this.label1.Text = "米盒自助打印终端";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(734, 345);
this.Controls.Add(this.panel1);
this.Name = "Form2";
this.Text = "Form2";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
}
}
|
6a98d03b6ea9f06d2fac99cced7fd1e6012cfecc
|
{
"blob_id": "6a98d03b6ea9f06d2fac99cced7fd1e6012cfecc",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-14T12:59:45",
"content_id": "acf14541cae07450e3eaf6bdfbb1201fc0f22a2a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "30952ebb519ec148530ccc755fd5eb58c62dec18",
"extension": "cs",
"filename": "Form2.Designer.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81944991,
"is_generated": true,
"is_vendor": false,
"language": "C#",
"length_bytes": 6541,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/MeboxPrinter/Form2.Designer.cs",
"provenance": "stack-edu-0013.json.gz:648949",
"repo_name": "DengrongGuan12/MeboxPrinter",
"revision_date": "2017-02-14T12:59:45",
"revision_id": "2ef4371d34a66d84aecde926e19e5a224c298fae",
"snapshot_id": "30405dc8e08f5b1f5fd4bff1baba3f2d9846533b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DengrongGuan12/MeboxPrinter/2ef4371d34a66d84aecde926e19e5a224c298fae/MeboxPrinter/Form2.Designer.cs",
"visit_date": "2021-01-22T09:17:03.366019",
"added": "2024-11-18T22:50:30.447310+00:00",
"created": "2017-02-14T12:59:45",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
// Copyright (c) 2019-2020, Andrey Kaydalov
// SPDX-FileCopyrightText: 2019-2022 Andrey Kaydalov <[email protected]>
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include <functional>
#include <hrodvitnir/core/boxes/composition-offset-box.hpp>
#include <hrodvitnir/core/boxes/edit-list-box.hpp>
#include <hrodvitnir/core/boxes/sample-dependency-type-box.hpp>
#include <hrodvitnir/core/boxes/sample-to-chunk-box.hpp>
#include <hrodvitnir/core/boxes/time-to-sample-box.hpp>
#include <hrodvitnir/core/fieldset.hpp>
#include <hrodvitnir/core/fourcc.hpp>
#include <hrodvitnir/core/tree/tree.hpp>
#include <hrodvitnir/core/uuid.hpp>
#include <iostream>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
namespace hrodvitnir::dump
{
struct dump_context
{
dump_context(size_t base_offset_, std::ostream& out_) : base_offset(base_offset_), offset(0), out(&out_) {}
size_t base_offset;
size_t offset;
std::ostream* out;
template <typename T>
void print(const T& value)
{
*out << value;
}
dump_context& operator<<(dump_context&)
{
return *this;
}
template <typename T>
dump_context& operator<<(const T& value)
{
print(value);
return *this;
}
};
struct dump_begin_t
{
};
struct dump_end_t
{
};
struct dump_offset_t
{
};
static constexpr const dump_begin_t dump_begin{};
static constexpr const dump_end_t dump_end{};
static constexpr const dump_offset_t dump_offset{};
template <>
void dump_context::print<dump_begin_t>(const dump_begin_t&)
{
offset += base_offset;
}
template <>
void dump_context::print<dump_end_t>(const dump_end_t&)
{
offset -= base_offset;
}
template <>
void dump_context::print<dump_offset_t>(const dump_offset_t&)
{
for (size_t iter = 0; iter < offset; ++iter)
{
*out << ' ';
}
}
dump_context& any_print(dump_context& o, const std::any& v);
template <typename T>
using ptr = std::shared_ptr<T>;
template <typename T>
using table_ptr_t = ptr<core::table<T>>;
struct any_printer
{
using printer_type = std::function<void(dump_context&, const std::any&)>;
std::unordered_map<std::type_index, printer_type> _printers;
template <typename T, typename Fn>
void register_printer(const Fn& fn)
{
auto printer = [fn](dump_context& o, const std::any& v)
{
const T& val = std::any_cast<const T&>(v);
fn(o, val);
};
_printers.emplace(std::type_index(typeid(T)), printer);
}
void print(dump_context& o, const std::any& v) const
{
auto iter = _printers.find(std::type_index(v.type()));
if (iter == _printers.end())
{
o << "<unprintable type " << v.type().name() << ">";
}
else
{
iter->second(o, v);
}
}
any_printer()
{
auto simple_printer = [](dump_context& o, const auto& x)
{
o << x;
};
auto list_printer = [](dump_context& o, const auto& xs)
{
o << "[ ";
for (const auto& x : xs)
{
any_print(o, x);
o << ", ";
}
o << "]";
};
auto int8_printer = [](dump_context& o, const auto& x)
{
o << static_cast<int16_t>(x);
};
register_printer<char>(simple_printer);
register_printer<uint8_t>(int8_printer);
register_printer<uint16_t>(simple_printer);
register_printer<uint32_t>(simple_printer);
register_printer<uint64_t>(simple_printer);
register_printer<int8_t>(int8_printer);
register_printer<int16_t>(simple_printer);
register_printer<int32_t>(simple_printer);
register_printer<int64_t>(simple_printer);
register_printer<float>(simple_printer);
register_printer<double>(simple_printer);
register_printer<std::string>(simple_printer);
register_printer<std::vector<core::fourcc>>(list_printer);
register_printer<std::vector<double>>(list_printer);
register_printer<std::vector<uint16_t>>(list_printer);
register_printer<std::vector<char>>(list_printer);
register_printer<std::vector<uint8_t>>(list_printer);
register_printer<std::vector<std::vector<uint8_t>>>(list_printer);
register_printer<std::vector<core::boxes::edit_list_item>>(list_printer);
register_printer<core::boxes::edit_list_item>(
[](auto& o, const core::boxes::edit_list_item& edit)
{
o << "{ segment_duration=" << edit.segment_duration << ", media_time=" << edit.media_time
<< ", media_rate_integer=" << edit.media_rate_integer
<< ", media_rate_fraction=" << edit.media_rate_fraction << "}";
});
using stts_entry = core::boxes::time_to_sample_entry;
using ctts_entry = core::boxes::composition_offset_entry;
using stsc_entry = core::boxes::sample_to_chunk_entry;
using sdtp_entry = core::boxes::sample_dependency_type_entry;
auto table_printer = [](auto& o, const auto& table)
{
o << "[table] size = " << table->size() << "\n" << dump_begin;
for (size_t iter = 0; iter < table->size(); ++iter)
{
const auto& entry = table->at(iter);
o << dump_offset << "- [" << iter << "]: ";
any_print(o, entry);
o << '\n';
}
o << dump_end;
};
register_printer<stts_entry>(
[](auto& o, const stts_entry& entry)
{
o << "{count=" << entry.sample_count << ", delta=" << entry.sample_delta << "}";
});
register_printer<ctts_entry>(
[](auto& o, const ctts_entry& entry)
{
o << "{count=" << entry.sample_count << ", offset=" << entry.sample_offset << "}";
});
register_printer<stsc_entry>(
[](auto& o, const stsc_entry& entry)
{
o << "{first_chunk=" << entry.first_chunk << ", samples_per_chunk=" << entry.samples_per_chunk
<< ", sample_description_index=" << entry.sample_description_index << "}";
});
register_printer<sdtp_entry>(
[](auto& o, const sdtp_entry& entry)
{
o << "{is_leading=" << any_print(o, entry.is_leading)
<< ", sample_depends_on=" << any_print(o, entry.sample_depends_on)
<< ", sample_is_depended_on=" << any_print(o, entry.sample_is_depended_on)
<< ", sample_has_redundancy=" << any_print(o, entry.sample_has_redundancy) << "}";
});
register_printer<table_ptr_t<stts_entry>>(table_printer);
register_printer<table_ptr_t<ctts_entry>>(table_printer);
register_printer<table_ptr_t<stsc_entry>>(table_printer);
register_printer<table_ptr_t<sdtp_entry>>(table_printer);
register_printer<table_ptr_t<uint32_t>>(table_printer);
register_printer<core::fourcc>(
[](auto& o, const core::fourcc& fcc)
{
o << fcc.string();
});
register_printer<core::uuid>(
[](auto& o, const core::uuid& u)
{
o << u.to_string();
});
register_printer<core::fieldset>(
[](auto& o, const core::fieldset& fs)
{
o << dump_begin;
if (fs._ordering)
{
for (const auto& ord : *fs._ordering)
{
auto iter = fs._fields.find(ord.second);
if (iter == fs._fields.end())
{
continue;
}
const auto& f = *iter;
auto name = core::property_base::get_name(f.first);
if (name == "__pos" || name == "__size")
{
continue;
}
o << dump_offset << "- [" << ord.first << "] " << core::property_base::get_name(f.first) << " ";
any_print(o, f.second);
o << '\n';
}
}
else
{
for (const auto& f : fs._fields)
{
auto name = core::property_base::get_name(f.first);
if (name == "__pos" || name == "__size")
{
continue;
}
o << dump_offset << "- " << core::property_base::get_name(f.first) << " ";
any_print(o, f.second);
o << '\n';
}
}
o << dump_end;
});
}
};
dump_context& any_print(dump_context& o, const std::any& v)
{
static any_printer printer;
printer.print(o, v);
return o;
}
void print_node(dump_context& o, const core::tree_node::ptr& node)
{
auto fcc = std::any_cast<core::fourcc>(node->get()->get("type"));
o << dump_offset << "[box \"" << fcc.string() << "\" " << node->size() << " @ " << node->position() << "]\n";
any_print(o, *(node->get()));
if (node->children().size() > 0)
{
o << dump_begin << dump_offset << "- children:\n";
o << dump_begin;
for (const auto& child : node->children())
{
print_node(o, child);
}
o << dump_end;
o << dump_end;
}
}
void print_tree(dump_context& o, const core::tree::ptr& tree)
{
for (const auto& node : tree->children())
{
print_node(o, node);
}
}
} // namespace hrodvitnir::dump
|
a2a4f64e0b260db27e049bfbe7bb7f785200b35b
|
{
"blob_id": "a2a4f64e0b260db27e049bfbe7bb7f785200b35b",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-27T22:12:04",
"content_id": "8b40b7db1c23eb4665592de862061f0750eadc0d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "a2c07e1353f919a01caa2ef6bdcba286bdfed84a",
"extension": "hpp",
"filename": "any_printer.hpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181935292,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9931,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hrodvitnir-dump/src/any_printer.hpp",
"provenance": "stack-edu-0008.json.gz:443502",
"repo_name": "sorsarre/hrodvitnir-core",
"revision_date": "2022-03-27T22:12:04",
"revision_id": "efae62da958c71f792fbdc25aff299b18057418a",
"snapshot_id": "0170b93f08665993c87cde12f2f8d3584a3182fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sorsarre/hrodvitnir-core/efae62da958c71f792fbdc25aff299b18057418a/hrodvitnir-dump/src/any_printer.hpp",
"visit_date": "2022-04-25T16:10:29.065135",
"added": "2024-11-18T23:07:30.292278+00:00",
"created": "2022-03-27T22:12:04",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
#ifndef RESOURCE_H
#define RESOURCE_H
#include <QDateTime>
#include <vector>
class QString;
class QVariant;
enum ApiDataType
{
DataTypeUnknown,
DataTypeBool,
DataTypeUInt8,
DataTypeUInt16,
DataTypeUInt32,
DataTypeInt8,
DataTypeInt16,
DataTypeInt32,
DataTypeReal,
DataTypeString,
DataTypeTime,
DataTypeTimePattern
};
// resource prefixes: /lights, /sensors, ...
extern const char *RSensors;
extern const char *RLights;
extern const char *RGroups;
extern const char *RConfig;
// resource events
extern const char *REventAdded;
extern const char *REventDeleted;
extern const char *REventValidGroup;
extern const char *REventCheckGroupAnyOn;
// resouce suffixes: state/buttonevent, config/on, ...
extern const char *RInvalidSuffix;
extern const char *RStateAlert;
extern const char *RStateAnyOn;
extern const char *RStateButtonEvent;
extern const char *RStateBri;
extern const char *RStateColorMode;
extern const char *RStateCt;
extern const char *RStateEffect;
extern const char *RStateHue;
extern const char *RStatePresence;
extern const char *RStateOn;
extern const char *RStateOpen;
extern const char *RStateDark;
extern const char *RStateDaylight;
extern const char *RStateLightLevel;
extern const char *RStateLux;
extern const char *RStateTemperature;
extern const char *RStateHumidity;
extern const char *RStatePressure;
extern const char *RStateFlag;
extern const char *RStateReachable;
extern const char *RStateSat;
extern const char *RStateStatus;
extern const char *RStateLastUpdated;
extern const char *RStateX;
extern const char *RStateY;
extern const char *RConfigOn;
extern const char *RConfigReachable;
extern const char *RConfigConfigured;
extern const char *RConfigDuration;
extern const char *RConfigBattery;
extern const char *RConfigGroup;
extern const char *RConfigUrl;
extern const char *RConfigLat;
extern const char *RConfigLong;
extern const char *RConfigSunriseOffset;
extern const char *RConfigSunsetOffset;
class ResourceItemDescriptor
{
public:
ResourceItemDescriptor() :
type(DataTypeUnknown),
suffix(RInvalidSuffix),
validMin(0),
validMax(0) { }
ResourceItemDescriptor(ApiDataType t, const char *s, int min = 0, int max = 0) :
type(t),
suffix(s),
validMin(min),
validMax(max) { }
bool isValid() const { return (type != DataTypeUnknown && suffix); }
ApiDataType type;
const char *suffix;
int validMin;
int validMax;
};
class ResourceItem
{
public:
ResourceItem(const ResourceItemDescriptor &rid);
const QString &toString() const;
qint64 toNumber() const;
bool toBool() const;
QVariant toVariant() const;
bool setValue(const QString &val);
bool setValue(qint64 val);
bool setValue(const QVariant &val);
const ResourceItemDescriptor &descriptor() const;
const QDateTime &lastSet() const;
const QDateTime &lastChanged() const;
private:
ResourceItem() :
m_num(-1), m_strIndex(0) {}
qint64 m_num;
size_t m_strIndex;
ResourceItemDescriptor m_rid;
QDateTime m_lastSet;
QDateTime m_lastChanged;
};
class Resource
{
public:
Resource(const char *prefix);
const char *prefix() const;
ResourceItem *addItem(ApiDataType type, const char *suffix);
ResourceItem *item(const char *suffix);
const ResourceItem *item(const char *suffix) const;
bool toBool(const char *suffix) const;
qint64 toNumber(const char *suffix) const;
const QString &toString(const char *suffix) const;
int itemCount() const;
ResourceItem *itemForIndex(size_t idx);
const ResourceItem *itemForIndex(size_t idx) const;
private:
Resource() {}
const char *m_prefix;
std::vector<ResourceItem> m_rItems;
};
void initResourceDescriptors();
const char *getResourcePrefix(const QString &str);
bool getResourceItemDescriptor(const QString &str, ResourceItemDescriptor &descr);
#endif // RESOURCE_H
|
76410c3e964d0adf64525e0710941bffbfde51bd
|
{
"blob_id": "76410c3e964d0adf64525e0710941bffbfde51bd",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-22T20:32:00",
"content_id": "107fe0f568adade24bf01af222f09e79a600bed0",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "592a605c76e74fcaa50346e30b73c4bb52d43793",
"extension": "h",
"filename": "resource.h",
"fork_events_count": 0,
"gha_created_at": "2017-05-28T06:44:07",
"gha_event_created_at": "2017-05-28T06:44:07",
"gha_language": null,
"gha_license_id": null,
"github_id": 92644714,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3962,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/resource.h",
"provenance": "stack-edu-0006.json.gz:9427",
"repo_name": "NisseDILLIGAF/deconz-rest-plugin",
"revision_date": "2017-07-22T20:32:00",
"revision_id": "6a5f5de1918c4a3ccdd07c81813fbedad40d8b7b",
"snapshot_id": "ebd63f6fafc054135fbf5b613fd7759dad9f9aec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NisseDILLIGAF/deconz-rest-plugin/6a5f5de1918c4a3ccdd07c81813fbedad40d8b7b/resource.h",
"visit_date": "2021-01-01T17:20:17.850909",
"added": "2024-11-18T22:22:49.935053+00:00",
"created": "2017-07-22T20:32:00",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
using FAManagementStudio.ViewModels;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace FAManagementStudio.Views
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TreeViewItem_MouseRightButtonDown(Object sender, MouseButtonEventArgs e)
{
TreeViewItem item = sender as TreeViewItem;
if (item != null)
{
item.IsSelected = true;
e.Handled = true;
}
}
private void TabItem_MouseRightButtonDown(Object sender, MouseButtonEventArgs e)
{
TabItem item = sender as TabItem;
if (item != null)
{
item.IsSelected = true;
e.Handled = true;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
QueryTab.SelectedIndex = 0;
}
private void TextBox_PreviewDragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
private void TabItem_Drag(object sender, MouseEventArgs e)
{
if (Mouse.PrimaryDevice.LeftButton != MouseButtonState.Pressed) return;
var tabItem = (TabItem)e.Source;
DragDrop.DoDragDrop(tabItem, tabItem, DragDropEffects.All);
}
private void TabItem_Drop(object sender, DragEventArgs e)
{
var obj = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);
while (obj.GetType() != typeof(TabItem))
{
obj = VisualTreeHelper.GetParent(obj);
}
var target = (TabItem)obj;
var source = (TabItem)e.Data.GetData(typeof(TabItem));
if (target.Equals(source)) return;
var itemSource = (ObservableCollection<QueryTabViewModel>)QueryTab.ItemsSource;
var sourceIdx = itemSource.IndexOf((QueryTabViewModel)source.Header);
var targetIdx = itemSource.IndexOf((QueryTabViewModel)target.Header);
if (itemSource.Count - 1 <= targetIdx) return;
itemSource.Move(sourceIdx, targetIdx);
}
}
}
|
982ce6966282f61f0bec0b61cb28fc4d7d35d36c
|
{
"blob_id": "982ce6966282f61f0bec0b61cb28fc4d7d35d36c",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-16T04:30:28",
"content_id": "0704104a24d9c4f6e0f30147b6f07ed0301b9285",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "21d247ea2747665b7e7cc11e0b7bc5727c135ceb",
"extension": "cs",
"filename": "MainWindow.xaml.cs",
"fork_events_count": 4,
"gha_created_at": "2015-09-24T13:46:12",
"gha_event_created_at": "2018-09-16T04:30:29",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 43069460,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2484,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/FAManagementStudio/Views/MainWindow.xaml.cs",
"provenance": "stack-edu-0013.json.gz:606623",
"repo_name": "degarashi0913/FAManagementStudio",
"revision_date": "2018-09-16T04:30:28",
"revision_id": "7301cc435729664a76d11b68d1e9994ee17b9a20",
"snapshot_id": "38cb8ac14004ddd5d566a9b8d353c38dc85d4c2a",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/degarashi0913/FAManagementStudio/7301cc435729664a76d11b68d1e9994ee17b9a20/FAManagementStudio/Views/MainWindow.xaml.cs",
"visit_date": "2021-01-23T19:39:25.778986",
"added": "2024-11-19T00:45:45.805675+00:00",
"created": "2018-09-16T04:30:28",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
<?php declare(strict_types=1);
namespace App\Services\Factory\Message;
use App\Model\Message\MessageModel;
use App\Entity\Message;
/**
* Take care about creating message object
*/
interface MessageFactoryInterface
{
/**
* create message object from message model object
* @param MessageModel $messageModel Message model object
* @return Message
*/
public function create(MessageModel $messageModel): Message;
}
|
1ac141e4366d0fa0f0a72147e9b7b03d566cb275
|
{
"blob_id": "1ac141e4366d0fa0f0a72147e9b7b03d566cb275",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T18:28:02",
"content_id": "7233224382052a1bf8816d7168167ecdc9f54606",
"detected_licenses": [
"MIT"
],
"directory_id": "486298d8f7a4d002cea63327004e531d07d7d488",
"extension": "php",
"filename": "MessageFactoryInterface.php",
"fork_events_count": 0,
"gha_created_at": "2020-06-04T20:05:14",
"gha_event_created_at": "2020-09-06T13:30:43",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 269454310,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 451,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Services/Factory/Message/MessageFactoryInterface.php",
"provenance": "stack-edu-0050.json.gz:233113",
"repo_name": "Kris1992/Chat",
"revision_date": "2020-09-07T18:28:02",
"revision_id": "a01d3d391432449ea8bd65598d9170e85ec685e4",
"snapshot_id": "18b891c486ffaec73fa5afaee75f136719874143",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Kris1992/Chat/a01d3d391432449ea8bd65598d9170e85ec685e4/src/Services/Factory/Message/MessageFactoryInterface.php",
"visit_date": "2022-12-14T04:00:20.324225",
"added": "2024-11-19T00:28:11.669242+00:00",
"created": "2020-09-07T18:28:02",
"int_score": 3,
"score": 2.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
function(name, extra) {
var control = this;
extra = extra || {};
// no DOM available yet, nothing to rerender -> exit
if (!this.dom) return;
// rerender the whole control
if (!name) {
if (this.dom) {
this.dom.content.replaceWith(this.render());
this.events.publish({"topic": "onRerender"});
}
return;
}
// if the list of elements passed, call rerender for each element
if ($.isArray(name)) {
$.map(name, function(element) {
control.rerender(element, extra);
});
return;
}
// exit if no element found
if (!name || !this.dom.get(name)) return;
if (extra.recursive) {
var template = $.isFunction(this.template) ? this.template() : this.template;
var html = this.substitute(template, this.data || {});
var newNode = $("." + cssPrefix + name, $(html));
var oldNode = this.dom.get(name);
newNode = Echo.Utils.toDOM(newNode, this.cssPrefix + "-",
function(name, element, dom) {
control.render.call(control, name, element, dom, extra);
}
).content;
oldNode.replaceWith(newNode);
} else {
this.render(name, this.dom.get(name), this.dom, extra);
}
}
|
4a803cb72ac50ac8d20a1758825f7277d0956275
|
{
"blob_id": "4a803cb72ac50ac8d20a1758825f7277d0956275",
"branch_name": "refs/heads/main",
"committer_date": "2022-10-18T10:08:50",
"content_id": "aed4b5f501b07dae15294d694f02a04a30fa8387",
"detected_licenses": [
"MIT"
],
"directory_id": "1a1e21c86d26e545d911a3948b66fe7baeb3bdbb",
"extension": "js",
"filename": "a7770d0ecfd3df47910078cb2eb07fb437dc1e3b_0_5.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 448797879,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1106,
"license": "MIT",
"license_type": "permissive",
"path": "/input/100+/after/a7770d0ecfd3df47910078cb2eb07fb437dc1e3b_0_5.js",
"provenance": "stack-edu-0043.json.gz:449947",
"repo_name": "AAI-USZ/FixJS",
"revision_date": "2022-10-18T10:08:50",
"revision_id": "0f7b4a2445340e147fdb7aef00fbe6230397501f",
"snapshot_id": "59db2b15d78e3eaadc72f7f046908e0ee0d4e0fc",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/AAI-USZ/FixJS/0f7b4a2445340e147fdb7aef00fbe6230397501f/input/100+/after/a7770d0ecfd3df47910078cb2eb07fb437dc1e3b_0_5.js",
"visit_date": "2023-04-17T15:26:29.043233",
"added": "2024-11-18T22:14:30.487753+00:00",
"created": "2022-10-18T10:08:50",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
#include <iostream>
#include <SDL2/SDL.h>
int main ()
{
std::string greetings = "Hello SDL2!";
std::cout << greetings << std::endl;
//Close SDL library to clean up memory resources
return EXIT_SUCCESS;
}
|
0cf60ad44b60e31f133efdd9ecffb7ef9e18191a
|
{
"blob_id": "0cf60ad44b60e31f133efdd9ecffb7ef9e18191a",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-25T03:34:13",
"content_id": "302b93d2f858d9c74e700b8d8c7cc1f1f5c4b419",
"detected_licenses": [
"Zlib"
],
"directory_id": "865e9044fb05e4c302e92031973a360f984dd83f",
"extension": "cpp",
"filename": "main.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 417461899,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 222,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/main.cpp",
"provenance": "stack-edu-0005.json.gz:68682",
"repo_name": "smithkm903/learnOpenGL",
"revision_date": "2021-10-25T03:34:13",
"revision_id": "96271343787a4799ae305338ef934e216d56aab9",
"snapshot_id": "61c03e573f39d8206bcbbec12b2534383aa3d6e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smithkm903/learnOpenGL/96271343787a4799ae305338ef934e216d56aab9/src/main.cpp",
"visit_date": "2023-09-03T16:06:48.411500",
"added": "2024-11-18T23:31:20.831203+00:00",
"created": "2021-10-25T03:34:13",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
module Config
class Log
def initialize(stream=StringIO.new)
@stream = stream
@indent_level = 0
@indent_string = " " * 2
end
attr_accessor :indent_string
def <<(input)
input.split("\n").each do |line|
@stream.puts "#{current_indent}#{line}"
end
end
def indent(level=1)
@indent_level += level
begin
yield
ensure
@indent_level -= level
end
end
protected
def current_indent
@indent_string * @indent_level
end
end
end
|
3767b8b46b3cb2344fb7b3d9aa0fc95234f72d41
|
{
"blob_id": "3767b8b46b3cb2344fb7b3d9aa0fc95234f72d41",
"branch_name": "refs/heads/master",
"committer_date": "2012-04-24T04:58:28",
"content_id": "2499e2df6d75e8dbaf5e5d2661aee49807f92a14",
"detected_licenses": [
"MIT"
],
"directory_id": "244f9a0f4d5c0e5c8a943430a3c9c723a55fe06a",
"extension": "rb",
"filename": "log.rb",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4126518,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 546,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/config/log.rb",
"provenance": "stack-edu-0067.json.gz:374609",
"repo_name": "mcolyer/config",
"revision_date": "2012-04-24T04:58:28",
"revision_id": "f3136a5833dc903b5bb18fb89261c1ea9cdce73f",
"snapshot_id": "3f9eecc09afca1930171565cea1623d0a86559f4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mcolyer/config/f3136a5833dc903b5bb18fb89261c1ea9cdce73f/lib/config/log.rb",
"visit_date": "2021-01-18T10:10:44.283265",
"added": "2024-11-19T03:00:20.815784+00:00",
"created": "2012-04-24T04:58:28",
"int_score": 3,
"score": 2.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
#include <ulib.h>
#include <stdio.h>
#include <string.h>
#include <file.h>
int main(void)
{
/* type '^C' to stop reading */
char c;
cprintf("now reading...\n");
do {
int ret = read(0, &c, sizeof(c));
assert(ret == 1);
cprintf("type [%03d] %c.\n", c, c);
} while (c != 3);
return 0;
}
|
c223c12cb02a2baf1c13b155821670ba8a3e9f56
|
{
"blob_id": "c223c12cb02a2baf1c13b155821670ba8a3e9f56",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-09T10:58:38",
"content_id": "63273a026152a9e5446a193cdefb956636e27da7",
"detected_licenses": [
"MIT"
],
"directory_id": "03b39c11d9e73bf4aee483dcd05af3865ebd9998",
"extension": "c",
"filename": "fread_test.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127878014,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 297,
"license": "MIT",
"license_type": "permissive",
"path": "/ucore/src/user-ucore/tests/fread_test.c",
"provenance": "stack-edu-0000.json.gz:436413",
"repo_name": "oscourse-tsinghua/OS2018spring-projects-g14",
"revision_date": "2018-06-09T10:58:38",
"revision_id": "94155cc7e560c740bf6d2938c1f08a2f3ac0ffb8",
"snapshot_id": "b51b8120b7dffc3923bb4de311dcf8f9d60fcea6",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/oscourse-tsinghua/OS2018spring-projects-g14/94155cc7e560c740bf6d2938c1f08a2f3ac0ffb8/ucore/src/user-ucore/tests/fread_test.c",
"visit_date": "2020-03-08T03:00:33.365276",
"added": "2024-11-18T22:41:29.527637+00:00",
"created": "2018-06-09T10:58:38",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Disqord;
using Disqord.Bot;
using Doraemon.Common.Extensions;
using Doraemon.Services.Core;
using Humanizer;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Qmmands;
using Serilog;
namespace Doraemon.Modules
{
[Name("Eval")]
[Description("Provides utilities to evaluate C-Sharp code.")]
[Group("eval", "evaluate", "exec", "e")]
public class CSharpEvalModule : DoraemonGuildModuleBase
{
[Command]
[RunMode(RunMode.Parallel)]
[Description("Evaluates the code provided.")]
public async Task<DiscordCommandResult> EvalAsync(
[Description("The code to evaluate.")] [Remainder]
string code)
{
if (! await Context.Bot.IsOwnerAsync(Context.Author.Id)) return null;
var scriptOptions = ScriptOptions.Default
.WithImports(EvalService.EvalNamespaces)
.WithReferences(AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location)));
code = EvalService.ValidateCode(code);
var script = CSharpScript.Create(code, scriptOptions, Context is DiscordGuildCommandContext ? typeof(EvalGuildGlobals) : typeof(EvalGlobals));
try
{
var stopwatch = Stopwatch.StartNew();
var diagnostics = script.Compile();
stopwatch.Stop();
if (diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error))
{
var compileErrorEmbed = new LocalEmbed()
.WithTitle("Compilation Failure")
.WithDescription($"{diagnostics.Length} {(diagnostics.Length > 1 ? "errors" : "error")}")
.WithColor(DColor.Red)
.WithFooter($"{stopwatch.Elapsed.TotalMilliseconds}ms");
for (var i = 0; i < diagnostics.Length; i++)
{
if (i > 3)
break;
var diagnostic = diagnostics[i];
var lineSpan = diagnostic.Location.GetLineSpan().Span;
compileErrorEmbed.AddField($"Error `{diagnostic.Id}` at {lineSpan.Start} - {lineSpan.End}", diagnostic.GetMessage());
}
return Response(compileErrorEmbed);
}
var globals = Context is DiscordGuildCommandContext guildContext ? new EvalGuildGlobals(guildContext) : new EvalGuildGlobals(Context);
var state = await script.RunAsync(globals, _ => true);
if (state.Exception != null)
{
var runErrorEmbed = new LocalEmbed()
.WithTitle($"Runtime Failure")
.WithDescription(state.Exception.ToString().Truncate(LocalEmbed.MaxDescriptionLength))
.WithColor(DColor.Red)
.WithFooter($"{stopwatch.Elapsed.TotalMilliseconds} ms");
return Response(runErrorEmbed);
}
switch (state.ReturnValue)
{
case null:
case string value when string.IsNullOrWhiteSpace(value):
return Reaction(new LocalEmoji("✅"));
case DiscordCommandResult commandResult:
return commandResult;
default:
return Response(state.ReturnValue.ToString());
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Eval unexpectedly failed.");
return Response($"An exception bubbled up: {ex.Message}");
}
}
}
}
|
0ea736c63065b21baa12e18e53bc9bb00a3bf9c0
|
{
"blob_id": "0ea736c63065b21baa12e18e53bc9bb00a3bf9c0",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-03T12:45:10",
"content_id": "8f2088587240446ea32f4d0697bdc92a644ea0df",
"detected_licenses": [
"MIT"
],
"directory_id": "ed05c0340f5e9c65dfa32b4e9c680493785c1941",
"extension": "cs",
"filename": "CSharpEvalModule.cs",
"fork_events_count": 5,
"gha_created_at": "2021-06-03T01:15:45",
"gha_event_created_at": "2021-06-30T19:00:12",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 373345069,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3957,
"license": "MIT",
"license_type": "permissive",
"path": "/Doraemon/Modules/CSharpEvalModule.cs",
"provenance": "stack-edu-0010.json.gz:604252",
"repo_name": "n-Ultima/Doraemon",
"revision_date": "2021-11-03T12:45:10",
"revision_id": "8c0de0672d3e8e6b90b2aba98350910e0caf4c2e",
"snapshot_id": "7b933abc2c626f117ff00f235bd3e6832a10a4ab",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/n-Ultima/Doraemon/8c0de0672d3e8e6b90b2aba98350910e0caf4c2e/Doraemon/Modules/CSharpEvalModule.cs",
"visit_date": "2023-08-22T21:48:53.900512",
"added": "2024-11-18T22:50:49.716472+00:00",
"created": "2021-11-03T12:45:10",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
<?php
/* [$DoYouHaoBaby] (C)WindsForce TEAM Since 2010.10.04.
使用Eaccelerator来缓存数据($Liu.XiangMin)*/
!defined('DYHB_PATH') && exit;
class EacceleratorCache{
protected $_arrOptions=array(
'cache_time'=>86400
);
public function __construct(array $arrOptions=null){
if(isset($arrOptions['cache_time'])){
$this->_arrOptions['cache_time']=(int)$arrOptions['cache_time'];
}
}
public function getCache($sCacheName){
return eaccelerator_get($sCacheName);
}
public function setCache($sCacheName,$Data,array $arrOptions=null){
$nCacheTime=!isset($arrOptions['cache_time'])?(int)$arrOptions['cache_time']:$this->_arrOptions['cache_time'];
eaccelerator_lock($sCacheName);
return eaccelerator_put($sCacheName,$Data,$nCacheTime);
}
public function deleleCache($sCacheName){
return eaccelerator_rm($sCacheName);
}
}
|
76518c5616e5de4ca37cb338f53527e03480efcd
|
{
"blob_id": "76518c5616e5de4ca37cb338f53527e03480efcd",
"branch_name": "refs/heads/master",
"committer_date": "2013-07-31T01:03:07",
"content_id": "4d76e2b610adf47b8f6838e200d5d16329c79b6e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2547f509548267a824080f0cef2c26afdf4d94f4",
"extension": "php",
"filename": "EacceleratorCache.class.php",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7035994,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 857,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/upload/source/include/DoYouHaoBaby/Cache/EacceleratorCache.class.php",
"provenance": "stack-edu-0051.json.gz:882891",
"repo_name": "dyhb/windsforce",
"revision_date": "2013-07-31T01:03:07",
"revision_id": "72ca34ff261b24c874ece5e3f0710060bbff1b16",
"snapshot_id": "9588b0c440db6f35d222cfd1795ec1f652e60e53",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dyhb/windsforce/72ca34ff261b24c874ece5e3f0710060bbff1b16/upload/source/include/DoYouHaoBaby/Cache/EacceleratorCache.class.php",
"visit_date": "2023-03-11T02:46:45.068475",
"added": "2024-11-19T03:31:15.735791+00:00",
"created": "2013-07-31T01:03:07",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
package com.yanwu.spring.cloud.common.demo.d03thread.t09pool.executor;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">baofeng Xu</a>
* @date 2020-05-31 23:04:18.
* <p>
* describe:
*/
public class D12FutureTask {
public static void main(String[] args) throws Exception {
FutureTask<String> futureTask = new FutureTask<>(() -> {
TimeUnit.SECONDS.sleep(1);
return RandomStringUtils.randomAlphabetic(12).toUpperCase();
});
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
}
|
213e872157a22bc1be604e03cdd9dab733388431
|
{
"blob_id": "213e872157a22bc1be604e03cdd9dab733388431",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T03:52:31",
"content_id": "4489a533f92cc253d368b2479affe123c187ad28",
"detected_licenses": [
"MIT"
],
"directory_id": "c7e3dc9ea909f976d4bf28a0afa7288164f259c3",
"extension": "java",
"filename": "D12FutureTask.java",
"fork_events_count": 1,
"gha_created_at": "2019-06-21T10:06:24",
"gha_event_created_at": "2023-02-24T11:21:00",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 193076462,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 698,
"license": "MIT",
"license_type": "permissive",
"path": "/yanwu-spring-cloud-common/src/main/java/com/yanwu/spring/cloud/common/demo/d03thread/t09pool/executor/D12FutureTask.java",
"provenance": "stack-edu-0020.json.gz:7052",
"repo_name": "yanwu12138/spring-cloud",
"revision_date": "2023-08-07T03:52:31",
"revision_id": "663b48f411a27bf623dde8c8ebf6cd7222e1e31b",
"snapshot_id": "479d72d6fdb20fbf4432d20e3ce96c14d46786e9",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/yanwu12138/spring-cloud/663b48f411a27bf623dde8c8ebf6cd7222e1e31b/yanwu-spring-cloud-common/src/main/java/com/yanwu/spring/cloud/common/demo/d03thread/t09pool/executor/D12FutureTask.java",
"visit_date": "2023-08-17T16:42:05.065488",
"added": "2024-11-18T22:25:10.335199+00:00",
"created": "2023-08-07T03:52:31",
"int_score": 3,
"score": 2.671875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
package com.wludio.microservice.pmp.exception;
import static java.lang.String.format;
public class ItemNotFoundException extends RuntimeException {
public ItemNotFoundException(String msg) {
super(msg);
}
public ItemNotFoundException(String msg, Object... params) {
super(format(msg, params));
}
}
|
245f84c18d8749884e23753e218fb9935aa83d9f
|
{
"blob_id": "245f84c18d8749884e23753e218fb9935aa83d9f",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-15T19:02:07",
"content_id": "99e902c3b6c063755883eab679211dc294a688f9",
"detected_licenses": [
"MIT"
],
"directory_id": "c3b36f499638528666bb6b384f8d31a73d41764b",
"extension": "java",
"filename": "ItemNotFoundException.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 253186587,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 334,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/com/wludio/microservice/pmp/exception/ItemNotFoundException.java",
"provenance": "stack-edu-0026.json.gz:688874",
"repo_name": "vladucuvoican/product-management-platform-backend",
"revision_date": "2020-04-15T19:02:07",
"revision_id": "79ebc5378a7bb4af7b959ecf8cc540575573f846",
"snapshot_id": "0df49be435f3d4a4ebe495eb8fde2b77a8906475",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vladucuvoican/product-management-platform-backend/79ebc5378a7bb4af7b959ecf8cc540575573f846/src/main/java/com/wludio/microservice/pmp/exception/ItemNotFoundException.java",
"visit_date": "2022-10-11T11:46:22.942637",
"added": "2024-11-19T02:48:17.204365+00:00",
"created": "2020-04-15T19:02:07",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
package de.jsmithy.rest.jaxrs.nutshell.client;
/**
* Signals any exceptional situation while processing a RestServiceClient.
*
* @author Erik Lotz
* @since 2016-07-24
*
*/
public class RestServiceClientException extends RuntimeException {
private static final long serialVersionUID = 3653367933177581941L;
public RestServiceClientException(RestServiceClient restServiceClient) {
if (restServiceClient == null) {
throw new IllegalArgumentException("Argument [restServiceClient] must not be 'null'.");
}
}
}
|
a05283f4e8d256a1ceda8f33678a4aeff9df21b1
|
{
"blob_id": "a05283f4e8d256a1ceda8f33678a4aeff9df21b1",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-16T16:46:21",
"content_id": "bbae447466b636f838f9efd54f7d04dbf693c3e7",
"detected_licenses": [
"MIT"
],
"directory_id": "1156b19396710bc0dc02b5af721e412e6d539d50",
"extension": "java",
"filename": "RestServiceClientException.java",
"fork_events_count": 1,
"gha_created_at": "2016-10-12T19:56:33",
"gha_event_created_at": "2022-06-24T01:26:14",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 70736286,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 526,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/de/jsmithy/rest/jaxrs/nutshell/client/RestServiceClientException.java",
"provenance": "stack-edu-0022.json.gz:753274",
"repo_name": "Rasumichin/jaxrs-client-in-a-nutshell",
"revision_date": "2022-08-16T16:46:21",
"revision_id": "b7ad9dd7888f1016497c736c92347bf61439e3d9",
"snapshot_id": "3924b93e0dc6279bad7d30d5d6f289888f8d863b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Rasumichin/jaxrs-client-in-a-nutshell/b7ad9dd7888f1016497c736c92347bf61439e3d9/src/main/java/de/jsmithy/rest/jaxrs/nutshell/client/RestServiceClientException.java",
"visit_date": "2022-09-01T20:32:15.444092",
"added": "2024-11-19T00:05:06.587598+00:00",
"created": "2022-08-16T16:46:21",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class GoblinBomberController : EnemyController
{
// NORMAL STUN: on any melee, causes a held bomb to be dropped
// SUPERSTUN: on critical ranged, causes a held bomb to be dropped
#region Public Vars
public float Range;
public float BombUpVel;
public float BombHorVel;
public Behaviour CurrentBehaviour;
public enum Behaviour
{
Idle, Throwing
}
public AttackData AttackData;
public GameObject BombPrefab;
#endregion
#region Private Vars
private IEnumerator currentRoutine;
private bool holdingBomb = false;
#endregion
#region Unity Messages
protected override void Awake()
{
base.Awake();
}
protected void OnDrawGizmosSelected()
{
DrawCircle(Range, Color.cyan);
}
#endregion
#region Public Methods
public void SetBehaviour(Behaviour newBehaviour)
{
if (newBehaviour != CurrentBehaviour)
CurrentBehaviour = newBehaviour;
}
public override void Die()
{
Debug.Log(name + "Is Dead.");
SetState(State.Dead);
if (currentRoutine != null) StopCoroutine(currentRoutine);
// Despawn
if (holdingBomb)
{
var bomb = Instantiate(BombPrefab, transform.position = Vector3.up, Quaternion.identity);
}
Destroy(gameObject);
}
#endregion
#region Protected/Private Methods
protected override void Act()
{
// ATTACK:
// launch bombs at player on regular timer @ a fixed angle
if (CurrentBehaviour == Behaviour.Throwing && CurrentState != State.Action)
{
if (currentRoutine != null) StopCoroutine(currentRoutine);
currentRoutine = ThrowBombRoutine();
StartCoroutine(currentRoutine);
}
}
protected override void DecideAction()
{
// If player in range, face player & start attacking
// otherwise: idle
if (DistToPlayer < Range)
{
SetBehaviour(Behaviour.Throwing);
}
else
{
SetBehaviour(Behaviour.Idle);
}
}
protected void DrawCircle(float radius, Color colour)
{
Handles.color = colour;
Handles.DrawWireDisc(transform.position, Vector3.forward, radius);
}
private IEnumerator ThrowBombRoutine()
{
// Startup
SetState(State.Action);
holdingBomb = true;
var timer = 0;
while (timer < AttackData.Startup) { yield return new WaitForFixedUpdate(); timer++; }
// Active: Throw bomb
var bomb = Instantiate(BombPrefab, transform.position + new Vector3(1,1), Quaternion.identity);
bomb.GetComponent<CharacterMotionController>().ContMotionVector.y = BombUpVel;
bomb.GetComponent<CharacterMotionController>().XSpeed = BombHorVel;
bomb.GetComponent<BouncingExplosiveProjectileController>().AttackData = AttackData;
timer = 0;
while (timer < AttackData.Active) { yield return new WaitForFixedUpdate(); timer++; }
// Recovery
holdingBomb = false;
timer = 0;
while (timer < AttackData.Recovery) { yield return new WaitForFixedUpdate(); timer++; }
// End of attack
SetState(State.Ready);
}
#endregion
}
|
f8e51d7ce10eac2b087dd06c8d5a7f1d2b1a99fb
|
{
"blob_id": "f8e51d7ce10eac2b087dd06c8d5a7f1d2b1a99fb",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-14T00:30:13",
"content_id": "ae3fed8808ed5ee363f02810ea399a9e865f584e",
"detected_licenses": [
"MIT"
],
"directory_id": "db8a2b99d5848a402ae787391f22b51b6a4d1a0c",
"extension": "cs",
"filename": "GoblinBomberController.cs",
"fork_events_count": 0,
"gha_created_at": "2019-01-10T01:35:10",
"gha_event_created_at": "2019-02-13T23:55:58",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 164967651,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3436,
"license": "MIT",
"license_type": "permissive",
"path": "/Assets/Scripts/Gameplay/Character Controllers/GoblinBomberController.cs",
"provenance": "stack-edu-0014.json.gz:672048",
"repo_name": "ScarletPhoenix5053/When-Hell-Freezes-Over",
"revision_date": "2019-02-14T00:30:13",
"revision_id": "6a6d9c5528c831881a51dcda66d5fae08dcd1f05",
"snapshot_id": "ceaf4d23ede7c256fdd177895f09303c93cde399",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ScarletPhoenix5053/When-Hell-Freezes-Over/6a6d9c5528c831881a51dcda66d5fae08dcd1f05/Assets/Scripts/Gameplay/Character Controllers/GoblinBomberController.cs",
"visit_date": "2020-04-15T19:50:49.548410",
"added": "2024-11-19T03:02:39.134833+00:00",
"created": "2019-02-14T00:30:13",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the CLI argument helper manager."""
import argparse
import unittest
from plaso.lib import errors
from plaso.cli.helpers import interface
from plaso.cli.helpers import manager
class TestHelper(interface.ArgumentsHelper):
"""Test CLI argument helper."""
NAME = 'test_helper'
DESCRIPTION = u'Test helper that does nothing.'
@classmethod
def AddArguments(cls, argument_group):
"""Add command line arguments to an argument group."""
argument_group.add_argument(
u'-d', u'--dynamic', action='store', default=u'', type=str,
help=u'Stuff to insert into the arguments.', dest=u'dynamic')
@classmethod
def ParseOptions(cls, options, unused_config_object):
"""Parse and validate the configuration options."""
if not getattr(options, 'dynamic', u''):
raise errors.BadConfigOption(u'Always set this.')
class AnotherTestHelper(interface.ArgumentsHelper):
"""Another test CLI argument helper."""
NAME = 'another_test_helper'
DESCRIPTION = u'Another test helper that does nothing.'
@classmethod
def AddArguments(cls, argument_group):
"""Add command line arguments to an argument group."""
argument_group.add_argument(
u'-c', u'--correcto', dest=u'correcto', action='store_true',
default=False, help=u'The correcto option.')
@classmethod
def ParseOptions(cls, options, unused_config_object):
"""Parse and validate the configurational options."""
if not hasattr(options, 'correcto'):
raise errors.BadConfigOption(u'Correcto not set.')
if not isinstance(getattr(options, u'correcto', None), bool):
raise errors.BadConfigOption(u'Correcto wrongly formatted.')
class HelperManagerTest(unittest.TestCase):
"""Tests for the parsers manager."""
def testHelperRegistration(self):
"""Tests the RegisterHelper and DeregisterHelper functions."""
# pylint: disable=protected-access
number_of_helpers = len(manager.ArgumentHelperManager._helper_classes)
manager.ArgumentHelperManager.RegisterHelper(TestHelper)
self.assertEqual(
len(manager.ArgumentHelperManager._helper_classes),
number_of_helpers + 1)
with self.assertRaises(KeyError):
manager.ArgumentHelperManager.RegisterHelper(TestHelper)
manager.ArgumentHelperManager.DeregisterHelper(TestHelper)
self.assertEqual(
len(manager.ArgumentHelperManager._helper_classes),
number_of_helpers)
def testGetHelperNames(self):
"""Tests the GetHelperNames function."""
manager.ArgumentHelperManager.RegisterHelper(TestHelper)
self.assertIn(
TestHelper.NAME, manager.ArgumentHelperManager.GetHelperNames())
manager.ArgumentHelperManager.DeregisterHelper(TestHelper)
def testCommandLineArguments(self):
"""Test the AddCommandLineArguments and function."""
manager.ArgumentHelperManager.RegisterHelpers(
[TestHelper, AnotherTestHelper])
arg_parser = argparse.ArgumentParser(conflict_handler=u'resolve')
manager.ArgumentHelperManager.AddCommandLineArguments(arg_parser)
# Assert the parameters have been set.
options = arg_parser.parse_args([])
self.assertTrue(hasattr(options, u'dynamic'))
self.assertTrue(hasattr(options, u'correcto'))
self.assertFalse(hasattr(options, u'foobar'))
# Make the parameters fail validation.
options.correcto = 'sfd'
with self.assertRaises(errors.BadConfigOption):
manager.ArgumentHelperManager.ParseOptions(options, None)
options.correcto = True
options.dynamic = 'now stuff'
manager.ArgumentHelperManager.ParseOptions(options, None)
manager.ArgumentHelperManager.DeregisterHelper(TestHelper)
manager.ArgumentHelperManager.DeregisterHelper(AnotherTestHelper)
if __name__ == '__main__':
unittest.main()
|
9d34020a82ff0fac456265272c0bfdecfe738761
|
{
"blob_id": "9d34020a82ff0fac456265272c0bfdecfe738761",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-06T18:48:16",
"content_id": "2869c170be55f671ab6212a9022b0838f0c17287",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e03e60074262d6da5258d5326bee34b3ee4f2421",
"extension": "py",
"filename": "manager.py",
"fork_events_count": 0,
"gha_created_at": "2015-09-26T01:37:44",
"gha_event_created_at": "2015-09-26T01:37:44",
"gha_language": null,
"gha_license_id": null,
"github_id": 43185317,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3831,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/cli/helpers/manager.py",
"provenance": "stack-edu-0055.json.gz:598689",
"repo_name": "8u1a/plaso",
"revision_date": "2015-10-06T18:48:16",
"revision_id": "b48d88fd6fb4acb0c35228d5e2cfb75e4f209bd5",
"snapshot_id": "c6874bb8ca86be503ba5ea123a64a5e6b277abb7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/8u1a/plaso/b48d88fd6fb4acb0c35228d5e2cfb75e4f209bd5/tests/cli/helpers/manager.py",
"visit_date": "2021-01-18T02:00:03.690917",
"added": "2024-11-18T20:10:50.069887+00:00",
"created": "2015-10-06T18:48:16",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz"
}
|
import re
from setuptools import find_packages, setup
def get_const(name, text):
return re.search(
r'^{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(name), text, re.MULTILINE
).group(1)
with open('requirements.txt') as f:
requirements = f.read().splitlines()
with open('README.md') as f:
readme = f.read()
with open('wowspy/__init__.py') as f:
t = f.read()
version = get_const('__version__', t)
title = get_const('__title__', t)
license_ = get_const('__license__', t)
author = get_const('__author__', t)
setup(
name=title,
version=version,
packages=find_packages(),
url='https://github.com/MaT1g3R/Warships.py',
license=license_,
author=author,
author_email='[email protected]',
description='A Python World of Warships API wrapper',
install_requires=requirements,
long_description=readme,
include_package_data=True,
classifiers=[
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'
]
)
|
e35f647b086d0a21cd29282bf4364f5a53e01948
|
{
"blob_id": "e35f647b086d0a21cd29282bf4364f5a53e01948",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-15T09:46:42",
"content_id": "801fcfabaf3738e0d1348d9c6940c2eb0c2354d5",
"detected_licenses": [
"MIT"
],
"directory_id": "1f3a5ebcd9123972ccff55e1b37333d6d0d1e5bf",
"extension": "py",
"filename": "setup.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87741095,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1388,
"license": "MIT",
"license_type": "permissive",
"path": "/setup.py",
"provenance": "stack-edu-0064.json.gz:609666",
"repo_name": "MaT1g3R/Warships.py",
"revision_date": "2017-07-15T09:43:05",
"revision_id": "d4d335c14e56ff110b525ae7ff2ec76c028aef57",
"snapshot_id": "6c8b3ede9e546810979306804d287431a3c918b1",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/MaT1g3R/Warships.py/d4d335c14e56ff110b525ae7ff2ec76c028aef57/setup.py",
"visit_date": "2021-01-19T09:13:08.888723",
"added": "2024-11-18T20:31:56.327925+00:00",
"created": "2017-07-15T09:43:05",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz"
}
|
package pl.sdacademy.java14poz.listopad24.zadanie3writetofile;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteToFileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Podaj tekst i zapiszę go do pliku");
String text = scanner.nextLine();
System.out.println("Podaj ścieżkę do zapisu:");
String path = scanner.nextLine();
// zapis do pliku
// try with resources
try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, true))){
// true zapewnia dopisanie czegoś do już istniejącego pliku (append, na końcu pliku); domyślnie jest false
writer.write(text);
} catch (IOException e) {
System.out.println("Nie udało się zapisać do pliku... buuuuuu.....");
}
}
}
|
712de4e0d9f193611220ee5378154731021f05bc
|
{
"blob_id": "712de4e0d9f193611220ee5378154731021f05bc",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-15T13:54:43",
"content_id": "a3755c57dd1dff6b62fbe0493304cf537839c627",
"detected_licenses": [
"MIT"
],
"directory_id": "b7c694df75e0bc79b7cfdda03fe3256fa6da9d95",
"extension": "java",
"filename": "WriteToFileExample.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 159030417,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 968,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/pl/sdacademy/java14poz/listopad24/zadanie3writetofile/WriteToFileExample.java",
"provenance": "stack-edu-0023.json.gz:32540",
"repo_name": "p-derezinski/java14",
"revision_date": "2018-12-15T13:54:43",
"revision_id": "5ed23fcd78eeb349028ac6e03a01f757599ceed5",
"snapshot_id": "f76119a390a3925af23813d71879d728aa342a65",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/p-derezinski/java14/5ed23fcd78eeb349028ac6e03a01f757599ceed5/src/main/java/pl/sdacademy/java14poz/listopad24/zadanie3writetofile/WriteToFileExample.java",
"visit_date": "2020-04-08T04:45:13.383225",
"added": "2024-11-18T22:37:53.011127+00:00",
"created": "2018-12-15T13:54:43",
"int_score": 3,
"score": 3.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
---
layout: post
title: Why do we need message queues?
date: 2019-08-02T10:06:01+02:00
tags: microservices
---
## HTTP might be good enough
For many systems there isn't a need for message queues. Regular HTTP-style request/response are often enough. If your system is architected without thinking about events you might have very little need for it.
A webhook can be good enough. It all depends on your architecture and business scenarios if it makes sense.
## What good is a message queue
A message queue is good for dealing with asynchronous messages not expected to be dealt with immediately. You can also use a message queue to create loosely coupled systems.
### PUB/SUB
One of the neat things with having a properly architected publish/subscribe is that you can decouple parts of your system. You can for instance use message systems with routing in order to have many consumers for selected messages or events. Products that fit the bill are:
- RabbitMQ
- Azure Service bus
- ActiveMQ
ZeroMQ looks particularly interesting as it doesn't require a dedicated deployment. Though I've never used it.
The assumption is that some systems are not interested in receiving some events. We see that [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) can use both RabbitMQ and Azure Service bus.
I've found that RabbitMQ style communication can be useful for dealing with longer running tasks generated by user input (not to be confused by cron-jobs). It's a known type of technology that has been around. Note for instance some of the standardisation around [AMQP](https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol).
### Event stream
If pushing a huge number of messages/events then routing might be less of a concern why you might want to look into systems like:
- Kafka
- AWS Kinesis
- Azure Event Hub
We have an example of using Kafka [from RedHat](https://github.com/redhat-developer-demos/eda-tutorial). We have also projects from Jet using Kafka: Note the mention of Kafka for projection in [Equinox](https://github.com/jet/equinox). Kafka is also used [by Netflix](https://github.com/Netflix/suro/tree/master/suro-kafka-producer) and [Spotify](https://github.com/spotify/docker-kafka).
Kafka has gotten a lot of attention in recent years and is probably still considered hot to work with.
## Conclusion
We might not need message queues for all systems and services, but they can be useful tools for certain use cases. You also need to decide on what style of message queues you need for your system.
|
683a2b38c609a2232fb1b7a68ff3ecbec6c94ee1
|
{
"blob_id": "683a2b38c609a2232fb1b7a68ff3ecbec6c94ee1",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-18T05:58:46",
"content_id": "38f06b86cfebcbce1947cb4677e40cd570ce95df",
"detected_licenses": [
"MIT"
],
"directory_id": "1f6a2d752104172318c07c8c6ff98887d549ceb3",
"extension": "md",
"filename": "2019-08-02-Why-do-we-need-message-queues.md",
"fork_events_count": 0,
"gha_created_at": "2018-10-26T13:24:31",
"gha_event_created_at": "2019-11-18T05:58:47",
"gha_language": "CSS",
"gha_license_id": "MIT",
"github_id": 154838444,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2563,
"license": "MIT",
"license_type": "permissive",
"path": "/_posts/2019-08-02-Why-do-we-need-message-queues.md",
"provenance": "stack-edu-markdown-0014.json.gz:208368",
"repo_name": "jackoliver/wallymathieu.github.io",
"revision_date": "2019-11-18T05:58:46",
"revision_id": "50ae9b9854f9d9be659c5e3fedc633f6fd848ae0",
"snapshot_id": "c744c46bac9945fcb1ed17164d09fddb9245a79a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jackoliver/wallymathieu.github.io/50ae9b9854f9d9be659c5e3fedc633f6fd848ae0/_posts/2019-08-02-Why-do-we-need-message-queues.md",
"visit_date": "2023-03-08T14:15:37.519798",
"added": "2024-11-18T23:21:51.125840+00:00",
"created": "2019-11-18T05:58:46",
"int_score": 3,
"score": 3.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0014.json.gz"
}
|
<?php
declare(strict_types = 1);
namespace Tests\Innmind\Git\Repository;
use Innmind\Git\{
Repository\Tag,
Repository\Tag\Name,
Message
};
use Innmind\TimeContinuum\PointInTime;
use PHPUnit\Framework\TestCase;
class TagTest extends TestCase
{
public function testInterface()
{
$tag = new Tag(
$name = new Name('1.0.0'),
$message = new Message('watev'),
$date = $this->createMock(PointInTime::class)
);
$this->assertSame($name, $tag->name());
$this->assertSame($message, $tag->message());
$this->assertSame($date, $tag->date());
}
}
|
8a393b209e973b6b95033a09f78a316e6dc4ac16
|
{
"blob_id": "8a393b209e973b6b95033a09f78a316e6dc4ac16",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-01T11:39:05",
"content_id": "904fefbf2871e5f2c8b950d022202f096b35d425",
"detected_licenses": [
"MIT"
],
"directory_id": "2faca83f14c0b1360a283b4794467856a88a25cb",
"extension": "php",
"filename": "TagTest.php",
"fork_events_count": 0,
"gha_created_at": "2020-09-02T18:29:11",
"gha_event_created_at": "2020-09-02T18:29:12",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 292363319,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 636,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/Repository/TagTest.php",
"provenance": "stack-edu-0052.json.gz:610245",
"repo_name": "open-source-contributions/Git-1",
"revision_date": "2020-02-01T11:39:05",
"revision_id": "c73048d4a7488b343805e49ef8e7b2248f13067e",
"snapshot_id": "29fd5ad4bb62396c2d6177628415713cdd5466a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/open-source-contributions/Git-1/c73048d4a7488b343805e49ef8e7b2248f13067e/tests/Repository/TagTest.php",
"visit_date": "2022-12-20T08:21:30.772286",
"added": "2024-11-19T01:14:14.199229+00:00",
"created": "2020-02-01T11:39:05",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Reddit.NET.Client.Models.Public.Streams;
namespace Reddit.NET.Client.UnitTests.Streams
{
public class PollingStreamTests
{
[Test]
public async Task PollingStream_PeriodicDataSource_ReturnsDataAsItBecomesAvailable()
{
var dataSource = new PeriodicDataSource();
var stream = PollingStream.Create(new PollingStreamOptions<string, string, string>(
(ct) => dataSource.GetData(),
mapper: v => v,
idSelector: v => v));
var data = await stream.Take(30).ToListAsync();
Assert.IsNotNull(data);
Assert.IsNotEmpty(data);
}
private class PeriodicDataSource
{
private readonly Random _random;
private readonly Timer _timer;
private IEnumerable<string> _data;
public PeriodicDataSource()
{
_random = new Random();
_timer = new Timer(
(_) => GenerateData(),
this,
TimeSpan.FromSeconds(0),
TimeSpan.FromSeconds(5));
}
public Task<IEnumerable<string>> GetData() => Task.FromResult(_data);
private void GenerateData()
{
_data = Enumerable
.Range(0, _random.Next(1, 10))
.Select(v => Guid.NewGuid().ToString())
.ToList();
}
}
}
}
|
50eb0c90b552751116a2f06144c1805c8b6cff29
|
{
"blob_id": "50eb0c90b552751116a2f06144c1805c8b6cff29",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-22T05:41:42",
"content_id": "e23b8a3ff349226f33fcbb809bf7e75e2414ac0b",
"detected_licenses": [
"MIT"
],
"directory_id": "5371b7b61f1db9358e21776c9ba3894ad646f2a7",
"extension": "cs",
"filename": "PollingStreamTests.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1652,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/Reddit.NET.Client.UnitTests/Streams/PollingStreamTests.cs",
"provenance": "stack-edu-0014.json.gz:141280",
"repo_name": "chrisjmccrum/Reddit.NET",
"revision_date": "2021-07-22T05:41:42",
"revision_id": "2e0e5fe162e807909bf48731cc01d7c492e80b9c",
"snapshot_id": "70bf05b0c99430d8493af59d965481eb04e33df3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chrisjmccrum/Reddit.NET/2e0e5fe162e807909bf48731cc01d7c492e80b9c/tests/Reddit.NET.Client.UnitTests/Streams/PollingStreamTests.cs",
"visit_date": "2023-06-21T05:06:15.871913",
"added": "2024-11-18T23:31:43.756717+00:00",
"created": "2021-07-22T05:41:42",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
const trialDivision = (number) => {
if (!Number.isInteger(number)) return false
if (number < 1 || number == 0 || number == 1 || number == 4) return false;
var counter = 2
while (counter < number) {
if ((number % counter) == 0) {
return false;
}
counter++
}
return true
}
module.exports = trialDivision;
|
64bb4413773c9ee4000f652b10d2d74fcea4743d
|
{
"blob_id": "64bb4413773c9ee4000f652b10d2d74fcea4743d",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-31T23:41:05",
"content_id": "9a1c71dd89392eeab0d02bb7f046ac9fe7663197",
"detected_licenses": [
"MIT"
],
"directory_id": "5cce4cfc115bad4b1d20d75e64fccaf9fb712dda",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": "2020-08-31T22:36:57",
"gha_event_created_at": "2020-08-31T22:36:58",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 291839275,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 339,
"license": "MIT",
"license_type": "permissive",
"path": "/src/index.js",
"provenance": "stack-edu-0038.json.gz:136881",
"repo_name": "emipmttt/challenge-javascript-04",
"revision_date": "2020-08-31T23:41:05",
"revision_id": "16b040004f86178883a441611a096ca9f56f748f",
"snapshot_id": "073fe73c176b69e09d5a7c3877d58a6a45fb27e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/emipmttt/challenge-javascript-04/16b040004f86178883a441611a096ca9f56f748f/src/index.js",
"visit_date": "2022-12-06T20:36:47.953899",
"added": "2024-11-19T01:10:47.191784+00:00",
"created": "2020-08-31T23:41:05",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz"
}
|
App::FatalHandler Component
===
## 1. Introduction
`App::FatalHandler` is a passive F' component for handling Fatal events seen by the ActiveLogger component. It saves the fatal events to OCM and then downlinks those
Fatal events on the next power up. Upon the receipt of a Fatal event, the system is rebooted after a set number of ticks.
## 2. Requirements
Requirement | Description | Verification Method |
----------- | ----------- | -------------------
FPrime-FatalHandler-00 | This component shall store up to 10 FATAL events in a buffer on the on-chip GR712 memory | unit-test |
FPrime-FatalHandler-01 | This component shall provide a command interface to clear the FATAL event buffer | unit-test |
FPrime-FatalHandler-02 | This component shall generate WARNING event if the FATAL event buffer is 50% or more full at initialization | unit-test |
FPrime-FatalHandler-03 | This component shall delay a soft reset of FSW by [10 seconds - should be what's in the FatalHandler component by default] after storing the FATAL event to on-chip memory | fit test |
FPrime-FatalHandler-04 | This component shall send all FATAL event data in the buffer for real-time and recorded downlink streams at initialization | unit and fit test |
## 3. Design
#### 3.1 Component Diagram
The component diagram is as follows:

#### 3.2 Ports
The `App::FatalHandler` component uses the following port types:
| Port Data Type | Name | Direction | Kind | Usage |
|--------------------------------------------------------|-------------------|-----------|---------------|----------------------------------------------------------|
| [`Fw::Log`](../../../../Fw/Log/docs/sdd.md) | fatalReceive | input | guarded_input | Port used to deliver a fatal event from the ActiveLogger |
| [`Fw::Log`](../../../../Fw/Log/docs/sdd.md) | storedEvrOut | output | output | Downlink the events at startup |
It also has the following role ports:
| Port Data Type | Name | Direction | Role |
|-------------------------------------------------------|----------------|-----------|-----------------|
| [`Fw::Cmd`](../../../../Fw/Cmd/docs/sdd.md) | cmdIn | input | Cmd |
| [`Fw::CmdReg`](../../../../Fw/Cmd/docs/sdd.md) | cmdRegOut | output | CmdRegistration |
| [`Fw::CmdResponse`](../../../../Fw/Cmd/docs/sdd.md) | cmdResponseOut | output | CmdResponse |
| [`Fw::Log`](../../../../Fw/Log/docs/sdd.md) | eventOut | output | Log |
| [`Fw::Ping`](../../../../Svc/Ping/docs/sdd.md) | PingRecv | input | Ping |
| [`Fw::Ping`](../../../../Svc/Ping/docs/sdd.md) | PingResponse | output | Ping |
| [`Svc::Time`](../../../../Svc/SphinxTime/docs/sdd.md) | timeCaller | output | TimeGet |
| [`Svc::TlmChan`](../../../../Svc/TlmChan/docs/sdd.md) | tlmOut | output | Telemetry |
#### 3.3 Functional Description
The fatal handler responds to the events on the fatalReceive port and saves the log messages to the on chip memory. The format of the records saved should follow the following tables:
| Field | Data Type |
|-----------------|-----|
| Size (bytes) | U32 |
| ID | U32 |
| Time (Seconds) | U32 |
| Time (USeconds) | U32 |
| Argument bytes | U8* |
*: The record is serialized into integers for use with the OCM. Thus some integers are only partially filled. Size reflects the true bytes, not the bytes for the number of integers used.
Ten of these records may be stored in the OCM, and after that new records are dropped. Cascading fatals, will stem from one event, thus the initial fatal event should be store, and hence any new
records should be dropped. When the OCM has filled more that 50% of the OCM a warning event will be sent with the percentage filled. Once a single fatal is received, the system is set to restart
after a set amount of time. Upon restart, the stored Fatals are downlinked but not removed.
There are two commands. The first emits a fatal event through normal channels and the other clears the memory.
|
ed900872ac7dcf953ed6ab5e09c0b054ccdd759f
|
{
"blob_id": "ed900872ac7dcf953ed6ab5e09c0b054ccdd759f",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-09T22:45:48",
"content_id": "2272334b902122d5853443eaf69dae147b892fc3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8fb7d80ce381d24fbfb910a51bf8857a1f4fb9ec",
"extension": "md",
"filename": "sdd.md",
"fork_events_count": 1,
"gha_created_at": "2020-09-14T20:32:51",
"gha_event_created_at": "2021-09-09T22:34:24",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 295532197,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4390,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/App/FatalHandler/docs/sdd.md",
"provenance": "stack-edu-markdown-0014.json.gz:161337",
"repo_name": "fprime-community/fprime-sphinx",
"revision_date": "2021-09-09T22:45:48",
"revision_id": "bb8de14874f262dbe22741fec286e1417c8ac8ca",
"snapshot_id": "6716e6b8a2ac1be76e1effae7dda6b03b7ddc9ee",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/fprime-community/fprime-sphinx/bb8de14874f262dbe22741fec286e1417c8ac8ca/App/FatalHandler/docs/sdd.md",
"visit_date": "2021-11-15T20:46:10.256003",
"added": "2024-11-18T23:25:21.707148+00:00",
"created": "2021-09-09T22:45:48",
"int_score": 4,
"score": 3.796875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0014.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.