text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
module.exports = function(scope) { /** * Ensure we have called the manifest at least once * * The manifest is a special call which builds the raw api calls * Raw api calls are used inside the simplified API that we export * * @returns {Promise} */ return function ensureManifest() { return new Promise(function(resolve) { if ( Object.keys(scope.rawApi).length ) { return resolve(); } return scope.fetchManifest(resolve); }).then(scope.noop); }; };
12e636bc3e9ccbf5d6b545ec2d4b52760313e1f9
{ "blob_id": "12e636bc3e9ccbf5d6b545ec2d4b52760313e1f9", "branch_name": "refs/heads/master", "committer_date": "2018-09-17T07:43:18", "content_id": "fa5205eb4faddcdac92ab26232e2014779ea09e2", "detected_licenses": [ "MIT" ], "directory_id": "886a75ec33e21da316832b50c22fcb896fbf23a7", "extension": "js", "filename": "ensure-manifest.js", "fork_events_count": 2, "gha_created_at": "2018-02-20T12:48:02", "gha_event_created_at": "2018-09-17T07:43:20", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 122197337, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 496, "license": "MIT", "license_type": "permissive", "path": "/src/helper/ensure-manifest.js", "provenance": "stack-edu-0038.json.gz:524994", "repo_name": "trackthis/js-api-client", "revision_date": "2018-09-17T07:43:18", "revision_id": "f058f1db5fb82078de64a33eeeae437cacdb8d12", "snapshot_id": "a69ae02ef35f63198589a41dd2f7012492246744", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/trackthis/js-api-client/f058f1db5fb82078de64a33eeeae437cacdb8d12/src/helper/ensure-manifest.js", "visit_date": "2018-11-10T00:01:38.835643", "added": "2024-11-18T19:07:29.648931+00:00", "created": "2018-09-17T07:43:18", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
#include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <pthread.h> #include <iostream> #include <fstream> #include <vector> #include <sstream> #include "tcp_client.h" using namespace std; #define NSECS_PER_SEC 1000000000 #define USECS_PER_SEC 1000000 #define NSECS_PER_USEC 1000 #define BYTES_PER_MBIT 125000 bool time_expired; struct itimerspec timer_setting; int query_test(TCPClient &client, long query_size) { cout << "query test - message size: " << query_size << endl; char *msg = new char[query_size]; memset(msg, '%', query_size); client.Send(msg, query_size); delete msg; return 0; } int throughput_test(TCPClient &client, long duration) { int status; char *msg = new char[MSG_SIZE]; memset(msg, '%', MSG_SIZE); // start timer and do until duration expires while (send) { try { client.Send(msg, MSG_SIZE); } catch (const char * e) { delete msg; break; } } return 0; } void timer_sighandler(union sigval val) { time_expired = true; } int convergence_test(TCPClient &client, long duration) { int status; char *msg = new char[MSG_SIZE]; memset(msg, '%', MSG_SIZE); // we want our signal handler to have the highest possible priority pthread_attr_t attr; pthread_attr_init(&attr); struct sched_param monitor_param; monitor_param.sched_priority = 255; struct sigevent timer_sig; timer_sig.sigev_notify = SIGEV_THREAD; timer_sig.sigev_notify_function = timer_sighandler; timer_sig.sigev_value.sival_int = 0; timer_sig.sigev_notify_attributes = &attr; timer_t timer_id; status = timer_create(CLOCK_REALTIME, &timer_sig, &timer_id); if (status != 0) { perror("timer_create"); return -1; } timer_setting.it_value.tv_sec = static_cast<long>(duration * NSECS_PER_SEC) / NSECS_PER_SEC; timer_setting.it_value.tv_nsec = static_cast<long>(duration * NSECS_PER_SEC) % NSECS_PER_SEC; timer_setting.it_interval.tv_sec = static_cast<long>(duration * NSECS_PER_SEC) / NSECS_PER_SEC; timer_setting.it_interval.tv_nsec = static_cast<long>(duration * NSECS_PER_SEC) % NSECS_PER_SEC; status = timer_settime(timer_id, 0, &timer_setting, NULL); // start timer and do until duration expires while (!time_expired) { try { client.Send(msg, MSG_SIZE); } catch (const char * e) { break; } } delete msg; return 0; } int main(int argc, char const *argv[]) { char *data; vector<string> test_info; if (argc < 2) { cerr << "usage: client <server hostname>" << endl; exit(1); } TCPClient client(argv[1]); data = new char[256]; memset(data, '\0', 256); client.Receive(data, 256); string buf; stringstream ss(data); while (ss >> buf) { test_info.push_back(buf); } if (test_info.size() < 1) { cerr << "fatal: empty request from server" << endl; exit(1); } string test_type = test_info[0]; if (test_type == "query") { if (test_info.size() < 2) { cerr << "fatal: too few arguments from server" << endl; exit(1); } long query_size = stol(test_info[1]); query_test(client, query_size); } else if (test_type == "throughput") { if (test_info.size() < 2) { cerr << "fatal: too few arguments from server" << endl; exit(1); } long duration = stol(test_info[1]); throughput_test(client, duration); } else if (test_type == "converge") { if (test_info.size() < 2) { cerr << "fatal: too few arguments from server" << endl; exit(1); } long duration = stol(test_info[1]); convergence_test(client, duration); } else { cerr << "fatal: server requested invalid test type" << endl; exit(1); } client.Close(); return 0; }
ddacc1e1940039aff76707d03faba9170a2e020f
{ "blob_id": "ddacc1e1940039aff76707d03faba9170a2e020f", "branch_name": "refs/heads/master", "committer_date": "2017-12-04T19:16:34", "content_id": "c42ceb7ae3826092adcbe6c1b8334269a452bc06", "detected_licenses": [ "MIT" ], "directory_id": "43edad95a92694e51311b896ec56a74c72d9d8c0", "extension": "cc", "filename": "worker.cc", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108890828, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4073, "license": "MIT", "license_type": "permissive", "path": "/src/worker.cc", "provenance": "stack-edu-0003.json.gz:243299", "repo_name": "chowes/data-center-bbr", "revision_date": "2017-12-04T19:16:34", "revision_id": "3fa50a7341ef4ef9bdc318313048e0a428bfc560", "snapshot_id": "4eefea81434b92c761b32ae5aa577fb65a3fd757", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/chowes/data-center-bbr/3fa50a7341ef4ef9bdc318313048e0a428bfc560/src/worker.cc", "visit_date": "2021-08-23T11:43:26.190645", "added": "2024-11-18T22:38:22.913354+00:00", "created": "2017-12-04T19:16:34", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
import chalk from "chalk" import * as core from "babel-core" function catchBabelVersionMismatch(fn) { return function() { try { fn.apply(null, arguments) } catch (e) { let logged = false if ( e.message.startsWith( "Plugin/Preset files are not allowed to export objects" ) ) { logged = true const { makeInstall } = require("../lingui-init") const install = makeInstall() console.log(chalk.red("Please install missing Babel 6 core package:")) console.log() console.log(install("babel-core@^6.0.0", true)) console.log() } else if ( e.message.startsWith( 'Requires Babel "^7.0.0-0", but was loaded with "6.26.3".' ) ) { logged = true const { makeInstall } = require("../lingui-init") const install = makeInstall() console.log(chalk.red("Please install missing Babel 7 core packages:")) console.log() console.log(install("babel-core@^7.0.0-bridge.0 @babel/core", true)) console.log() } if (logged) { console.log("Original error:") console.log(e) process.exit(1) } else { throw e } } } } export const transform = catchBabelVersionMismatch(core.transform) export const transformFileSync = catchBabelVersionMismatch( core.transformFileSync )
84feae5ed2a1d5694eee13fd0f1b983c30ae1475
{ "blob_id": "84feae5ed2a1d5694eee13fd0f1b983c30ae1475", "branch_name": "refs/heads/master", "committer_date": "2019-12-02T09:39:26", "content_id": "543344e7a5b95dcd904ef5eb195f8c000c9d2924", "detected_licenses": [ "MIT" ], "directory_id": "4c60418e95190b630ec1f5a8083fa97f92ca6a68", "extension": "js", "filename": "compat.js", "fork_events_count": 0, "gha_created_at": "2019-02-25T22:41:22", "gha_event_created_at": "2019-02-25T22:41:22", "gha_language": null, "gha_license_id": "MIT", "github_id": 172597029, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1414, "license": "MIT", "license_type": "permissive", "path": "/packages/cli/src/api/compat.js", "provenance": "stack-edu-0045.json.gz:522988", "repo_name": "toolness/js-lingui", "revision_date": "2019-12-02T09:39:26", "revision_id": "7f6a3ffc31368c6976d000236079299191424154", "snapshot_id": "dca081783e0c1eb46fe61a96ee95a55473240052", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/toolness/js-lingui/7f6a3ffc31368c6976d000236079299191424154/packages/cli/src/api/compat.js", "visit_date": "2021-07-04T16:29:21.791038", "added": "2024-11-19T03:42:46.768870+00:00", "created": "2019-12-02T09:39:26", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
/* * mandelbrot.c * * Created on: 2017/04/02 * Author: minoru */ #include <stdio.h> #include <math.h> static int isDiverge(float x, float y) { return x * x + y * y > 2.0f * 2.0f; } static int divergeCount(float cx, float cy, int repeat) { float x = 0.0f, y = 0.0f; int count; for (count = 0; count < repeat; ++count) { float zx = x * x - y * y + cx; float zy = 2.0f * x * y + cy; if (isDiverge(zx, zy)) { return count; } x = zx; y = zy; } return count; } static unsigned short count2color(int count, int repeat) { if (count == repeat) { return 0; } else { unsigned char r = 15.0f * count / repeat; unsigned char g = 15.0f * count / repeat * count / repeat; unsigned char b = (count > repeat / 2) ? (15.0f * (count - repeat / 2) / repeat) : 15.0f * 2 * count / repeat; return (r << 8) | (g << 4) | b; } } // マンデルブロ集合の描画 void drawMandelbrot(volatile unsigned short *vram, int w, int h, int repeat) { for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { float cx = (float)x / (w / 3.0f) - 2.0f; float cy = (float)y / (h / 2.0f) - 1.0f; int count = divergeCount(cx, cy, repeat); vram[x + y * w] = count2color(count, repeat); } } }
7da2cff1419b6348f7d65d9f28134a6613f1e570
{ "blob_id": "7da2cff1419b6348f7d65d9f28134a6613f1e570", "branch_name": "refs/heads/master", "committer_date": "2017-04-16T03:45:25", "content_id": "19b569d3dc3e3ca26fa9a068a324a048bccd3c7a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f178718a3bf16ba44fec5b2ca23452bdf53eef01", "extension": "c", "filename": "mandelbrot.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 87028424, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1225, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Zybo/vgagraph/SDK/mandelbrot.c", "provenance": "stack-edu-0001.json.gz:474674", "repo_name": "minosys-jp/FPGA", "revision_date": "2017-04-16T03:45:25", "revision_id": "f6c42a6627e02baa9f70dffdb7a589795fd1fa8e", "snapshot_id": "b8415c07c9c04fe0ade9ecdea58572bfe89806d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/minosys-jp/FPGA/f6c42a6627e02baa9f70dffdb7a589795fd1fa8e/Zybo/vgagraph/SDK/mandelbrot.c", "visit_date": "2021-01-18T21:55:38.766004", "added": "2024-11-18T23:11:23.334148+00:00", "created": "2017-04-16T03:45:25", "int_score": 3, "score": 3.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
--- layout: post title: "【Research & Competition】CVPR2023 Workshop 竞赛汇总" subtitle: "" date: 2023-02-22 author: "ShawnD" header-img: "img/post-bg-rwd.jpg" catalog: flase tags: - Research & Competition - 深度学习 - CVPR 2023 --- # Vision-Centric Autonomous Driving (VCAD) [http://www.vcad.site/#/challenge](http://www.vcad.site/#/challenge) # Workshop on Autonomous Driving (WAD) [https://cvpr2023.wad.vision/](https://cvpr2023.wad.vision/) # Workshop on End-to-end Autonomous Driving [https://opendrivelab.com/e2ead/cvpr23](https://opendrivelab.com/e2ead/cvpr23) # CVPR 2023 Biometrics Workshop # The 4th Face Anti-spoofing Workshop and Challenge [https://sites.google.com/view/face-anti-spoofing-challenge/winners-results/challengecvpr2023?authuser=0](https://sites.google.com/view/face-anti-spoofing-challenge/winners-results/challengecvpr2023?authuser=0) # 8th New Trends in Image Restoration and Enhancement Workshop and Challenges [https://cvlai.net/ntire/2023/](https://cvlai.net/ntire/2023/) # Second Workshop of Mobile Intelligent Photography and Imaging [http://mipi-challenge.org/MIPI2023/](http://mipi-challenge.org/MIPI2023/) # The 3rd Workshop on Light Fields for Computer Vision LFNAT: New Applications and Trends in Light Fields [http://www.lfchallenge.com/LFNAT@CVPR2023/challenge/](http://www.lfchallenge.com/LFNAT@CVPR2023/challenge/) # The 6th Workshop and Prize Challenge Bridging the Gap between Computational Photography and Visual Recognition (UG2+) in conjunction with IEEE CVPR 2023 [http://cvpr2023.ug2challenge.org/index.html](http://cvpr2023.ug2challenge.org/index.html) # 19th CVPR Workshop on Perception Beyond the Visible Spectrum (PBVS 2023) [https://pbvs-workshop.github.io/challenge.html](https://pbvs-workshop.github.io/challenge.html) # # AVA: Accessibility, Vision, and Autonomy Meet [https://accessibility-cv.github.io/index.html#challenge](https://accessibility-cv.github.io/index.html#challenge) # 2023 VizWiz Grand Challenge Workshop [https://vizwiz.org/workshops/2023-workshop/](https://vizwiz.org/workshops/2023-workshop/) # 8th Workshop on Computer Vision for Microscopy Image Analysis [https://cvmi-workshop.github.io/index.html](https://cvmi-workshop.github.io/index.html) # 2nd Workshop on Multimodal Learning for Earth and Environment (MultiEarth) [https://sites.google.com/view/rainforest-challenge/multiearth-2023](https://sites.google.com/view/rainforest-challenge/multiearth-2023) # EarthVision: Large Scale Computer Vision for Remote Sensing Imagery [https://www.grss-ieee.org/events/earthvision-2023/](https://www.grss-ieee.org/events/earthvision-2023/) # 3rd Workshop and Challenge on Computer Vision in the Built Environment for the Design, Construction, and Operation of Buildings [https://cv4aec.github.io/#challenge](https://cv4aec.github.io/#challenge) # DL-UIA: Deep Learning in Ultrasound Image Analysis [https://www.cvpr2023-dl-ultrasound.com/](https://www.cvpr2023-dl-ultrasound.com/) # Workshop on Vision-based InduStrial InspectiON (VISION) [https://vision-based-industrial-inspection.github.io/cvpr-2023/](https://vision-based-industrial-inspection.github.io/cvpr-2023/) # 2nd Workshop and Challenge on Vision Datasets Understanding [https://sites.google.com/view/vdu-cvpr23/competition](https://sites.google.com/view/vdu-cvpr23/competition) # 3rd Mobile AI Workshop and Challenges [https://ai-benchmark.com/workshops/mai/2023/#challenges](https://ai-benchmark.com/workshops/mai/2023/#challenges) # 5th Workshop and Competition on Affective Behavior Analysis in-the-wild [https://ibug.doc.ic.ac.uk/resources/cvpr-2023-5th-abaw/](https://ibug.doc.ic.ac.uk/resources/cvpr-2023-5th-abaw/) # 2nd Challenge on Machine Visual Common Sense: Perception, Prediction, Planning [https://mvcs-workshop.github.io/](https://mvcs-workshop.github.io/) # 4D Hand Object Interaction: Geometric Understanding and Applications in Dexterous Manipulation [https://4dhoi.github.io/](https://4dhoi.github.io/) # Catch UAVs that Want to Watch You: Detection and Tracking of Unmanned Aerial Vehicle (UAV) in the Wild and the 3rd Anti-UAV Workshop & Challenge [https://anti-uav.github.io/](https://anti-uav.github.io/) # Image Matching: Local Features and Beyond [https://image-matching-workshop.github.io/](https://image-matching-workshop.github.io/) # OmniCV 4 Workshop Proposal [https://sites.google.com/view/omnicv2023/home?authuser=0](https://sites.google.com/view/omnicv2023/home?authuser=0) # RetailVision - Revolutionizing the World of Retail [https://retailvisionworkshop.github.io/#challenge](https://retailvisionworkshop.github.io/#challenge) # VAND: Visual Anomaly and Novelty Detection [https://sites.google.com/view/vand-cvpr23/challenge?authuser=0](https://sites.google.com/view/vand-cvpr23/challenge?authuser=0) # 1st Workshop on Compositional 3D Vision & 3DCoMPaT Challenge [https://3dcompat-dataset.org/workshop/#main-section](https://3dcompat-dataset.org/workshop/#main-section) # The Fifth Workshop on Deep Learning for Geometric Computing [https://sites.google.com/view/dlgc-workshop-cvpr2023/challenge?authuser=0](https://sites.google.com/view/dlgc-workshop-cvpr2023/challenge?authuser=0) # The Second Workshop on Structural and Compositional Learning on 3D Data [https://struco3d.github.io/cvpr2023/](https://struco3d.github.io/cvpr2023/) # AI for Content Creation [https://ai4cc.net/](https://ai4cc.net/) # 4th Workshop on Continual Learning in Computer Vision (CLVision) [https://sites.google.com/view/clvision2023](https://sites.google.com/view/clvision2023) # FGVC10: 10th Workshop on Fine-grained Visual Categorization [https://sites.google.com/view/fgvc10/competitions?authuser=0](https://sites.google.com/view/fgvc10/competitions?authuser=0) # L3D-IVU: 2nd Workshop on Learning with Limited Labelled Data for Image and Video Understanding [https://sites.google.com/view/l3d-ivu-2023/challenges?authuser=0](https://sites.google.com/view/l3d-ivu-2023/challenges?authuser=0) # The 3rd Workshop of Adversarial Machine Learning on Computer Vision: Art of Robustness [https://robustart.github.io/#challenge](https://robustart.github.io/#challenge) # 5th ScanNet Indoor Scene Understanding Challenge [http://www.scan-net.org/cvpr2023workshop/](http://www.scan-net.org/cvpr2023workshop/) # Computer Vision in the Wild [https://computer-vision-in-the-wild.github.io/cvpr-2023/](https://computer-vision-in-the-wild.github.io/cvpr-2023/) # OmniLabel: Infinite label spaces for semantic understanding via natural language [https://sites.google.com/view/omnilabel-workshop-cvpr23/challenge?authuser=0](https://sites.google.com/view/omnilabel-workshop-cvpr23/challenge?authuser=0) # Visual Perception via Learning in an Open World [https://vplow.github.io/vplow_3rd.html#competition](https://vplow.github.io/vplow_3rd.html#competition) # 2nd Workshop on Tracking and Its Many Guises: Tracking Any Object in Open-World [http://taodataset.org/workshop/cvpr23/](http://taodataset.org/workshop/cvpr23/) # 9th IEEE International Workshop on Computer Vision in Sports (CVsports) [https://www.soccer-net.org/challenges/2023](https://www.soccer-net.org/challenges/2023) # Workshop on Foundation Models: 1st Foundation Model Challenge [https://foundation-model.com/competition](https://foundation-model.com/competition) # 4th Embodied AI Workshop [https://embodied-ai.org/#challenges](https://embodied-ai.org/#challenges) # Vision for All Seasons: Adverse Weather and Lighting Conditions [https://vision4allseason.net/](https://vision4allseason.net/) # 2nd Monocular Depth Estimation Challenge [https://jspenmar.github.io/MDEC/#challenge](https://jspenmar.github.io/MDEC/#challenge) # First Rhobin Challenge - Reconstruction of human-object interaction [https://rhobin-challenge.github.io/](https://rhobin-challenge.github.io/) # 7th AI City Challenge Workshop [https://www.aicitychallenge.org/2023-challenge-tracks/](https://www.aicitychallenge.org/2023-challenge-tracks/) # Joint 3rd Ego4D and 11th EPIC Workshop on Egocentric Vision [https://sites.google.com/view/ego4d-epic-cvpr2023-workshop/](https://sites.google.com/view/ego4d-epic-cvpr2023-workshop/) # Pixel-level Video Understanding in the Wild Challenge [https://www.vspwdataset.com/Workshop%202023.html](https://www.vspwdataset.com/Workshop%202023.html) # New Frontiers for Zero-Shot Image Captioning Evaluation [https://nice.lgresearch.ai/](https://nice.lgresearch.ai/)
eb3dcf33de32f2d00f8207239e581866d68c97b0
{ "blob_id": "eb3dcf33de32f2d00f8207239e581866d68c97b0", "branch_name": "refs/heads/master", "committer_date": "2023-08-26T10:59:11", "content_id": "b3ec5858d2c8ba4a0127f3e73a0acfd5856c9af3", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "ae2c8bb5f9bb78ef0f22665683572ca9aef12a02", "extension": "md", "filename": "2023-02-22-【Research & Competition】CVPR2023 Workshop 竞赛汇总.md", "fork_events_count": 2, "gha_created_at": "2019-12-23T13:10:55", "gha_event_created_at": "2023-03-03T11:24:45", "gha_language": "HTML", "gha_license_id": "Apache-2.0", "github_id": 229755347, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8581, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/_posts/2023-02-22-【Research & Competition】CVPR2023 Workshop 竞赛汇总.md", "provenance": "stack-edu-markdown-0017.json.gz:249674", "repo_name": "ShawnDong98/ShawnDong98.github.io", "revision_date": "2023-08-26T10:59:11", "revision_id": "8020b89d9aaa11a566dd220b569d6cf46b748e24", "snapshot_id": "43915632ed79cadbdc01d5a2c1909403fadfc041", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/ShawnDong98/ShawnDong98.github.io/8020b89d9aaa11a566dd220b569d6cf46b748e24/_posts/2023-02-22-【Research & Competition】CVPR2023 Workshop 竞赛汇总.md", "visit_date": "2023-08-31T01:28:42.131785", "added": "2024-11-18T19:18:18.770076+00:00", "created": "2023-08-26T10:59:11", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0017.json.gz" }
/* This file is part of the FRED system. Copyright (c) 2010-2015, University of Pittsburgh, John Grefenstette, Shawn Brown, Roni Rosenfield, Alona Fyshe, David Galloway, Nathan Stone, Jay DePasse, Anuroop Sriram, and Donald Burke. Licensed under the BSD 3-Clause license. See the file "LICENSE" for more information. */ // // // File: Neighborhood.cc // #include "Neighborhood.h" #include "Global.h" #include "Params.h" #include "Random.h" #include "Person.h" #include "Disease.h" #include "Disease_List.h" //Private static variables that will be set by parameter lookups double Neighborhood::contacts_per_day = 0.0; double Neighborhood::same_age_bias = 0.0; double** Neighborhood::prob_transmission_per_contact = NULL; double Neighborhood::weekend_contact_rate = 0.0; Neighborhood::Neighborhood(const char* lab, char _subtype, fred::geo lon, fred::geo lat) : Place(lab, lon, lat) { this->set_type(Place::TYPE_NEIGHBORHOOD); this->set_subtype(_subtype); this->intimacy = 0.0025; } void Neighborhood::get_parameters() { Params::get_param_from_string("neighborhood_contacts", &Neighborhood::contacts_per_day); Params::get_param_from_string("neighborhood_same_age_bias", &Neighborhood::same_age_bias); int n = Params::get_param_matrix((char *)"neighborhood_trans_per_contact", &Neighborhood::prob_transmission_per_contact); if(Global::Verbose > 1) { printf("\nNeighborhood_contact_prob:\n"); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { printf("%f ", Neighborhood::prob_transmission_per_contact[i][j]); } printf("\n"); } } Params::get_param_from_string("weekend_contact_rate", &Neighborhood::weekend_contact_rate); if(Global::Verbose > 0) { printf("\nprob_transmission_per_contact before normalization:\n"); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { printf("%f ", Neighborhood::prob_transmission_per_contact[i][j]); } printf("\n"); } printf("\ncontact rate: %f\n", Neighborhood::contacts_per_day); } // normalize contact parameters // find max contact prob double max_prob = 0.0; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(Neighborhood::prob_transmission_per_contact[i][j] > max_prob) { max_prob = Neighborhood::prob_transmission_per_contact[i][j]; } } } // convert max contact prob to 1.0 if(max_prob > 0) { for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { Neighborhood::prob_transmission_per_contact[i][j] /= max_prob; } } // compensate contact rate Neighborhood::contacts_per_day *= max_prob; // end normalization if(Global::Verbose > 0) { printf("\nprob_transmission_per_contact after normalization:\n"); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { printf("%f ", Neighborhood::prob_transmission_per_contact[i][j]); } printf("\n"); } printf("\ncontact rate: %f\n", Neighborhood::contacts_per_day); } // end normalization } } int Neighborhood::get_group(int disease, Person* per) { int age = per->get_age(); if(age < Global::ADULT_AGE) { return 0; } else { return 1; } } double Neighborhood::get_transmission_probability(int disease, Person* i, Person* s) { double age_i = i->get_real_age(); double age_s = s->get_real_age(); double diff = fabs(age_i - age_s); double prob = exp(-Neighborhood::same_age_bias * diff); return prob; } double Neighborhood::get_transmission_prob(int disease, Person* i, Person* s) { // i = infected agent // s = susceptible agent int row = get_group(disease, i); int col = get_group(disease, s); double tr_pr = Neighborhood::prob_transmission_per_contact[row][col]; return tr_pr; } double Neighborhood::get_contacts_per_day(int disease) { return Neighborhood::contacts_per_day; }
4eee532caeb45f41e543cabd275372b4182fa624
{ "blob_id": "4eee532caeb45f41e543cabd275372b4182fa624", "branch_name": "refs/heads/FRED-v2.12.0", "committer_date": "2021-03-04T18:16:39", "content_id": "813d428f0fae8c3326de2fdd139edafdaf0af9ff", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "031a94bc5dfffed307ad9db31a46ee08940be36e", "extension": "cc", "filename": "Neighborhood.cc", "fork_events_count": 27, "gha_created_at": "2014-09-29T11:37:08", "gha_event_created_at": "2018-05-20T12:40:42", "gha_language": "C++", "gha_license_id": null, "github_id": 24592652, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3910, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/src/Neighborhood.cc", "provenance": "stack-edu-0005.json.gz:429004", "repo_name": "PublicHealthDynamicsLab/FRED", "revision_date": "2021-03-04T18:16:39", "revision_id": "501ed824ec58da3044c726478413e7a9ebd5f70a", "snapshot_id": "149cd3d03e10825ba516f2730fff40fb04ac08c6", "src_encoding": "UTF-8", "star_events_count": 67, "url": "https://raw.githubusercontent.com/PublicHealthDynamicsLab/FRED/501ed824ec58da3044c726478413e7a9ebd5f70a/src/Neighborhood.cc", "visit_date": "2021-10-24T01:56:28.528585", "added": "2024-11-18T19:46:06.296805+00:00", "created": "2021-03-04T18:16:39", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
# SPDX-FileCopyrightText: 2022-present Ofek Lev <[email protected]> # # SPDX-License-Identifier: MIT import errno import os import shutil import stat import tempfile from contextlib import contextmanager import pytest from .utils import create_file, git, write_file def handle_remove_readonly(func, path, exc): # no cov # PermissionError: [WinError 5] Access is denied: '...\\.git\\...' if func in (os.rmdir, os.remove, os.unlink) and exc[1].errno == errno.EACCES: os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # noqa: S103 func(path) else: raise @pytest.fixture def temp_dir(): directory = tempfile.mkdtemp() try: directory = os.path.realpath(directory) yield directory finally: shutil.rmtree(directory, ignore_errors=False, onerror=handle_remove_readonly) @contextmanager def create_project(directory, metadata, *, setup_vcs=True, nested=False): root_dir = project_dir = os.path.join(directory, 'my-app') os.mkdir(root_dir) gitignore_file = os.path.join(root_dir, '.gitignore') write_file(gitignore_file, '/my_app/version.py') if nested: project_dir = os.path.join(root_dir, 'project') os.mkdir(project_dir) project_file = os.path.join(project_dir, 'pyproject.toml') write_file(project_file, metadata) package_dir = os.path.join(project_dir, 'my_app') os.mkdir(package_dir) create_file(os.path.join(package_dir, '__init__.py')) create_file(os.path.join(package_dir, 'foo.py')) create_file(os.path.join(package_dir, 'bar.py')) create_file(os.path.join(package_dir, 'baz.py')) origin = os.getcwd() os.chdir(project_dir) try: if setup_vcs: if nested: os.chdir(root_dir) git('init') git('config', '--local', 'user.name', 'foo') git('config', '--local', 'user.email', '[email protected]') git('add', '.') git('commit', '-m', 'test') git('tag', '1.2.3') if nested: os.chdir(project_dir) yield project_dir finally: os.chdir(origin) @pytest.fixture def new_project_basic(temp_dir): with create_project( temp_dir, """\ [build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "my-app" dynamic = ["version"] [tool.hatch.version] source = "vcs" """, ) as project: yield project @pytest.fixture def new_project_write(temp_dir): with create_project( temp_dir, """\ [build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "my-app" dynamic = ["version"] [tool.hatch.version] source = "vcs" [tool.hatch.build.targets.wheel.hooks.vcs] version-file = "my_app/_version.py" """, ) as project: yield project @pytest.fixture def new_project_fallback(temp_dir): with create_project( temp_dir, """\ [build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "my-app" dynamic = ["version"] [tool.hatch.version] source = "vcs" fallback-version = "7.8.9" """, setup_vcs=False, ) as project: yield project @pytest.fixture def new_project_root_elsewhere(temp_dir): with create_project( temp_dir, """\ [build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "my-app" dynamic = ["version"] [tool.hatch.version] source = "vcs" raw-options = { root = ".." } """, nested=True, ) as project: yield project @pytest.fixture def new_project_metadata(temp_dir): with create_project( temp_dir, """\ [build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "my-app" dynamic = ["version", "urls"] [tool.hatch.version] source = "vcs" [tool.hatch.metadata.hooks.vcs.urls] Homepage = "https://www.google.com" foo = "https://github.com/bar/baz#{commit_hash}" """, ) as project: yield project
a66e7adcc93badace27c1d6c30d9989f09bb359f
{ "blob_id": "a66e7adcc93badace27c1d6c30d9989f09bb359f", "branch_name": "refs/heads/master", "committer_date": "2023-06-16T13:56:47", "content_id": "713feb4abb88136fd5cb75f799ccdc6304305262", "detected_licenses": [ "MIT" ], "directory_id": "5ecacec7c799d0a5756b254e5ad41b828bf75cae", "extension": "py", "filename": "conftest.py", "fork_events_count": 9, "gha_created_at": "2022-01-19T00:20:23", "gha_event_created_at": "2023-06-16T13:56:49", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 449491149, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4110, "license": "MIT", "license_type": "permissive", "path": "/tests/conftest.py", "provenance": "stack-edu-0061.json.gz:70052", "repo_name": "ofek/hatch-vcs", "revision_date": "2023-06-16T13:56:47", "revision_id": "425d529cd24295311ca5b52b589a6308165fb244", "snapshot_id": "137a3c11e238b947b3e703bbc50dbabe05386d7d", "src_encoding": "UTF-8", "star_events_count": 45, "url": "https://raw.githubusercontent.com/ofek/hatch-vcs/425d529cd24295311ca5b52b589a6308165fb244/tests/conftest.py", "visit_date": "2023-06-28T03:23:49.865605", "added": "2024-11-18T19:29:38.443423+00:00", "created": "2023-06-16T13:56:47", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz" }
from numpy import * from sklearn.tree import DecisionTreeClassifier from stratified_choice import stratified_choice class RF: """ Random Forest on a stream of features. We may add a single or multiple features at once. We may add a single or multiple trees at once. The used decision tree is from sklearn -> see the documentation for sklearn.tree. """ def __init__(self, y, n_jobs=10, mtry=0.1, seed=2001): """ Initialize the random forest. :param y: the label (a vector with the class labels) :param n_jobs: how many new trees to train at each update (integer in range 1..inf) :param mtry: the feature sampling probability (double in range 0..1) :param seed: for reproducibility """ self.y = y self.n_jobs = n_jobs self.mtry = mtry self.seed = seed self.X = empty((len(y), 0)) self.feature_usage_count = array([], int) self.trees = [] # Contains tuples: (tree, feature_set, weight) def fit(self, X): """ We treat all features as numerical. Since we are interested only in contrasting challenger vs. baseline, it is ok. :param X: vector or a matrix with the new feature(s) """ n_old_cols = size(self.X, 1) if len(shape(X)) == 1: n_new_cols = 1 else: n_new_cols = size(X, 1) random.seed(self.seed) # Append column(s) self.X = column_stack((self.X, X)) # Sample old features (no stratification and no guarantee of the counts - only of the probabilities...) mtry = self.get_mtry(n_old_cols, n_new_cols) print(mtry, self.mtry) old_features_pack = random.choice([False, True], (self.n_jobs, n_old_cols), p=[1 - mtry, mtry]) # Complement the old features with the new features features = column_stack((old_features_pack, ones((self.n_jobs, n_new_cols), dtype=bool))) # Get unweighted feature use count of the new trees feature_use_count = sum(features, axis=0) # Get tree weight and update feature_usage_count if n_old_cols > 0 and self.mtry < 1.0: tree_weight = mean(self.feature_usage_count[0:n_old_cols]) / (mean(feature_use_count[n_old_cols:n_old_cols+n_new_cols]) - mean(feature_use_count[0:n_old_cols])) new_feature_usage_count = tree_weight * feature_use_count new_feature_usage_count[0:n_old_cols] += self.feature_usage_count self.feature_usage_count = new_feature_usage_count else: tree_weight = 1 self.feature_usage_count = feature_use_count for i in range(self.n_jobs): # Sample training instances samples = stratified_choice(self.y, replace=True) # Train the tree tree = DecisionTreeClassifier(max_depth=6) tree.fit(self.X[ix_(samples, features[i, :])], self.y[samples]) # Store the tree self.trees.append((tree, features[i, :], tree_weight)) return self.feature_usage_count def score(self, X_t): """ Returns a weighted average prediction from the individual trees. :param X_t: a 2D array to score """ predictions = empty((size(X_t, 0), 0)) for t in self.trees: tree, feature_set, tree_weight = t data = X_t[:, 0:len(feature_set)] data = data[:, feature_set] predictions = column_stack((predictions, tree_weight * tree.predict_proba(data)[:, 1])) return mean(predictions, 1) def get_mtry(self, n_old_cols, n_new_cols): # We want to preserve the constant mtry regardless of the count of the features (we have to take into account the # new feature is always present while the rest is sampled). # This is important for a fair comparison to normal random forest implementations. if n_old_cols == 0: return self.mtry # Not important... else: return (self.mtry * (n_old_cols + n_new_cols) - n_new_cols) / n_old_cols
c500369ef91b5bace434f516ceccd99c251f062a
{ "blob_id": "c500369ef91b5bace434f516ceccd99c251f062a", "branch_name": "refs/heads/master", "committer_date": "2019-10-18T07:36:16", "content_id": "b08b22447ebc08507a660322717e4adc415c44e2", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "39c9eca3fb492150338f8419aea00bd8d080fbd7", "extension": "py", "filename": "rf.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 191593410, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4127, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/rf.py", "provenance": "stack-edu-0058.json.gz:200916", "repo_name": "janmotl/rf", "revision_date": "2019-10-18T07:36:16", "revision_id": "55f6e65146ab98d34377a21a5507d652c65e4d8b", "snapshot_id": "c075f3eedfd5901975c81ef4561d65f119f72448", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/janmotl/rf/55f6e65146ab98d34377a21a5507d652c65e4d8b/rf.py", "visit_date": "2020-06-03T13:53:07.269694", "added": "2024-11-18T20:31:50.838164+00:00", "created": "2019-10-18T07:36:16", "int_score": 3, "score": 3.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
package tester; import java.util.ArrayList; import framework.ValueUtility; import framework.InfoGame; import framework.Player; import framework.Score; /** * プレイヤーの戦略を表すクラスです。 * 何も考えずランダムなカードを出します。 * * @author 鈴木大河 * @see Player * @return カードの識別番号(0-51) */ public class SRandom extends Player { /** * プレイヤー名を指定するコンストラクタです。 */ public SRandom() { super("SRandom"); } /** * プレイヤーの戦略を表すメソッドです。 * @param hands 自分の手札 * @param score プレイヤー全員のターン・ラウンドの得点 * @return 手札から出すカード番号 */ @Override public int strategy(ArrayList<Integer> hands, Score score, int id, InfoGame info) { return (int)Math.random()*51; } }
d39d855abe9bb82e9f40e3206ec7b4cb96b5e1cd
{ "blob_id": "d39d855abe9bb82e9f40e3206ec7b4cb96b5e1cd", "branch_name": "refs/heads/master", "committer_date": "2019-02-08T06:52:07", "content_id": "82f15d61b22322c57cfd91f7230100f73516e9f5", "detected_licenses": [ "MIT" ], "directory_id": "885dbdcfbb6c50300f575b893501d2bd13340a2c", "extension": "java", "filename": "SRandom.java", "fork_events_count": 2, "gha_created_at": "2018-04-04T01:49:08", "gha_event_created_at": "2018-07-27T07:41:22", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 127991479, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 879, "license": "MIT", "license_type": "permissive", "path": "/src/tester/SRandom.java", "provenance": "stack-edu-0020.json.gz:228012", "repo_name": "shiba33/SaichugenJava", "revision_date": "2019-02-08T06:52:07", "revision_id": "7f51aa9823b428b3fc515e7e0ac7d30c37864dc2", "snapshot_id": "ac379e5f717bd74487e714baf4bbc777be6b6e4d", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/shiba33/SaichugenJava/7f51aa9823b428b3fc515e7e0ac7d30c37864dc2/src/tester/SRandom.java", "visit_date": "2021-05-26T08:01:11.499410", "added": "2024-11-19T00:37:26.287871+00:00", "created": "2019-02-08T06:52:07", "int_score": 3, "score": 2.90625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
import { JA_PUNC, EN_PUNC } from './helpers/testTables'; import { HIRAGANA_END, HIRAGANA_START } from '../src/constants'; import convertFullwidthCharsToASCII from '../src/utils/convertFullwidthCharsToASCII'; import getChunk from '../src/utils/getChunk'; import getChunkSize from '../src/utils/getChunkSize'; import isEmpty from '../src/utils/isEmpty'; import isCharInRange from '../src/utils/isCharInRange'; import isCharVowel from '../src/utils/isCharVowel'; import isCharConsonant from '../src/utils/isCharConsonant'; import isCharLongDash from '../src/utils/isCharLongDash'; import isCharSlashDot from '../src/utils/isCharSlashDot'; import isCharKatakana from '../src/utils/isCharKatakana'; import isCharHiragana from '../src/utils/isCharHiragana'; import isCharKana from '../src/utils/isCharKana'; import isCharKanji from '../src/utils/isCharKanji'; import isCharRomaji from '../src/utils/isCharRomaji'; import isCharJapanese from '../src/utils/isCharJapanese'; import isCharJapanesePunctuation from '../src/utils/isCharJapanesePunctuation'; import isCharEnglishPunctuation from '../src/utils/isCharEnglishPunctuation'; import isCharPunctuation from '../src/utils/isCharPunctuation'; import isCharUpperCase from '../src/utils/isCharUpperCase'; import romajiToHiragana from '../src/utils/romajiToHiragana'; import hiraganaToKatakana from '../src/utils/hiraganaToKatakana'; import katakanaToHiragana from '../src/utils/katakanaToHiragana'; describe('Methods should return sane defaults when given no input', () => { it('convertFullwidthCharsToASCII()', () => expect(convertFullwidthCharsToASCII()).toBe('')); it('getChunk()', () => expect(getChunk()).toBe('')); it('getChunkSize()', () => expect(getChunkSize()).toBe(0)); it('isEmpty()', () => expect(isEmpty()).toBe(true)); it('isCharInRange()', () => expect(isCharInRange()).toBe(false)); it('isCharVowel()', () => expect(isCharVowel()).toBe(false)); it('isCharConsonant()', () => expect(isCharConsonant()).toBe(false)); it('isCharLongDash()', () => expect(isCharLongDash()).toBe(false)); it('isCharSlashDot()', () => expect(isCharSlashDot()).toBe(false)); it('isCharKatakana()', () => expect(isCharKatakana()).toBe(false)); it('isCharHiragana()', () => expect(isCharHiragana()).toBe(false)); it('isCharKana()', () => expect(isCharKana()).toBe(false)); it('isCharKanji()', () => expect(isCharKanji()).toBe(false)); it('isCharRomaji()', () => expect(isCharRomaji()).toBe(false)); it('isCharJapanese()', () => expect(isCharJapanese()).toBe(false)); it('isCharJapanesePunctuation()', () => expect(isCharJapanesePunctuation()).toBe(false)); it('isCharEnglishPunctuation()', () => expect(isCharEnglishPunctuation()).toBe(false)); it('isCharPunctuation()', () => expect(isCharPunctuation()).toBe(false)); it('isCharUpperCase()', () => expect(isCharUpperCase()).toBe(false)); it('romajiToHiragana() with no input', () => expect(romajiToHiragana()).toBe('')); it('hiraganaToKatakana() with no input', () => expect(hiraganaToKatakana()).toBe('')); it('katakanaToHiragana() with no input', () => expect(katakanaToHiragana()).toBe('')); }); describe('isEmpty', () => { it('passes parameter tests', () => { expect(isEmpty()).toBe(true); expect(isEmpty(22)).toBe(true); expect(isEmpty(null)).toBe(true); expect(isEmpty('')).toBe(true); expect(isEmpty([])).toBe(true); expect(isEmpty({})).toBe(true); expect(isEmpty('nope')).toBe(false); }); }); describe('convertFullwidthCharsToASCII', () => { it('passes parameter tests', () => { expect(convertFullwidthCharsToASCII('come on FHQWHGADS')).toBe( 'come on FHQWHGADS' ); expect(convertFullwidthCharsToASCII('FHQWHGADS')).toBe( 'FHQWHGADS' ); expect(convertFullwidthCharsToASCII('fhqwhgads')).toBe( 'fhqwhgads' ); }); }); describe('getChunk', () => { it('passes parameter tests', () => { expect(getChunk('derpalerp', 3, 6)).toBe('pal'); expect(getChunk('de', 0, 1)).toBe('d'); expect(getChunk('', 1, 2)).toBe(''); }); }); describe('getChunkSize', () => { it('passes parameter tests', () => { expect(getChunkSize(4, 2)).toBe(2); expect(getChunkSize(2, 2)).toBe(2); expect(getChunkSize(2, 4)).toBe(2); expect(getChunkSize(0, 0)).toBe(0); expect(getChunkSize(3, -1)).toBe(-1); }); }); describe('isCharInRange', () => { it('passes parameter tests', () => { expect(isCharInRange('は', HIRAGANA_START, HIRAGANA_END)).toBe(true); expect(isCharInRange('d', HIRAGANA_START, HIRAGANA_END)).toBe(false); }); }); describe('isCharVowel', () => { it('passes parameter tests', () => { [...'aeiou'].forEach((vowel) => expect(isCharVowel(vowel)).toBe(true)); expect(isCharVowel('y' /* includes 'y' as a vowel by default */)).toBe( true ); expect(isCharVowel('y', false /* excludes 'y' as a vowel */)).toBe(false); expect(isCharVowel('x')).toBe(false); expect(isCharVowel('!')).toBe(false); expect(isCharVowel('')).toBe(false); }); }); describe('isCharConsonant', () => { it('passes parameter tests', () => { [...'bcdfghjklmnpqrstvwxyz'].forEach((consonant) => expect(isCharConsonant(consonant)).toBe(true) ); expect(isCharConsonant('y', false /* excludes 'y' as a consonant */)).toBe( false ); expect(isCharConsonant('a')).toBe(false); expect(isCharConsonant('!')).toBe(false); expect(isCharConsonant('')).toBe(false); }); }); describe('isCharLongDash', () => { it('passes parameter tests', () => { expect(isCharLongDash('ー')).toBe(true); expect(isCharLongDash('-')).toBe(false); expect(isCharLongDash('f')).toBe(false); expect(isCharLongDash('ふ')).toBe(false); }); }); describe('isCharSlashDot', () => { it('passes parameter tests', () => { expect(isCharSlashDot('・')).toBe(true); expect(isCharSlashDot('/')).toBe(false); expect(isCharSlashDot('f')).toBe(false); expect(isCharSlashDot('ふ')).toBe(false); }); }); describe('isCharRomaji', () => { it('passes parameter tests', () => { expect(isCharRomaji('n')).toBe(true); expect(isCharRomaji('!')).toBe(true); expect(isCharRomaji('ナ')).toBe(false); expect(isCharRomaji('は')).toBe(false); expect(isCharRomaji('缶')).toBe(false); expect(isCharRomaji('')).toBe(false); }); }); describe('isCharJapanese', () => { it('passes parameter tests', () => { // zenkaku/latin numbers considered neutral expect(isCharJapanese('1')).toBe(true); expect(isCharJapanese('1')).toBe(true); expect(isCharJapanese('ナ')).toBe(true); expect(isCharJapanese('は')).toBe(true); expect(isCharJapanese('缶')).toBe(true); expect(isCharJapanese('〜')).toBe(true); expect(isCharJapanese('n')).toBe(false); expect(isCharJapanese('!')).toBe(false); expect(isCharJapanese('')).toBe(false); }); }); describe('isCharKatakana', () => { it('passes parameter tests', () => { expect(isCharKatakana('ナ')).toBe(true); expect(isCharKatakana('は')).toBe(false); expect(isCharKatakana('n')).toBe(false); expect(isCharKatakana('!')).toBe(false); expect(isCharKatakana('')).toBe(false); }); }); describe('isCharHiragana', () => { it('passes parameter tests', () => { expect(isCharHiragana('な')).toBe(true); expect(isCharHiragana('ナ')).toBe(false); expect(isCharHiragana('n')).toBe(false); expect(isCharHiragana('!')).toBe(false); expect(isCharHiragana('')).toBe(false); }); }); describe('isCharKana', () => { it('passes parameter tests', () => { expect(isCharKana('は')).toBe(true); expect(isCharKana('ナ')).toBe(true); expect(isCharKana('n')).toBe(false); expect(isCharKana('!')).toBe(false); expect(isCharKana('')).toBe(false); expect(isCharKana('-')).toBe(false); expect(isCharKana('ー')).toBe(true); }); }); describe('isCharKanji', () => { it('passes parameter tests', () => { expect(isCharKanji('腹')).toBe(true); expect(isCharKanji('一')).toBe(true); // kanji for いち・1 - not a long hyphen expect(isCharKanji('ー')).toBe(false); // long hyphen expect(isCharKanji('は')).toBe(false); expect(isCharKanji('ナ')).toBe(false); expect(isCharKanji('n')).toBe(false); expect(isCharKanji('!')).toBe(false); expect(isCharKanji('')).toBe(false); }); }); describe('isCharJapanesePunctuation', () => { it('passes parameter tests', () => { expect(JA_PUNC.every((char) => isCharJapanesePunctuation(char))).toBe(true); expect(EN_PUNC.every((char) => isCharJapanesePunctuation(char))).toBe( false ); expect(isCharJapanesePunctuation('?')).toBe(false); expect(isCharJapanesePunctuation('a')).toBe(false); expect(isCharJapanesePunctuation('ふ')).toBe(false); expect(isCharJapanesePunctuation('字')).toBe(false); expect(isCharJapanesePunctuation('')).toBe(false); }); }); describe('isCharEnglishPunctuation', () => { it('passes parameter tests', () => { expect(EN_PUNC.every((char) => isCharEnglishPunctuation(char))).toBe(true); expect(JA_PUNC.every((char) => isCharEnglishPunctuation(char))).toBe(false); expect(isCharEnglishPunctuation('a')).toBe(false); expect(isCharEnglishPunctuation('ふ')).toBe(false); expect(isCharEnglishPunctuation('字')).toBe(false); expect(isCharEnglishPunctuation('')).toBe(false); }); }); describe('isCharPunctuation', () => { it('passes parameter tests', () => { expect(JA_PUNC.every((char) => isCharPunctuation(char))).toBe(true); expect(EN_PUNC.every((char) => isCharPunctuation(char))).toBe(true); expect(isCharPunctuation('a')).toBe(false); expect(isCharPunctuation('ふ')).toBe(false); expect(isCharPunctuation('字')).toBe(false); expect(isCharPunctuation('')).toBe(false); }); }); describe('isCharUpperCase', () => { it('passes parameter tests', () => { expect(isCharUpperCase('A')).toBe(true); expect(isCharUpperCase('D')).toBe(true); expect(isCharUpperCase('')).toBe(false); expect(isCharUpperCase('-')).toBe(false); expect(isCharUpperCase('ー')).toBe(false); expect(isCharUpperCase('a')).toBe(false); expect(isCharUpperCase('d')).toBe(false); }); });
73eaec0585ac0030fb363486a35b99965882580b
{ "blob_id": "73eaec0585ac0030fb363486a35b99965882580b", "branch_name": "refs/heads/master", "committer_date": "2017-12-29T11:28:57", "content_id": "86fa53d120fa1b0fbf66a49df163f32a7d3d113c", "detected_licenses": [ "MIT" ], "directory_id": "b6deb35b0dbacc63759f777a53409985571fc149", "extension": "js", "filename": "utils.test.js", "fork_events_count": 1, "gha_created_at": "2016-02-24T23:29:53", "gha_event_created_at": "2016-02-24T23:29:53", "gha_language": null, "gha_license_id": null, "github_id": 52482136, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10309, "license": "MIT", "license_type": "permissive", "path": "/test/utils.test.js", "provenance": "stack-edu-0032.json.gz:167178", "repo_name": "fmestrone/WanaKana", "revision_date": "2017-12-29T11:28:57", "revision_id": "6343059970ba41f1f5767475f669f2c3c2d5cf97", "snapshot_id": "535373cb1ae6aa987acf43cafdbe2eb942fa8db5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fmestrone/WanaKana/6343059970ba41f1f5767475f669f2c3c2d5cf97/test/utils.test.js", "visit_date": "2023-08-11T23:23:16.581173", "added": "2024-11-19T02:36:14.580687+00:00", "created": "2017-12-29T11:28:57", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
<?php namespace Weblog\Users\Domain\Models; use Weblog\Users\Domain\ValueObjects\UserId; final class User implements UserInterface { private UserId $id; private string $name; private string $emailAddress; private ?\DateTimeImmutable $emailVerifiedAt; private ?\DateTimeImmutable $confirmedAt; private string $password; public function __construct( UserId $id, string $name, string $emailAddress, ?\DateTimeImmutable $emailVerifiedAt, ?\DateTimeImmutable $confirmedAt, string $password ) { $this->setId($id); $this->setName($name); $this->setEmailAddress($emailAddress); $this->setEmailVerifiedAt($emailVerifiedAt); $this->setConfirmedAt($confirmedAt); $this->setPassword($password); } public function getId(): UserId { return $this->id; } private function setId(UserId $userId): void { $this->id = $userId; } public function getName(): string { return $this->name; } private function setName(string $name): void { $this->name = $name; } public function getEmailAddress(): string { return $this->emailAddress; } private function setEmailAddress(string $emailAddress) { if (!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) { throw new \InvalidArgumentException( 'Invalid email address' ); } $this->emailAddress = $emailAddress; } public function getEmailVerifiedAt(): ?\DateTimeImmutable { return $this->emailVerifiedAt; } private function setEmailVerifiedAt(?\DateTimeImmutable $emailVerifiedAt): void { $this->emailVerifiedAt = $emailVerifiedAt; } public function getConfirmedAt(): ?\DateTimeImmutable { return $this->confirmedAt; } private function setConfirmedAt(?\DateTimeImmutable $confirmedAt): void { $this->confirmedAt = $confirmedAt; } public function getPassword(): string { return $this->password; } private function setPassword(string $password): void { if (strlen($password) < 6) { throw new \InvalidArgumentException( 'Password must be greater than or equal to 6 character long' ); } $this->password = $password; } }
96acc794f4eceb96b5ed121c4e5c9e6b5e201e5d
{ "blob_id": "96acc794f4eceb96b5ed121c4e5c9e6b5e201e5d", "branch_name": "refs/heads/master", "committer_date": "2020-07-22T17:05:25", "content_id": "bc4bb4006c082897557a67885e6771767d3dc976", "detected_licenses": [ "MIT" ], "directory_id": "7ec95611b1039ed3e05fe6a3ade1e8abaf90d859", "extension": "php", "filename": "User.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": 2434, "license": "MIT", "license_type": "permissive", "path": "/src/Users/Domain/Models/User.php", "provenance": "stack-edu-0049.json.gz:193683", "repo_name": "rayblair06/ddd-blog", "revision_date": "2020-07-22T17:05:25", "revision_id": "58e9dc7159c097c93ec1544efb8a03dfca740b17", "snapshot_id": "9c5e631855b4e6d18988bbc2818bb1e38c4ede3d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rayblair06/ddd-blog/58e9dc7159c097c93ec1544efb8a03dfca740b17/src/Users/Domain/Models/User.php", "visit_date": "2022-11-19T00:17:41.437011", "added": "2024-11-18T22:35:49.718639+00:00", "created": "2020-07-22T17:05:25", "int_score": 3, "score": 3.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz" }
#!/bin/bash # Run tests when they are changed. # Usage: # src/SIL.XForge.Scripture/ClientApp/monitor-test-headless.sh [arguments to test-headless.sh] set -u readonly ROOT_PATH="$(dirname "$0")" command -v inotifywait >/dev/null || { echo "Prerequisite not found. Run sudo apt install inotify-tools" exit 1 } echo -n "Press CTRL-C to stop automatically running tests when files are saved. " echo "If that fails, in another terminal first run pkill 'ng test'; sleep 1s; pkill -9 'ng test'" "$ROOT_PATH"/test-headless.sh "$@" while inotifywait -qre close_write --format "" "$ROOT_PATH"; do "$ROOT_PATH"/test-headless.sh "$@" done
19ec589d8a33dfc077a7b22dde6eccd08f24c2f4
{ "blob_id": "19ec589d8a33dfc077a7b22dde6eccd08f24c2f4", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T19:25:24", "content_id": "d962db5859d04cadde0a6449cc1417e1adbf4cc5", "detected_licenses": [ "MIT" ], "directory_id": "b79053a1d1ac0c595e56dcbd79a03a708fef1868", "extension": "sh", "filename": "monitor-test-headless.sh", "fork_events_count": 8, "gha_created_at": "2019-04-27T03:43:35", "gha_event_created_at": "2023-09-14T01:31:16", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 183724808, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 640, "license": "MIT", "license_type": "permissive", "path": "/src/SIL.XForge.Scripture/ClientApp/monitor-test-headless.sh", "provenance": "stack-edu-0069.json.gz:148208", "repo_name": "sillsdev/web-xforge", "revision_date": "2023-08-31T19:25:24", "revision_id": "f134d6d50dc3ebbc168367f10347a9a6c5e4f3dc", "snapshot_id": "ac04c192df0b6bd49b5813b841aa579b551d6872", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/sillsdev/web-xforge/f134d6d50dc3ebbc168367f10347a9a6c5e4f3dc/src/SIL.XForge.Scripture/ClientApp/monitor-test-headless.sh", "visit_date": "2023-09-01T14:47:59.669845", "added": "2024-11-18T23:06:52.541252+00:00", "created": "2023-08-31T19:25:24", "int_score": 4, "score": 3.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; namespace SpssLibCore.FileParser.Records { internal class InfoRecordParser : IRecordParser { public RecordType Accepts => RecordType.InfoRecord; private readonly IDictionary<int, Type> _infoRecordsTypes; public InfoRecordParser(IDictionary<int, Type> infoRecordsTypes) { _infoRecordsTypes = infoRecordsTypes; } public IRecord ParseRecord(BinaryReader reader) { IRecord record = CreateRecord(reader); record.FillRecord(reader); return record; } private IRecord CreateRecord(BinaryReader reader) { int subType = reader.ReadInt32(); Type type; var record = _infoRecordsTypes.TryGetValue(subType, out type) ? (BaseInfoRecord)FormatterServices.GetUninitializedObject(type) : new UnknownInfoRecord(subType); // Check that we created the correct one if (record.SubType != subType) { // if it gets to here, we fucked up registering the infoRecordsTypes when calling the constructor throw new Exception( $"Wrong info record created for {subType}, obtained record instance for {record.SubType}. Please, fix the InfoRecordParser"); } return record; } } }
f6737b76ef39bb9892e889ce2cbdcf0fea157de3
{ "blob_id": "f6737b76ef39bb9892e889ce2cbdcf0fea157de3", "branch_name": "refs/heads/master", "committer_date": "2021-09-22T04:54:16", "content_id": "624b004fd6fc3ffc0647d16f804fdac8937fb55f", "detected_licenses": [ "MIT" ], "directory_id": "6cdb395f4ac42522ae2af9e125ec2fa1b09d897c", "extension": "cs", "filename": "InfoRecordParser.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 409068917, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1519, "license": "MIT", "license_type": "permissive", "path": "/SpssLibCore/FileParser/Records/InfoRecordParser.cs", "provenance": "stack-edu-0010.json.gz:539446", "repo_name": "BunyodUz/SpssLibCore", "revision_date": "2021-09-22T04:54:16", "revision_id": "ab33d65cf96a7dadd42a306dd34d247c909573ae", "snapshot_id": "6968f72613398d0d002f99febbcafe3b3b80dc3a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BunyodUz/SpssLibCore/ab33d65cf96a7dadd42a306dd34d247c909573ae/SpssLibCore/FileParser/Records/InfoRecordParser.cs", "visit_date": "2023-07-30T02:15:26.727859", "added": "2024-11-18T19:42:44.782634+00:00", "created": "2021-09-22T04:54:16", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
export interface IResource { id: number, name: string, location?: string, placesCount?: number, rent?: number }
0dc7c11cb56290d1d134de8ff9f1c15aaeb1dd93
{ "blob_id": "0dc7c11cb56290d1d134de8ff9f1c15aaeb1dd93", "branch_name": "refs/heads/master", "committer_date": "2018-04-20T10:27:53", "content_id": "aafdf85be6a23f40a208c12d007d88b1f261e2cd", "detected_licenses": [ "MIT" ], "directory_id": "de77e9ffb3cdac8f40696b2b9b55d2ecf2b956bc", "extension": "ts", "filename": "resource.model.ts", "fork_events_count": 1, "gha_created_at": "2018-04-20T08:24:24", "gha_event_created_at": "2022-12-07T18:55:01", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 130332737, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 134, "license": "MIT", "license_type": "permissive", "path": "/EventManagement.Resources/EventManagement.Resources.Web/ClientApp/app/models/resource.model.ts", "provenance": "stack-edu-0075.json.gz:414638", "repo_name": "atanas-georgiev/EventManagement", "revision_date": "2018-04-20T10:27:53", "revision_id": "552f20a3d0d4ed776a82e3015af65801df096b93", "snapshot_id": "ee2c6e13d65278c6005c8d9867665af7d78d2dc8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/atanas-georgiev/EventManagement/552f20a3d0d4ed776a82e3015af65801df096b93/EventManagement.Resources/EventManagement.Resources.Web/ClientApp/app/models/resource.model.ts", "visit_date": "2022-12-09T12:36:40.556365", "added": "2024-11-18T21:28:16.193486+00:00", "created": "2018-04-20T10:27:53", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
using System; using System.IO; using System.Xml; using System.Xml.Serialization; using ColossalFramework.IO; namespace AutoLineColor { [Serializable] public class Configuration { public ColorStrategy ColorStrategy { get; set; } public NamingStrategy NamingStrategy { get; set; } public int? MinimumColorDifferencePercentage { get; set; } public int? MaximunDifferentCollorPickAtempt { get; set; } private const string ConfigFileName = "AutoLineColorSettings.xml"; private const string ModName = "AutoLineColor"; public static Configuration LoadConfig() { try { var serializer = new XmlSerializer(typeof(Configuration)); Configuration config; var fullConfigPath = GetModFileName(ConfigFileName); if (File.Exists(fullConfigPath) == false) { Console.Message("No config file. Building default and writing it to " + fullConfigPath); config = GetDefaultConfig(); SaveConfig(config); return config; } using (var reader = XmlReader.Create(fullConfigPath)) { config = (Configuration)serializer.Deserialize(reader); } //check new configuration properties if (!config.MaximunDifferentCollorPickAtempt.HasValue || !config.MinimumColorDifferencePercentage.HasValue) { var defaultConfig = GetDefaultConfig(); config.MinimumColorDifferencePercentage = defaultConfig.MinimumColorDifferencePercentage; config.MaximunDifferentCollorPickAtempt = defaultConfig.MaximunDifferentCollorPickAtempt; SaveConfig(config); } return config; } catch (Exception ex) { Console.Error("Error reading configuration settings - " + ex); return GetDefaultConfig(); } } public static string GetModFileName(string fileName) { return fileName; } private static Configuration GetDefaultConfig() { return new Configuration { ColorStrategy = ColorStrategy.RandomColor, NamingStrategy = NamingStrategy.Districts, MaximunDifferentCollorPickAtempt = 10, MinimumColorDifferencePercentage = 5 }; } private static void SaveConfig(Configuration config) { var serializer = new XmlSerializer(typeof(Configuration)); using (var writer = XmlWriter.Create(GetModFileName(ConfigFileName))) { serializer.Serialize(writer, config); } } private static Configuration _instance; public static Configuration Instance { get { if (_instance == null) { _instance = LoadConfig(); } return _instance; } } } public enum ColorStrategy { RandomHue, RandomColor, CategorisedColor } public enum NamingStrategy { None, Districts, London } }
ad975b6e67e6af3b8a44e44790cddf0391ff1a69
{ "blob_id": "ad975b6e67e6af3b8a44e44790cddf0391ff1a69", "branch_name": "refs/heads/master", "committer_date": "2015-09-24T21:49:58", "content_id": "70a1b4daf63b27c544045c009a023364e71675e9", "detected_licenses": [ "MIT" ], "directory_id": "f44f9d39c05761d74ea1966df10ef099ce8963ca", "extension": "cs", "filename": "Configuration.cs", "fork_events_count": 0, "gha_created_at": "2015-03-15T02:36:12", "gha_event_created_at": "2018-06-17T23:21:06", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 32241869, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3451, "license": "MIT", "license_type": "permissive", "path": "/AutoLineColor/Configuration.cs", "provenance": "stack-edu-0012.json.gz:773552", "repo_name": "phil-scott-78/CitiesSkylinesAutoColorMod", "revision_date": "2015-09-24T21:45:27", "revision_id": "8528ccb7d9d74198cf4a5db05a709a25a94f9cc9", "snapshot_id": "304828168e2a8a39fe2b44bba3f3711cb3557c6e", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/phil-scott-78/CitiesSkylinesAutoColorMod/8528ccb7d9d74198cf4a5db05a709a25a94f9cc9/AutoLineColor/Configuration.cs", "visit_date": "2021-06-17T06:47:24.208780", "added": "2024-11-18T21:27:11.106996+00:00", "created": "2015-09-24T21:45:27", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
using System; using Unity.Mathematics; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.Perception.GroundTruth.Sensors { #if PERCEPTION_EXPERIMENTAL /// <summary> /// A <see cref="CameraSensor"/> that can generate fisheye projections with field of views up to 360 degrees. /// </summary> [Serializable] [MovedFrom("UnityEngine.Perception.GroundTruth.Internal")] public class CircularFisheyeCameraSensor : CubemapCameraSensor { static readonly int k_RenderCorners = Shader.PropertyToID("_RenderCorners"); static readonly int k_CubemapTex = Shader.PropertyToID("_CubemapTex"); static readonly int k_FieldOfView = Shader.PropertyToID("_FieldOfView"); static Material s_CircularFisheyeMaterial; /// <summary> /// The field of view of the fisheye sensor in degrees. /// </summary> [Range(1, 360)] public float fieldOfView = 360f; /// <summary> /// Enables the corners of the fisheye image that exceed the sensor's designated field of view /// to be rendered as long as the extended fov is below the 360 degree fov limit. /// </summary> [Tooltip("Enables the corners of the fisheye image that exceed the sensor's designated field of view to be " + "rendered as long as the extended fov is below the 360 degree fov limit.")] public bool renderCorners = true; /// <inheritdoc/> public override CameraSensorIntrinsics intrinsics => new() { projection = "fisheye", matrix = float3x3.identity }; /// <inheritdoc/> protected override void Setup() { base.Setup(); if (s_CircularFisheyeMaterial == null) s_CircularFisheyeMaterial = new(RenderUtilities.LoadPrewarmedShader("Perception/CircularFisheyeProjection")); } /// <inheritdoc/> protected override void ProjectFisheyeFromCubemap( CommandBuffer cmd, RenderTexture cubemap, RenderTargetIdentifier output) { cmd.SetGlobalInteger(k_RenderCorners, renderCorners ? 1 : 0); cmd.SetGlobalFloat(k_FieldOfView, fieldOfView); cmd.SetGlobalTexture(k_CubemapTex, cubemap); cmd.Blit(cubemap, output, s_CircularFisheyeMaterial); } } #endif }
eb41d93245e59d7e1f6ead54871777b876a8883c
{ "blob_id": "eb41d93245e59d7e1f6ead54871777b876a8883c", "branch_name": "refs/heads/main", "committer_date": "2022-11-28T22:25:29", "content_id": "84deafe2cd515eb46c7122468be8f349ba0f98f0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3113997a990f78b449efd31b04a964f280281922", "extension": "cs", "filename": "CircularFisheyeCameraSensor.cs", "fork_events_count": 175, "gha_created_at": "2020-04-03T19:54:21", "gha_event_created_at": "2023-04-29T10:09:59", "gha_language": "C#", "gha_license_id": "NOASSERTION", "github_id": 252827390, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2413, "license": "Apache-2.0", "license_type": "permissive", "path": "/com.unity.perception/Runtime/GroundTruth/Sensors/SensorTypes/CircularFisheyeCameraSensor.cs", "provenance": "stack-edu-0010.json.gz:320586", "repo_name": "Unity-Technologies/com.unity.perception", "revision_date": "2022-11-28T22:25:29", "revision_id": "0c79e0c78d02362745e56f7b307d65ea825f4913", "snapshot_id": "1ee2a4fada5777155709c5933af48fb4bab55d82", "src_encoding": "UTF-8", "star_events_count": 803, "url": "https://raw.githubusercontent.com/Unity-Technologies/com.unity.perception/0c79e0c78d02362745e56f7b307d65ea825f4913/com.unity.perception/Runtime/GroundTruth/Sensors/SensorTypes/CircularFisheyeCameraSensor.cs", "visit_date": "2023-09-05T23:07:10.597145", "added": "2024-11-18T21:53:56.490359+00:00", "created": "2022-11-28T22:25:29", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
/** * Created by intern on 2017/9/15. */ // 获得图片链接 export const mixin = { methods:{ getImgUrl: function (hash, size) { //获取第一个字符,第二三字符,最后三个字符 let dir1 = hash.substring(0, 1); let dir2 = hash.substring(1, 3); let img = ''; if(hash.substring(hash.length - 4) === 'jpeg'){ img = hash.substring(hash.length - 4); } else { img = hash.substring(hash.length - 3); } let strContent = hash.substr(3); //https://fuss10.elemecdn.com/f/b8/6fe12681eb97d9c7013ece81af62bjpeg.jpeg?imageMogr/thumbnail/!90x90r/gravity/Center/crop/90x90 const url = 'https://fuss10.elemecdn.com/' + dir1 + '/' + dir2 + '/' + strContent + '.' + img + '?imageMogr/thumbnail/!' + size + 'r/gravity/Center/crop/' + size + '/'; // console.log(url); return url; }, getImgUrl2: function (hash, size) { //获取第一个字符,第二三字符,最后三个字符 let dir1 = hash.substring(0, 1); let dir2 = hash.substring(1, 3); let img = hash.substring(hash.length - 4); let strContent = hash.substr(3); const url = 'https://fuss10.elemecdn.com/' + dir1 + '/' + dir2 + '/' + strContent + '.' + img + '?imageMogr/thumbnail/!' + size + 'r/gravity/Center/crop/' + size + '/'; return url; console.log('haha',url); }, getBackgroundImgUrl: function (hash) { let dir1 = hash.substring(0, 1); let dir2 = hash.substring(1, 3); let img = ''; if(hash.substring(hash.length - 4) === 'jpeg'){ img = hash.substring(hash.length - 4); } else { img = hash.substring(hash.length - 3); } let strContent = hash.substr(3); //覆盖背景url:background-image: url("https://fuss10.elemecdn.com/f/8d/f29dbf20be425fc12426c0b1f90b7jpeg.jpeg?imageMogr/format/webp/thumbnail/!40p/blur/50x40/"); const url = "url('"+'https://fuss10.elemecdn.com/' + dir1 + '/' + dir2 + '/' + strContent + '.' + img + '?imageMogr/format/webp/thumbnail/!40p/blur/50x40/'+ "')"; //console.log(url); return url; } } };
3af587fab5f9f274d3fd1892149e8ed6c31377aa
{ "blob_id": "3af587fab5f9f274d3fd1892149e8ed6c31377aa", "branch_name": "refs/heads/master", "committer_date": "2017-10-14T02:20:09", "content_id": "1e6d72086df90250dbbc2dd881cdb5a9e01b1772", "detected_licenses": [ "MIT" ], "directory_id": "cdeb11b00e7e4ab386cb916f8f8df43bbe9366ec", "extension": "js", "filename": "getImgUrl.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 106886460, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2413, "license": "MIT", "license_type": "permissive", "path": "/src/config/getImgUrl.js", "provenance": "stack-edu-0033.json.gz:646852", "repo_name": "zeal-ming/Zm-Elm-master", "revision_date": "2017-10-14T02:20:09", "revision_id": "bb2e51a7de60ad8e038726928ddf236c551cc15e", "snapshot_id": "8df8c114189cdf3548bf997819bebccd2bbb0dd8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zeal-ming/Zm-Elm-master/bb2e51a7de60ad8e038726928ddf236c551cc15e/src/config/getImgUrl.js", "visit_date": "2021-07-11T16:03:23.575497", "added": "2024-11-19T01:01:47.448359+00:00", "created": "2017-10-14T02:20:09", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
export function updateDeviceType(type: number) { return { type: '@deviceType/UPDATE_DEVICETYPE', payload: type, }; }
42afaf3e59efe92bdf13816f138f3817a1dfbd9d
{ "blob_id": "42afaf3e59efe92bdf13816f138f3817a1dfbd9d", "branch_name": "refs/heads/master", "committer_date": "2021-02-15T14:14:40", "content_id": "d854dce5dc153fffe025579a129296d4dc98769c", "detected_licenses": [ "MIT" ], "directory_id": "9b9735088ff1a111e2dc045278bbb3878e9e95f7", "extension": "ts", "filename": "actions.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 338198074, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 129, "license": "MIT", "license_type": "permissive", "path": "/src/store/modules/deviceType/actions.ts", "provenance": "stack-edu-0075.json.gz:728814", "repo_name": "maycooliveira/wisertest", "revision_date": "2021-02-15T14:14:40", "revision_id": "b3720c2d324354686e2ec0cdd65734c210d62692", "snapshot_id": "5665140ffdc9d945d86d6033b1e1b781e4d2bbf1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/maycooliveira/wisertest/b3720c2d324354686e2ec0cdd65734c210d62692/src/store/modules/deviceType/actions.ts", "visit_date": "2023-03-04T14:41:24.643470", "added": "2024-11-18T18:59:18.025636+00:00", "created": "2021-02-15T14:14:40", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
{ var slickInint = function () { $('.slider-for').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slider-nav' }); $('.slider-nav').slick({ slidesToShow: 3, slidesToScroll: 1, asNavFor: '.slider-for', dots: true, centerMode: true, centerPadding: '40px', focusOnSelect: true }); } const itemId = $.getParameterByName('itemId', window.location.toString()); $.ajax({ url: `/Jam/usedItemDetail`, type: `POST`, dataType: `json`, data: { itemId }, }).done(response => { console.log(response); const { usedItem, pics, status, seller, sellerPic, bidderList } = response; $('#secondhand-detail-title').children('h1').html(usedItem.title); $('#secondhand-detail-seller').html(seller).attr('href', `member.html?userId=${usedItem.seller}`); $('#secondhand-detail-price').html(usedItem.expectedPrice); $('#secondhand-detail-brnad').html(usedItem.brand); $('#secondhand-detail-model').html(usedItem.model); $('#secondhand-detail-condition').html(status); $('#secondhand-detail-usedTime').html(usedItem.usedTime); console.log(usedItem.description); let desc = $.ReplaceAll(usedItem.description, "\n", "<br>"); $('#secondhand-detail-desc').html(desc); $('#secondhand-detail-seller-pic').attr('src', sellerPic) const pic_arr = pics; pic_arr.map(pic => { // console.log($('.slider-for').slickAdd(`<div class="secondhand-full-pic-div"><img class="secondhand-full-pic" data-lazy="${pic}"></div>`) // ); // slickInint(); $('.slider-for').slick('slickAdd', `<div class="secondhand-full-pic-div"><img class="secondhand-full-pic" src="${pic}"></div>`) $('.slider-nav').slick('slickAdd', `<div class="secondhand-small-pic-div"><img class="secondhand-small-pic" src="${pic}"></div>`) // $('.slider-for').slickAdd(`<div class="secondhand-full-pic-div"><img class="secondhand-full-pic" src="${pic}"></div>`) //$('.slider-nav').slickAdd(`<div class="secondhand-small-pic-div"><img class="secondhand-small-pic" src="${pic}"></div>`) // $('.slider-for').append(`<div class="secondhand-full-pic-div"><img class="secondhand-full-pic" src="${pic}"></div>`) // $('.slider-nav').append(`<div class="secondhand-full-pic-div"><img class="secondhand-full-pic" src="${pic}"></div>`) }) //如果登入的不是自己頁面的判斷式 if (window.location.toString().indexOf('Jam/secondhand_detail.html') !== -1) { $('#mail-recipient').val(seller); $('#mail-title').val(`[我想買] ${usedItem.title}`); function getBidBtn(status) { $('.detail-show-op-buy').html(`<button class="btn btn-primary buy-btn ${status === 1 ? "cancel" : status === 0 ? "buy" : "sold"}" ${status === -1 || status === 2 ? "disabled" : ""}>${status === 2 ? "您已得標!" : status === 1 ? "已下標" : status === 0 ? "出價購買" : "已售出"}</button>`) } getBidBtn(0); bidderList.map(bid => { if (bid.userId == sessionStorage.getItem("LoginId")) { getBidBtn(bid.status); return; } }) //站內信 $('#mail-submit').on('click', () => { const msg = $('#mail-content').val(); $.ajax({ url: `/Jam/sendMsg`, type: 'POST', dataType: `json`, data: { title: usedItem.title, receiver: usedItem.seller, msg } }).done(response => { $('.mailbox-modal').removeClass('is-visible'); $('.confirm-success').addClass('is-visible'); console.log('信件已寄出!'); }).fail(() => { console.log('信件寄出失敗!'); }); }); //下標 $('.detail-show-op-buy').on('click', '.buy', () => { $.ajax({ url: `/Jam/newBid`, type: `POST`, dataType: `json`, data: { itemId, bidded: false } }).done(() => { getBidBtn(1); }) }) $('.detail-show-op-buy').on('click', '.cancel', () => { $.ajax({ url: `/Jam/newBid`, type: `POST`, dataType: `json`, data: { itemId, bidded: true } }).done(() => { getBidBtn(0); }) }) } else { //自己的頁面 produceList(bidderList); $('.detail-client-info-wrapper').on('click', '.btn.btn-primary.client-btn.confirm-btn', function () { console.log(this, $(this)); const bidder = $(this).attr('class').substr($(this).attr('class').lastIndexOf(' ') + 1); $.ajax({ url: `/Jam/confirmBid`, type: `POST`, dataType: `json`, data: { decision: 1, bidder, itemId } }).done(response => { let { bidderList } = response; console.log(bidderList); $('.detail-client-info-wrapper').empty(); produceList(bidderList); }) }); $('.detail-client-info-wrapper').on('click', '.btn.btn-primary.client-btn.refuse-btn.cancel', function () { $.ajax({ url: `/Jam/confirmBid`, type: `POST`, dataType: `json`, data: { decision: -1, itemId } }).done(response => { let { bidderList } = response; $('.detail-client-info-wrapper').empty(); produceList(bidderList); }) }) $('.detail-client-info-wrapper').on('click', '.btn.btn-primary.client-btn.refuse-btn.reject', function () { const bidder = $(this).attr('class').substr($(this).attr('class').lastIndexOf(' ') + 1); $.ajax({ url: `/Jam/confirmBid`, type: `POST`, dataType: `json`, data: { decision: -2, bidder, itemId } }).done(response => { let { bidderList } = response; $('.detail-client-info-wrapper').empty(); produceList(bidderList); }) }) function produceList(bidderList) { let temp = ''; bidderList.map(bid => { temp += `<div class="detail-client-info"> <img class="member-small-pic" src="${bid.pic}"> <a href="member.html?userId=${bid.userId}">${bid.alias}</a> 想跟您購買此商品 <div class="client-btn-wrapper"> <button class="btn btn-primary client-btn confirm-btn ${bid.userId}" ${bid.status === 1 ? "" : "disabled"}>${bid.status === 2 ? "成交" : "確認"}</button> <button class="btn btn-primary client-btn refuse-btn ${bid.status === 2 ? "cancel" : "reject"} ${bid.userId}" ${bid.status === -1 ? "disabled" : ""}>${bid.status === 2 ? "取消" : "拒絕"}</button> </div> </div>` }) $('.detail-client-info-wrapper').html(temp); } $('#secondhand-detail-edit').on('click', () => { window.location.assign(`/Jam/secondhand_edit.html?itemId=${usedItem.usedItemId}`); }) } }) }
978f017dd722d941465ce503e947a90659c3297b
{ "blob_id": "978f017dd722d941465ce503e947a90659c3297b", "branch_name": "refs/heads/master", "committer_date": "2017-04-21T13:09:24", "content_id": "4aa9d9e2acdcbb7aba318aa846455b7fc4af8e30", "detected_licenses": [ "MIT" ], "directory_id": "c596c2aeb63d95212d24908e70d92b973eb362c8", "extension": "js", "filename": "river_secondhand_detail.js", "fork_events_count": 0, "gha_created_at": "2017-02-13T10:55:35", "gha_event_created_at": "2017-04-10T12:07:11", "gha_language": "CSS", "gha_license_id": null, "github_id": 81815263, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8149, "license": "MIT", "license_type": "permissive", "path": "/WebContent/_997_framework/js/river_secondhand_detail.js", "provenance": "stack-edu-0034.json.gz:59244", "repo_name": "RuChuanLin/jam", "revision_date": "2017-04-21T13:09:24", "revision_id": "239be35503ffb14c904cb0f0f80ab460aea85c84", "snapshot_id": "39eba878ae28c7ca7cb6852d1f8abfb80407bc5d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RuChuanLin/jam/239be35503ffb14c904cb0f0f80ab460aea85c84/WebContent/_997_framework/js/river_secondhand_detail.js", "visit_date": "2021-01-13T17:32:26.563903", "added": "2024-11-19T01:24:37.092465+00:00", "created": "2017-04-21T13:09:24", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz" }
import { HostedConnection } from "../network/server/HostedConnection"; import { RemoteGamepadAPI } from "./RemoteGamepadAPI"; /** * Specifications follow https://www.w3.org/TR/gamepad/#gamepad-interface. * * Implementation of the native Gamepad implementation. */ export class RemoteGamepad implements Gamepad { /* readonly attribute DOMString id; readonly attribute long index; readonly attribute boolean connected; readonly attribute DOMHighResTimeStamp timestamp; readonly attribute GamepadMappingType mapping; readonly attribute FrozenArray<double> axes; readonly attribute FrozenArray<GamepadButton> buttons; */ hand: GamepadHand = ""; readonly hapticActuators: GamepadHapticActuator[]; id: string = "<no id>"; index: number = -1; mapping: GamepadMappingType = "standard"; pose: GamepadPose = null; readonly displayId: number = -1; connected: boolean = true; timestamp: DOMHighResTimeStamp = window.performance.now(); readonly remote: HostedConnection; private readonly api: RemoteGamepadAPI; readonly axes: [number, number, number, number] = [ 0, // pad left x0 0, // pad left y0 0, // pad right x1 0 // pad right y1 ]; /** * 20 Gamepad buttons. * readonly attribute boolean pressed; * readonly attribute boolean touched; // mirror pressed value * readonly attribute double value; // mirror pressed (0 <= value <= 1) */ readonly buttons: { pressed: boolean, value: number, touched: boolean }[] = [ { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false }, { pressed: false, value: 0, touched: false } ]; constructor(client: HostedConnection, api: RemoteGamepadAPI) { this.remote = client; this.api = api; this.registerClientListeners(); } private registerClientListeners() { this.remote.events.on('buttonUpdate', this.onButtonUpdate); this.remote.events.on('axisUpdate', this.onAxisUpdate); this.remote.events.on('disconnect', this.disconnect); } updateButton(buttonId: number, pressed: boolean) { // update gamepad timestamp this.timestamp = window.performance.now(); // get button let button = this.buttons[buttonId]; if (!button) { // define new button with an id to enable customized buttons button = { pressed: false, value: 0, touched: false }; this.buttons[buttonId] = button; } button.pressed = pressed; // mirror touched and value // https://www.w3.org/TR/gamepad/#gamepadbutton-interface button.touched = pressed; button.value = pressed ? 1 : 0; } /* Callbacks */ private disconnect = () => { this.connected = false; // remove gamepad this.api.remoteGamepads[this.index] = undefined; let event = new CustomEvent('gamepaddisconnected', {}); (<any> event).gamepad = this; // add gamepad to event window.dispatchEvent(event); } private onButtonUpdate = (buttonIndex: number, pressed: boolean) => { this.updateButton(buttonIndex, pressed); } private onAxisUpdate = (axisIndex: number, value: number) => { this.timestamp = window.performance.now(); this.axes[axisIndex] = value; } }
f341f8445ca16a543c4bce763d6936fde05fc8ba
{ "blob_id": "f341f8445ca16a543c4bce763d6936fde05fc8ba", "branch_name": "refs/heads/master", "committer_date": "2020-07-23T18:03:52", "content_id": "0956fcf52967f6f36fae2317d5e12021ab3f93ae", "detected_licenses": [ "MIT" ], "directory_id": "05c4b436b5af793dceb9b71c7a6eb692df979ed7", "extension": "ts", "filename": "RemoteGamepad.ts", "fork_events_count": 0, "gha_created_at": "2019-05-17T14:59:47", "gha_event_created_at": "2020-07-23T18:03:53", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 187235875, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4360, "license": "MIT", "license_type": "permissive", "path": "/src/serverlib/RemoteGamepad.ts", "provenance": "stack-edu-0076.json.gz:460799", "repo_name": "marcoklein/remotegamepad", "revision_date": "2020-07-23T18:03:52", "revision_id": "8c9c676c47d7c0f0b2ec2f2d69e5a4710c3fac60", "snapshot_id": "2880726a81f5fc2e103be78d4af0d5f138b3a2ad", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/marcoklein/remotegamepad/8c9c676c47d7c0f0b2ec2f2d69e5a4710c3fac60/src/serverlib/RemoteGamepad.ts", "visit_date": "2021-07-15T21:50:18.189101", "added": "2024-11-19T03:34:25.685108+00:00", "created": "2020-07-23T18:03:52", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz" }
/* ================================================================== * Eniware Open Source:Nikolai Manchev * Apache License 2.0 * ================================================================== */ package org.eniware.central.user.dao; import java.util.List; import org.eniware.central.dao.GenericDao; import org.eniware.central.user.domain.UserAlert; import org.eniware.central.user.domain.UserAlertSituation; import org.eniware.central.user.domain.UserAlertType; import org.joda.time.DateTime; /** * DAO API for UserAlert objects. * * @version 1.1 */ public interface UserAlertDao extends GenericDao<UserAlert, Long> { /** * Find a set of alerts that need processing. The results are sorted by ID * in ascending order. * * @param type * The type of alert to find. * @param startingId * An optional {@link UserAlert} ID value to start from. Only alerts * with an ID value <em>higher</em> than this ID will be considered. * If <em>null</em> then consider all alerts. * @param validDate * A timestamp to use for the validity check date. If * {@code startingId} is provided, this value can be provided to * issue a stable batch query based on the same valid date as the * previous call to this method. If not provided the current time * will be used, but then a subsequent batch call might not have the * same date if another batch call is needed. Therefore it is * recommended to always pass a value for this parameter. * @param max * An optional maximum number of result rows to return. * @return The found alerts, or an empty list if none found. */ List<UserAlert> findAlertsToProcess(UserAlertType type, Long startingId, DateTime validDate, Integer max); /** * Get a set of all alerts configured for a user. The alerts will have the * most recently available active {@link UserAlertSituation} populated on * the {@link UserAlert#getSituation()} property. * * @param userId * The ID of the user to get all alerts for. * @return The found alerts, or an empty list if none found. */ List<UserAlert> findAlertsForUser(Long userId); /** * Delete all alerts configured for a given user and Edge. * * @param userId * The ID of the owner of the alerts. * @param EdgeId * The ID of the Edge. * @return The count of alerts deleted. * @since 1.1 */ int deleteAllAlertsForEdge(Long userId, Long EdgeId); /** * Get a specific alert with the most recently available active * {@link UserAlertSituation} populated on the * {@link UserAlert#getSituation()} property. * * @param alertId * The ID of the alert to get. * @return The found alert, or <em>null</em> if not available. */ UserAlert getAlertSituation(Long alertId); /** * Update the {@code validTo} property to a new date. * * @param alertId * The ID of the alert to update. * @param validTo * The new value for the {@code validTo} property. * @since 1.1 */ void updateValidTo(Long alertId, DateTime validTo); /** * Get all available active situations for a given user. The situations are * returned as {@link UserAlert} entities with the * {@link UserAlert#getSituation()} populated. * * @param userId * The ID of the user to get all active situations for. * @return The found alerts with active situations. * @since 1.1 */ List<UserAlert> findActiveAlertSituationsForUser(Long userId); /** * Get all available active situations for a given Edge. The situations are * returned as {@link UserAlert} entities with the * {@link UserAlert#getSituation()} populated. * * @param EdgeId * The ID of the Edge to get all active situations for. * @return The found alerts with active situations. * @since 1.1 */ List<UserAlert> findActiveAlertSituationsForEdge(Long EdgeId); /** * Get a count of <em>active</em> alert situations for a given user. * * @param userId * The ID of the user to get the alert situation count for. * @return The number of active alert situations for the given user. * @since 1.1 */ int alertSituationCountForUser(Long userId); }
50a07db35dea60f54368a7d41aefdedef9943725
{ "blob_id": "50a07db35dea60f54368a7d41aefdedef9943725", "branch_name": "refs/heads/master", "committer_date": "2019-01-31T08:50:15", "content_id": "c603cc6d18d428873a73846fb23d863ddb04d26b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9fcab1b26b9d67abd7a3233b66ea4bf3d68f57a4", "extension": "java", "filename": "UserAlertDao.java", "fork_events_count": 0, "gha_created_at": "2018-03-20T17:45:14", "gha_event_created_at": "2018-10-03T10:40:06", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 126059141, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4248, "license": "Apache-2.0", "license_type": "permissive", "path": "/org.eniware.central.user/src/org/eniware/central/user/dao/UserAlertDao.java", "provenance": "stack-edu-0022.json.gz:418898", "repo_name": "eniware-org/org.eniware.central", "revision_date": "2019-01-31T08:50:15", "revision_id": "64d999cd743a1ebc39dccbe89c68772cae5129d7", "snapshot_id": "46e89a071d38f97cad8ae721d6ea40bf568d7e56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/eniware-org/org.eniware.central/64d999cd743a1ebc39dccbe89c68772cae5129d7/org.eniware.central.user/src/org/eniware/central/user/dao/UserAlertDao.java", "visit_date": "2021-10-12T01:00:35.826991", "added": "2024-11-19T01:00:26.179994+00:00", "created": "2019-01-31T08:50:15", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
//Orders service used to communicate Orders REST endpoints (function () { 'use strict'; angular .module('orders') .factory('OrdersService', OrdersService); OrdersService.$inject = ['$resource']; function OrdersService($resource) { return $resource('api/orders/:orderId', { orderId: '@_id' }, { update: { method: 'PUT' } }); } })();
6382ad20a1819e95f8e67a34c981f82f18b684af
{ "blob_id": "6382ad20a1819e95f8e67a34c981f82f18b684af", "branch_name": "refs/heads/master", "committer_date": "2016-05-05T03:39:21", "content_id": "6d7855044b88e2fe76482687b658999f71dec370", "detected_licenses": [ "MIT" ], "directory_id": "788bbd6f3a1b77f74179d2f925a76eee8917420a", "extension": "js", "filename": "orders.client.service.js", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 53921138, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 391, "license": "MIT", "license_type": "permissive", "path": "/modules/orders/client/services/orders.client.service.js", "provenance": "stack-edu-0035.json.gz:540025", "repo_name": "JavaScriptAcademy/oneStep", "revision_date": "2016-05-05T03:39:21", "revision_id": "51ac3c967631267a32da365cd4db0592f934c40b", "snapshot_id": "6d02888f86903d9d534606ef6dcd6bae13817e31", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/JavaScriptAcademy/oneStep/51ac3c967631267a32da365cd4db0592f934c40b/modules/orders/client/services/orders.client.service.js", "visit_date": "2021-01-10T16:31:27.043197", "added": "2024-11-19T00:03:50.423213+00:00", "created": "2016-05-05T03:39:21", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
require 'spec_helper' describe Squib::DSL do let(:deck) { Squib::Deck.new } Squib::DSL.constants.each do |m| it "method #{m} calls warn_if_unexpected" do method_obj = Squib::DSL.const_get(m).new(deck, m) expect(method_obj).to receive(:warn_if_unexpected).and_throw(:warned) catch :warned do method_obj.run({}) end end it "method #{m} has dsl_method and deck defined" do method_obj = Squib::DSL.const_get(m).new(deck, m) expect(method_obj).to have_attributes({deck: deck, dsl_method: m}) end end end
58d3a7221014476f64c1bbc2fabe8c8bd2dab9e7
{ "blob_id": "58d3a7221014476f64c1bbc2fabe8c8bd2dab9e7", "branch_name": "refs/heads/dev", "committer_date": "2023-04-09T02:33:44", "content_id": "c5cfe448bd7fba402d6226a95b85c9e1ef54dc2d", "detected_licenses": [ "MIT" ], "directory_id": "919ed374a75ef1953406db706cd60a35efa8b1fb", "extension": "rb", "filename": "consistent_dsl_methods.rb", "fork_events_count": 102, "gha_created_at": "2014-07-16T20:46:39", "gha_event_created_at": "2022-01-16T00:39:54", "gha_language": "Ruby", "gha_license_id": "MIT", "github_id": 21916531, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 569, "license": "MIT", "license_type": "permissive", "path": "/spec/dsl/consistent_dsl_methods.rb", "provenance": "stack-edu-0066.json.gz:644475", "repo_name": "andymeneely/squib", "revision_date": "2023-04-09T02:33:44", "revision_id": "1132233747bae3fc68a6aee6ce27feb132d450c8", "snapshot_id": "7cddd9c79c510c0e6712ba39559305cc0a1dc013", "src_encoding": "UTF-8", "star_events_count": 974, "url": "https://raw.githubusercontent.com/andymeneely/squib/1132233747bae3fc68a6aee6ce27feb132d450c8/spec/dsl/consistent_dsl_methods.rb", "visit_date": "2023-06-20T17:07:38.702850", "added": "2024-11-18T19:55:31.739065+00:00", "created": "2023-04-09T02:33:44", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const P = require("parsimmon"); function beforePrim(f, s) { return P.custom((success, failure) => { return (stream, i) => { const index = stream.substr(i).indexOf(s); if (index !== -1 && i <= stream.length) { return success(i + index, f(stream.substr(i, index))); } else { return failure(i, `'${s}' not found`); } }; }); } const before = (s) => beforePrim((x) => x, s); exports.before = before; const beforeAndSkip = (s) => before(s).skip(P.string(s)); exports.beforeAndSkip = beforeAndSkip; const trimBefore = (s) => beforePrim((x) => x.trim(), s).skip(spaces); exports.trimBefore = trimBefore; const trimBeforeAndSkip = (s) => trimBefore(s).skip(P.string(s)).skip(spaces); exports.trimBeforeAndSkip = trimBeforeAndSkip; const spaces = P.regex(/\s*/); exports.spaces = spaces; const token = (s) => P.string(s).skip(spaces); exports.token = token; //# sourceMappingURL=combinator.js.map
930bc02e418979afde34d90f6bf36ccf2dc2c2e5
{ "blob_id": "930bc02e418979afde34d90f6bf36ccf2dc2c2e5", "branch_name": "refs/heads/master", "committer_date": "2018-08-20T02:33:03", "content_id": "1a6a9f622d659c68092d579027311bb78e040885", "detected_licenses": [ "MIT" ], "directory_id": "e84162616b1e274469016ff5b01b7469ef60fa10", "extension": "js", "filename": "combinator.js", "fork_events_count": 0, "gha_created_at": "2018-10-16T09:07:37", "gha_event_created_at": "2018-10-16T09:07:37", "gha_language": null, "gha_license_id": "MIT", "github_id": 153256057, "is_generated": true, "is_vendor": false, "language": "JavaScript", "length_bytes": 1079, "license": "MIT", "license_type": "permissive", "path": "/lib/parser/combinator.js", "provenance": "stack-edu-0036.json.gz:389055", "repo_name": "buggymcbugfix/agda-mode", "revision_date": "2018-08-20T02:33:03", "revision_id": "2d49146c11c5843d8ab44b5bc8a847ccc13ee0c5", "snapshot_id": "91d391a89f1fa9a410943061e1a735cee52006e6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/buggymcbugfix/agda-mode/2d49146c11c5843d8ab44b5bc8a847ccc13ee0c5/lib/parser/combinator.js", "visit_date": "2020-04-01T13:31:28.448667", "added": "2024-11-19T01:26:50.074877+00:00", "created": "2018-08-20T02:33:03", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
import React from 'react'; // MUI import Box from '@mui/material/Box'; const boxStyle = { display: "block", width: "100%", maxWidth: "4rem", marginTop: "1rem" } const imageStyle = { display: "block", width: "100%", height: "auto", } const LinkTileImage = ({ image, alt }) => { return ( <Box style={boxStyle}> {image && <img style={imageStyle} src={image} alt={alt} /> } </Box> ); }; export default LinkTileImage;
217104008983b87643488a55bd176ca9f25e0532
{ "blob_id": "217104008983b87643488a55bd176ca9f25e0532", "branch_name": "refs/heads/master", "committer_date": "2023-08-09T09:24:36", "content_id": "e550e5444856d446df940b7e5f391739dacf5aa4", "detected_licenses": [], "directory_id": "dd34c5960ee3f05cf618a74033c944f780667034", "extension": "jsx", "filename": "LinkTileImage.jsx", "fork_events_count": 0, "gha_created_at": "2019-09-11T11:12:58", "gha_event_created_at": "2022-12-10T06:10:24", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 207792878, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 464, "license": "", "license_type": "permissive", "path": "/src/components/LinkTileImage.jsx", "provenance": "stack-edu-0033.json.gz:419174", "repo_name": "shellbryson/edinburghsff", "revision_date": "2023-08-09T09:24:36", "revision_id": "681f7354ca3511ddb554c7301b02a5fa31372db0", "snapshot_id": "738bf9599c4668be7782ecdaeb63308e697a4a5f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shellbryson/edinburghsff/681f7354ca3511ddb554c7301b02a5fa31372db0/src/components/LinkTileImage.jsx", "visit_date": "2023-08-09T16:25:52.865196", "added": "2024-11-19T01:09:40.726626+00:00", "created": "2023-08-09T09:24:36", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
/** * */ package org.mediaresponse.ai.platform.esb; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author bhagvan_kommadi * */ public class DataValidator { private List<String> monthList = new ArrayList<String>(); /** * */ public DataValidator() { // TODO Auto-generated constructor stub } public void init() { monthList.add("JAN"); monthList.add("FEB"); monthList.add("MAR"); monthList.add("APR"); monthList.add("MAY"); monthList.add("JUN"); monthList.add("JUL"); monthList.add("AUG"); monthList.add("SEP"); monthList.add("OCT"); monthList.add("NOV"); monthList.add("DEC"); } public List<String> validateData(String dataValue,String type) { List<String> errorMessage = null; if(type.contentEquals("year")) { if(dataValue.length() == 4 || dataValue.length() ==2) { for(int i=0; i < dataValue.length(); i++) { char charValue = dataValue.charAt(i); if(Character.isDigit(charValue)) { } else { errorMessage = new ArrayList<String>(); errorMessage.add(charValue +"is not an integer"); } //Integer. } } } else if(type.contentEquals("month")) { if(dataValue.length() == 2 || dataValue.length() ==1) { for(int i=0; i < dataValue.length(); i++) { char charValue = dataValue.charAt(i); if(Character.isDigit(charValue)) { } else { if(errorMessage == null) { errorMessage = new ArrayList<String>(); errorMessage.add(charValue +"is not an integer"); } else { errorMessage.add(charValue +"is not an integer"); } } //Integer. } } else if(dataValue.length() == 3) { for(String month: monthList) { if(month.equalsIgnoreCase(dataValue)) { } else { if(errorMessage == null) { errorMessage = new ArrayList(); errorMessage.add(dataValue +"is not a month"); } else { errorMessage.add(dataValue +"is not a month"); } } } } } else if(type.contentEquals("day")) { if(dataValue.length() == 2 || dataValue.length() ==1) { for(int i=0; i < dataValue.length(); i++) { char charValue = dataValue.charAt(i); if(Character.isDigit(charValue)) { } else { if(errorMessage == null) { errorMessage = new ArrayList<String>(); errorMessage.add(charValue +"is not a day"); } else { errorMessage.add(charValue +"is not a day"); } } //Integer. } } else { if(errorMessage == null) { errorMessage = new ArrayList<String>(); errorMessage.add(dataValue +"is not a day"); } else { errorMessage.add(dataValue +"is not a day"); } } } else if(type.contentEquals("date")) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); try { dateFormat.parse(dataValue); } catch(ParseException exception) { if(errorMessage == null) { errorMessage = new ArrayList<String>(); errorMessage.add(dataValue +"is not a date"); } else { errorMessage.add(dataValue +"is not a date"); } } } else if(type.contentEquals("number")) { for(int i=0; i < dataValue.length(); i++) { char charValue = dataValue.charAt(i); if(Character.isDigit(charValue)) { } else { if(errorMessage == null) { errorMessage = new ArrayList(); errorMessage.add(charValue +"is not a number"); } else { errorMessage.add(charValue +"is not a number"); } } //Integer. } } else if(type.contentEquals("email")) { //TBD } //System.out.println(errorMessage.toString()); return errorMessage; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
fb4d81f0422c4d92981147b43bb3abc1365f92ad
{ "blob_id": "fb4d81f0422c4d92981147b43bb3abc1365f92ad", "branch_name": "refs/heads/master", "committer_date": "2019-10-14T08:26:06", "content_id": "0af7c5180477e7db56234a74ad5af1236758bdf9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "254825fa94aff12ca0a393e55c166926bf6f9c66", "extension": "java", "filename": "DataValidator.java", "fork_events_count": 0, "gha_created_at": "2019-02-16T13:44:02", "gha_event_created_at": "2019-10-14T08:26:08", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 171008306, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4115, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/org/mediaresponse/ai/platform/esb/DataValidator.java", "provenance": "stack-edu-0020.json.gz:844260", "repo_name": "bhagvank/MediaResponse", "revision_date": "2019-10-14T08:26:06", "revision_id": "fb6f5514d8caee9854d4325d9ad0cea028cf2acc", "snapshot_id": "d05683c489ac4dc4b05ccbe589bef07811637529", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bhagvank/MediaResponse/fb6f5514d8caee9854d4325d9ad0cea028cf2acc/src/org/mediaresponse/ai/platform/esb/DataValidator.java", "visit_date": "2020-04-23T07:30:30.911544", "added": "2024-11-19T01:59:29.787301+00:00", "created": "2019-10-14T08:26:06", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
# WECG Meetings 2022, Public Notes, Jun 9 * Chair: Simeon Vincent * Scribes: Rob Wu Time: 8 AM PST = https://everytimezone.com/?t=62a13800,3c0 Call-in details: [WebExtensions CG, 9th June 2022](https://www.w3.org/events/meetings/d7bbce8f-549f-46ea-b440-ea6902f8707c/20220609T080000) Zoom issues? Ping @zombie (Tomislav Jovanovic) in [chat](https://github.com/w3c/webextensions/blob/main/CONTRIBUTING.md#joining-chat) ## Agenda: [discussion in #220](https://github.com/w3c/webextensions/issues/220), [github issues](https://github.com/w3c/webextensions/issues) The meeting will start at 3 minutes after the hour. * **Carry-over from previous meetings** * [TPAC 2022](https://www.w3.org/wiki/TPAC/2022) update * **Other new issues** * [Issue 216](https://github.com/w3c/webextensions/issues/216): Support action.setBadgeTextColor() * [Issue 217](https://github.com/w3c/webextensions/issues/217): Make WebExtension Javascript APIs available in WebWorkers spawned from a bundled document * [Issue 218](https://github.com/w3c/webextensions/issues/218): Inconsistency: Meta description character length * [Issue 219](https://github.com/w3c/webextensions/issues/219): Inconsistency: Right-click missing Options menu item for the browser extension * [PR 221](https://github.com/w3c/webextensions/pull/221): Add host_permissions and optional_host_permissions * [PR 222](https://github.com/w3c/webextensions/pull/222): Move list of meetings into a collapsible section * [Issue 223](https://github.com/w3c/webextensions/issues/223): Proposal: if extension has "storage" permission it should be allowed to use Web Storage API and Cookies API * [Issue 224](https://github.com/w3c/webextensions/issues/224): Extensions Store Badge (get the extension button) * [Issue 225](https://github.com/w3c/webextensions/issues/225): Document DNR's regex validation rules * **Open discussion queue (add yourself at the bottom)** * * **Check-in on ongoing issues** * [Issue 100](https://github.com/w3c/webextensions/issues/100): Inconsistency: Mandatory manifest keys * [Issue 162](https://github.com/w3c/webextensions/issues/162): DNR: disable individual static rules ## Attendees (sign yourself in) 1. Simeon Vincent (Google) 2. Rob Wu (Mozilla) 3. Tim Heflin (Keeper) 4. Mukul Purohit (Microsoft) 5. Bradley Cushing (Dashlane) 6. Oliver Dunk (1Password) 7. Benjamin Bruneau (1Password) 8. Carlos Jeurissen (Jeurissen Apps) 9. Richard Worth (Capital One) 10. Brian Weinstein (Apple) 11. Gaurang Tandon (Blaze Today) 12. David Johnson (Apple) 13. Tomislav Jovanovic (Mozilla) 14. Sam Macbeth (DuckDuckGo) 15. Felipe Erias (Igalia) 16. Alexei (Privacy Badger) 17. Frederic Rivain (Dashlane) 18. Tyler Carson (Keeper) 19. Ellie Epskamp-Hunt (Apple) ## Meeting notes [TPAC 2022](https://www.w3.org/wiki/TPAC/2022) update * [simeon] Planning to draft a shortlist of topics soon. Sorry for the delay. [Issue 216](https://github.com/w3c/webextensions/issues/216): Support action.setBadgeTextColor() * [carlos] Applies to both browserAction and action. * [timothy] Largest concern with color APIs is dark mode. Should ideally have a way to specify two colors. * [tomislav] When the feature was originally introduced, the use case was to support different “levels”, e.g. warnings/error in the UI. * [simeon] Before the meeting I introduced the ["Chrome: follow-up" label](https://github.com/w3c/webextensions/labels/Chrome%3A%20follow-up) to help with tracking these kind of issues. I'm going to discuss this with the team and provide feedback. * [tomislav] To Tim's point, we welcome support for that. * [simeon] Reminds me that we have work in progress on allowing extensions to specify different colors that adjust based on browser/user/OS preferences. I'll get back with that. [Issue 217](https://github.com/w3c/webextensions/issues/217): Make WebExtension Javascript APIs available in WebWorkers spawned from a bundled document * [bradley] Reporter is working for Dashlane; I'll read into this and get back to this. * [rob] Let's postpone this topic to the next meeting. [Issue 218](https://github.com/w3c/webextensions/issues/218): Inconsistency: Meta description character length * [carlos] Different stores have different length / character requirements. Would make sense if we start with documenting the guidelines first. * [simeon] On the Chrome side, similar to the name field, there is no limit imposed in the field, whereas the Chrome Web Store imposes a limit. * [rob] Was discussed before in name/short_name (https://github.com/w3c/webextensions/issues/60). We could consider looking into minimum requirements, but the webstore policies etc. are out of scope. Even minimums cannot be guaranteed, e.g. if the description does not fit in the UI. * [simeon] The current charter's scope is browser implementations, web stores are out of scope. How could we account for these kinds of developer concerns in the spec? * [timothy] I think that we talked about this before, and considered including notes in the spec * [tomislav] “Non-normative note” is the term you're looking for. * [simeon] In the context of this meeting, we could consider adding a normative note to describe “safe” lengths. [Issue 219](https://github.com/w3c/webextensions/issues/219): Inconsistency: Right-click missing Options menu item for the browser extension * [carlos] Would be nice if the Options menu option is available by default everywhere. * [timothy] No strong reason not do it * [tomislav] Similarly don't see a reason not to do this, but the UI is not a part of this group. File a bug in Firefox if a change is desired. * [mukul] Agreed with Tomislav, changes in UI is a differentiator for Edge. * [simeon] Another way to frame this is, not all browsers need to agree on the UI. Capabilities may be useful, e.g. exposing a boolean through the extension API to show whether the functionality is available. [PR 221](https://github.com/w3c/webextensions/pull/221): Add host_permissions and optional_host_permissions * [simeon] LGTM * [tomislav] Will LGTM today/tomorrow. [PR 222](https://github.com/w3c/webextensions/pull/222): Move list of meetings into a collapsible section * [simeon] List of minutes is overwhelming. Proposed PR moves notes in separate sections and mentions the latest meeting at the top. * [timothy] Approved * [rob] I'll provide feedback asynchronously, on the PR. [Issue 223](https://github.com/w3c/webextensions/issues/223): Proposal: if extension has "storage" permission it should be allowed to use Web Storage API and Cookies API * [rob] Browser/user settings can disable storage APIs. Reporter is asking for a way to guarantee the availability of these APIs, e.g. with extension permissions. * [simeon] This is the downside of building upon the web platform. Using extension-specific APIs is a way around this. I'd currently say that this is working as expected, but can follow up offline. [Issue 224](https://github.com/w3c/webextensions/issues/224): Extensions Store Badge (get the extension button) * [simeon] The reporter asks for images/resources. This seems more like a community question and is out of scope for this group. But on behalf of the reporter: browser vendors, please take a look at the issue and respond on the issue. [Issue 225](https://github.com/w3c/webextensions/issues/225): Document DNR's regex validation rules * [simeon] Chrome has constraints on regexp support, which needs to be documented/specified better. * [rob] Safari/Webkit's implementation has an even more constrained regexp format, but it does not have an arbitrary cut-off / length limit like Chrome's. * [timothy] I was trying to quickly look up the source, and it seems that there is indeed not a length limit. [Issue 100](https://github.com/w3c/webextensions/issues/100): Inconsistency: Mandatory manifest keys * [simeon] icons requirement? * [timothy] We require it in the App store, but not in Safari. It falls back to the icon of the app container (all Safari extensions should be packaged in an app). * [tomislav] Technically the ID is not required, but it is strongly recommended to include it. We are considering requiring it for submission of MV3 extensions to AMO. * [simeon] Let's define the 3 common keys as required and document browser-specific requirements in non-normative notes. [Issue 162](https://github.com/w3c/webextensions/issues/162): DNR: disable individual static rules * [felipe] Quick update from my side: worked on performance issues. Looked into a previously suggested solution, i.e. rate-limits. * [simeon] Last week I looked at this issue to see if there was anything specific that the Chrome team could do. I saw a CL, but the last update was a month ago. Does that patch represent the latest, or are you expecting the CL to change? * [felipe] The CL implements the current API proposal. Basically, I worked on it until I was able to do testing and use it to iterate on the proposal. * [simeon] So the API proposal is in a state where we can take a hard look at, or is it something we should take a look at once in a while? * [felipe] You could take a hard look at it to see if the API and the approach to implementing it make sense. If that's not the case, I will update the proposal and implementation. (out of topics after 45 minutes) [Issue 160](https://github.com/w3c/webextensions/issues/160): Ensure consistency of action.openPopup API across browsers * [oliver] I have looked at the behaviors of openPopup across browsers and documented the results. Would be great if everyone could take a look at it and see if it makes sense, and then implement it consistently everywhere. * [timothy] Looks sensible, thanks. I'll take a look. [PR 186](https://github.com/w3c/webextensions/pull/186/files): Add mock for browser.secureStorage proposal * [oliver] Renamed polyfill to mock. [PR 226](https://github.com/w3c/webextensions/pull/226): Update browser.secureStorage proposal with authentication levels * [oliver] Updated proposal based on last meeting where we discussed authentication levels. * [simeon] Will look at these two PRs after the end of the meeting. Redundant labels * [carlos] We have quite a few labels that aren't being used, especially defaults provided by GitHub. * [carlos] Also thinking we could use the projects feature from GitHub to * [rob] We have considered using more Github features, but sticked to the basic issues/PR so that there is not too many places that we'd need to follow/triage. * [simeon] Just occurred to me that we could use GitHub's kanban board to track items that need follow-up from individual vendors. Getting back on track, I'm open to using more github features. If anyone has thoughts on how we can leverage GitHub to better achieve our goals, please let us know. Host permission changes * [alexei] Opt-in host permission changes are a major source of concern. Don't understand the benefit of denying permissions by default, but can see it causing confusion. We know users don't read prompts. * [timothy] Safari's perspective: we introduced this model when we added support for WebExtensions. We saw that many extensions asked for broad host permissions upfront. Between the user installing the extension and the extension using the permissions, the user may already have forgotten about the extension, so we wanted to bring the permission request closer to the time of use, similar to the rest of the Apple ecosystem. * [alexei] What you're saying makes sense for extensions that work on a particular set of sites, but I don't see how that works for extensions that operate everywhere. * [simeon] Does this happen at install time, or is there an extra grant flow? * [timothy] There is an extra button and dialog flow. * [simeon] Briefly touched on in the last meeting, there will be an extra grant flow in Chrome too: extensions will need to get a user gesture and call `permissions.request()`. Sounds like Safari has an extra option to click when enabling an extension in the settings menu? * [timothy] Yes, there's another box to check in a menu. You cannot request `<all_urls>` via permissions.request() in Safari. The dialog allows the user to grant for everything, which is off by default or an additional button/dialog to grant all. * [oliver] Is there a user interaction requirement? Would be nice to document that. We have encountered issues where we send a message to our app and when we get a response we lose the user gesture that triggered the flow in the first place. * [tomislav] opening popups requires user gestures on the web platform side, but extension APIs are mostly async, and the gesture may be lost. * [alexei] When the user installs uBlock Origin, AdGuard or Ghostery, the user won't read and click approve. But now the user has to read/confirm another prompt. I don't see how it helps users. It harms extensions. * [simeon] This is where malicious actors are impacting legitimate actors. Our assessment is that users often don't understand the extent to which they have given extensions permission to run everywhere and potentially collect data and do nefarious things with it. * [tomislav] Even for good actors, people don't understand the implications of installing the extension. Users are surprised that the extensions are able to access all websites, including their banking websites. This is to give users more visibility and control. * [rob] End of meeting, [let's file an issue for this topic](https://github.com/w3c/webextensions/issues/227) so we can discuss it in more detail. The next meeting will be on [Thursday, June 23th, 8 AM PST (3 PM UTC)](https://everytimezone.com/?t=62b3ad00,3c0).
f3774f16fcfdbfbbf2fb29fb6e4ee9f6edafd84c
{ "blob_id": "f3774f16fcfdbfbbf2fb29fb6e4ee9f6edafd84c", "branch_name": "refs/heads/main", "committer_date": "2023-08-16T22:56:57", "content_id": "9f9bd9f44db7b023096e947aa8a4cbaf93fc7313", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "32247a8efe7d5490cdf621d7298f55747be68142", "extension": "md", "filename": "2022-06-09-wecg.md", "fork_events_count": 44, "gha_created_at": "2021-06-01T15:43:58", "gha_event_created_at": "2023-09-12T21:56:50", "gha_language": "HTML", "gha_license_id": "NOASSERTION", "github_id": 372882560, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13772, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/_minutes/2022-06-09-wecg.md", "provenance": "stack-edu-markdown-0012.json.gz:286715", "repo_name": "w3c/webextensions", "revision_date": "2023-08-16T22:56:57", "revision_id": "96d9cd2b08b41950d25bfc41c6ec04046d843e6b", "snapshot_id": "5ae78e19ecd84d75bf619f98e97ca12e15229053", "src_encoding": "UTF-8", "star_events_count": 524, "url": "https://raw.githubusercontent.com/w3c/webextensions/96d9cd2b08b41950d25bfc41c6ec04046d843e6b/_minutes/2022-06-09-wecg.md", "visit_date": "2023-08-18T22:43:40.495047", "added": "2024-11-19T00:19:28.288243+00:00", "created": "2023-08-16T22:56:57", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz" }
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux' import { CHANGE_BAZ } from './actions'; /** * Simple redux reducer that handles the CHANGE_BAZ action, updating * the redux store to have the new value of baz. */ function app(state = {}, action) { switch (action.type) { case CHANGE_BAZ: return { ...state, baz: action.payload, }; default: return state; } } export default combineReducers({ app, routing: routerReducer, // add in state about routing via react-router-redux });
47a6017ce33ae6565e897ad18510b9a5535c5e9b
{ "blob_id": "47a6017ce33ae6565e897ad18510b9a5535c5e9b", "branch_name": "refs/heads/master", "committer_date": "2019-09-09T22:47:40", "content_id": "46bb26264cf22c2a19dc16519101a3824e4e8a03", "detected_licenses": [ "MIT" ], "directory_id": "d6e1d922cec1817c9f20e5d5e3fb0e8f467ba5ae", "extension": "js", "filename": "rootReducer.js", "fork_events_count": 0, "gha_created_at": "2019-09-05T22:30:17", "gha_event_created_at": "2019-09-05T23:39:15", "gha_language": null, "gha_license_id": "MIT", "github_id": 206667723, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 574, "license": "MIT", "license_type": "permissive", "path": "/examples/react-router-v2-and-redux/src/state/rootReducer.js", "provenance": "stack-edu-0040.json.gz:344279", "repo_name": "koordinates/react-url-query", "revision_date": "2019-09-09T22:47:40", "revision_id": "14426c50b63f20659a5c6673840bc481cf626e91", "snapshot_id": "026118cb29e6a73879949141ef95184e30fdb96e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/koordinates/react-url-query/14426c50b63f20659a5c6673840bc481cf626e91/examples/react-router-v2-and-redux/src/state/rootReducer.js", "visit_date": "2020-07-20T15:22:16.464757", "added": "2024-11-19T03:21:09.343190+00:00", "created": "2019-09-09T22:47:40", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
package sample.alibabacloud.photosharing; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.alibaba.sdk.android.oss.ClientException; import com.alibaba.sdk.android.oss.OSS; import com.alibaba.sdk.android.oss.OSSClient; import com.alibaba.sdk.android.oss.ServiceException; import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback; import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider; import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider; import com.alibaba.sdk.android.oss.internal.OSSAsyncTask; import com.alibaba.sdk.android.oss.model.ListObjectsRequest; import com.alibaba.sdk.android.oss.model.ListObjectsResult; import java.util.ArrayList; import java.util.List; import sample.alibabacloud.photosharing.model.ImageData; /** * Created by saisarathchandra on 25/12/17. */ public class ImageRecyclerList extends Activity { private List<ImageData> imageDataList = new ArrayList<>(); private RecyclerView recyclerView; private ImageDataAdapter mAdapter; OSS oss; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_img_recycler); recyclerView = findViewById(R.id.recycler_view); mAdapter = new ImageDataAdapter(imageDataList,this); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(getString(R.string.AccessKey),getString(R.string.AccessKeySecret),getString(R.string.stsToken)); oss = new OSSClient(getApplicationContext(), getString(R.string.Endpoint), credentialProvider); getFiles(); } public void getFiles(){ ListObjectsRequest listObjects = new ListObjectsRequest(getString(R.string.Bucket_Name)); OSSAsyncTask task = oss.asyncListObjects(listObjects, new OSSCompletedCallback<ListObjectsRequest, ListObjectsResult>() { @Override public void onSuccess(ListObjectsRequest request, ListObjectsResult result) { Log.d("AyncListObjects", "Success!"); imageDataList.clear(); for (int i = 0; i < result.getObjectSummaries().size(); i++) { Log.d("AyncListObjects", "object: " + result.getObjectSummaries().get(i).getKey() + " " + result.getObjectSummaries().get(i).getETag() + " " + result.getObjectSummaries().get(i).getLastModified()); ImageData imageData = new ImageData(); imageData.setImageName(result.getObjectSummaries().get(i).getKey()); imageData.setImageURL(getString(R.string.Bucket_Endpoint)+result.getObjectSummaries().get(i).getKey()); imageDataList.add(imageData); } mAdapter.notifyDataSetChanged(); } @Override public void onFailure(ListObjectsRequest request, ClientException clientExcepion, ServiceException serviceException) { // Request exception if (clientExcepion != null) { // Local exception, such as a network exception clientExcepion.printStackTrace(); } if (serviceException != null) { // Service exception Log.e("ErrorCode", serviceException.getErrorCode()); Log.e("RequestId", serviceException.getRequestId()); Log.e("HostId", serviceException.getHostId()); Log.e("RawMessage", serviceException.getRawMessage()); } } }); task.waitUntilFinished(); } }
bfff4e9f7b7068579642d06c0fac38f42679cf06
{ "blob_id": "bfff4e9f7b7068579642d06c0fac38f42679cf06", "branch_name": "refs/heads/master", "committer_date": "2017-12-26T04:43:10", "content_id": "08d4543f57f937d8fddf303379209150b76a1f4e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "744a9e01afd93fed11589532aff4a7478c0d6171", "extension": "java", "filename": "ImageRecyclerList.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 114589639, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4217, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/src/main/java/sample/alibabacloud/photosharing/ImageRecyclerList.java", "provenance": "stack-edu-0024.json.gz:192051", "repo_name": "saichandu415/OSS-Android-Sample", "revision_date": "2017-12-26T04:43:10", "revision_id": "ff14d516b672c4c8a92c1d6abbaae38bf4e6fd6e", "snapshot_id": "46556636d7587bf686507b37067c6b28df0a5a34", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/saichandu415/OSS-Android-Sample/ff14d516b672c4c8a92c1d6abbaae38bf4e6fd6e/app/src/main/java/sample/alibabacloud/photosharing/ImageRecyclerList.java", "visit_date": "2021-09-01T08:58:51.993497", "added": "2024-11-18T21:45:45.845129+00:00", "created": "2017-12-26T04:43:10", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
import { ICourierClientConfiguration } from "../types"; import * as TenantTypes from "./types"; const deleteTenant = (options: ICourierClientConfiguration) => async ( tenantId: string ): Promise<void> => { await options.httpClient.delete<void>(`/tenants/${tenantId}`); }; const getTenant = (options: ICourierClientConfiguration) => { return async (tenantId: string): Promise<TenantTypes.ITenant> => { const response = await options.httpClient.get<TenantTypes.ITenant>( `/tenants/${tenantId}` ); return response.data; }; }; const listTenants = (options: ICourierClientConfiguration) => { return async ( listOptions?: TenantTypes.ITenantListOptions ): Promise<TenantTypes.IPaginatedResult<TenantTypes.ITenant>> => { const response = await options.httpClient.get< TenantTypes.IPaginatedResult<TenantTypes.ITenant> >("/tenants", undefined, { params: { cursor: listOptions?.cursor || "", limit: listOptions?.limit || "20", }, }); return response.data; }; }; const putTenant = (options: ICourierClientConfiguration) => { return async ( tenant: Omit<TenantTypes.ITenant, "type"> ): Promise<TenantTypes.ITenant> => { const response = await options.httpClient.put<TenantTypes.ITenant>( `/tenants/${tenant.id}`, tenant ); return response.data; }; }; export const tenants = (options: ICourierClientConfiguration) => ({ delete: deleteTenant(options), get: getTenant(options), listTenants: listTenants(options), put: putTenant(options), });
f00c99ef66ce7c74f24484b99bfe2af466352f7d
{ "blob_id": "f00c99ef66ce7c74f24484b99bfe2af466352f7d", "branch_name": "refs/heads/master", "committer_date": "2023-08-25T17:45:40", "content_id": "75b88a03218065c36a2014d137fc9916e20f9a6c", "detected_licenses": [ "MIT" ], "directory_id": "67b0f3f5dba519ed7fd74d250214c228147a6668", "extension": "ts", "filename": "index.ts", "fork_events_count": 8, "gha_created_at": "2019-07-13T00:53:48", "gha_event_created_at": "2023-09-07T19:23:54", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 196662521, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1561, "license": "MIT", "license_type": "permissive", "path": "/src/tenants/index.ts", "provenance": "stack-edu-0076.json.gz:58805", "repo_name": "trycourier/courier-node", "revision_date": "2023-08-25T17:45:40", "revision_id": "4a8ebf17a50d23fa29bd554cdf6b110e6668932f", "snapshot_id": "b08c72702e4bc6147e989369f43f32607dda049f", "src_encoding": "UTF-8", "star_events_count": 57, "url": "https://raw.githubusercontent.com/trycourier/courier-node/4a8ebf17a50d23fa29bd554cdf6b110e6668932f/src/tenants/index.ts", "visit_date": "2023-08-31T14:17:09.184848", "added": "2024-11-19T01:12:36.689396+00:00", "created": "2023-08-25T17:45:40", "int_score": 3, "score": 2.765625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz" }
package org.yellowbinary.server.security.basic.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.yellowbinary.server.security.basic.model.BasicUser; @Repository @Transactional public interface BasicUserDao extends JpaRepository<BasicUser, Long> { @Query("select u from BasicUser u where u.email=?1") BasicUser findByEmail(String email); }
3b636aff95538ab4f9dfeb3af73b33fec11790e7
{ "blob_id": "3b636aff95538ab4f9dfeb3af73b33fec11790e7", "branch_name": "refs/heads/master", "committer_date": "2014-09-13T00:39:16", "content_id": "6fe259276d765bc06b4dbb94e28a80938fa1387a", "detected_licenses": [ "MIT" ], "directory_id": "1d485c58ab0a17b140d47330cf52e741ec8a2644", "extension": "java", "filename": "BasicUserDao.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": 547, "license": "MIT", "license_type": "permissive", "path": "/backend-security/src/main/java/org/yellowbinary/server/security/basic/dao/BasicUserDao.java", "provenance": "stack-edu-0025.json.gz:845344", "repo_name": "YellowBinary/server", "revision_date": "2014-09-13T00:39:16", "revision_id": "3ac50e97a85f1587c4e940535e2f03607fd92e86", "snapshot_id": "9c18d222af1b3672d1dfb35a924757b34861d1f0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/YellowBinary/server/3ac50e97a85f1587c4e940535e2f03607fd92e86/backend-security/src/main/java/org/yellowbinary/server/security/basic/dao/BasicUserDao.java", "visit_date": "2021-01-13T01:21:47.713154", "added": "2024-11-19T00:38:51.807332+00:00", "created": "2014-09-13T00:39:16", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
from zope.component import getGlobalSiteManager from zope.interface import Interface, implements class IModifierPlugin(Interface): """ Interface for modifier plugins """ class IData(Interface): pass import e03_subscribers as me class MakeUpperCasePlugin(object): implements(me.IModifierPlugin) def __init__(self, context): self.context = context def run(self): self.context.text = self.context.text.upper() class MakeBig(object): implements(me.IModifierPlugin) def __init__(self, context): self.context = context def run(self): self.context.text = self.context.text.replace('a few', 'over 9000').replace("A FEW", "OVER 9000") class Data(object): implements(me.IData) text = "We have a few missed opportunities here." class OtherData(object): implements(Interface) text = "We have a few missed opportunities here." def demo_subscribers(load_zcml): gsm = getGlobalSiteManager() if load_zcml: from zope.configuration.xmlconfig import xmlconfig fname = __file__[:-3] + '.zcml' xmlconfig(open(fname)) else: gsm.registerSubscriptionAdapter(me.MakeUpperCasePlugin, (me.IData,)) gsm.registerSubscriptionAdapter(me.MakeBig, (Interface,)) data = me.Data() subscribers = gsm.subscribers((data,), me.IModifierPlugin) for plugin in subscribers: plugin.run() print data.text # WE HAVE OVER 9000 MISSED OPPORTUNITIES HERE. otherdata = me.OtherData() subscribers = gsm.subscribers((otherdata,), me.IModifierPlugin) for plugin in subscribers: plugin.run() print otherdata.text # We have over 9000 missed opportunities here. #print subscribers if __name__ == "__main__": import sys load_zcml = bool(len(sys.argv) > 1 and sys.argv[1] == 'zcml') demo_subscribers(load_zcml)
fba1680aa758431538a11cf91d75c7e84eefa99d
{ "blob_id": "fba1680aa758431538a11cf91d75c7e84eefa99d", "branch_name": "refs/heads/master", "committer_date": "2014-04-02T14:06:42", "content_id": "9cce95a6f2e69dea93c9c578874b3c9817e374eb", "detected_licenses": [ "MIT" ], "directory_id": "ab79e011f4b409b9609e0f6ecea6293d0ac5e3e1", "extension": "py", "filename": "e03_subscribers.py", "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": "Python", "length_bytes": 1885, "license": "MIT", "license_type": "permissive", "path": "/3-zca/e03_subscribers.py", "provenance": "stack-edu-0066.json.gz:155057", "repo_name": "tiberiuichim/ZopeTraining", "revision_date": "2014-04-02T14:06:42", "revision_id": "56e7df5f7c80484db59ee36c19a61f9fa760fc8c", "snapshot_id": "d74395cb9e513ac2a1723f1d193cc8dbb18d8ede", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tiberiuichim/ZopeTraining/56e7df5f7c80484db59ee36c19a61f9fa760fc8c/3-zca/e03_subscribers.py", "visit_date": "2016-09-06T17:15:21.133045", "added": "2024-11-19T00:50:18.120588+00:00", "created": "2014-04-02T14:06:42", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
import Vue from "vue"; import Vuex from "vuex"; import createPagination from "../../../index"; Vue.use(Vuex); export default new Vuex.Store({ state: { records: records(25) }, getters: { pageCount(state, getters) { return getters['pagination/pageCount'](getters.totalRecordCount); }, currentPage(state, getters) { return getters['pagination/currentPage']; }, hasNextPage(state, getters) { return getters.currentPage < getters.pageCount; }, hasPrevPage(state, getters) { return getters.currentPage > 1; }, visibleRecords(state, getters) { return getters['pagination/slice'](state.records); }, totalRecordCount(state, getters) { return state.records.length; } }, mutations: {}, actions: { goToNextPage(context) { const currentPage = context.getters['pagination/currentPage']; context.dispatch('pagination/goToPage', { page: currentPage + 1 }); }, goToPrevPage(context) { const currentPage = context.getters['pagination/currentPage']; context.dispatch('pagination/goToPage', { page: currentPage - 1 }); }, goToPage(context, payload) { context.dispatch('pagination/goToPage', { page: payload.page }); } }, modules: { pagination: createPagination({ pageSize: 5 }) } }); function records(count) { return [...new Array(count)] .map((r, i) => { return { id: i, label: `Record ${i}` }; }); }
b0cd75e7dd79133bfe3f899b5ea18aa7305f429e
{ "blob_id": "b0cd75e7dd79133bfe3f899b5ea18aa7305f429e", "branch_name": "refs/heads/master", "committer_date": "2021-05-12T23:50:10", "content_id": "b6448f6f9a84ff57b5e60c1a3101d36d3486145c", "detected_licenses": [ "MIT" ], "directory_id": "33dd72d438278ef850e243eb2742225597f3148c", "extension": "js", "filename": "store.js", "fork_events_count": 1, "gha_created_at": "2019-09-04T04:08:30", "gha_event_created_at": "2022-02-12T13:17:49", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 206228801, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1532, "license": "MIT", "license_type": "permissive", "path": "/examples/pagination/src/store.js", "provenance": "stack-edu-0036.json.gz:96033", "repo_name": "psalaets/vuex-local-pagination", "revision_date": "2021-05-12T23:50:10", "revision_id": "3982708e4ea2c74a8471d3c1781bc734e50ae538", "snapshot_id": "db271bede01d9c030effde9e6c47073e4a38e92f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/psalaets/vuex-local-pagination/3982708e4ea2c74a8471d3c1781bc734e50ae538/examples/pagination/src/store.js", "visit_date": "2022-02-25T10:21:59.302793", "added": "2024-11-18T22:23:53.209307+00:00", "created": "2021-05-12T23:50:10", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
<?php /** * This file is part of CSBill package. * * (c) 2013-2014 Pierre du Plessis <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace CSBill\ClientBundle\Form; use Doctrine\Common\Persistence\ManagerRegistry; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Validator\Constraints; use CSBill\ClientBundle\Entity\ContactType; use CSBill\ClientBundle\Form\DataTransformer\ContactTypeTransformer; class ContactDetail extends AbstractType { /** * @var ManagerRegistry */ protected $registry; /** * @var \CSBill\ClientBundle\Entity\ContactType */ private $type; /** * @param ManagerRegistry $registry * @param ContactType $type */ public function __construct(ManagerRegistry $registry, ContactType $type) { $this->registry = $registry; $this->type = $type; } /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $transformer = new ContactTypeTransformer($this->registry); $options = array( 'required' => $this->type->isRequired(), 'data' => $this->type, 'data_class' => null ); $contstraints = $this->buildConstraints(); if ($this->type->isRequired()) { $contstraints[] = new Constraints\NotBlank(); } $builder->add( $builder->create('type', 'hidden', $options) ->addModelTransformer($transformer) ); $builder->add('value', $this->type->getType(), array( 'label' => $this->humanize($this->type->getName()), 'constraints' => $contstraints )); } /** * @return string */ public function getName() { return 'contact_detail'; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'CSBill\ClientBundle\Entity\ContactDetail' )); } /** * @param string $text * * @return string */ private function humanize($text) { return ucwords(str_replace('_', ' ', $text)); } /** * @return array */ private function buildConstraints() { $options = $this->type->getOptions(); $constraints = array(); if (is_array($options) && array_key_exists('constraints', $options)) { foreach ($options['constraints'] as $constraint) { $constraint = str_replace(' ', '', $this->humanize($constraint)); if (class_exists($class = sprintf('Symfony\Component\Validator\Constraints\\%s', $constraint))) { $constraints[] = new $class; } } } return $constraints; } }
3fe85edd1c3306920059c17170775c7cdf245ccf
{ "blob_id": "3fe85edd1c3306920059c17170775c7cdf245ccf", "branch_name": "refs/heads/master", "committer_date": "2014-09-29T15:24:21", "content_id": "6d40a8881b280a1fabbdf0ad063f0ed37ca0bc33", "detected_licenses": [ "MIT" ], "directory_id": "0aa4c900a5d0c9010d361211f58109074db8ff8a", "extension": "php", "filename": "ContactDetail.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": 3239, "license": "MIT", "license_type": "permissive", "path": "/src/CSBill/ClientBundle/Form/ContactDetail.php", "provenance": "stack-edu-0050.json.gz:89693", "repo_name": "gitter-badger/CSBill", "revision_date": "2014-09-29T15:24:21", "revision_id": "5352c5c4677a44ab8670f31aa23ef64ad2d3f1f3", "snapshot_id": "c452f864f4ce632d010f7c96bb5bdb447635aa50", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gitter-badger/CSBill/5352c5c4677a44ab8670f31aa23ef64ad2d3f1f3/src/CSBill/ClientBundle/Form/ContactDetail.php", "visit_date": "2020-12-26T00:36:17.727615", "added": "2024-11-18T21:17:56.584829+00:00", "created": "2014-09-29T15:24:21", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
#!/usr/bin/python """ GCAT - Grand Canonical Analysis Toolkit @author Tomas Lazauskas, 2016-2018 """ import numpy as np from optparse import OptionParser import source.Canonical as Canonical import source.Data as Data import source.IO as IO import source.GrandPotential as GrandPotential from source.Utilities import log _accuracy = np.longdouble def cmd_line_args(): """ Handles command line arguments and options. """ usage = "usage: %prog input_data.csv" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_option("-o", "--output", dest="outputData", action="store_true", default=False, help="A flag to write the data into files") parser.add_option("-p", "--permutations", dest="permCalc", action="store_true", default=False, help="Permutations will be calculated instead of read from the data file. User must modify: DistributionAnalysis.calc_permutation") parser.add_option('-t', dest="temps", default="1", help="List of temperatures separated by a comma (default: T=0)") parser.add_option('-u', dest="urange", default=None, help="Chemical potential range: (default: None, syntax: 0,0.1,0.1)") parser.add_option("-v", dest="verbose", default=1, type="int", help="Verbose: 0 - off, 1 - on.") (options, args) = parser.parse_args() if (len(args) != 1): parser.error("incorrect number of arguments") return options, args def main(options, args): """ The main routine. """ data_file = args[0] # reading in the data success, error, names, permutations, chem_pot_multi, data = IO.read_in_data(data_file, _accuracy, options) if success: # prepare analysis parameters success, error, temperatures, chem_pot_range = Data.prepare_parameters(options) if success: # prepare the data energies, min_energies, shifted_energies, experiment_cnts, delta_E_sums = Data.prepare_data(data, temperatures, _accuracy, options) if success: # canonical analysis log(__name__, "Performing the canonical analysis", options.verbose, indent=1) success, error, omega_c_arr = Canonical.perform_canonical_analysis(chem_pot_multi, names, permutations, temperatures, min_energies, delta_E_sums, experiment_cnts, shifted_energies, _accuracy, options) if success and chem_pot_range is not None: # grand canonical analysis log(__name__, "Performing the grand canonical analysis", options.verbose, indent=1) success, error = GrandPotential.perform_grand_canonical_analysis(permutations, chem_pot_multi, names, temperatures, chem_pot_range, min_energies, delta_E_sums, experiment_cnts, omega_c_arr, _accuracy, options) return success, error if __name__ == "__main__": # command line arguments and options options, args = cmd_line_args() log(__name__, "Grand Canonical Potential", options.verbose) # the main routine success, error = main(options, args) if success: log(__name__, "Finished.", options.verbose) else: log(__name__, "ERROR: %s" % (error), 1)
01b0f6536769b8bfb3bd1d287d52b6543122dba2
{ "blob_id": "01b0f6536769b8bfb3bd1d287d52b6543122dba2", "branch_name": "refs/heads/master", "committer_date": "2018-02-16T16:40:21", "content_id": "f954780a5742a247219255c5166130fa3f259e27", "detected_licenses": [ "MIT" ], "directory_id": "79924af8cda1670d4faab7cbb2efdfddf4040455", "extension": "py", "filename": "GCAT.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 84933536, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3327, "license": "MIT", "license_type": "permissive", "path": "/GCAT.py", "provenance": "stack-edu-0063.json.gz:529642", "repo_name": "tomaslaz/Grand_Cannonical_Potential", "revision_date": "2018-02-16T16:40:21", "revision_id": "9a015f9e0c0b464b51dc3d066cea5476eeaa1a50", "snapshot_id": "b20e53259d8ba26f1b79138871b1f9ce4df2863c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tomaslaz/Grand_Cannonical_Potential/9a015f9e0c0b464b51dc3d066cea5476eeaa1a50/GCAT.py", "visit_date": "2021-09-07T03:32:09.677609", "added": "2024-11-18T19:14:27.780718+00:00", "created": "2018-02-16T16:40:21", "int_score": 3, "score": 2.59375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz" }
import React from "react"; import { Container, Row, Card, CardBody, } from "reactstrap"; import { AiOutlineCalendar, AiOutlineFieldTime, BiCalendarAlt, BiDetail, FaHotel, FaUsers, MdEvent, } from "react-icons/all"; import E1 from "assets/img/Event1.jpg"; import E2 from "assets/img/Event2.png"; function SectionEvents() { return ( <> <div id="events" className="section section-buttons"> <Container> <div className="title"> <h1 className="text-md-center text-dark">Events</h1> </div> <Row> <div className="col-3"> <Row> <Card> <img src={E1} alt=""/> </Card> </Row> </div> <div className="col-7"> <Card> <CardBody className="bg-light"> <h5>Event Informations</h5> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <MdEvent/> Event Title : .... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <FaUsers/> Collaborators : .... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <AiOutlineCalendar/> Event Date : ... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <FaHotel/> Place : ... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <BiDetail/> Description : ... </h6> </CardBody> </Card> </div> <div className="col-2"> <Card> <CardBody className="bg-light"> <h5>Event Date</h5> <BiCalendarAlt/> From : ... <br/> <AiOutlineFieldTime/> At : ... </CardBody> </Card> </div> </Row> <Row> <div className="col-3"> <Row> <Card> <img src={E2} alt=""/> </Card> </Row> </div> <div className="col-7"> <Card> <CardBody className="bg-light"> <h5>Event Informations</h5> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <MdEvent/> Event Title : .... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <FaUsers/> Collaborators : .... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <AiOutlineCalendar/> Event Date : ... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <FaHotel/> Place : ... </h6> <h6 className="text-dark justify-content-lg-between justify-content-lg-end"> <BiDetail/> Description : ... </h6> </CardBody> </Card> </div> <div className="col-2"> <Card> <CardBody className="bg-light"> <h5>Event Date</h5> <BiCalendarAlt/> From : ... <br/> <AiOutlineFieldTime/> At : ... </CardBody> </Card> </div> </Row> </Container> </div> </> ); } export default SectionEvents;
947ac91229d2ec402e6ca98bb1771e186515e0fe
{ "blob_id": "947ac91229d2ec402e6ca98bb1771e186515e0fe", "branch_name": "refs/heads/main", "committer_date": "2021-03-17T14:28:18", "content_id": "dbdb4be183456179fa612a5794e1da4cdd9e3368", "detected_licenses": [ "MIT" ], "directory_id": "6e203da50a6f0141e0bef407133235c4dc678576", "extension": "js", "filename": "EventsSection.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 347205823, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5237, "license": "MIT", "license_type": "permissive", "path": "/TemplateMediteravenir/src/views/index-sections/EventsSection.js", "provenance": "stack-edu-0032.json.gz:27796", "repo_name": "Syrine868/Full-Stack-GenIF-I", "revision_date": "2021-03-17T14:28:18", "revision_id": "f0a8f93dff7b5d30560f5e964876181b1d5aa1cb", "snapshot_id": "016ae4e98215285a83457265797e74baa24048c5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Syrine868/Full-Stack-GenIF-I/f0a8f93dff7b5d30560f5e964876181b1d5aa1cb/TemplateMediteravenir/src/views/index-sections/EventsSection.js", "visit_date": "2023-03-20T12:01:39.851202", "added": "2024-11-19T00:59:49.667227+00:00", "created": "2021-03-17T14:28:18", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
/* * Copyright 2017 Skolkovo Institute of Science and Technology * * 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 ru.skoltech.cedl.dataexchange.structure.model.diff; import org.apache.commons.beanutils.BeanUtils; import org.apache.log4j.Logger; import ru.skoltech.cedl.dataexchange.Utils; import ru.skoltech.cedl.dataexchange.entity.ExternalModel; import ru.skoltech.cedl.dataexchange.entity.PersistedEntity; import ru.skoltech.cedl.dataexchange.entity.model.ModelNode; import ru.skoltech.cedl.dataexchange.external.ExternalModelException; import java.lang.reflect.InvocationTargetException; import java.util.LinkedList; import java.util.List; import java.util.Objects; /** * Created by D.Knoll on 19.05.2017. */ public class ExternalModelDifference extends ModelDifference { private static final Logger logger = Logger.getLogger(ExternalModelDifference.class); private ModelNode parent; private ExternalModel externalModel1; private ExternalModel externalModel2; public ExternalModelDifference(ModelNode parent, ExternalModel externalModel1, String name, ChangeType changeType, ChangeLocation changeLocation) { this.parent = parent; this.externalModel1 = externalModel1; this.attribute = name; this.changeType = changeType; this.changeLocation = changeLocation; } public ExternalModelDifference(ExternalModel externalModel1, ExternalModel externalModel2, String name, ChangeType changeType, ChangeLocation changeLocation, String value1, String value2) { this.parent = externalModel1.getParent(); this.externalModel1 = externalModel1; this.externalModel2 = externalModel2; this.attribute = name; this.changeType = changeType; this.changeLocation = changeLocation; this.value1 = value1; this.value2 = value2; } @Override public PersistedEntity getChangedEntity() { if (changeType == ChangeType.MODIFY) { return changeLocation == ChangeLocation.ARG1 ? externalModel1 : externalModel2; } else if (changeType == ChangeType.ADD || changeType == ChangeType.REMOVE) { return externalModel1; } else { throw new IllegalArgumentException("Unknown change type and location combination"); } } @Override public String getElementPath() { return externalModel1.getNodePath(); } public ExternalModel getExternalModel1() { return externalModel1; } @Override public ModelNode getParentNode() { return externalModel1.getParent(); } @Override public boolean isMergeable() { return changeLocation == ChangeLocation.ARG2; } @Override public boolean isRevertible() { return changeLocation == ChangeLocation.ARG1; } @Override public void mergeDifference() { if (changeLocation != ChangeLocation.ARG2) // handling only remote changes throw new IllegalStateException("local difference can not be merged"); switch (changeType) { case ADD: { // add node to local parent Objects.requireNonNull(parent); final List<ExternalModel> externalModels = parent.getExternalModels(); // TODO: block changes that make the model inconsistent (name duplicates, ...) ExternalModel newExternalModel = null; try { newExternalModel = (ExternalModel) BeanUtils.cloneBean(externalModel1); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { logger.error("Cannot clone external model: " + externalModel1.getNodePath(), e); throw new IllegalStateException("Cannot clone external model: " + externalModel1.getNodePath(), e); } parent.addExternalModel(newExternalModel); this.setupCache(newExternalModel); break; } case REMOVE: { // remove node from local parent Objects.requireNonNull(parent); final String uuid = externalModel1.getUuid(); final List<ExternalModel> externalModels = parent.getExternalModels(); // TODO: block changes that make the model inconsistent (links to this parameter, ...) boolean removed = externalModels.removeIf(em -> em.getUuid().equals(uuid)); if (!removed) { logger.warn("external model to remove not present: " + externalModel1.getNodePath()); } else { // this avoids Hibernate to check list changes with persisted bags and try to replicate deletes in DB which are no longer there parent.setExternalModels(new LinkedList<>(externalModels)); } break; } case MODIFY: { // copy remote over local Objects.requireNonNull(externalModel1); Objects.requireNonNull(externalModel2); Utils.copyBean(externalModel2, externalModel1); externalModel1.setParent(parent); // link new item to actual new parent break; } default: { logger.error("MERGE IMPOSSIBLE:\n" + toString()); throw new UnsupportedOperationException(); } } } @Override public void revertDifference() { if (changeLocation != ChangeLocation.ARG1) throw new IllegalStateException("non-local difference can not be reverted"); final String uuid = externalModel1.getUuid(); switch (changeType) { case ADD: { // remove local again Objects.requireNonNull(parent); List<ExternalModel> externalModels = parent.getExternalModels(); // TODO: block changes that make the model inconsistent (links to this parameter, ...) boolean removed = externalModels.removeIf(em -> em.getUuid().equals(uuid)); if (!removed) { logger.warn("external model to remove not present: " + externalModel1.getNodePath()); } else { // this avoids Hibernate to check list changes with persisted bags and try to replicate deletes in DB which are no longer there parent.setExternalModels(new LinkedList<>(externalModels)); } break; } case REMOVE: { // re-add local again Objects.requireNonNull(parent); if (parent.getExternalModelMap().containsKey(externalModel1.getName())) { logger.error("unable to re-add parameter, because another external model of same name is already there"); } else { parent.addExternalModel(externalModel1); this.setupCache(externalModel1); } break; } case MODIFY: { // copy remote over local Objects.requireNonNull(externalModel1); Objects.requireNonNull(externalModel2); Utils.copyBean(externalModel2, externalModel1); externalModel1.setParent(parent); // link new item to actual new parent break; } default: { logger.error("MERGE IMPOSSIBLE:\n" + toString()); throw new UnsupportedOperationException(); } } } private void setupCache(ExternalModel externalModel) { try { Objects.requireNonNull(externalModel); externalModel.init(); externalModel.updateCacheFromAttachment(); } catch (ExternalModelException e) { logger.error("Failed to update cached external model: " + externalModel1.getNodePath(), e); throw new IllegalStateException("Failed to updated cached external model: " + externalModel1.getName()); } } @Override public String toString() { final StringBuilder sb = new StringBuilder("NodeDifference{"); sb.append("node1='").append(externalModel1.getName()).append('\''); if (externalModel2 != null) { sb.append(", node2='").append(externalModel2.getName()).append('\''); } sb.append(", attribute='").append(attribute).append('\''); sb.append(", changeType=").append(changeType); sb.append(", changeLocation=").append(changeLocation); sb.append(", value1='").append(value1).append('\''); sb.append(", value2='").append(value2).append('\''); sb.append(", author='").append(author).append('\''); sb.append("}\n "); return sb.toString(); } }
f62fb7ee2d545f224987bcedac4ba68c0b032d66
{ "blob_id": "f62fb7ee2d545f224987bcedac4ba68c0b032d66", "branch_name": "refs/heads/master", "committer_date": "2019-12-02T12:54:22", "content_id": "193371453d41e1dd446c4f42c9348e9542d54be6", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "3a037722ee972c33494232f10e494ac26f31c7f9", "extension": "java", "filename": "ExternalModelDifference.java", "fork_events_count": 0, "gha_created_at": "2017-07-24T13:44:40", "gha_event_created_at": "2022-09-01T22:33:30", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 98195360, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9443, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/client/src/main/java/ru/skoltech/cedl/dataexchange/structure/model/diff/ExternalModelDifference.java", "provenance": "stack-edu-0019.json.gz:106732", "repo_name": "cedesk/data-exchange", "revision_date": "2019-12-02T12:54:22", "revision_id": "ca21179490cd7933804f444b5ed57beab31bc611", "snapshot_id": "adb87cf67dfa49233c16575c981eab7d716d35dd", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/cedesk/data-exchange/ca21179490cd7933804f444b5ed57beab31bc611/client/src/main/java/ru/skoltech/cedl/dataexchange/structure/model/diff/ExternalModelDifference.java", "visit_date": "2022-09-19T17:05:54.105415", "added": "2024-11-18T19:14:24.020805+00:00", "created": "2019-12-02T12:54:22", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BotTerminator.Configuration; using BotTerminator.Models; namespace BotTerminator.Data { public class NullBotDatabase : IBotDatabase { public Task<Boolean> CheckUserAsync(String username, String groupName) => Task.FromResult(false); public Task<BanListConfig> ReadConfigAsync() => Task.FromResult(new BanListConfig()); public Task WriteConfigAsync(BanListConfig config, bool force) => Task.CompletedTask; public Task<IReadOnlyDictionary<String, Group>> GetAllGroupsAsync() => Task.FromResult<IReadOnlyDictionary<String, Group>>(new Dictionary<String, Group>()); public Task<IReadOnlyCollection<Group>> GetDefaultBannedGroupsAsync() => Task.FromResult(Array.Empty<Group>() as IReadOnlyCollection<Group>); public Task<IReadOnlyCollection<Group>> GetGroupsForUserAsync(String name) => Task.FromResult(Array.Empty<Group>() as IReadOnlyCollection<Group>); public Task UpdateUserAsync(String username, String groupName, Boolean value, Boolean force = false) => Task.CompletedTask; } }
83b7b9764659b95b5d7eec1b52c38c4285c8b834
{ "blob_id": "83b7b9764659b95b5d7eec1b52c38c4285c8b834", "branch_name": "refs/heads/master", "committer_date": "2022-04-08T05:51:35", "content_id": "87138e56188e68284f37c29b3c53c03e2585ca7e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b9e7f1b9c13bf10052a347274e9515b1ce5213c8", "extension": "cs", "filename": "NullBotDatabase.cs", "fork_events_count": 7, "gha_created_at": "2019-11-24T00:56:48", "gha_event_created_at": "2019-12-31T06:03:47", "gha_language": "C#", "gha_license_id": "Apache-2.0", "github_id": 223674237, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1127, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/Data/NullBotDatabase.cs", "provenance": "stack-edu-0011.json.gz:107182", "repo_name": "justcool393/BotTerminator", "revision_date": "2022-04-08T05:51:35", "revision_id": "9b616674155caa3b3dd499ed53217f0302066218", "snapshot_id": "e87597d87c63962c322a2c0eb98ca8e2b623170f", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/justcool393/BotTerminator/9b616674155caa3b3dd499ed53217f0302066218/src/Data/NullBotDatabase.cs", "visit_date": "2022-05-05T17:09:35.054321", "added": "2024-11-18T23:58:13.985866+00:00", "created": "2022-04-08T05:51:35", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
"use strict"; var _chai = require("chai"); var _chai2 = _interopRequireDefault(_chai); var _chaiHttp = require("chai-http"); var _chaiHttp2 = _interopRequireDefault(_chaiHttp); require("chai/register-should"); var _app = require("../app"); var _app2 = _interopRequireDefault(_app); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const { expect } = _chai2.default; _chai2.default.use(_chaiHttp2.default); describe('users can signup', () => { let token; let token2; it('it should return validation error', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', type: 'client', isadmin: 'false' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup').send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return confirm password error', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'inhgfdka' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup').send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return password strength', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'kwizera', confirmPassword: 'kwizera' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup').send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return account created', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPassword123!' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup').send(newUser).end((err, res) => { expect(res.statusCode).to.equal(201); done(); }); }); it('it should return account already exits', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPassword123!' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup').send(newUser).end((err, res) => { expect(res.statusCode).to.equal(409); done(); }); }); it('it should validation error', done => { const user = { email: 'john45gmail.com', password: 'aPassword123!' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signin').send(user).end((err, res) => { expect(res.status).to.equal(400); done(); }); }); it('it should Login successfuly', done => { const user = { email: '[email protected]', password: 'aPassword123!' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signin').send(user).end((err, res) => { token2 = res.body.data.token; expect(res.status).to.equal(200); done(); }); }); it('it should Login successfuly', done => { const user = { email: '[email protected]', password: 'aPassword123!' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signin').send(user).end((err, res) => { token = res.body.data.token; expect(res.status).to.equal(200); done(); }); }); it('it should return incorect password', done => { const user = { email: '[email protected]', password: 'kwizer4567a' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signin').send(user).end((err, res) => { expect(res.status).to.equal(400); done(); }); }); it('it should User not found', done => { const user = { email: '[email protected]', password: 'kwizera' }; _chai2.default.request(_app2.default).post('/api/v1/auth/signin').send(user).end((err, res) => { expect(res.status).to.equal(404); done(); }); }); it('it should return password strength', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'kwizera', confirmPassword: 'kwizera', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token2).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return No access', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPassword123!', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(403); done(); }); }); it('it should return not matching', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPasswo123!', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token2).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return account created', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPassword123!', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token2).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(201); done(); }); }); it('it should return validation', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: 'john45gmail.com', password: 'aPassword123!', confirmPassword: 'aPassword123!', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token2).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return account already exits', done => { const newUser = { firstname: 'John', lastname: 'Ishimwe', email: '[email protected]', password: 'aPassword123!', confirmPassword: 'aPassword123!', type: 'client', isadmin: false }; _chai2.default.request(_app2.default).post('/api/v1/auth/signup/admin').set('token', token2).send(newUser).end((err, res) => { expect(res.statusCode).to.equal(409); done(); }); }); it('it should return confirm password required', done => { const newAcc = { password: "kwizera" }; _chai2.default.request(_app2.default).post('/api/v1/[email protected]/reset').send(newAcc).set('token', token2).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return invalid email', done => { const newAcc = { password: "kwizera", confirmPassword: "kwizera" }; _chai2.default.request(_app2.default).post('/api/v1/kwizeragmail.com/reset').send(newAcc).set('token', token2).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should email not found', done => { const newAcc = { password: "kwizera", confirmPassword: "kwizera" }; _chai2.default.request(_app2.default).post('/api/v1/[email protected]/reset').send(newAcc).set('token', token).end((err, res) => { expect(res.statusCode).to.equal(404); done(); }); }); it('it should return password strength', done => { const newAcc = { password: "kwizera", confirmPassword: "kwizera" }; _chai2.default.request(_app2.default).post('/api/v1/[email protected]/reset').send(newAcc).set('token', token2).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return not matching', done => { const newAcc = { password: "aPassword123!", confirmPassword: "aPassword123" }; _chai2.default.request(_app2.default).post('/api/v1/[email protected]/reset').send(newAcc).set('token', token2).end((err, res) => { expect(res.statusCode).to.equal(400); done(); }); }); it('it should return reset succesful', done => { const newAcc = { password: "aPassword123!", confirmPassword: "aPassword1231" }; _chai2.default.request(_app2.default).post('/api/v1/[email protected]/reset').send(newAcc).set('token', token2).end((err, res) => { expect(res.statusCode).to.equal(200); done(); }); }); });
f4727547a5a524e5ed6c9cb87af76e781a797b69
{ "blob_id": "f4727547a5a524e5ed6c9cb87af76e781a797b69", "branch_name": "refs/heads/develop", "committer_date": "2020-08-13T14:04:32", "content_id": "32501f956c4e33a243ba110afaee4ce7ea8b036a", "detected_licenses": [ "MIT" ], "directory_id": "5319cb3a1ee0de6d62a717cb4406a1748232a189", "extension": "js", "filename": "user.js", "fork_events_count": 0, "gha_created_at": "2020-02-01T19:53:08", "gha_event_created_at": "2022-12-30T19:42:03", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 237669390, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9147, "license": "MIT", "license_type": "permissive", "path": "/build/tests/user.js", "provenance": "stack-edu-0038.json.gz:763638", "repo_name": "kabundege/Papel", "revision_date": "2020-08-13T14:04:32", "revision_id": "7ee3f98184ad5f5168c9c7ef236fe58571d6546f", "snapshot_id": "87c6694713f11c94869221943364c3dbf318d46a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kabundege/Papel/7ee3f98184ad5f5168c9c7ef236fe58571d6546f/build/tests/user.js", "visit_date": "2023-02-05T20:42:04.388942", "added": "2024-11-19T00:50:21.304424+00:00", "created": "2020-08-13T14:04:32", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
package es.boart.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @Entity public class Grupo { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String title; private String description; private String img; @ManyToMany private List<User> groupMembers = new ArrayList<>(); @OneToMany(cascade=CascadeType.ALL) private List<Publication> publications = new ArrayList<>(); /** * @param title * @param description * @param img */ public Grupo(String title, String description, String img){ this.title = title; this.description = description; this.img = img; } public Grupo(){} /** * @return the id */ public long getId() { return id; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String descripcion) { this.description = descripcion; } /** * @return the img */ @JsonIgnore public String getImg() { return img; } /** * @param img the img to set */ public void setImg(String imgPerfil) { this.img = imgPerfil; } /** * @return the miembroGrupos */ public List<User> getMiembroGrupos() { return groupMembers; } /** * @return the publications */ public List<Publication> getPublications() { return publications; } /** * @param publications the publications to set */ public void setPublications(List<Publication> publications) { this.publications = publications; } /* CUSTOM METHODS */ public void addMember(User user){ this.groupMembers.add(user); } public void removeMember(User user){ this.groupMembers.remove(user); } public boolean hasUser(User user){ return this.groupMembers.contains(user); } public void addPublication(Publication p){ this.getPublications().add(p); } @JsonProperty("img") public String getImgJSON(){ return getImg(); } }
c8ff6d372f9fedc3fd1ae48637583e258724fee5
{ "blob_id": "c8ff6d372f9fedc3fd1ae48637583e258724fee5", "branch_name": "refs/heads/master", "committer_date": "2017-05-16T07:18:06", "content_id": "1432ec3424d0492c7779c6180b64dd68c8849bcd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0ca5643869018998961da123e268e196c178ac18", "extension": "java", "filename": "Grupo.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79596395, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2495, "license": "Apache-2.0", "license_type": "permissive", "path": "/boart-back/src/main/java/es/boart/model/Grupo.java", "provenance": "stack-edu-0027.json.gz:348889", "repo_name": "priverop/boart", "revision_date": "2017-05-16T07:18:06", "revision_id": "75432cf5bc39cf4afa56d2e4eab21b9740a5668e", "snapshot_id": "2e7849ea9820292bd8ec417b39795bf5eff57e36", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/priverop/boart/75432cf5bc39cf4afa56d2e4eab21b9740a5668e/boart-back/src/main/java/es/boart/model/Grupo.java", "visit_date": "2021-01-18T18:52:23.721092", "added": "2024-11-18T19:16:17.409358+00:00", "created": "2017-05-16T07:18:06", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
module packadic.extensions { var defaultConfig:any = { 'default': { layout: ['header-fixed', 'footer-fixed'], theme: 'default' }, 'condensed-dark': { layout: ['header-fixed', 'footer-fixed', 'page-edged', 'sidebar-condensed'], theme: 'dark-sidebar' } }; var $body:JQuery = $('body'); export module timedTour { export class Progress { protected _el:JQuery; protected value:number; protected max:number; protected percent:number; protected timeoutRef:number; protected intervalRef:number; protected destroyed:boolean = false; constructor(value:number = 0, max:number = 100) { this.max = max; this._el = $('<progress>') .addClass('progress progress-info') .attr({max: this.max}) .css({margin: 0, height: '5px'}) .text('0%') .data('Progress', this); this.setValue(value); } public static create(value:number = 0, max:number = 100):Progress { return new Progress(value, max); } public setValue(value:number):Progress { if (value > this.max) { console.warn('cannot set value over max'); return; } this.value = value; this.percent = this.max / 100 * value; this._el.attr({value: value}).text(this.percent + '%'); return this; } public getValue():number { return this.value; } get el():JQuery { return this._el; } public destroy():Progress { if (this.destroyed === true) { return; } if (defined(this.timeoutRef)) { clearTimeout(this.timeoutRef); } if (defined(this.intervalRef)) { clearInterval(this.intervalRef); } this._el.remove(); this.destroyed = true; return this; } public setTimeout(timeoutMs:number, onReady:Function):Progress { var self:Progress = this; var tickInterval:number = timeoutMs / 100; var tickIncrement:number = this.max / 100; this.timeoutRef = setTimeout(onReady.bind(this), timeoutMs); (function loop() { self.intervalRef = setTimeout(() => { if (self.value >= self.max) { return clearInterval(self.intervalRef); } self.setValue(self.getValue() + tickIncrement); loop(); }, tickInterval); })(); return this; } } } export interface Anno extends AnnoJS { constructor(opts?:any); } export class Manno extends Anno { public timeout:number; constructor(arg?:any) { super(<AnnoJSOptions>{}); var key, options, others, val; if (arg.__proto__ === Array.prototype) { options = arg.shift(); others = arg; } else { options = arg; } for (key in options) { val = options[key]; this[key] = val; } if ((others != null ? others.length : void 0) > 0) { this.chainTo(new Manno(others)); } } _chainNext:any; chainTo(obj) { if (obj != null) { if (this._chainNext == null) { this._chainNext = obj instanceof Manno ? obj : new Manno(obj); this._chainNext._chainPrev = this; } else { if (obj instanceof Manno !== true) { console.warn('obj instanceof Manno !== true'); } this._chainNext.chainTo(obj); } } else { console.error("Can't chainTo a null object."); } return this; } onShow(anno:any, $target:JQuery, $annoElem:JQuery):any { if (!defined(anno.timeout)) { console.warn('!defined(anno.timedTour)'); return; } if (defined(this._onShow)) { this._onShow.call(this, anno, $target, $annoElem); } var progress = timedTour.Progress.create(); ///setTimeout(()=> { progress .setTimeout(anno.timeout, () => { progress.destroy(); anno.switchToChainNext(); }) .el .appendTo($annoElem.find('.anno-inner')); //}, 1400); $annoElem.css({'z-index': 9999}); return progress; } onHide(anno:any, $target:JQuery, $annoElem:JQuery, returnFromOnShow:any):any { console.log(returnFromOnShow.getValue()); console.log('onHide', arguments); returnFromOnShow.destroy(); if (defined(this._onHide)) { this._onHide.call(this, anno, $target, $annoElem); } } _onShow:Function; _onHide:Function; } @extension('demo_tour', defaultConfig) export class DemoTour extends Extension { public static dependencies:string[] = ['layout', 'quick_sidebar']; protected tour:Manno; public start() { var self:DemoTour = this; var oldZ = $('#quick-sidebar').css('z-index'); $('#quick-sidebar').css({'z-index': 9980}); var tour:any = new Manno([ this.timedStep(3000, '.page-header .quick-sidebar-toggler', 'left', 'The quick sidebar contains a demo of the layout API actions', { _onShow: function (anno:any, $target:JQuery, $annoElem:JQuery, returnFromOnShow:any) { setTimeout(() => self.layout.api('qs-show'), 1000); } }), this.qsApiButton(4000, 'page-boxed', 'Switch boxed display', (action:string) => setTimeout(() => self.layout.api(action), 3000)), this.qsApiButton(4000, 'page-edged', 'Switch edged display', (action:string) => setTimeout(() => self.layout.api(action), 3000)), this.qsApiButton(4000, 'sidebar-close', 'Open/close the sidebar', (action:string) => setTimeout(() => self.layout.api('sidebar-open'), 3000)), this.qsApiButton(4000, 'sidebar-hide', 'Hide/show the sidebar', (action:string) => setTimeout(() => self.layout.api('sidebar-show'), 3000)), this.qsApiButton(4000, 'sidebar-condensed', 'Big/small sidebar', (action:string) => setTimeout(() => self.layout.api(action), 3000)), this.qsApiButton(4000, 'sidebar-reversed', 'Big/small sidebar', (action:string) => { self.layout.api('qs-hide'); setTimeout(() => { self.layout.api('qs-show'); self.layout.api(action); }, 3000); } ), this.timedStep(4000, '#quick-sidebar', 'left', 'Change the theme', { _onShow: function (anno:any, $target:JQuery, $annoElem:JQuery, returnFromOnShow:any) { setTimeout(() => self.layout.api('theme', 'default'), 500); } }), this.timedStep(9000, '#quick-sidebar', 'left', 'Change some stuff at random', { _onShow: function (anno:any, $target:JQuery, $annoElem:JQuery, returnFromOnShow:any) { var notify:NotifyExtension = <NotifyExtension> self.extensions.get('notify'); setTimeout(() => { self.layout.api('page-edged'); self.layout.api('sidebar-hide'); }, 500); setTimeout(() => { notify.topRight('Showing some notifications'); }, 1500); setTimeout(() => { notify.footer('In the footerrr', 'error'); }, 2500); setTimeout(() => { self.layout.api('page-boxed'); self.layout.api('sidebar-open'); self.layout.api('sidebar-condensed'); self.layout.api('theme', 'dark-sidebar'); }, 5500); setTimeout(() => { self.layout.api('qs-show'); }, 7500); } }), this.qsApiButton(4000, 'qs-next', 'Navigate the quick sidebar', (action:string) => setTimeout(() => self.layout.api(action), 2000)), this.qsApiButton(4000, 'qs-hide', 'Thats it for now!') ]); tour.start(); console.log(tour); } protected qsApiButton(timeout:number, action:string, content:string, onShow?:Function, onHide?:Function) { var self:DemoTour = this; var bc:any; return this.timedStep(timeout, '#quick-sidebar', 'left', content, { // a[data-layout-api="' + action + '"] _onShow: function (anno:Manno, $target:JQuery, $annoElem:JQuery) { var $a = $target.find('a[data-layout-api="' + action + '"]'); bc = $a.css('border-color'); $a.css({'border-color': 'red'}); var offset:any = $a.offset(); $annoElem.css({ top: offset.top, //left: offset.left - $annoElem.outerWidth() }); setTimeout(() => self.layout.api(action), 1000); defined(onShow) && onShow.call(this, action, anno, $target, $annoElem); }, _onHide: function (anno:any, $target:JQuery, $annoElem:JQuery) { $target.find('a[data-layout-api="' + action + '"]').css('border-color', bc); defined(onHide) && onHide.call(this, action, anno, $target, $annoElem); } }) } protected timedStep(timeout:number, target:string, position:string, content:string, options:any = {}):any { var step:any = this.step(target, position, content, $.extend(true, { timeout: timeout }, options)); return step; } protected step(target:string, position:string, content:string, options:any = {}):AnnoJSOptions { options = $.extend(true, { target: target, position: position, content: content, showOverlay: ()=> { }, // overide to disable }, options); return <AnnoJSOptions> options; } /*protected loadAssets():util.promise.PromiseInterface<any> { var defer:util.promise.DeferredInterface<any> = util.promise.create(); async.parallel([ (d:any) => this.app.loadJS('jquery-scrollintoview/jquery.scrollintoview.min', true).then(d), (d:any) => this.app.loadJS('anno.js/anno', true).then(d), (d:any) => this.app.loadCSS('anno.js/anno', true).then(d) ], (res:any, err:any) => { DemoTour.assetsLoaded = true; defer.resolve(); }); return defer.promise; }*/ public init() { this.app.debug.log('DemoTour init'); this.app.on('booted', () => { debug.log('DemoTour received event emitted from app: booted'); }); } public boot() { var self:DemoTour = this; this._initLayoutApiActions(); } protected _initLayoutApiActions() { var self:DemoTour = this; var apiActions:any = { 'demo-tour-start': () => { console.log('demo-tour-start', this, self); this.start(); } }; self.layout.setApiActions(apiActions); } protected get layout():LayoutExtension { return <LayoutExtension> this.extensions.get('layout'); // this.app['layout']; } protected get quick_sidebar():QuickSidebarExtension { return <QuickSidebarExtension> this.extensions.get('quick_sidebar'); //this.app['quick_sidebar']; } } //Extensions.register('presets', DemoTour, defaultConfig); }
5cfa7b472d1b428037005b7f1a3d9f5b5f576579
{ "blob_id": "5cfa7b472d1b428037005b7f1a3d9f5b5f576579", "branch_name": "refs/heads/master", "committer_date": "2015-10-22T03:48:58", "content_id": "75872c2e867aabd65e80b7d0706e78e75c28f996", "detected_licenses": [ "MIT" ], "directory_id": "e608a1fe31019db6e2034eb907fdf0efcb03fa18", "extension": "ts", "filename": "demo-tour.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41556990, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13209, "license": "MIT", "license_type": "permissive", "path": "/src/ts/addons/extensions/demo-tour.ts", "provenance": "stack-edu-0073.json.gz:736964", "repo_name": "packadic/framework", "revision_date": "2015-10-22T03:48:58", "revision_id": "520716f2f31cfb40e4682752afa628910c0234c2", "snapshot_id": "881230047cd9a816f00bb9a0f420116344103c1a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/packadic/framework/520716f2f31cfb40e4682752afa628910c0234c2/src/ts/addons/extensions/demo-tour.ts", "visit_date": "2020-05-01T14:43:39.948385", "added": "2024-11-18T20:59:38.073933+00:00", "created": "2015-10-22T03:48:58", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz" }
/* ___ ___ __ __ ____________ | | | | |__|__|__ ___/ Ubiquitout Internet @ IIT-CNR | | | | /__/ / / / REST wrapper around cpprest | | | |/__/ / / / https://github.com/ccicconetti/rest/ |_______|__|__/__/ /__/ Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2019 Claudio Cicconetti https://ccicconetti.github.io/ 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 "problemdetails.h" #include "Rest/utils.h" #include "Support/tostring.h" #include <cassert> namespace uiiit { namespace rest { ProblemDetails::ProblemDetails(const std::string& aType, const std::string& aTitle, const web::http::status_code aStatus, const std::string& aDetail, const std::string& aInstance) : DataType() { rest::setIfNotEmpty(theObject, "type", aType, false); rest::setIfNotEmpty(theObject, "title", aTitle, false); theObject["status"] = web::json::value(aStatus); rest::setIfNotEmpty(theObject, "detail", aDetail, false); rest::setIfNotEmpty(theObject, "instance", aInstance, false); } ProblemDetails::ProblemDetails(const web::http::status_code aStatus, const std::string& aDetail) : ProblemDetails("", "", aStatus, aDetail, "") { } ProblemDetails::ProblemDetails(const web::json::value& aJson) : DataType(aJson) { std::string myErr; if (not aJson.has_integer_field("status")) { myErr += " status"; } if (not aJson.has_string_field("detail")) { myErr += " detail"; } if (not myErr.empty()) { throw std::runtime_error( "Error creating a ProblemDetails without required fields: " + myErr); } } std::string ProblemDetails::type() const { return theObject.has_field("type") ? theObject.as_object().at("type").as_string() : std::string(); } std::string ProblemDetails::title() const { return theObject.has_field("title") ? theObject.as_object().at("title").as_string() : std::string(); } web::http::status_code ProblemDetails::status() const { assert(theObject.has_field("status")); return theObject.as_object().at("status").as_integer(); } std::string ProblemDetails::detail() const { assert(theObject.has_field("detail")); return theObject.as_object().at("detail").as_string(); } std::string ProblemDetails::instance() const { return theObject.has_field("instance") ? theObject.as_object().at("instance").as_string() : std::string(); } std::string safeProblemDetailsString(const web::json::value& aJson) noexcept { try { return toString(ProblemDetails(aJson)); } catch (...) { } return "invalid ProblemDetails"; } } // namespace rest } // namespace uiiit std::ostream& operator<<(std::ostream& aStream, const uiiit::rest::ProblemDetails& aProblemDetails) { const auto myType = aProblemDetails.type(); // can be empty const auto myTitle = aProblemDetails.title(); // can be empty const auto myStatus = aProblemDetails.status(); // cannot be empty const auto myDetail = aProblemDetails.detail(); // cannot be empty const auto myInstance = aProblemDetails.instance(); // can be empty auto myFirst = true; if (not myType.empty()) { aStream << "type: " << myType; myFirst = false; } if (not myTitle.empty()) { if (not myFirst) { aStream << ", "; } aStream << "title: " << myTitle; myFirst = false; } if (not myFirst) { aStream << ", "; } aStream << "status: " << myStatus << ", " << "detail: " << myDetail; if (not myInstance.empty()) { aStream << ", instance: " << myInstance; } return aStream; }
9afe90b497697327a0672e225b9d60290994c3dc
{ "blob_id": "9afe90b497697327a0672e225b9d60290994c3dc", "branch_name": "refs/heads/master", "committer_date": "2022-11-17T07:47:31", "content_id": "3736e614d6c6f55bcf384d1f179e3861abf3b8f5", "detected_licenses": [ "MIT" ], "directory_id": "be9e36a2c9039f22995d5aedf5e8c9ca2a862104", "extension": "cpp", "filename": "problemdetails.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190770303, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4910, "license": "MIT", "license_type": "permissive", "path": "/Rest/problemdetails.cpp", "provenance": "stack-edu-0004.json.gz:156936", "repo_name": "ccicconetti/rest", "revision_date": "2022-11-17T07:47:31", "revision_id": "33ce4f169b985d30ce52eab9523b32d7d7121fb7", "snapshot_id": "ed202edcbf4e15e7b216d3f2d6081d6e3eb1e2f0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ccicconetti/rest/33ce4f169b985d30ce52eab9523b32d7d7121fb7/Rest/problemdetails.cpp", "visit_date": "2022-11-29T16:13:02.624120", "added": "2024-11-18T22:53:56.482010+00:00", "created": "2022-11-17T07:47:31", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
#!/usr/bin/env python import sys import os import os.path import numpy as np # valid 12 157 51 522 378 # category left1 top1 left2 top2 # test Prediction: Monitor Location: 127 541 50 366 # category left1 left2 top1 top2 category = [ "Backpack", "Batteries", "Bottle", "Bucket", "Candles", "Drill", "Flipflops", "Hammer", "Helmet", "Keyboard", "Knives", "Marker", "Monitor", "Mug", "Pan", "Scissors", "Screwdriver", "Sneakers", "Toys", "TrashCan", "Webcam" ] def getTest(data): if(len(data) > 0): category = "" left = "" top = "" right = "" bottom = "" p_category = 0 p_left = 0 p_top = 0 p_right = 0 p_bottom = 0 data_old = data data = list() for d in data_old: if(len(d) > 0): data.append(d) for i in range(len(data)): if(str(data[i]).find("Prediction:") > -1): p_category = i + 1 elif(str(data[i]).find("Location:") > -1): p_left = i + 1 p_top = i + 3 p_right = i + 2 p_bottom = i + 4 category = data[p_category] left = data[p_left] top = data[p_top] right = data[p_right] bottom = data[p_bottom] return [category, left, top, right, bottom] else: return [] def borderFit(tleft, ttop, tright, tbottom, vleft, vtop, vright, vbottom): if(vleft < tleft < vright or vtop < ttop < vbottom or vleft < tright < vright or vtop < tbottom < vbottom): return True return False tp = np.zeros(len(category)) fp = np.zeros(len(category)) fn = np.zeros(len(category)) iou = [list() for l in range(len(category))] if(len(sys.argv) < 3): print("usage: python3 %s test_dir valid_dir" % (sys.argv[0])) exit() test_dir_path = sys.argv[1] valid_dir_path = sys.argv[2] test_dir = os.listdir(test_dir_path) valid_dir = os.listdir(valid_dir_path) new_test_dir = list() new_valid_dir = list() for element in test_dir: filter_exp = ".txt" if(str(element).find(filter_exp, len(element) - len(filter_exp)) > 0): new_test_dir.append(element) for element in valid_dir: filter_exp = ".txt" if(str(element).find(filter_exp, len(element) - len(filter_exp)) > 0): new_valid_dir.append(element) for f in new_valid_dir: test_exists = os.path.isfile(str(test_dir_path) + str(f)) valid_exists = os.path.isfile(str(valid_dir_path) + str(f)) if(test_exists and valid_exists): testf = open(str(test_dir_path) + str(f), "r") validf = open(str(valid_dir_path) + str(f), "r") test_str = [line.rstrip('\n').rstrip('\r') for line in testf] valid_str = [line.rstrip('\n').rstrip('\r') for line in validf] testf.close() validf.close() test = list() valid = list() for e in test_str: test.append(getTest(str(e).split(" "))) for e in valid_str: valid.append(str(e).split(" ")) # print(test) # print(valid) # check for TP and FP for t in test: if(len(t) > 1): for v in valid: if(len(v) > 1): if(category.index(t[0]) == int(v[0]) and borderFit(t[1], t[2], t[3], t[4], v[1], v[2], v[3], v[4])): tp[category.index(t[0])] += 1 for i in range(1, len(t)): t[i] = int(t[i]) for i in range(1, len(v)): v[i] = int(v[i]) intersection_left = max(t[1], v[1]) intersection_top = max(t[2], v[2]) intersection_right = min(t[3], v[3]) intersection_bottom = min(t[4], v[4]) intersection = ( intersection_right - intersection_left) * ( intersection_bottom - intersection_top) overlap = (t[3] - t[1]) * (t[4] - t[2]) + ( v[3] - v[1]) * (v[4] - v[2]) - intersection iou[int(v[0])].append( float(intersection) / float(overlap)) else: fp[category.index(t[0])] += 1 else: fp[category.index(t[0])] += 1 # check for FN for v in valid: if(len(v) > 1): for t in test: if(len(t) > 1): if(category.index(t[0]) == int(v[0])): if(not borderFit(t[1], t[2], t[3], t[4], v[1], v[2], v[3], v[4])): fn[int(v[0])] += 1 else: fn[int(v[0])] += 1 else: fn[int(v[0])] += 1 print("Test: %s %s" % (test_dir_path, len(new_test_dir))) print("Valid: %s %s" % (valid_dir_path, len(new_valid_dir))) print("TP: %s" % (tp)) print("FP: %s" % (fp)) print("FN: %s" % (fn)) precision = np.zeros(len(category)) recall = np.zeros(len(category)) for i in range(len(category)): if((float(tp[i]) + float(fp[i])) > 0): precision[i] = float(tp[i]) / (float(tp[i]) + float(fp[i])) if((float(tp[i]) + float(fn[i])) > 0): recall[i] = float(tp[i]) / (float(tp[i]) + float(fn[i])) print("Precision: %s" % (precision)) print("Recall: %s" % (recall)) print("\n\nIoU") for i in range(len(category)): average = 0 if(len(iou[i]) > 0): sum = 0 for j in iou[i]: sum += j average = sum / len(iou[i]) print("\t%s: %s with %s" % (category[i], average, iou[i]))
afb95ef6a3f465fc183403b638c39c2c13d51b98
{ "blob_id": "afb95ef6a3f465fc183403b638c39c2c13d51b98", "branch_name": "refs/heads/master", "committer_date": "2019-11-04T19:40:49", "content_id": "89a479f9c00137f4aabd4439359913baad8093c2", "detected_licenses": [ "MIT" ], "directory_id": "313e3fb7d95f6c0afa391d8ca7b93e469eae3058", "extension": "py", "filename": "evalf_yolo.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 218322607, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6188, "license": "MIT", "license_type": "permissive", "path": "/results/scripts/evalf_yolo.py", "provenance": "stack-edu-0065.json.gz:560618", "repo_name": "TheLurps/turtlebot3_objdetection", "revision_date": "2019-11-04T19:40:49", "revision_id": "98dddf1e75aa88b41753275545dfe801e477831e", "snapshot_id": "76bc3284e971ef074b6f79e911bcbe7a757941a2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TheLurps/turtlebot3_objdetection/98dddf1e75aa88b41753275545dfe801e477831e/results/scripts/evalf_yolo.py", "visit_date": "2020-08-30T08:41:34.535403", "added": "2024-11-18T23:48:08.937988+00:00", "created": "2019-11-04T19:40:49", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz" }
#include <iostream> #include "src/Runtime.hpp" #include "src/Process.hpp" #include "src/ModuleLoader.hpp" #include <cstdlib> #include "src/REPL.hpp" using namespace std; int main(int argc, const char *argv[]) { // run script if(argc == 2) { char actualpath[PATH_MAX+1]; realpath(argv[1], actualpath); Runtime runtime; // the executable file located in cmake-build-debug Module module = Module::loadModule(actualpath); Process process0 = runtime.createProcess(module); runtime.addProcess(process0); runtime.schedule(); // runtime.execute(process0); return 0; } // REPL else { REPL::start(); } }
c9719f58f610760f890c3ca59dd8b9397120e7c0
{ "blob_id": "c9719f58f610760f890c3ca59dd8b9397120e7c0", "branch_name": "refs/heads/master", "committer_date": "2020-09-13T09:42:05", "content_id": "79a173c97cd1debcc64ca899c841d70bc29c6053", "detected_licenses": [ "MIT" ], "directory_id": "e16d9632607787f32b5a04acf9e72e7c851864b9", "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": 238425729, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 710, "license": "MIT", "license_type": "permissive", "path": "/main.cpp", "provenance": "stack-edu-0004.json.gz:368625", "repo_name": "zlin888/irispl", "revision_date": "2020-09-13T09:42:05", "revision_id": "ee2228eb1155c4cffb906a327b7257fb1d360590", "snapshot_id": "fe6a1259c682c71abb0b8e408005b0077e1a398a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zlin888/irispl/ee2228eb1155c4cffb906a327b7257fb1d360590/main.cpp", "visit_date": "2022-12-11T13:29:32.415642", "added": "2024-11-18T22:09:18.676129+00:00", "created": "2020-09-13T09:42:05", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
$(function(){ var $top = $("<div id='h_goTop' title='"+$.i18n.message('common.js.msg.goToTop')+"'></div>"); var $bottom = $("<div id='h_goBottom' title='"+$.i18n.message('common.js.msg.goToBottom')+"'></div>"); $bottom.add($top).css({ 'background':'url(./images/go_bottom_blue.png) no-repeat center center', 'width':'80px', 'height':'70px', 'margin-top':'20px', 'position':'fixed', 'right':'30px', 'cursor':'pointer', 'bottom':'55px', 'margin-left':'500px', 'left':'50%' }).appendTo($(document.body)); $top.css({ 'background':'url(./images/go_top_blue.png) no-repeat center center', 'display':'none', 'bottom':'110px', 'margin-left':'500px', 'left':'50%' }).appendTo($(document.body)); $bottom.hover(function(){ $(this).css('background','url(./images/go_bottom_red.png) no-repeat center center'); $(this).css('color','#ff0000'); },function(){ $(this).css('background','url(./images/go_bottom_blue.png) no-repeat center center'); $(this).css('color','#666'); }); $top.hover(function(){ $(this).css('background','url(./images/go_top_red.png) no-repeat center center'); $(this).css('color','#ff0000'); },function(){ $(this).css('background','url(./images/go_top_blue.png) no-repeat center center'); $(this).css('color','#666'); }); if($.browser.msie&&$.browser.version=='6.0'){ $bottom.add($top).css({ 'position':'absolute' }); }; var wh = $(window).height(); $(window).bind('scroll',function(){ ($(this).scrollTop()!=0)?$top.fadeIn():$top.fadeOut(); ($(window).scrollTop() + wh!=$(document).height())?$bottom.fadeIn():$bottom.fadeOut(); if($.browser.msie&&$.browser.version=='6.0'){ $bottom.css({ top:$(this).scrollTop()+wh-84 }); $top.css({ top:$(this).scrollTop()+wh-154 }); } }) $top.click(function(){ $("html,body").animate({ scrollTop:0 },"fast"); }); $bottom.click(function(){ $("body,html").animate({ scrollTop:document.body.clientHeight },500); }) })
5b20b7103bcb92bda8c7b4cbe49af557fa575979
{ "blob_id": "5b20b7103bcb92bda8c7b4cbe49af557fa575979", "branch_name": "refs/heads/master", "committer_date": "2022-04-01T18:30:03", "content_id": "8cc39572c54618377453179e34b2c1f0f3fe026e", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "a34026eed3dcf676c5fc8c8819e62e3447ae7142", "extension": "js", "filename": "ocs_scroll.js", "fork_events_count": 1, "gha_created_at": "2015-09-27T03:47:07", "gha_event_created_at": "2022-04-01T18:30:04", "gha_language": "Java", "gha_license_id": "NOASSERTION", "github_id": 43233278, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2333, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/source/builder/web/js/ocs_scroll.js", "provenance": "stack-edu-0038.json.gz:757911", "repo_name": "amida-tech/indaba", "revision_date": "2022-04-01T18:30:03", "revision_id": "c41a237d9420231af7a119fee9ec7e77719accf0", "snapshot_id": "49dbc251c22190c0ccbeb8db18ca4b9f9d4584c9", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/amida-tech/indaba/c41a237d9420231af7a119fee9ec7e77719accf0/source/builder/web/js/ocs_scroll.js", "visit_date": "2022-05-03T12:17:59.823348", "added": "2024-11-19T01:46:46.979947+00:00", "created": "2022-04-01T18:30:03", "int_score": 2, "score": 2, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
module Discovery class DateBuilder < GeoWorks::Discovery::DocumentBuilder::DateBuilder private # Overrides the date field parsing from GeoWorks # Builds date fields such as layer year and modified date. # Prefers the field parsed by GeoWorks, but defaults to <dc:date> # @return [Integer] year def layer_year year = super if year.blank? date = geo_concern.date.first year_m = date.match(/(?<=\D|^)(\d{4})(?=\D|$)/) year = year_m ? year_m[0].to_i : nil end year rescue '' end end end
85de33046e4b9080e7fe7b1b16452780339d71c5
{ "blob_id": "85de33046e4b9080e7fe7b1b16452780339d71c5", "branch_name": "refs/heads/master", "committer_date": "2018-04-09T13:16:08", "content_id": "cf2f78ba322c1ad5031af85cbbb6181751c7a61f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "813e110d24fd5d49776330cd938347f1b7043695", "extension": "rb", "filename": "date_builder.rb", "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": "Ruby", "length_bytes": 604, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/services/discovery/date_builder.rb", "provenance": "stack-edu-0067.json.gz:632465", "repo_name": "conorom/plum", "revision_date": "2018-04-09T13:16:08", "revision_id": "64f105648ab0553e1167b00705d945f05bc1fffc", "snapshot_id": "5afd58a9226efdbe71ba8926fee9b166067c4542", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/conorom/plum/64f105648ab0553e1167b00705d945f05bc1fffc/app/services/discovery/date_builder.rb", "visit_date": "2020-04-21T13:16:18.339259", "added": "2024-11-18T22:59:17.009281+00:00", "created": "2018-04-09T13:16:08", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
using System; using System.IO; using ADODB; using Stream = System.IO.Stream; namespace AE.Net.Mail { public class StreamInterceptor : IDisposable { private readonly MemoryStream _memoryStream; private readonly bool _firstLf; private readonly bool _lastCr; public StreamInterceptor(Stream stream, int size) { _memoryStream = new MemoryStream(); byte[] bytes = stream.Read(size); _firstLf = bytes.Length > 0 && bytes[0] == '\n'; _lastCr = bytes.Length > 0 && bytes[bytes.Length-1] == '\r'; _memoryStream.Write(bytes,0, bytes.Length); _memoryStream.Position = 0; } public MemoryStream Stream { get { return _memoryStream; } } public void SaveTo(Stream stream) { long savedPos = _memoryStream.Position; _memoryStream.Position = 0; if (_firstLf) _memoryStream.Position = 1; _memoryStream.CopyTo(stream); if (_lastCr) stream.Write(new byte[]{(byte) '\n'},0,1); _memoryStream.Position = savedPos; } public void SaveTo(string fileName) { using (var fs = new FileStream(fileName, FileMode.Create)) { SaveTo(fs); } } public void Dispose() { _memoryStream.Dispose(); } } }
f4c563a66606ade5001f78ad1d41e801e14e55e1
{ "blob_id": "f4c563a66606ade5001f78ad1d41e801e14e55e1", "branch_name": "refs/heads/master", "committer_date": "2016-12-05T20:07:16", "content_id": "4bd4e1f8a936abb33dc6967b902e3b33ef044a77", "detected_licenses": [ "MIT" ], "directory_id": "e3d6c807a6eb75cfb33fc26efc54652a06ecdc8a", "extension": "cs", "filename": "StreamInterceptor.cs", "fork_events_count": 0, "gha_created_at": "2015-09-04T23:53:18", "gha_event_created_at": "2015-09-04T23:53:19", "gha_language": "C#", "gha_license_id": null, "github_id": 41942415, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1446, "license": "MIT", "license_type": "permissive", "path": "/StreamInterceptor.cs", "provenance": "stack-edu-0014.json.gz:544402", "repo_name": "harold4/aenetmail", "revision_date": "2015-09-08T20:00:00", "revision_id": "f7dd27b70396b9c0760eafca70dc911c079562d6", "snapshot_id": "af6acb18c63ff1aa1574f166e2551bb3a3ac45c0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/harold4/aenetmail/f7dd27b70396b9c0760eafca70dc911c079562d6/StreamInterceptor.cs", "visit_date": "2021-01-17T11:59:04.090773", "added": "2024-11-18T23:24:37.136628+00:00", "created": "2015-09-08T20:00:00", "int_score": 3, "score": 2.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import pty import select import shlex import subprocess import sys import termios import tty from typing import List LOGGER = logging.getLogger(__name__) def execute_in_subprocess(cmd: List[str], **kwargs): """ Execute a process and stream output to logger :param cmd: command and arguments to run :type cmd: List[str] """ # function copied from gh:apache/airflow project output = b"" LOGGER.info("Executing cmd: %s", " ".join(shlex.quote(c) for c in cmd)) with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, close_fds=True, **kwargs ) as proc: if proc.stdout: with proc.stdout: for line in iter(proc.stdout.readline, b""): output += line proc.wait() return proc, output def execute_interactive(cmd: List[str], **kwargs): """ Runs the new command as a subprocess and ensures that the terminal's state is restored to its original state after the process is completed e.g. if the subprocess hides the cursor, it will be restored after the process is completed. """ # function copied from gh:apache/airflow project LOGGER.info("Executing cmd: %s", " ".join(shlex.quote(c) for c in cmd)) output = b"" old_tty = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) # open pseudo-terminal to interact with subprocess master_fd, slave_fd = pty.openpty() try: # use os.setsid() make it run in a new process group, or bash job control will not be enabled with subprocess.Popen( cmd, stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, universal_newlines=True, **kwargs ) as proc: while proc.poll() is None: readable_fbs, _, _ = select.select([sys.stdin, master_fd], [], [], 0.1) if sys.stdin in readable_fbs: input_data = os.read(sys.stdin.fileno(), 10240) os.write(master_fd, input_data) if master_fd in readable_fbs: output_data = os.read(master_fd, 10240) if output_data: os.write(sys.stdout.fileno(), output_data) output += output_data finally: # restore tty settings back termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty) return proc, output
2c583b69ffc4d3028585d0365be9097c15f10c92
{ "blob_id": "2c583b69ffc4d3028585d0365be9097c15f10c92", "branch_name": "refs/heads/main", "committer_date": "2021-08-17T15:24:15", "content_id": "936a01f90b666318b24ace8fd94fb9f0f596e107", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5c9d0f7a0b74613dc633004dcaa000f36cdd6096", "extension": "py", "filename": "process.py", "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": "Python", "length_bytes": 3050, "license": "Apache-2.0", "license_type": "permissive", "path": "/model_navigator/utils/process.py", "provenance": "stack-edu-0059.json.gz:542043", "repo_name": "mayani-nv/model_navigator", "revision_date": "2021-08-17T15:24:15", "revision_id": "925255bbeb9be7ac6f35407267e87a29a33087ab", "snapshot_id": "05291ed5f2fea7fd286da38f231cf3e391d2f82a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mayani-nv/model_navigator/925255bbeb9be7ac6f35407267e87a29a33087ab/model_navigator/utils/process.py", "visit_date": "2023-07-17T02:24:13.432380", "added": "2024-11-18T21:52:41.704647+00:00", "created": "2021-08-17T15:24:15", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
package postgresql import ( "database/sql" "github.com/spolabs/affiliate/src/service/db" ) func AllCryptocurrency(tx *sql.Tx) []db.CryptocurrencyInfo { rows, err := tx.Query("SELECT SHORT_NAME,FULL_NAME,RATE,UNIT_POWER,ENABLED FROM ALL_CRYPTOCURRENCY order by SHORT_NAME") checkErr(err) res := make([]db.CryptocurrencyInfo, 0, 10) defer rows.Close() for rows.Next() { var shortName, fullName, rate string var unitPower int32 var enabled bool err = rows.Scan(&shortName, &fullName, &rate, &unitPower, &enabled) checkErr(err) res = append(res, db.CryptocurrencyInfo{shortName, fullName, rate, unitPower, enabled}) } return res } func AddBatchCryptocurrency(tx *sql.Tx, batch []db.CryptocurrencyInfo) { stmt, err := tx.Prepare("insert into ALL_CRYPTOCURRENCY(SHORT_NAME,FULL_NAME,RATE,UNIT_POWER,ENABLED) values ($1, $2, $3, $4,$5)") defer stmt.Close() checkErr(err) for _, info := range batch { _, err = stmt.Exec(info.ShortName, info.FullName, info.Rate, info.UnitPower, info.Enabled) checkErr(err) } } func UpdateBatchRateAndEnabled(tx *sql.Tx, batch []db.CryptocurrencyInfo) { stmt, err := tx.Prepare("update ALL_CRYPTOCURRENCY set RATE=$1,ENABLED=$2 where SHORT_NAME=$3") defer stmt.Close() checkErr(err) for _, info := range batch { _, err = stmt.Exec(info.Rate, info.Enabled, info.ShortName) checkErr(err) } } func GetCryptocurrency(tx *sql.Tx, shortName string) *db.CryptocurrencyInfo { rows, err := tx.Query("SELECT SHORT_NAME,FULL_NAME,RATE,UNIT_POWER,ENABLED FROM ALL_CRYPTOCURRENCY where SHORT_NAME=$1", shortName) checkErr(err) defer rows.Close() for rows.Next() { var shortName, fullName, rate string var unitPower int32 var enabled bool err = rows.Scan(&shortName, &fullName, &rate, &unitPower, &enabled) checkErr(err) return &db.CryptocurrencyInfo{shortName, fullName, rate, unitPower, enabled} } return nil }
fc90cb4024ee04160dce9f2aac115da63b90a97a
{ "blob_id": "fc90cb4024ee04160dce9f2aac115da63b90a97a", "branch_name": "refs/heads/master", "committer_date": "2018-03-16T16:36:48", "content_id": "30d3c7b149a10a13025854d8779060892f8e307d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "38fa84980b368111204cccafb80431eeab97f463", "extension": "go", "filename": "all_cryptocurrency.go", "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": "Go", "length_bytes": 1886, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/service/postgresql/all_cryptocurrency.go", "provenance": "stack-edu-0018.json.gz:114782", "repo_name": "therealssj/affiliate", "revision_date": "2018-03-16T16:36:48", "revision_id": "034229f17d896c5f53b9f26a792b72b2ecd736e6", "snapshot_id": "daa49d9af6634359b370e9a30878a68e40f48e6d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/therealssj/affiliate/034229f17d896c5f53b9f26a792b72b2ecd736e6/src/service/postgresql/all_cryptocurrency.go", "visit_date": "2021-09-09T13:43:59.313437", "added": "2024-11-18T20:49:00.677964+00:00", "created": "2018-03-16T16:36:48", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
<?php use BEM\BH; class contentTest extends PHPUnit_Framework_TestCase { /** * @before */ function setupBhInstance () { $this->bh = new BH(); } function test_it_should_return_bemjson_content () { $this->bh->match('button', function ($ctx) { $this->assertEquals( 'Hello', $ctx->content()); }); $this->bh->apply(['block' => 'button', 'content' => 'Hello']); } function test_it_should_set_bemjson_content () { $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text']); }); $this->assertEquals( '<div class="button"><div class="button__text"></div></div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_set_bemjson_array_content () { $this->bh->match('button', function ($ctx) { $ctx->content([['elem' => 'text1'], ['elem' => 'text2']]); }); $this->assertEquals( '<div class="button"><div class="button__text1"></div><div class="button__text2"></div></div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_set_bemjson_string_content () { $this->bh->match('button', function ($ctx) { $ctx->content('Hello World'); }); $this->assertEquals( '<div class="button">Hello World</div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_set_bemjson_numeric_content () { $this->bh->match('button', function ($ctx) { $ctx->content(123); }); $this->assertEquals( '<div class="button">123</div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_set_bemjson_zero_numeric_content () { $this->bh->match('button', function ($ctx) { $ctx->content(0); }); $this->assertEquals( '<div class="button">0</div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_not_override_user_content () { $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text']); }); $this->assertEquals( '<div class="button">Hello</div>', $this->bh->apply(['block' => 'button', 'content' => 'Hello'])); } function test_it_should_not_override_later_declarations () { $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text2']); }); $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text1']); }); $this->assertEquals( '<div class="button"><div class="button__text1"></div></div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_override_later_declarations_with_force_flag () { $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text2'], true); }); $this->bh->match('button', function ($ctx) { $ctx->content(['elem' => 'text1']); }); $this->assertEquals( '<div class="button"><div class="button__text2"></div></div>', $this->bh->apply(['block' => 'button'])); } function test_it_should_override_user_declarations_with_force_flag () { $this->bh->match('button', function ($ctx) { $ctx->content('text', true); }); $this->assertEquals( '<div class="button">text</div>', $this->bh->apply(['block' => 'button', 'content' => 'Hello'])); } }
0034eac8aa499b0db4c6a37ac26f81465b596875
{ "blob_id": "0034eac8aa499b0db4c6a37ac26f81465b596875", "branch_name": "refs/heads/master", "committer_date": "2016-10-26T02:23:06", "content_id": "a5aee7457a9b8256f4eca70ed4f4cf9499a41951", "detected_licenses": [ "MIT" ], "directory_id": "daffb5bdc3feddb92cf9c6e0401771acab8e0e19", "extension": "php", "filename": "content.test.php", "fork_events_count": 0, "gha_created_at": "2016-01-25T09:18:55", "gha_event_created_at": "2016-01-25T09:18:55", "gha_language": null, "gha_license_id": null, "github_id": 50339640, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3690, "license": "MIT", "license_type": "permissive", "path": "/tests/content.test.php", "provenance": "stack-edu-0047.json.gz:510684", "repo_name": "DevGroup-ru/bh-php", "revision_date": "2016-10-26T02:23:06", "revision_id": "4991a04e531372874f010b0827ce13db5f71625c", "snapshot_id": "ed3b6933c0b23c141f661400db344d9870bb5d8d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DevGroup-ru/bh-php/4991a04e531372874f010b0827ce13db5f71625c/tests/content.test.php", "visit_date": "2023-08-10T23:01:33.968863", "added": "2024-11-18T21:22:47.384571+00:00", "created": "2016-10-26T02:23:06", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
--- layout: post title: "Starburst Jelly Beans: Ice Cream Flavors" brand: Starburst variety: Ice Cream Flavors date: 2018-02-22 permalink: starburst-ice-cream-flavors image: starburst-ice-cream-flavors.jpg image-credit: Walmart.com image-layout: float --- Next up to bat, another variety of a very popular brand of jelly beans: Starburst's Ice Cream Flavors. In the technical categories, I expect results consistent with my previous reviews of Starburst jelly beans ([Original](/starburst-jelly-beans), [Crazy Beans](/starburst-crazy-beans), and [Sour](/starburst-sour-jelly-beans)). Though this doesn't officially affect any scores, I must note for the record that there was only a dozen, at most, orange beans in this bag. Given that there are only four flavors, this is _far_ under the roughly 1-in-4 proportion that it should be. On to the review. ## Size and shape No surprises here. I still think they're slightly small, but on the whole, Starburst consistently does well in this category. **4 out of 5 beans** ## Chewability Starburst consistently does well in size and shape, but they consistently _knock it out of the park_ in chewability. For the fourth time, a bag of Starburst beans is awarded a perfect subscore in this category. **5 out of 5 beans** ## Texture In the most recent Starburst Jelly Beans review, [I demoted their texture score to 3](/starburst-sour-jelly-beans#texture), on account of the shell being too grainy on breakup. That must've been a phenomenon isolated to that bag or that variety, because I don't have that problem with these Ice Cream beans, and I didn't have it with the first two varieties. These beans are equally deserving of the 4 I gave to those first two. **4 out of 5 beans** ## Taste and flavor <div class="inset"> <h3>Flavors</h3> <ul class="emoji-list"> <li>:strawberry: Strawberry</li> <li>:orange: Orange Sherbet</li> <li>:heart: Red Raspberry</li> <li>:lemon: Lemon Sorbet</li> </ul> </div> And now we're on to the meat of this review. Starburst has always done well, if not excelled, in the taste and flavor category, so I was looking forward to seeing what they did with some less-conventional flavors. The funny thing is, I never read the actual bean flavors when buying the bag, and I was disappointed to realize that three out of four of these Flavors are just variants on classic Starburst flavors. Still, they taste good, and they made a solid effort to make them actually resemble ice cream, sherbet, or sorbet. They have a bit of milkiness to them. I feel like I pick up a bit of coconut in the strawberry, but there doesn't appear to be any coconut derivatives in the ingredients. Not being a fan of coconut, this is a slight turnoff, but I understand how it adds to the "ice cream" effect of the flavor. I think this is a first for a review here: I'm going to dock a bean for the fact that the colors of the strawberry and red raspberry beans are so close that they're indistinguishable without taking a very close look. This is pretty annoying when you're trying to reach for a specific flavor. And we're not talking [Gimbal's 41 flavors](/gimbals-gourmet-jelly-beans) here. There are _four flavors_ in this bag. Coulda made just a little more effort there, Starburst. **6 out of 10 beans** ## The one-of-each test Perhaps the ultimate test of a bag of jelly beans is how enjoyable it is to take one of each flavor and eat them all at the same time.[^1] Four beans on the smaller side never fill the mouth as much as I would like, but the flavors complement each other very well, and Starburst's stellar chewability makes for an effortless test. There's a good balance of acidity from the lemon sorbet and red raspberry and creaminess from the orange sherbet and strawberry. **8 out of 10 beans** ## Conclusion Category | Score ---------------- | --------------- Size and shape | **4**/5 beans Chewability | **5**/5 beans Texture | **4**/5 beans Taste and flavor | **6**/10 beans One-of-each test | **8**/10 beans ---------------- | --------------- _Total_ | **27**/35 beans Another solid effort by Starburst. Most likely, I'd reach for the Originals or the Sours before these, but a lot of that is my personal bias toward acidity. This is a unique, if modestly so, bag that any jelly bean lover should try. --- [^1]: This test is specific to fruit flavors _only_. While non-fruit flavors like licorice or buttered popcorn may be welcome, they are exempt from this test. Because that's just nasty.
0eac6787f0ccbbab466ac2ffca97583c8faa42f2
{ "blob_id": "0eac6787f0ccbbab466ac2ffca97583c8faa42f2", "branch_name": "refs/heads/gh-pages", "committer_date": "2023-04-09T18:16:43", "content_id": "a61613e290abed8a0771a3100bc315db702a5952", "detected_licenses": [ "MIT" ], "directory_id": "6499deaef6d61243a6d63de6f5d03ae4a2760040", "extension": "md", "filename": "2018-02-22-starburst-ice-cream-flavors.md", "fork_events_count": 2, "gha_created_at": "2016-03-07T22:21:05", "gha_event_created_at": "2023-04-17T02:19:41", "gha_language": "CSS", "gha_license_id": "MIT", "github_id": 53363420, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4577, "license": "MIT", "license_type": "permissive", "path": "/_posts/2018-02-22-starburst-ice-cream-flavors.md", "provenance": "stack-edu-markdown-0009.json.gz:69401", "repo_name": "Scotchester/jellybeans", "revision_date": "2023-04-09T18:16:43", "revision_id": "7a7a40baee518a1791aee1f6317290e9949c87cd", "snapshot_id": "e22e058c64c5783b01e5c3c039c28ebb17205a1e", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Scotchester/jellybeans/7a7a40baee518a1791aee1f6317290e9949c87cd/_posts/2018-02-22-starburst-ice-cream-flavors.md", "visit_date": "2023-04-17T03:56:11.945885", "added": "2024-11-18T22:04:56.730572+00:00", "created": "2023-04-09T18:16:43", "int_score": 3, "score": 3.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz" }
function byId(id) { return typeof id === "string" ? document.getElementById(id):id } function byClass(sClass, oParent){ var aClass = []; var reClass = new RegExp("(^| )" + sClass + "( |$)"); var aElem = byTagName("*",oParent); for (var i = 0; i < aElem.length; i++) { reClass.test(aElem[i].className) && aClass.push(aElem[i]); } return aClass; } function byTagName(elem,obj){ return (obj || document).getElementsByTagName(elem); } window.onload = function(){ var oCate = byClass("cate")[0]; var oCateMenu = byClass("cate_menu",oCate)[0]; var aCateItem = byClass("cate_menu_item",oCate); var oCatePop = byClass("cate_pop",oCate)[0]; var aCatePart = byClass("cate_part",oCate); var timer = null for (var i = 0; i < aCateItem.length; i++) { aCateItem[i].index = i; aCatePart[i].index = i; aCateItem[i].onmouseover = function(){ for (var j = 0; j < aCateItem.length; j++) { aCateItem[j].className = "cate_menu_item"; aCatePart[j].style.display = "none"; aCatePart[j].parentNode.style.display = "none"; }; this.className += " cate_menu_item_on"; aCatePart[this.index].style.display = "block"; aCatePart[this.index].parentNode.style.display = "block"; clearTimeout(timer); } aCateItem[i].onmouseout = function(){ var that = this; timer = setTimeout(function(){ that.className = "cate_menu_item"; aCatePart[that.index].style.display = "none"; aCatePart[that.index].parentNode.style.display = "none"; },200) } aCatePart[i].onmouseover = function(){ clearTimeout(timer) } aCatePart[i].onmouseout = function(){ var that = this; timer = setTimeout(function(){ aCateItem[that.index].className = "cate_menu_item"; that.style.display = "none"; that.parentNode.style.display = "none"; },200) } }; }
1ea4a4ffd770768ce4899f29764fcfd4d899c509
{ "blob_id": "1ea4a4ffd770768ce4899f29764fcfd4d899c509", "branch_name": "refs/heads/master", "committer_date": "2017-11-06T09:42:37", "content_id": "53e7d47eea5f019175e1c80b9de4d6dcead145ea", "detected_licenses": [ "MIT" ], "directory_id": "1366d537eefd16bfd010df799af9c51af2dab73c", "extension": "js", "filename": "jdnavigation.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92247358, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1910, "license": "MIT", "license_type": "permissive", "path": "/example/js/jdnavigation.js", "provenance": "stack-edu-0035.json.gz:52814", "repo_name": "liuyanly/javascript", "revision_date": "2017-11-06T09:42:37", "revision_id": "4f521dec79df5ec3c9764aeb1bf328e4fb24edfa", "snapshot_id": "8f3b24aaa4f3c369e7fbd29c10407ddcea04fea5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liuyanly/javascript/4f521dec79df5ec3c9764aeb1bf328e4fb24edfa/example/js/jdnavigation.js", "visit_date": "2021-01-21T20:33:35.312414", "added": "2024-11-19T00:28:06.991147+00:00", "created": "2017-11-06T09:42:37", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
// defines WADO routes async function wadoRoutes(fastify) { // WADO URI Retrieve Instance // GET {s}?{querystring} fastify.route({ method: 'GET', url: '/', schema: { querystring: { type: 'object', properties: { studyUID: { type: 'string', }, seriesUID: { type: 'string', }, objectUID: { type: 'string', }, contentType: { type: 'string', }, transferSyntax: { type: 'string', }, frame: { type: 'string', }, }, required: ['objectUID'], }, }, handler: fastify.retrieveInstance, }); // WADO Retrieve Instance // GET {s}/studies/{study}/series/{series}/instances/{instance} fastify.route({ method: 'GET', url: '/studies/:study/series/:series/instances/:instance', schema: { params: { type: 'object', properties: { study: { type: 'string', }, series: { type: 'string', }, instance: { type: 'string', }, }, }, }, handler: fastify.retrieveInstanceRS, }); // WADO Retrieve Instance frame // GET {s}/studies/{study}/series/{series}/instances/{instance}/frames/{frames} fastify.route({ method: 'GET', url: '/studies/:study/series/:series/instances/:instance/frames/:frames', schema: { params: { type: 'object', properties: { study: { type: 'string', }, series: { type: 'string', }, instance: { type: 'string', }, frames: { type: 'string', }, }, }, }, handler: fastify.retrieveInstanceFrames, }); // WADO Retrieve Study Metadata // GET {s}/studies/{study}/metadata fastify.route({ method: 'GET', url: '/studies/:study/metadata', schema: { params: { type: 'object', properties: { study: { type: 'string', }, }, }, }, handler: fastify.getStudyMetadata, }); // WADO Retrieve Series Metadata // GET {s}/studies/{study}/series/{series}/metadata fastify.route({ method: 'GET', url: '/studies/:study/series/:series/metadata', schema: { params: { type: 'object', properties: { study: { type: 'string', }, series: { type: 'string', }, }, }, }, handler: fastify.getSeriesMetadata, }); // WADO Retrieve Instance Metadata // GET {s}/studies/{study}/series/{series}/instances/{instance}/metadata fastify.route({ method: 'GET', url: '/studies/:study/series/:series/instances/:instance/metadata', schema: { params: { type: 'object', properties: { study: { type: 'string', }, series: { type: 'string', }, instance: { type: 'string', }, }, }, }, handler: fastify.getInstanceMetadata, }); fastify.route({ method: 'GET', url: '/studies/:study', schema: { params: { type: 'object', properties: { study: { type: 'string', }, }, }, }, handler: fastify.getWado, }); fastify.route({ method: 'GET', url: '/studies/:study/series/:series', schema: { params: { type: 'object', properties: { study: { type: 'string', }, series: { type: 'string', }, }, }, }, handler: fastify.getWado, }); } module.exports = wadoRoutes;
c3ba57a5f7bf7a76378f30e9e32f831ee8ec31fc
{ "blob_id": "c3ba57a5f7bf7a76378f30e9e32f831ee8ec31fc", "branch_name": "refs/heads/master", "committer_date": "2023-07-09T15:58:14", "content_id": "a7ec38361104c6fd984c3c906f4b3c34ba6852c1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "461575f09c5e2e67fbdaf65d552723dbd22e4c2c", "extension": "js", "filename": "wado.js", "fork_events_count": 24, "gha_created_at": "2019-01-25T00:48:33", "gha_event_created_at": "2023-07-15T21:09:47", "gha_language": "JavaScript", "gha_license_id": "Apache-2.0", "github_id": 167460684, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3907, "license": "Apache-2.0", "license_type": "permissive", "path": "/routes/wado.js", "provenance": "stack-edu-0040.json.gz:650867", "repo_name": "dcmjs-org/dicomweb-server", "revision_date": "2023-07-09T15:58:14", "revision_id": "7702d31051c9392a5ca554a685a40a255bec7557", "snapshot_id": "1462942716b4cec19ba487e75da02f6cb9cddb25", "src_encoding": "UTF-8", "star_events_count": 83, "url": "https://raw.githubusercontent.com/dcmjs-org/dicomweb-server/7702d31051c9392a5ca554a685a40a255bec7557/routes/wado.js", "visit_date": "2023-08-14T02:51:41.052642", "added": "2024-11-19T01:04:08.577525+00:00", "created": "2023-07-09T15:58:14", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
import { store } from '../store.js'; import { deepClone } from '../1-utils/deep-clone.js'; export const insert = (key = '', value) => { if (typeof key !== 'string') { throw new TypeError(`key is not a string`); } if (key in store) { throw new ReferenceError(`cannot insert: "${key}" is already in store`); } else { console.log(`: insert "${key}":`, value); store[key] = deepClone(value); } };
5dda577bfaac1d35bb2a5e491b938b3a06a5b2d0
{ "blob_id": "5dda577bfaac1d35bb2a5e491b938b3a06a5b2d0", "branch_name": "refs/heads/master", "committer_date": "2021-09-05T06:53:58", "content_id": "a4fe059b06535a0606bfc1c5089f03ad10a10e7d", "detected_licenses": [ "MIT" ], "directory_id": "f3a2e9167c2cdaa03e47082fdf96e7be7b32ecb0", "extension": "js", "filename": "insert.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 400610196, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 423, "license": "MIT", "license_type": "permissive", "path": "/function-roles/2-data-access/insert.js", "provenance": "stack-edu-0037.json.gz:632387", "repo_name": "perezrei/architecture", "revision_date": "2021-09-05T06:53:58", "revision_id": "4a8c6cd786829575d1bb106f5cbae281f5e1b3e9", "snapshot_id": "668d2a316056218ace1a603f530f41d2ffbf2206", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/perezrei/architecture/4a8c6cd786829575d1bb106f5cbae281f5e1b3e9/function-roles/2-data-access/insert.js", "visit_date": "2023-07-27T15:48:43.793405", "added": "2024-11-18T23:04:44.172811+00:00", "created": "2021-09-05T06:53:58", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
<?php if (IS_CLI) { //得到最前面的字符最大长度 $maxlen = 0; foreach (Profiler::groups() as $group => $benchmarks){ foreach ($benchmarks as $name => $tokens){ $maxlen = max(strlen($name.' ('.count($tokens).')'),$maxlen); } } $strlen = $maxlen+64; echo "\n"; echo "\x1b[0;33;44m"; echo str_pad('PHP Version:'.PHP_VERSION,$strlen,' ',STR_PAD_BOTH); foreach (Profiler::groups() as $group => $benchmarks){ echo "\x1b[32m"; echo "\n".str_pad($group,$strlen,'-',STR_PAD_BOTH); echo "\x1b[33m"; foreach ($benchmarks as $name => $tokens){ echo "\x1b[35m"; echo "\n".str_pad($name.' ('.count($tokens).')',$maxlen,' ',STR_PAD_LEFT); echo "\x1b[36m"; foreach (array('Min ', 'Max ', 'Average ', 'Total ') as $key){ echo ' '; echo "\x1b[36m"; echo $key; } $stats = Profiler::stats($tokens); echo "\x1b[36m"; echo "\n".str_pad('Time:',$maxlen,' ',STR_PAD_LEFT); foreach (array('min', 'max', 'average', 'total') as $key){ echo ' '; echo "\x1b[33m"; echo number_format($stats[$key]['time'], 6)."s "; } echo "\x1b[36m"; echo "\n".str_pad('Memory:',$maxlen,' ',STR_PAD_LEFT); foreach (array('min', 'max', 'average', 'total') as $key){ echo ' '; echo "\x1b[33m"; echo str_pad(number_format($stats[$key]['memory'] / 1024, 4).'kb',13); } echo "\n".str_pad('',$strlen,' '); } } echo "\x1b[33m"; $stats = Profiler::application(); echo "\x1b[32m"; echo "\n".str_pad('Application Execution',$strlen,'-',STR_PAD_BOTH); echo "\n".str_pad('',$maxlen,' ',STR_PAD_LEFT); echo "\x1b[36m"; foreach (array('Min ', 'Max ', 'Average ', 'Total ') as $key){ echo ' '; echo "\x1b[36m"; echo $key; } echo "\x1b[36m"; echo "\n".str_pad('Time:',$maxlen,' ',STR_PAD_LEFT); foreach (array('min', 'max', 'average', 'total') as $key){ echo ' '; echo "\x1b[33m"; echo number_format($stats[$key]['time'], 6)."s "; } echo "\x1b[36m"; echo "\n".str_pad('Memory:',$maxlen,' ',STR_PAD_LEFT); foreach (array('min', 'max', 'average', 'total') as $key){ echo ' '; echo "\x1b[33m"; echo str_pad(number_format($stats[$key]['memory'] / 1024, 4).'kb',13); } echo "\n".str_pad('',$strlen,' '); echo "\x1b[33m"; echo "\x1b[0m\n"; }else{ ?> <style type="text/css"> .profilerdiv {padding:10px;text-align:left;font-size:11px;font-family:Arial,sans-serif,Helvetica,"宋体";} .profilerdiv table.profiler { width: 100%; margin: 0 auto 1em; border-collapse: collapse; } .profilerdiv table.profiler th, .profilerdiv table.profiler td { font-size:10px;padding: 0.2em 0.4em; background: #fff; border: solid 1px #ccc; text-align: left; font-weight: normal; font-size: 11px; color: #111; font-family:Arial } .profilerdiv table.profiler tr.profiler_group th { background: #222; color: #eee; border-color: #222;font-size: 18px; } .profilerdiv table.profiler tr.profiler_headers th { text-transform: lowercase; font-variant: small-caps; background: #ddd; color: #777;font-size: 12px; } .profilerdiv table.profiler tr.profiler_mark th.profiler_name { float:none;width: 40%; font-size: 16px; background: #fff; vertical-align: middle; } .profilerdiv table.profiler tr.profiler_mark td.profiler_current { background: #eddecc; } .profilerdiv table.profiler tr.profiler_mark td.profiler_min { background: #d2f1cb; } .profilerdiv table.profiler tr.profiler_mark td.profiler_max { background: #ead3cb; } .profilerdiv table.profiler tr.profiler_mark td.profiler_average { background: #ddd; } .profilerdiv table.profiler tr.profiler_mark td.profiler_total { background: #d0e3f0; } .profilerdiv table.profiler tr.profiler_mark td.profiler_otherdata { background: #e6e6e6; } .profilerdiv table.profiler tr.profiler_time td { border-bottom: 0; } .profilerdiv table.profiler tr.profiler_memory td { border-top: none; } .profilerdiv table.profiler tr.final th.profiler_name { float:none;background: #222; color: #fff; } .profilerdiv tbody.hover td{background:#fffacd;} </style><div style="text-align:left;z-index:100000;position:fixed;_position:absolute;width:100%;bottom:0px;left:0;height:26px;background:#000;filter:alpha(opacity=80);opacity:0.8;"><div style="padding:5px 14px;color:#fff;text-decoration:none;font-size:12px;line-height:15px;"><a href="#onlineprofiler" style="color:#fff;text-decoration:none;font-size:12px;line-height:15px;" >调试:</a><?php echo Form::checkbox(null,'1',Core::debug()->profiler('sql')->is_open(),array('id'=>'_profiler_sql')),'<label for="_profiler_sql">SQL:Explain</label> ', Form::checkbox(null,'1',Core::debug()->profiler('nocached')->is_open(),array('id'=>'_profiler_nocached')),'<label for="_profiler_nocached">显示无缓存内容</label> ', Form::checkbox(null,'1',Core::debug()->profiler('output')->is_open(),array('id'=>'_profiler_output')),'<label for="_profiler_output">显示模板变量</label> ', Form::checkbox(null,'1',Core::debug()->profiler('filelist')->is_open(),array('id'=>'_profiler_filelist')),'<label for="_profiler_filelist">显示加载文件</label> ', Form::checkbox(null,'1',Core::debug()->profiler('xhprof')->is_open(),array('id'=>'_profiler_xhprof')),'<label for="_profiler_xhprof">开启Xhprof</label> ' ;?><input type="button" value="GO" onclick="profilerdiv_reload()"/> <input type="button" value="网格" onclick="if(document.body.style.backgroundImage==''){document.body.style.backgroundImage='url(<?php echo Core::url('statics/');?>images/tape.gif)';}else{document.body.style.backgroundImage='';}this.blur();" /></input></div></div> <script type="text/javascript"> function profilerdiv_reload(){ var s=document.location.search.substr(1); var s2=s.split('&'); var newsearch = '?'; for (var i=0 ;i< s2.length;i++){ var item = s2[i].split('='); var n=item[0]; var v=item[1]; if (n=='debug'){ v = document.getElementById('_profiler_sql').checked?'sql':''; v += document.getElementById('_profiler_nocached').checked?(v?'|':'')+'nocached':''; v += document.getElementById('_profiler_output').checked?(v?'|':'')+'output':''; v += document.getElementById('_profiler_filelist').checked?(v?'|':'')+'filelist':''; v += document.getElementById('_profiler_xhprof').checked?(v?'|':'')+'xhprof':''; if(!v)v='yes'; } newsearch +=n+'='+v; } document.location.href = newsearch+document.location.hash; } </script> <div style="position:absolute;z-index:99999;width:100%;left:0;background:#fff;"> <div class="profilerdiv"><a name="onlineprofiler"></a><?php foreach (Profiler::groups() as $group => $benchmarks): ?><table class="profiler"> <tr class="profiler_group"> <th class="profiler_name" colspan="5" style="float:none;"><?php echo ucfirst($group) ?></th> </tr> <tr class="profiler_headers"> <th class="profiler_name" style="float:none;">Benchmark</th> <th class="profiler_min">Min</th> <th class="profiler_max">Max</th> <th class="profiler_average">Average</th> <th class="profiler_total">Total</th> </tr> <?php foreach ($benchmarks as $name => $tokens): ?> <tr class="profiler_mark profiler_time"> <?php $stats = Profiler::stats($tokens); ?> <th class="profiler_name" rowspan="2"><?php echo $name, ' (', count($tokens), ')' ?></th> <?php foreach (array('min', 'max', 'average', 'total') as $key): ?> <td class="profiler_<?php echo $key ?>"><?php echo number_format($stats[$key]['time'], 6), ' ', 'seconds' ?></td> <?php endforeach ?> </tr> <tr class="profiler_mark profiler_memory"> <?php foreach (array('min', 'max', 'average', 'total') as $key): ?> <td class="profiler_<?php echo $key ?>"><?php echo number_format($stats[$key]['memory'] / 1024, 4), ' kb' ?></td> <?php endforeach ?> </tr> <?php if ($stats[$key]['data']):?> </table><table class="profiler" style="margin-top:-15px;"> <tr class="profiler_mark profiler_memory"> <td colspan="5" class="profiler_otherdata"> <table width="100%" style="white-space:nowrap"> <?php $i=1; foreach ($stats[$key]['data'] as $item){ if ($i==1){ echo '<tr class="profiler_headers"><th width="26">no.</th>'; echo "<th>runtime</th>"; echo "<th>memory</th>"; foreach ($item['rows'][0] as $key=>$value){ echo "<th>{$key}</th>"; } echo '</tr>'; } $row_num = count($item['rows']); echo '<tbody onmouseover="this.className=\'hover\';" onmouseout="this.className=\'\';">'; foreach ($item['rows'] as $r=>$row){ echo '<tr>'; if ($r==0){ echo '<td rowspan="'.$row_num.'" style="text-align:center;">'.$i.'</td>'; echo "<td rowspan='{$row_num}'>"; echo '<font style="color:red">'.number_format($item['runtime'], 6). '</font>'; echo "</td>"; echo "<td rowspan='{$row_num}'>"; echo '<font style="color:green">'.number_format($item['memory'] / 1024, 4). ' kb</font>'; echo "</td>"; } foreach ($row as $key=>$value){ $tmpr = $r+1; $tmp_row_num = 1; while ($tmpr<$row_num){ if (isset($item['rows'][$tmpr][$key])){ break; }else{ $tmp_row_num++; } $tmpr++; } echo "<td rowspan=\"{$tmp_row_num}\"><div style=\"max-width:1500px;max-height:500px;padding-right:18px;overflow:auto;\">"; if (is_array($value)) { echo '<pre style="padding:0;margin:0;">', htmlspecialchars(print_r($value,true)), '</pre>'; }else{ echo $value; } echo "</div></td>"; } echo '</td></tr>'; } echo '</tbody>'; $i++; } ?> </table> </td> </tr> <?php endif;?> <?php endforeach ?></table><?php endforeach ?><?php if ( Core::debug()->profiler('filelist')->is_open() ){ $includepath = Core::$include_path; $filelist = get_included_files(); ?><table class="profiler"><tr class="profiler_group"> <th colspan="3" class="profiler_name" style="float:none;"><?php echo 'Include Path ('.count($includepath).')' ?></th> </tr> <?php foreach ($includepath as $value): ?> <tr class="final profiler_mark profiler_memory"> <td style="width:88%"><?php echo Core::debug_path($value); ?></td> </tr> <?php endforeach ?> </table><table class="profiler"><tr class="profiler_group"> <th colspan="3" class="profiler_name" style="float:none;"><?php echo 'Included Files ('.count($filelist).')' ?></th> </tr> <?php foreach ($filelist as $i=>$value): ?> <tr class="final profiler_mark profiler_memory"> <td class="profiler_average" style="width:4%;text-align:center;"><?php echo ($i+1); ?></td> <td style="width:8%"><?php echo Profiler::bytes(filesize($value));?></td> <td style="width:88%"><?php echo Core::debug_path($value); ?></td> </tr> <?php endforeach ?> </table><?php } ?><table class="profiler"> <?php $stats = Profiler::application() ?> <tr class="final profiler_mark profiler_time"> <th class="profiler_name" rowspan="2" style="float:none;"><?php echo 'Application Execution ('.$stats['count'].')' ?></th> <?php foreach (array('min', 'max', 'average', 'current') as $key): ?> <td class="profiler_<?php echo $key ?>"><?php echo number_format($stats[$key]['time'], 6), ' ', 'seconds' ?></td> <?php endforeach ?> </tr> <tr class="final profiler_mark profiler_memory"> <?php foreach (array('min', 'max', 'average', 'current') as $key): ?> <td class="profiler_<?php echo $key ?>"><?php echo number_format($stats[$key]['memory'] / 1024, 4), ' kb' ?></td> <?php endforeach ?> </tr> </table> </div> <br /><br /> </div> <?php } ?>
e84987fc8f8b8d6d4c751d1ef40c2530d231754e
{ "blob_id": "e84987fc8f8b8d6d4c751d1ef40c2530d231754e", "branch_name": "refs/heads/master", "committer_date": "2012-09-18T12:10:50", "content_id": "74267d03685db1681e11f288bde054b96f02f937", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2899dd55cd9cd6b29a5fa4083f921af608da72ce", "extension": "php", "filename": "profiler.view.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": 13411, "license": "Apache-2.0", "license_type": "permissive", "path": "/libraries/myqee/develop/views/debug/profiler.view.php", "provenance": "stack-edu-0048.json.gz:693003", "repo_name": "iMarlboro/myqee-v2", "revision_date": "2012-09-18T12:10:50", "revision_id": "936acafe983df322cd5a2b3f0c48ae1aa2288ac6", "snapshot_id": "e31c00d57190c25514c124966476db7f29ae7ab3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iMarlboro/myqee-v2/936acafe983df322cd5a2b3f0c48ae1aa2288ac6/libraries/myqee/develop/views/debug/profiler.view.php", "visit_date": "2020-12-25T10:34:26.653218", "added": "2024-11-19T03:31:19.291743+00:00", "created": "2012-09-18T12:10:50", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
import styled, { keyframes } from 'styled-components' import { RED } from '@/utils/constants' const bounceDelayAnimation = keyframes` 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1.0); } ` export const Container = styled.div` width: 70px; height: 70px; border-radius: 50%; border: 3px solid ${RED}; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.7s; transition-delay: 3s; transition-timing-function: ease-in-out; ` export const Spinner = styled.div` margin: 100px auto 0; width: 70px; text-align: center; ` export const BounceOne = styled.div` width: 12px; height: 12px; background-color: ${RED}; border-radius: 100%; display: inline-block; animation: ${bounceDelayAnimation} 1s infinite ease-in-out both; animation-delay: -0.32s; ` export const BounceTwo = styled.div` width: 12px; height: 12px; background-color: ${RED}; border-radius: 100%; display: inline-block; animation: ${bounceDelayAnimation} 1s infinite ease-in-out both; animation-delay: -0.16s; margin: 0 4px; ` export const BounceThree = styled.div` width: 18px; height: 18px; background-color: ${RED}; border-radius: 100%; display: inline-block; animation: ${bounceDelayAnimation} 1s infinite ease-in-out both; `
d7413e87f5279285ab10b4ba16fc9432921d3494
{ "blob_id": "d7413e87f5279285ab10b4ba16fc9432921d3494", "branch_name": "refs/heads/master", "committer_date": "2020-07-18T05:04:30", "content_id": "4021effd210fdc227914fd351a24ee5237c29e80", "detected_licenses": [ "MIT" ], "directory_id": "977c17a0c34caa09b58cebf8c6ac5d4812d53143", "extension": "js", "filename": "styles.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 235285111, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1418, "license": "MIT", "license_type": "permissive", "path": "/src/components/Loader/styles.js", "provenance": "stack-edu-0032.json.gz:73314", "repo_name": "cbvictorio/pokedex-example", "revision_date": "2020-07-18T05:04:30", "revision_id": "0525b3de27b87641c0d0d6fc93dff68327a49d15", "snapshot_id": "0aab347fcb51d28b7c22a32c48a0ef194524c741", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cbvictorio/pokedex-example/0525b3de27b87641c0d0d6fc93dff68327a49d15/src/components/Loader/styles.js", "visit_date": "2020-12-17T06:00:09.055263", "added": "2024-11-19T01:19:55.664954+00:00", "created": "2020-07-18T05:04:30", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
<?php namespace LE_ACME2\Response\Authorization; use LE_ACME2\Response\Authorization\Struct; class Get extends AbstractAuthorization { public function getIdentifier() : Struct\Identifier { return new Struct\Identifier($this->_raw->body['identifier']['type'], $this->_raw->body['identifier']['value']); } public function getStatus() : string { return $this->_raw->body['status']; } public function getExpires() : string { return $this->_raw->body['expires']; } public function getChallenges() : array { return $this->_raw->body['challenges']; } /** * @param $type * @return Struct\Challenge */ public function getChallenge(string $type) : Struct\Challenge { foreach($this->getChallenges() as $challenge) { if($type == $challenge['type']) return new Struct\Challenge($challenge['type'], $challenge['status'], $challenge['url'], $challenge['token']); } throw new \RuntimeException('No challenge found with given type'); } }
8cd1c6fe2211d06f427f77d52c8050e8dc000444
{ "blob_id": "8cd1c6fe2211d06f427f77d52c8050e8dc000444", "branch_name": "refs/heads/master", "committer_date": "2019-07-06T08:37:12", "content_id": "ee2697e470bbfcb5e6f3a2513cfe6a0752391b67", "detected_licenses": [ "MIT" ], "directory_id": "1964dd53de5158e465713ae1578855e13334b67e", "extension": "php", "filename": "Get.php", "fork_events_count": 0, "gha_created_at": "2019-09-07T07:54:49", "gha_event_created_at": "2019-09-07T07:54:50", "gha_language": null, "gha_license_id": "MIT", "github_id": 206935237, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1073, "license": "MIT", "license_type": "permissive", "path": "/src/LE_ACME2/Response/Authorization/Get.php", "provenance": "stack-edu-0052.json.gz:646721", "repo_name": "krishnkant1996/le-acme2-php", "revision_date": "2019-07-06T08:37:12", "revision_id": "11b0864157748761b368ff2015938662fc1bd2d1", "snapshot_id": "285135ba463f0655334c5060bf0cbaa07fc69d52", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/krishnkant1996/le-acme2-php/11b0864157748761b368ff2015938662fc1bd2d1/src/LE_ACME2/Response/Authorization/Get.php", "visit_date": "2020-07-21T17:48:00.020141", "added": "2024-11-18T23:10:34.743678+00:00", "created": "2019-07-06T08:37:12", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package com.amazon.opendistroforelasticsearch.sql.elasticsearch.data.utils; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; /** * Regardless the underling data format, the {@link Content} define the data in abstract manner. * which could be parsed by ElasticsearchExprValueFactory. * There are two major use cases: * 1. Represent the JSON data retrieve from Elasticsearch search response. * 2. Represent the Object data extract from the Elasticsearch aggregation response. */ public interface Content { /** * Is null value. */ boolean isNull(); /** * Is number value. */ boolean isNumber(); /** * Is string value. */ boolean isString(); /** * Get integer value. */ Integer intValue(); /** * Get long value. */ Long longValue(); /** * Get short value. */ Short shortValue(); /** * Get byte value. */ Byte byteValue(); /** * Get float value. */ Float floatValue(); /** * Get double value. */ Double doubleValue(); /** * Get string value. */ String stringValue(); /** * Get boolean value. */ Boolean booleanValue(); /** * Get map of {@link Content} value. */ Iterator<Map.Entry<String, Content>> map(); /** * Get array of {@link Content} value. */ Iterator<? extends Content> array(); /** * Get geo point value. */ Pair<Double, Double> geoValue(); /** * Get {@link Object} value. */ Object objectValue(); }
0da32c1e64c6c99c9951de834878e68eccebf777
{ "blob_id": "0da32c1e64c6c99c9951de834878e68eccebf777", "branch_name": "refs/heads/develop", "committer_date": "2022-07-14T20:06:32", "content_id": "0d4698330095021d9b8a604b2a0ba526e37484ef", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c21ad867752435377c599fb34df6d9074e2f014d", "extension": "java", "filename": "Content.java", "fork_events_count": 215, "gha_created_at": "2018-12-19T20:20:57", "gha_event_created_at": "2022-07-19T21:52:44", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 162486600, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2154, "license": "Apache-2.0", "license_type": "permissive", "path": "/elasticsearch/src/main/java/com/amazon/opendistroforelasticsearch/sql/elasticsearch/data/utils/Content.java", "provenance": "stack-edu-0024.json.gz:497032", "repo_name": "opendistro-for-elasticsearch/sql", "revision_date": "2022-07-14T20:06:32", "revision_id": "a549025e42e71fb3146f0ba2a1705cbd3fa2db9c", "snapshot_id": "e7f5c3a4bd232237b837aa7b9c5704c33c80547b", "src_encoding": "UTF-8", "star_events_count": 639, "url": "https://raw.githubusercontent.com/opendistro-for-elasticsearch/sql/a549025e42e71fb3146f0ba2a1705cbd3fa2db9c/elasticsearch/src/main/java/com/amazon/opendistroforelasticsearch/sql/elasticsearch/data/utils/Content.java", "visit_date": "2023-09-03T03:47:50.986152", "added": "2024-11-19T01:59:42.263568+00:00", "created": "2022-07-14T20:06:32", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
/** * Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] */ class Solution { public int[] sortedSquares(int[] nums) { for(int i = 0; i < nums.length; i++){ nums[i] *= nums[i]; } Arrays.sort(nums); return nums; } } /** * This is a really cool solution utilising binary search to insert values at right point in the code. * I believe it will only however work for non decreasing arrays * */ class Solution { public int[] sortedSquares(int[] nums) { int[] res = new int[nums.length]; //Keep track of left and right indexes to slowly move inwards using two pointes int l = 0, r = nums.length - 1; //normal index track to keep of int index = r; while(l <= r){ // The absolute value here is a non negative representation of a number // We simply choose the bigger value at each step since pow will remove any negative signs. // The biggest value is then appended to the end of the array. if(Math.abs(nums[l]) > Math.abs(nums[r])){ res[index--] = nums[l] * nums[l]; l++; } else { res[index--] = nums[r] * nums[r]; r--; } } return res; } }
98a4e70ddb074e45f2be7b9f683b81ebbd5fbe53
{ "blob_id": "98a4e70ddb074e45f2be7b9f683b81ebbd5fbe53", "branch_name": "refs/heads/master", "committer_date": "2021-11-02T18:49:50", "content_id": "dc00c555a62dcc08796a1d93c84abea5b554da68", "detected_licenses": [ "MIT" ], "directory_id": "199944530a5a16968fbbcb7a924dae12d6f39c46", "extension": "java", "filename": "squares_sorted_array.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 98170263, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1638, "license": "MIT", "license_type": "permissive", "path": "/java/src/easy_leetcode/squares_sorted_array.java", "provenance": "stack-edu-0022.json.gz:138374", "repo_name": "sinderpl/CodingExamples", "revision_date": "2021-11-02T18:49:50", "revision_id": "9bc59a0345589bf51fc74fe9ad527e9498b9b5c9", "snapshot_id": "aac6f9c239050fb730b277b6249971e307a66e09", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sinderpl/CodingExamples/9bc59a0345589bf51fc74fe9ad527e9498b9b5c9/java/src/easy_leetcode/squares_sorted_array.java", "visit_date": "2021-11-12T15:19:02.917180", "added": "2024-11-19T01:15:22.419652+00:00", "created": "2021-11-02T18:49:50", "int_score": 4, "score": 4.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
<?php /** * @name eolinker ams open source,eolinker开源版本 * @link https://www.eolinker.com/ * @package eolinker * @author www.eolinker.com 广州银云信息科技有限公司 ©2015-2018 * eoLinker是目前全球领先、国内最大的在线API接口管理平台,提供自动生成API文档、API自动化测试、Mock测试、团队协作等功能,旨在解决由于前后端分离导致的开发效率低下问题。 * 如在使用的过程中有任何问题,欢迎加入用户讨论群进行反馈,我们将会以最快的速度,最好的服务态度为您解决问题。 * * eoLinker AMS开源版的开源协议遵循Apache License 2.0,如需获取最新的eolinker开源版以及相关资讯,请访问:https://www.eolinker.com/#/os/download * * 官方网站:https://www.eolinker.com/ * 官方博客以及社区:http://blog.eolinker.com/ * 使用教程以及帮助:http://help.eolinker.com/ * 商务合作邮箱:[email protected] * 用户讨论QQ群:284421832 */ class InstallModule { /** * 检测环境 * @param $dbURL string 数据库主机地址 * @param $dbName string 数据库名 * @param $dbUser string 数据库用户名 * @param $dbPassword string 数据库密码 * @return array */ public function checkoutEnv(&$dbURL, &$dbName, &$dbUser, &$dbPassword) { $result = array('fileWrite' => 0, 'db' => 0, 'curl' => 0, 'mbString' => 0, 'sessionPath' => 0, 'isInstalled' => 0); //检测配置目录写入权限 try { if (file_put_contents(PATH_FW . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'fileWriteTest.txt', 'ok')) { $result['fileWrite'] = 1; unlink(PATH_FW . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'fileWriteTest.txt'); //检测导出目录写入权限 if (file_put_contents('./dump' . DIRECTORY_SEPARATOR . 'fileWriteTest.txt', 'ok')) { $result['fileWrite'] = 1; unlink('./dump' . DIRECTORY_SEPARATOR . 'fileWriteTest.txt'); //检测根目录写入权限 if (file_put_contents('../fileWriteTest.txt', 'ok')) { $result['fileWrite'] = 1; unlink('../fileWriteTest.txt'); } else $result['fileWrite'] = 0; } else $result['fileWrite'] = 0; } else $result['fileWrite'] = 0; } catch (\Exception $e) { $result['fileWrite'] = '0'; $result['fileWriteError'] = $e->getMessage(); } //检测数据库连接 try { $dbURL = explode(':', $dbURL); if (empty($dbURL[1])) $dbURL[1] = '3306'; if (!class_exists('PDO')) { $result['db'] = 0; } else { $conInfo = 'mysql:host=' . $dbURL[0] . ';port=' . $dbURL[1] . ';dbname=' . $dbName . ';charset=utf8'; if ($con = new \PDO($conInfo, $dbUser, $dbPassword)) { $result['db'] = 1; //检测数据库是否有内容(已经安装过) $stat = $con->query("SELECT * FROM eo_user;"); if($stat) { $table_name = $stat -> fetch(\PDO::FETCH_ASSOC); if ($table_name) { $result['isInstalled'] = 1; } else { $result['isInstalled'] = 0; } }else{ $result['isInstalled'] = 0; } } else { $result['db'] = 0; } } } catch (\Exception $e) { $result['db'] = 0; $result['dbError'] = $e->getMessage(); } //检测CURL try { if (!function_exists('curl_init')) { $result['curl'] = 0; } else { $ch = curl_init(realpath('./index.php')); if ($ch) { curl_close($ch); $result['curl'] = 1; } else $result['curl'] = 0; } } catch (\Exception $e) { $result['curl'] = 0; $result['curlError'] = $e->getMessage(); } //检测mbString try { if (!function_exists('mb_strlen')) { $result['mbString'] = 0; } else { $len = mb_strlen('test', 'utf8'); if ($len) { $result['mbString'] = 1; } else { $result['mbString'] = 0; } } } catch (\Exception $e) { $result['mbString'] = 0; $result['mbStringError'] = $e->getMessage(); } //检测session路径写入权限 try { if (session_save_path() == '') { $session_path = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? 'C:/Windows/Temp' : '/tmp'; } else { $session_path = session_save_path(); } if (is_writable($session_path)) { $result['sessionPath'] = 1; } else { $result['sessionPath'] = 0; } } catch (\Exception $e) { $result['sessionPath'] = 0; $result['sessionPathError'] = $e->getMessage(); } return $result; } /** * 写入配置文件 * @param $dbURL string 数据库主机地址 * @param $dbName string 数据库名 * @param $dbUser string 数据库用户名 * @param $dbPassword string 数据库密码 * @param $websiteName string 网站名称 * @param $language string 语言 * @return bool */ public function createConfigFile(&$dbURL, &$dbName, &$dbUser, &$dbPassword, &$websiteName, &$language) { if (file_exists(PATH_FW . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'eo_config.php')) { //不存在配置文件,需要跳转至引导页面进行安装 unlink(realpath(PATH_FW . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'eo_config.php')); } $dbURL = explode(':', $dbURL); if (empty($dbURL[1])) $dbURL[1] = '3306'; $websiteName = isset($websiteName) ? $websiteName : 'eolinker开源版'; $config = "<?php //主机地址 defined('DB_URL') or define('DB_URL', '{$dbURL[0]}'); //主机端口,默认mysql为3306 defined('DB_PORT') or define('DB_PORT', '{$dbURL[1]}'); //连接数据库的用户名 defined('DB_USER') or define('DB_USER', '{$dbUser}'); //连接数据库的密码,推荐使用随机生成的字符串 defined('DB_PASSWORD') or define('DB_PASSWORD', '{$dbPassword}'); //数据库名 defined('DB_NAME') or define('DB_NAME', '{$dbName}'); //是否允许新用户注册 defined('ALLOW_REGISTER') or define('ALLOW_REGISTER', TRUE); //是否允许更新项目,如果设置为FALSE,那么自动更新和手动更新都将失效 defined('ALLOW_UPDATE') or define('ALLOW_UPDATE', TRUE); //网站名称 defined('WEBSITE_NAME') or define('WEBSITE_NAME', '{$websiteName}'); //数据表前缀 defined('DB_TABLE_PREFIXION') or define('DB_TABLE_PREFIXION', 'eo'); //语言 defined('LANGUAGE') or define ('LANGUAGE', '{$language}'); ?>"; if ($configFile = file_put_contents(PATH_FW . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'eo_config.php', $config)) return TRUE; else return FALSE; } /** * 安装数据库 */ public function installDatabase() { //读取数据库文件 $sql = file_get_contents(PATH_FW . DIRECTORY_SEPARATOR . 'db/eolinker_os_mysql.sql'); $sqlArray = array_filter(explode(';', $sql)); $dao = new InstallDao; $result = $dao->installDatabase($sqlArray); return $result; } } ?>
c37ab2e7512b6a687296d91de969bc3e7687d901
{ "blob_id": "c37ab2e7512b6a687296d91de969bc3e7687d901", "branch_name": "refs/heads/master", "committer_date": "2018-03-18T12:59:07", "content_id": "4cc8bc574795f854ed7b41e1e9278425518083ed", "detected_licenses": [ "Apache-2.0" ], "directory_id": "77595970fb4ec0a8b8164754e972c07f955ed7c6", "extension": "php", "filename": "InstallModule.class.php", "fork_events_count": 0, "gha_created_at": "2018-03-20T09:20:21", "gha_event_created_at": "2018-03-20T09:20:22", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 125991698, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8121, "license": "Apache-2.0", "license_type": "permissive", "path": "/backend_resource[后端源码]/Server/Web/Module/InstallModule.class.php", "provenance": "stack-edu-0051.json.gz:741081", "repo_name": "zuoliguang/eoLinker-API-Management-System-for-php", "revision_date": "2018-03-18T12:59:07", "revision_id": "fa98b12a21fe9b2ff0cde35ea33e495b4bfc1e74", "snapshot_id": "55b4a9747c024bf3661503ec11c617c5bdf0bd4a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zuoliguang/eoLinker-API-Management-System-for-php/fa98b12a21fe9b2ff0cde35ea33e495b4bfc1e74/backend_resource[后端源码]/Server/Web/Module/InstallModule.class.php", "visit_date": "2021-04-12T04:31:24.434665", "added": "2024-11-19T01:05:54.079027+00:00", "created": "2018-03-18T12:59:07", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
// Copyright 2011-2012 Brent Rowland. // Use of this source code is governed the Apache License, Version 2.0, as described in the LICENSE file. package pdf import ( "bytes" "strconv" ) func g(value float64) string { s := strconv.FormatFloat(value, 'f', 4, 64) n := len(s) for n > 0 && s[n-1] == '0' { n-- } if n > 0 && s[n-1] == '.' { n-- } return s[:n] } type Location struct { X, Y float64 } func (this Location) equal(other Location) bool { return this.X == other.X && this.Y == other.Y } type Size struct { Width, Height float64 } type SizeMap map[string]Size type intSlice []int func (s intSlice) join(separator string) string { var buf bytes.Buffer for i, v := range s { if i > 0 { buf.WriteString(separator) } buf.WriteString(strconv.Itoa(v)) } return buf.String() } type float64Slice []float64 func (s float64Slice) join(separator string) string { var buf bytes.Buffer for i, v := range s { if i > 0 { buf.WriteString(separator) } buf.WriteString(g(v)) } return buf.String() } func stringSlicesEqual(sl1, sl2 []string) bool { if len(sl1) != len(sl2) { return false } for i, s := range sl1 { if s != sl2[i] { return false } } return true }
532cd9610b40f90c2dba9dc4f72628dbf3e332c6
{ "blob_id": "532cd9610b40f90c2dba9dc4f72628dbf3e332c6", "branch_name": "refs/heads/master", "committer_date": "2015-03-25T01:03:09", "content_id": "8371891c9e2e4ad759e85229a82cce40dcfb5bd2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cc43564c6c5d328e4ff48c291051fb716c303649", "extension": "go", "filename": "support.go", "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": "Go", "length_bytes": 1215, "license": "Apache-2.0", "license_type": "permissive", "path": "/pdf/support.go", "provenance": "stack-edu-0018.json.gz:219066", "repo_name": "hasancgi/leadtype", "revision_date": "2015-03-25T01:03:09", "revision_id": "b0074f6d2bd5aadffd99d97fe780ab49ad3423ef", "snapshot_id": "0be925b674d743eba1a5aebbf2da0bcf47e22636", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hasancgi/leadtype/b0074f6d2bd5aadffd99d97fe780ab49ad3423ef/pdf/support.go", "visit_date": "2021-05-28T11:27:30.430301", "added": "2024-11-18T20:56:02.753098+00:00", "created": "2015-03-25T01:03:09", "int_score": 3, "score": 2.921875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
# Natural language image search with a Dual Encoder **Author:** [Khalid Salama](https://www.linkedin.com/in/khalid-salama-24403144/)<br> **Date created:** 2021/01/30<br> **Last modified:** 2021/01/30<br> **Description:** Implementation of a dual encoder model for retrieving images that match natural language queries. <img class="k-inline-icon" src="https://colab.research.google.com/img/colab_favicon.ico"/> [**View in Colab**](https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/nlp/ipynb/nl_image_search.ipynb) <span class="k-dot">•</span><img class="k-inline-icon" src="https://github.com/favicon.ico"/> [**GitHub source**](https://github.com/keras-team/keras-io/blob/master/examples/nlp/nl_image_search.py) --- ## Introduction The example demonstrates how to build a dual encoder (also known as two-tower) neural network model to search for images using natural language. The model is inspired by the [CLIP](https://openai.com/blog/clip/) approach, introduced by Alec Radford et al. The idea is to train a vision encoder and a text encoder jointly to project the representation of images and their captions into the same embedding space, such that the caption embeddings are located near the embeddings of the images they describe. This example requires TensorFlow 2.4 or higher. In addition, [TensorFlow Hub](https://www.tensorflow.org/hub) and [TensorFlow Text](https://www.tensorflow.org/tutorials/tensorflow_text/intro) are required for the BERT model, and [TensorFlow Addons](https://www.tensorflow.org/addons) is required for the AdamW optimizer. These libraries can be installed using the following command: ```python pip install -q -U tensorflow-hub tensorflow-text tensorflow-addons ``` --- ## Setup ```python import os import collections import json import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_hub as hub import tensorflow_text as text import tensorflow_addons as tfa import matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm import tqdm # Suppressing tf.hub warnings tf.get_logger().setLevel("ERROR") ``` --- ## Prepare the data We will use the [MS-COCO](https://cocodataset.org/#home) dataset to train our dual encoder model. MS-COCO contains over 82,000 images, each of which has at least 5 different caption annotations. The dataset is usually used for [image captioning](https://www.tensorflow.org/tutorials/text/image_captioning) tasks, but we can repurpose the image-caption pairs to train our dual encoder model for image search. ### Download and extract the data First, let's download the dataset, which consists of two compressed folders: one with images, and the other—with associated image captions. Note that the compressed images folder is 13GB in size. ```python root_dir = "datasets" annotations_dir = os.path.join(root_dir, "annotations") images_dir = os.path.join(root_dir, "train2014") tfrecords_dir = os.path.join(root_dir, "tfrecords") annotation_file = os.path.join(annotations_dir, "captions_train2014.json") # Download caption annotation files if not os.path.exists(annotations_dir): annotation_zip = tf.keras.utils.get_file( "captions.zip", cache_dir=os.path.abspath("."), origin="http://images.cocodataset.org/annotations/annotations_trainval2014.zip", extract=True, ) os.remove(annotation_zip) # Download image files if not os.path.exists(images_dir): image_zip = tf.keras.utils.get_file( "train2014.zip", cache_dir=os.path.abspath("."), origin="http://images.cocodataset.org/zips/train2014.zip", extract=True, ) os.remove(image_zip) print("Dataset is downloaded and extracted successfully.") with open(annotation_file, "r") as f: annotations = json.load(f)["annotations"] image_path_to_caption = collections.defaultdict(list) for element in annotations: caption = f"{element['caption'].lower().rstrip('.')}" image_path = images_dir + "/COCO_train2014_" + "%012d.jpg" % (element["image_id"]) image_path_to_caption[image_path].append(caption) image_paths = list(image_path_to_caption.keys()) print(f"Number of images: {len(image_paths)}") ``` <div class="k-default-codeblock"> ``` Downloading data from http://images.cocodataset.org/annotations/annotations_trainval2014.zip 252878848/252872794 [==============================] - 5s 0us/step Downloading data from http://images.cocodataset.org/zips/train2014.zip 13510574080/13510573713 [==============================] - 394s 0us/step Dataset is downloaded and extracted successfully. Number of images: 82783 ``` </div> ### Process and save the data to TFRecord files You can change the `sample_size` parameter to control many image-caption pairs will be used for training the dual encoder model. In this example we set `train_size` to 30,000 images, which is about 35% of the dataset. We use 2 captions for each image, thus producing 60,000 image-caption pairs. The size of the training set affects the quality of the produced encoders, but more examples would lead to longer training time. ```python train_size = 30000 valid_size = 5000 captions_per_image = 2 images_per_file = 2000 train_image_paths = image_paths[:train_size] num_train_files = int(np.ceil(train_size / images_per_file)) train_files_prefix = os.path.join(tfrecords_dir, "train") valid_image_paths = image_paths[-valid_size:] num_valid_files = int(np.ceil(valid_size / images_per_file)) valid_files_prefix = os.path.join(tfrecords_dir, "valid") tf.io.gfile.makedirs(tfrecords_dir) def bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def create_example(image_path, caption): feature = { "caption": bytes_feature(caption.encode()), "raw_image": bytes_feature(tf.io.read_file(image_path).numpy()), } return tf.train.Example(features=tf.train.Features(feature=feature)) def write_tfrecords(file_name, image_paths): caption_list = [] image_path_list = [] for image_path in image_paths: captions = image_path_to_caption[image_path][:captions_per_image] caption_list.extend(captions) image_path_list.extend([image_path] * len(captions)) with tf.io.TFRecordWriter(file_name) as writer: for example_idx in range(len(image_path_list)): example = create_example( image_path_list[example_idx], caption_list[example_idx] ) writer.write(example.SerializeToString()) return example_idx + 1 def write_data(image_paths, num_files, files_prefix): example_counter = 0 for file_idx in tqdm(range(num_files)): file_name = files_prefix + "-%02d.tfrecord" % (file_idx) start_idx = images_per_file * file_idx end_idx = start_idx + images_per_file example_counter += write_tfrecords(file_name, image_paths[start_idx:end_idx]) return example_counter train_example_count = write_data(train_image_paths, num_train_files, train_files_prefix) print(f"{train_example_count} training examples were written to tfrecord files.") valid_example_count = write_data(valid_image_paths, num_valid_files, valid_files_prefix) print(f"{valid_example_count} evaluation examples were written to tfrecord files.") ``` <div class="k-default-codeblock"> ``` 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 15/15 [03:19<00:00, 13.27s/it] 0%| | 0/3 [00:00<?, ?it/s] 60000 training examples were written to tfrecord files. 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:33<00:00, 11.07s/it] 10000 evaluation examples were written to tfrecord files. ``` </div> ### Create `tf.data.Dataset` for training and evaluation ```python feature_description = { "caption": tf.io.FixedLenFeature([], tf.string), "raw_image": tf.io.FixedLenFeature([], tf.string), } def read_example(example): features = tf.io.parse_single_example(example, feature_description) raw_image = features.pop("raw_image") features["image"] = tf.image.resize( tf.image.decode_jpeg(raw_image, channels=3), size=(299, 299) ) return features def get_dataset(file_pattern, batch_size): return ( tf.data.TFRecordDataset(tf.data.Dataset.list_files(file_pattern)) .map( read_example, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False, ) .shuffle(batch_size * 10) .prefetch(buffer_size=tf.data.AUTOTUNE) .batch(batch_size) ) ``` --- ## Implement the projection head The projection head is used to transform the image and the text embeddings to the same embedding space with the same dimensionality. ```python def project_embeddings( embeddings, num_projection_layers, projection_dims, dropout_rate ): projected_embeddings = layers.Dense(units=projection_dims)(embeddings) for _ in range(num_projection_layers): x = tf.nn.gelu(projected_embeddings) x = layers.Dense(projection_dims)(x) x = layers.Dropout(dropout_rate)(x) x = layers.Add()([projected_embeddings, x]) projected_embeddings = layers.LayerNormalization()(x) return projected_embeddings ``` --- ## Implement the vision encoder In this example, we use [Xception](https://keras.io/api/applications/xception/) from [Keras Applications](https://keras.io/api/applications/) as the base for the vision encoder. ```python def create_vision_encoder( num_projection_layers, projection_dims, dropout_rate, trainable=False ): # Load the pre-trained Xception model to be used as the base encoder. xception = keras.applications.Xception( include_top=False, weights="imagenet", pooling="avg" ) # Set the trainability of the base encoder. for layer in xception.layers: layer.trainable = trainable # Receive the images as inputs. inputs = layers.Input(shape=(299, 299, 3), name="image_input") # Preprocess the input image. xception_input = tf.keras.applications.xception.preprocess_input(inputs) # Generate the embeddings for the images using the xception model. embeddings = xception(xception_input) # Project the embeddings produced by the model. outputs = project_embeddings( embeddings, num_projection_layers, projection_dims, dropout_rate ) # Create the vision encoder model. return keras.Model(inputs, outputs, name="vision_encoder") ``` --- ## Implement the text encoder We use [BERT](https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-256_A-4/1) from [TensorFlow Hub](https://tfhub.dev) as the text encoder ```python def create_text_encoder( num_projection_layers, projection_dims, dropout_rate, trainable=False ): # Load the BERT preprocessing module. preprocess = hub.KerasLayer( "https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2", name="text_preprocessing", ) # Load the pre-trained BERT model to be used as the base encoder. bert = hub.KerasLayer( "https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1", "bert", ) # Set the trainability of the base encoder. bert.trainable = trainable # Receive the text as inputs. inputs = layers.Input(shape=(), dtype=tf.string, name="text_input") # Preprocess the text. bert_inputs = preprocess(inputs) # Generate embeddings for the preprocessed text using the BERT model. embeddings = bert(bert_inputs)["pooled_output"] # Project the embeddings produced by the model. outputs = project_embeddings( embeddings, num_projection_layers, projection_dims, dropout_rate ) # Create the text encoder model. return keras.Model(inputs, outputs, name="text_encoder") ``` --- ## Implement the dual encoder To calculate the loss, we compute the pairwise dot-product similarity between each `caption_i` and `images_j` in the batch as the predictions. The target similarity between `caption_i` and `image_j` is computed as the average of the (dot-product similarity between `caption_i` and `caption_j`) and (the dot-product similarity between `image_i` and `image_j`). Then, we use crossentropy to compute the loss between the targets and the predictions. ```python class DualEncoder(keras.Model): def __init__(self, text_encoder, image_encoder, temperature=1.0, **kwargs): super(DualEncoder, self).__init__(**kwargs) self.text_encoder = text_encoder self.image_encoder = image_encoder self.temperature = temperature self.loss_tracker = keras.metrics.Mean(name="loss") @property def metrics(self): return [self.loss_tracker] def call(self, features, training=False): # Place each encoder on a separate GPU (if available). # TF will fallback on available devices if there are fewer than 2 GPUs. with tf.device("/gpu:0"): # Get the embeddings for the captions. caption_embeddings = text_encoder(features["caption"], training=training) with tf.device("/gpu:1"): # Get the embeddings for the images. image_embeddings = vision_encoder(features["image"], training=training) return caption_embeddings, image_embeddings def compute_loss(self, caption_embeddings, image_embeddings): # logits[i][j] is the dot_similarity(caption_i, image_j). logits = ( tf.matmul(caption_embeddings, image_embeddings, transpose_b=True) / self.temperature ) # images_similarity[i][j] is the dot_similarity(image_i, image_j). images_similarity = tf.matmul( image_embeddings, image_embeddings, transpose_b=True ) # captions_similarity[i][j] is the dot_similarity(caption_i, caption_j). captions_similarity = tf.matmul( caption_embeddings, caption_embeddings, transpose_b=True ) # targets[i][j] = avarage dot_similarity(caption_i, caption_j) and dot_similarity(image_i, image_j). targets = keras.activations.softmax( (captions_similarity + images_similarity) / (2 * self.temperature) ) # Compute the loss for the captions using crossentropy captions_loss = keras.losses.categorical_crossentropy( y_true=targets, y_pred=logits, from_logits=True ) # Compute the loss for the images using crossentropy images_loss = keras.losses.categorical_crossentropy( y_true=tf.transpose(targets), y_pred=tf.transpose(logits), from_logits=True ) # Return the mean of the loss over the batch. return (captions_loss + images_loss) / 2 def train_step(self, features): with tf.GradientTape() as tape: # Forward pass caption_embeddings, image_embeddings = self(features, training=True) loss = self.compute_loss(caption_embeddings, image_embeddings) # Backward pass gradients = tape.gradient(loss, self.trainable_variables) self.optimizer.apply_gradients(zip(gradients, self.trainable_variables)) # Monitor loss self.loss_tracker.update_state(loss) return {"loss": self.loss_tracker.result()} def test_step(self, features): caption_embeddings, image_embeddings = self(features, training=False) loss = self.compute_loss(caption_embeddings, image_embeddings) self.loss_tracker.update_state(loss) return {"loss": self.loss_tracker.result()} ``` --- ## Train the dual encoder model In this experiment, we freeze the base encoders for text and images, and make only the projection head trainable. ```python num_epochs = 5 # In practice, train for at least 30 epochs batch_size = 256 vision_encoder = create_vision_encoder( num_projection_layers=1, projection_dims=256, dropout_rate=0.1 ) text_encoder = create_text_encoder( num_projection_layers=1, projection_dims=256, dropout_rate=0.1 ) dual_encoder = DualEncoder(text_encoder, vision_encoder, temperature=0.05) dual_encoder.compile( optimizer=tfa.optimizers.AdamW(learning_rate=0.001, weight_decay=0.001) ) ``` Note that training the model with 60,000 image-caption pairs, with a batch size of 256, takes around 12 minutes per epoch using a V100 GPU accelerator. If 2 GPUs are available, the epoch takes around 8 minutes. ```python print(f"Number of GPUs: {len(tf.config.list_physical_devices('GPU'))}") print(f"Number of examples (caption-image pairs): {train_example_count}") print(f"Batch size: {batch_size}") print(f"Steps per epoch: {int(np.ceil(train_example_count / batch_size))}") train_dataset = get_dataset(os.path.join(tfrecords_dir, "train-*.tfrecord"), batch_size) valid_dataset = get_dataset(os.path.join(tfrecords_dir, "valid-*.tfrecord"), batch_size) # Create a learning rate scheduler callback. reduce_lr = keras.callbacks.ReduceLROnPlateau( monitor="val_loss", factor=0.2, patience=3 ) # Create an early stopping callback. early_stopping = tf.keras.callbacks.EarlyStopping( monitor="val_loss", patience=5, restore_best_weights=True ) history = dual_encoder.fit( train_dataset, epochs=num_epochs, validation_data=valid_dataset, callbacks=[reduce_lr, early_stopping], ) print("Training completed. Saving vision and text encoders...") vision_encoder.save("vision_encoder") text_encoder.save("text_encoder") print("Models are saved.") ``` <div class="k-default-codeblock"> ``` Number of GPUs: 2 Number of examples (caption-image pairs): 60000 Batch size: 256 Steps per epoch: 235 Epoch 1/5 235/235 [==============================] - 573s 2s/step - loss: 60.8318 - val_loss: 9.0531 Epoch 2/5 235/235 [==============================] - 553s 2s/step - loss: 7.8959 - val_loss: 5.2654 Epoch 3/5 235/235 [==============================] - 541s 2s/step - loss: 4.6644 - val_loss: 4.9260 Epoch 4/5 235/235 [==============================] - 538s 2s/step - loss: 4.0188 - val_loss: 4.6312 Epoch 5/5 235/235 [==============================] - 539s 2s/step - loss: 3.5555 - val_loss: 4.3503 Training completed. Saving vision and text encoders... Models are saved. ``` </div> Plotting the training loss: ```python plt.plot(history.history["loss"]) plt.plot(history.history["val_loss"]) plt.ylabel("Loss") plt.xlabel("Epoch") plt.legend(["train", "valid"], loc="upper right") plt.show() ``` ![png](/img/examples/nlp/nl_image_search/nl_image_search_23_0.png) --- ## Search for images using natural language queries We can then retrieve images corresponding to natural language queries via the following steps: 1. Generate embeddings for the images by feeding them into the `vision_encoder`. 2. Feed the natural language query to the `text_encoder` to generate a query embedding. 3. Compute the similarity between the query embedding and the image embeddings in the index to retrieve the indices of the top matches. 4. Look up the paths of the top matching images to display them. Note that, after training the `dual encoder`, only the fine-tuned `vision_encoder` and `text_encoder` models will be used, while the `dual_encoder` model will be discarded. ### Generate embeddings for the images We load the images and feed them into the `vision_encoder` to generate their embeddings. In large scale systems, this step is performed using a parallel data processing framework, such as [Apache Spark](https://spark.apache.org) or [Apache Beam](https://beam.apache.org). Generating the image embeddings may take several minutes. ```python print("Loading vision and text encoders...") vision_encoder = keras.models.load_model("vision_encoder") text_encoder = keras.models.load_model("text_encoder") print("Models are loaded.") def read_image(image_path): image_array = tf.image.decode_jpeg(tf.io.read_file(image_path), channels=3) return tf.image.resize(image_array, (299, 299)) print(f"Generating embeddings for {len(image_paths)} images...") image_embeddings = vision_encoder.predict( tf.data.Dataset.from_tensor_slices(image_paths).map(read_image).batch(batch_size), verbose=1, ) print(f"Image embeddings shape: {image_embeddings.shape}.") ``` <div class="k-default-codeblock"> ``` Loading vision and text encoders... Models are loaded. Generating embeddings for 82783 images... 324/324 [==============================] - 437s 1s/step Image embeddings shape: (82783, 256). ``` </div> ### Retrieve relevant images In this example, we use exact matching by computing the dot product similarity between the input query embedding and the image embeddings, and retrieve the top k matches. However, *approximate* similarity matching, using frameworks like [ScaNN](https://github.com/google-research/google-research/tree/master/scann), [Annoy](https://github.com/spotify/annoy), or [Faiss](https://github.com/facebookresearch/faiss) is preferred in real-time use cases to scale with a large number of images. ```python def find_matches(image_embeddings, queries, k=9, normalize=True): # Get the embedding for the query. query_embedding = text_encoder(tf.convert_to_tensor(queries)) # Normalize the query and the image embeddings. if normalize: image_embeddings = tf.math.l2_normalize(image_embeddings, axis=1) query_embedding = tf.math.l2_normalize(query_embedding, axis=1) # Compute the dot product between the query and the image embeddings. dot_similarity = tf.matmul(query_embedding, image_embeddings, transpose_b=True) # Retrieve top k indices. results = tf.math.top_k(dot_similarity, k).indices.numpy() # Return matching image paths. return [[image_paths[idx] for idx in indices] for indices in results] ``` Set the `query` variable to the type of images you want to search for. Try things like: 'a plate of healthy food', 'a woman wearing a hat is walking down a sidewalk', 'a bird sits near to the water', or 'wild animals are standing in a field'. ```python query = "a family standing next to the ocean on a sandy beach with a surf board" matches = find_matches(image_embeddings, [query], normalize=True)[0] plt.figure(figsize=(20, 20)) for i in range(9): ax = plt.subplot(3, 3, i + 1) plt.imshow(mpimg.imread(matches[i])) plt.axis("off") ``` ![png](/img/examples/nlp/nl_image_search/nl_image_search_30_0.png) --- ## Evaluate the retrieval quality To evaluate the dual encoder model, we use the captions as queries. We use the out-of-training-sample images and captions to evaluate the retrieval quality, using top k accuracy. A true prediction is counted if, for a given caption, its associated image is retrieved within the top k matches. ```python def compute_top_k_accuracy(image_paths, k=100): hits = 0 num_batches = int(np.ceil(len(image_paths) / batch_size)) for idx in tqdm(range(num_batches)): start_idx = idx * batch_size end_idx = start_idx + batch_size current_image_paths = image_paths[start_idx:end_idx] queries = [ image_path_to_caption[image_path][0] for image_path in current_image_paths ] result = find_matches(image_embeddings, queries, k) hits += sum( [ image_path in matches for (image_path, matches) in list(zip(current_image_paths, result)) ] ) return hits / len(image_paths) print("Scoring training data...") train_accuracy = compute_top_k_accuracy(train_image_paths) print(f"Train accuracy: {round(train_accuracy * 100, 3)}%") print("Scoring evaluation data...") eval_accuracy = compute_top_k_accuracy(image_paths[train_size:]) print(f"Eval accuracy: {round(eval_accuracy * 100, 3)}%") ``` <div class="k-default-codeblock"> ``` 0%| | 0/118 [00:00<?, ?it/s] Scoring training data... 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 118/118 [04:12<00:00, 2.14s/it] 0%| | 0/207 [00:00<?, ?it/s] Train accuracy: 13.373% Scoring evaluation data... 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 207/207 [07:23<00:00, 2.14s/it] Eval accuracy: 6.235% ``` </div> --- ## Final remarks You can obtain better results by increasing the size of the training sample, train for more epochs, explore other base encoders for images and text, set the base encoders to be trainable, and tune the hyperparameters, especially the `temperature` for the softmax in the loss computation.
517032cb18b2083471406fdf08c58fa977f919ff
{ "blob_id": "517032cb18b2083471406fdf08c58fa977f919ff", "branch_name": "refs/heads/master", "committer_date": "2021-08-24T11:49:51", "content_id": "30d53f43cff22994719e6dfdf462abfedff57748", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e7fd342b77b6d6be7a773589d53b590616f36e9d", "extension": "md", "filename": "nl_image_search.md", "fork_events_count": 0, "gha_created_at": "2021-08-24T11:46:03", "gha_event_created_at": "2021-08-24T11:46:03", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 399444427, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26130, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/nlp/md/nl_image_search.md", "provenance": "stack-edu-markdown-0012.json.gz:261431", "repo_name": "amshrbo/keras-io", "revision_date": "2021-08-24T11:49:51", "revision_id": "4686c217ada75abeb95cdc40916ffd50605d152e", "snapshot_id": "2fb32901f57f1e9556dd4818ad648b20d8528dde", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/amshrbo/keras-io/4686c217ada75abeb95cdc40916ffd50605d152e/examples/nlp/md/nl_image_search.md", "visit_date": "2023-07-09T15:42:55.784388", "added": "2024-11-18T22:20:28.699164+00:00", "created": "2021-08-24T11:49:51", "int_score": 4, "score": 3.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz" }
# Kernel A kernel represents the app itself. It consists of modular pieces called subsystems, responsible for different functionalities of the app. ## `create(subsystems, initData, [config])` Creates an app kernel using a given array of subsystems, initial structure of the app and an optional configuration. ### Usage ```javascript import { Kernel, defaultSubsystems } from '@skele/classic' import navigationSubsystem from './customSubsystems/navigation' const initData = { kind: 'app' } Kernel.create([...defaultSubsystems, navigationSubsystem], initData) ```
137c4c60db2460f6a682c7f2f1870d41ed563db3
{ "blob_id": "137c4c60db2460f6a682c7f2f1870d41ed563db3", "branch_name": "refs/heads/master", "committer_date": "2019-10-07T05:41:01", "content_id": "1abe69492784fd4a67f1d7229e2f0ad9839a9c17", "detected_licenses": [ "MIT" ], "directory_id": "1c8fac3d0fb5279f9328a2a906f08eff8148901f", "extension": "md", "filename": "kernel.md", "fork_events_count": 0, "gha_created_at": "2018-10-16T10:30:00", "gha_event_created_at": "2019-10-07T05:41:02", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 153267385, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 569, "license": "MIT", "license_type": "permissive", "path": "/packages/classic/docs/api/kernel.md", "provenance": "stack-edu-markdown-0007.json.gz:229491", "repo_name": "smartkarma/skele", "revision_date": "2019-10-07T05:41:01", "revision_id": "17301d905b654ca286e7c4a04bec156528f718d2", "snapshot_id": "6ad2fe9ec7421e850d4873fa96486ee68d2b8be2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/smartkarma/skele/17301d905b654ca286e7c4a04bec156528f718d2/packages/classic/docs/api/kernel.md", "visit_date": "2020-04-01T13:47:42.578062", "added": "2024-11-18T23:32:57.090367+00:00", "created": "2019-10-07T05:41:01", "int_score": 3, "score": 3.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
# Reading schema # --- !Ups CREATE TABLE Reading ( id bigint(20) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, targetTempC double NOT NULL, postcode varchar(20) NOT NULL, country varchar(20) NOT NULL, externalTempC double NOT NULL, PRIMARY KEY (id) ); # --- !Downs DROP TABLE Reading;
65b64fb8b21880a5ff083a993653b45930c8b66b
{ "blob_id": "65b64fb8b21880a5ff083a993653b45930c8b66b", "branch_name": "refs/heads/master", "committer_date": "2015-06-06T12:07:39", "content_id": "76d0d31d72aace36e3f5ad020b215983c61aee58", "detected_licenses": [ "Apache-2.0" ], "directory_id": "880a1e2e0c00b68960c65a6cc3e23846cdff69a8", "extension": "sql", "filename": "1.sql", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 36646245, "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 323, "license": "Apache-2.0", "license_type": "permissive", "path": "/conf/evolutions/default/1.sql", "provenance": "stack-edu-0070.json.gz:554588", "repo_name": "kevinpetersavage/leaky-houses", "revision_date": "2015-06-06T12:07:39", "revision_id": "3b7e224c7558a3e7cb0d6405ea0a93ffa7a1069f", "snapshot_id": "f147b2b03ab6b17ab6f8219e1fbe0b62416a4b61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kevinpetersavage/leaky-houses/3b7e224c7558a3e7cb0d6405ea0a93ffa7a1069f/conf/evolutions/default/1.sql", "visit_date": "2021-01-10T08:23:29.382174", "added": "2024-11-18T19:39:30.327310+00:00", "created": "2015-06-06T12:07:39", "int_score": 3, "score": 2.90625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
package com.wvkity.mybatis.spring.boot.data.auditing.config; import com.wvkity.mybatis.core.data.auditing.AuditorAware; /** * 审计注解配置 * @author wvkity */ public interface AuditingConfiguration { /** * 是否开启保存审计 * @return true: 是 false: 否 */ boolean enableInserted(); /** * 是否开启更新审计 * @return true: 是 false: 否 */ boolean enableModified(); /** * 是否开启删除审计 * @return true: 是 false: 否 */ boolean enableDeleted(); /** * {@link AuditorAware}实例名 * @return {@link AuditorAware}实例名 */ String getAuditorAwareRef(); }
c4b9abe222fd6dced149c69effb061cba8edc2a4
{ "blob_id": "c4b9abe222fd6dced149c69effb061cba8edc2a4", "branch_name": "refs/heads/master", "committer_date": "2020-05-24T06:24:20", "content_id": "c246b9b9d93530da3f8c70c02f15c7ed24e36834", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3a2113ba18b25c3a53eb0c268e6608afa156ea45", "extension": "java", "filename": "AuditingConfiguration.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": 689, "license": "Apache-2.0", "license_type": "permissive", "path": "/mybatis-spring-boot-starter/src/main/java/com/wvkity/mybatis/spring/boot/data/auditing/config/AuditingConfiguration.java", "provenance": "stack-edu-0020.json.gz:450663", "repo_name": "phial3/mybatis-ext", "revision_date": "2020-05-24T06:24:20", "revision_id": "c448d029ac641997528d21f17f4f7936be050550", "snapshot_id": "074cc5d939a0aaa782782f098f819d28842a1460", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/phial3/mybatis-ext/c448d029ac641997528d21f17f4f7936be050550/mybatis-spring-boot-starter/src/main/java/com/wvkity/mybatis/spring/boot/data/auditing/config/AuditingConfiguration.java", "visit_date": "2022-12-19T01:37:05.140760", "added": "2024-11-18T21:39:26.720501+00:00", "created": "2020-05-24T06:24:20", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
// Copyright (c) 2019, Paul Ferrand // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <benchmark/benchmark.h> #include <random> #include <numeric> #include <vector> #include <cmath> #include <iostream> #include "../sfizz/SIMDHelpers.h" #include "../sfizz/Config.h" #include "absl/types/span.h" class PanArray : public benchmark::Fixture { public: void SetUp(const ::benchmark::State& state) { std::random_device rd { }; std::mt19937 gen { rd() }; std::uniform_real_distribution<float> dist { 0.001, 1 }; pan = std::vector<float>(state.range(0)); left = std::vector<float>(state.range(0)); right = std::vector<float>(state.range(0)); std::generate(pan.begin(), pan.end(), [&]() { return dist(gen); }); std::generate(right.begin(), right.end(), [&]() { return dist(gen); }); std::generate(left.begin(), left.end(), [&]() { return dist(gen); }); temp1 = std::vector<float>(state.range(0)); temp2 = std::vector<float>(state.range(0)); span1 = absl::MakeSpan(temp1); span2 = absl::MakeSpan(temp2); } void TearDown(const ::benchmark::State& state [[maybe_unused]]) { } std::vector<float> pan; std::vector<float> left; std::vector<float> right; std::vector<float> temp1; std::vector<float> temp2; absl::Span<float> span1; absl::Span<float> span2; }; BENCHMARK_DEFINE_F(PanArray, Scalar)(benchmark::State& state) { for (auto _ : state) { sfz::pan<float, false>(pan, absl::MakeSpan(left), absl::MakeSpan(right)); } } BENCHMARK_DEFINE_F(PanArray, SIMD)(benchmark::State& state) { for (auto _ : state) { sfz::pan<float, true>(pan, absl::MakeSpan(left), absl::MakeSpan(right)); } } BENCHMARK_DEFINE_F(PanArray, BlockOps)(benchmark::State& state) { for (auto _ : state) { sfz::fill<float>(span2, 1.0f); sfz::add<float>(span1, span2); sfz::applyGain<float>(piFour<float>, span2); sfz::cos<float>(span2, span1); sfz::sin<float>(span2, span2); sfz::applyGain<float>(span1, absl::MakeSpan(left)); sfz::applyGain<float>(span2, absl::MakeSpan(right)); } } BENCHMARK_REGISTER_F(PanArray, Scalar)->RangeMultiplier(4)->Range(1 << 2, 1 << 12); BENCHMARK_REGISTER_F(PanArray, SIMD)->RangeMultiplier(4)->Range(1 << 2, 1 << 12); BENCHMARK_REGISTER_F(PanArray, BlockOps)->RangeMultiplier(4)->Range(1 << 2, 1 << 12); BENCHMARK_MAIN();
722cb14f356de1b86f0b4a4472d05d53f2939d0e
{ "blob_id": "722cb14f356de1b86f0b4a4472d05d53f2939d0e", "branch_name": "refs/heads/master", "committer_date": "2019-12-24T20:50:59", "content_id": "5792b476a28aaf10331a26e50b017b45dd4b60ee", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ee87c773e2ad9bcc7bbcf9c19df41fb566f9eac5", "extension": "cpp", "filename": "BM_pan.cpp", "fork_events_count": 0, "gha_created_at": "2019-12-29T20:37:31", "gha_event_created_at": "2020-10-13T17:36:47", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 230800696, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3676, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/benchmarks/BM_pan.cpp", "provenance": "stack-edu-0009.json.gz:12436", "repo_name": "jpcima/sfizz", "revision_date": "2019-12-24T20:50:59", "revision_id": "09526938ab011d8800a4921109b783307ab11615", "snapshot_id": "ab3aad16071dd73277a149626f0a1f1b7bd3764e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/jpcima/sfizz/09526938ab011d8800a4921109b783307ab11615/benchmarks/BM_pan.cpp", "visit_date": "2021-11-27T07:50:37.890909", "added": "2024-11-18T20:52:54.317483+00:00", "created": "2019-12-24T20:50:59", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
package com.example.hog; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by Nitin Khurana on 10/12/18. * * A {@link RecyclerView.Adapter} that loads items containing a single {@link TextView} * in the {@link RecyclerView}, such that whenever the user scrolls the {@link RecyclerView} * this adapter will highlight the middle item that's on the screen * */ public class NumbersAdapter extends RecyclerView.Adapter<NumbersAdapter.MyHolder> { // private final String TAG = getClass().getSimpleName(); /** * Will hold the context of the {@link android.app.Activity} in which this adapter will be set to a {@link RecyclerView} */ private Context context; /** * The number of items to be inflated in the {@link RecyclerView} */ private int itemCount; /** * Will contain all the physical items in the recycler view */ private List<MyHolder> holders = new ArrayList<>(); /** * Initialize the {@link RecyclerView} with the number of items passed in the constructor * @param context the context of the activity * @param count the number of items that the {@link RecyclerView} will contain */ NumbersAdapter(Context context, int count){ this.context = context; this.itemCount = count; } @Override public void onAttachedToRecyclerView(@NonNull final RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); // Highlight Logic Begins here final int itemHeight = context.getResources().getDimensionPixelOffset(R.dimen.item_height); // height of each item recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int top = recyclerView.computeVerticalScrollOffset() / itemHeight; // get the current top item index int rv_center = recyclerView.getHeight() / 2; // center position of the recycler view in pixels int itemsInTopHalf = rv_center / itemHeight; // the number of items in the top half of the recycler view int midPos = top + itemsInTopHalf; // middle item = top item + number of items in top half MyHolder holder = (MyHolder) recyclerView.findViewHolderForAdapterPosition(midPos); // get the view holder at middle position if (holder != null){ for (MyHolder holder1 : holders){ holder1.highLight(false); // unhighlight all the items } holder.highLight(true); // highlight the middle item } } }); // Highlight Logic Ends here } @NonNull @Override public NumbersAdapter.MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { MyHolder holder = new MyHolder(LayoutInflater.from(context).inflate(R.layout.item_numbers, viewGroup, false), context); holders.add(holder); return holder; } @Override public void onBindViewHolder(@NonNull NumbersAdapter.MyHolder viewHolder , int i) { // set item number as text to the item's TextView viewHolder.setText(Integer.toString(i)); } @Override public int getItemCount() { return itemCount; } /** * Class that contains all the views inside an item in the {@link RecyclerView} */ public class MyHolder extends RecyclerView.ViewHolder { private TextView textView; /** * The color to be highlighted with */ int highlightColor; MyHolder(@NonNull View itemView, Context context) { super(itemView); textView = itemView.findViewById(R.id.textView); highlightColor = context.getResources().getColor(R.color.colorAccent); } /** * Set the text of the {@link TextView} in the view holder * @param text the text to be set to the {@code textView} */ public void setText(String text){ if (text != null) { this.textView.setText(text); } } /** * Highlight the current item * @param highLight true to highlight, false to unhighlight */ void highLight(boolean highLight){ itemView.setBackgroundColor(highLight ? highlightColor : Color.TRANSPARENT); } } }
0423278f64024fc6135e4ec5f2535a1d035d3867
{ "blob_id": "0423278f64024fc6135e4ec5f2535a1d035d3867", "branch_name": "refs/heads/master", "committer_date": "2018-12-10T13:32:25", "content_id": "cae6d09aa6b08ac82d67ecf0ed32134e64869739", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e96ea290a93361e17b4633ab6aa79a4ba9c992e0", "extension": "java", "filename": "NumbersAdapter.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 161177534, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5126, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/src/main/java/com/example/hog/NumbersAdapter.java", "provenance": "stack-edu-0025.json.gz:178572", "repo_name": "nitin070895a/MiddlePointingRecyclerView", "revision_date": "2018-12-10T13:32:25", "revision_id": "f0b42bc7f06c47533f0205e9a55ef44de8a38cbd", "snapshot_id": "bee6058eb29137d2be68de16723e88741be9603f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nitin070895a/MiddlePointingRecyclerView/f0b42bc7f06c47533f0205e9a55ef44de8a38cbd/app/src/main/java/com/example/hog/NumbersAdapter.java", "visit_date": "2020-04-10T17:33:45.085967", "added": "2024-11-18T20:30:58.953246+00:00", "created": "2018-12-10T13:32:25", "int_score": 3, "score": 2.828125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
using System; using System.Collections.Generic; using System.Linq; namespace p04_Hospital { class Program { static void Main(string[] args) { Dictionary<string, List<string>> departments = new Dictionary<string, List<string>>(); Dictionary<string, List<string>> doctors = new Dictionary<string, List<string>>(); string input; while ((input = Console.ReadLine()) != "Output") { List<string> tokens = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList(); string department = tokens[0]; string doctorFullname = $"{tokens[1]} {tokens[2]}"; string patient = tokens[3]; if (!departments.ContainsKey(department)) { departments.Add(department, new List<string>()); } if (departments[department].Count < 60) { departments[department].Add(patient); } if (!doctors.ContainsKey(doctorFullname)) { doctors.Add(doctorFullname, new List<string>()); } doctors[doctorFullname].Add(patient); } string commandsArgs; while ((commandsArgs = Console.ReadLine()) != "End") { var inputCommand = commandsArgs.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (inputCommand.Count == 1) { PrintDepartmentPatients(inputCommand[0], departments); } else { if (int.TryParse(inputCommand[1], out int number)) { int skipPatients = (int.Parse(inputCommand[1]) - 1) * 3; PrintPatientsByRoom(skipPatients, inputCommand[0], departments); } else { string doctorName = inputCommand[0] + " " + inputCommand[1]; PrintDoctorPatients(doctorName, doctors); } } } } private static void PrintPatientsByRoom(int skipPatients, string department, Dictionary<string, List<string>> departments) { foreach (var patient in departments[department].Skip(skipPatients).Take(3).OrderBy(p => p)) { Console.WriteLine(patient); } } private static void PrintDoctorPatients(string doctorName, Dictionary<string, List<string>> doctors) { foreach (var patient in doctors[doctorName].OrderBy(p => p)) { Console.WriteLine(patient); } } private static void PrintDepartmentPatients(string department, Dictionary<string, List<string>> departments) { foreach (var patient in departments[department]) { Console.WriteLine(patient); } } } }
d28849ca9861fe4fafbcb08976588606c41d3341
{ "blob_id": "d28849ca9861fe4fafbcb08976588606c41d3341", "branch_name": "refs/heads/master", "committer_date": "2018-02-09T16:13:32", "content_id": "165746a2dfafb761f7ad89089b1a5a096cf498fe", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6b49f9f3067888d80cb83b15f32aa17287b124aa", "extension": "cs", "filename": "Program.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120817690, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3152, "license": "Apache-2.0", "license_type": "permissive", "path": "/05_ExamPreparation-I/p04_Hospital/Program.cs", "provenance": "stack-edu-0010.json.gz:648620", "repo_name": "svetliub/Softuni-CSharp-Advanced", "revision_date": "2018-02-09T16:13:32", "revision_id": "e51197587cf689402bae06213444d702a56d9dd8", "snapshot_id": "ad7d7fd80143371187fa72d5b0abffc278822e73", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/svetliub/Softuni-CSharp-Advanced/e51197587cf689402bae06213444d702a56d9dd8/05_ExamPreparation-I/p04_Hospital/Program.cs", "visit_date": "2021-05-02T09:09:16.005479", "added": "2024-11-19T00:51:31.059414+00:00", "created": "2018-02-09T16:13:32", "int_score": 3, "score": 3.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Dell Technologies """ CHAP config operations""" from PyPowerStore import powerstore_conn CONN = powerstore_conn.PowerStoreConn(username="<username>", password="<password>", server_ip="<IP>", verify=False, application_type="<Application>", timeout=180.0) print(CONN) # Get chap config list chap_configs_list = CONN.config_mgmt.get_chap_configs() print(chap_configs_list) # Get chap config details chap_config_details = CONN.config_mgmt.get_chap_config_details(chap_config_id=chap_configs_list[0]['id']) print(chap_config_details) # Modify chap config updated_chap_config_details = CONN.config_mgmt.modify_chap_config(chap_config_id=chap_configs_list[0]['id'], mode='Disabled') print(updated_chap_config_details)
2e0abbdd90fa5a226c003e2d9801784d70e4b356
{ "blob_id": "2e0abbdd90fa5a226c003e2d9801784d70e4b356", "branch_name": "refs/heads/main", "committer_date": "2023-06-28T11:26:48", "content_id": "49cddeaebb5395c478a48f8aad8c874f3f76e3ec", "detected_licenses": [ "Apache-2.0" ], "directory_id": "15c9b1e32b36c7ae2a6abd69f04d7cf3f58d9d1a", "extension": "py", "filename": "chap_config_examples.py", "fork_events_count": 7, "gha_created_at": "2020-05-06T11:30:38", "gha_event_created_at": "2023-06-28T11:26:50", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 261738648, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license": "Apache-2.0", "license_type": "permissive", "path": "/ProgrammersGuideExamples/chap_config_examples.py", "provenance": "stack-edu-0056.json.gz:39523", "repo_name": "dell/python-powerstore", "revision_date": "2023-06-28T11:26:48", "revision_id": "f9e3bcee6be231d4565812231ebdf4058ebe4c04", "snapshot_id": "2907c9d4059ca58cc57ac72670048da400b6bdf7", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/dell/python-powerstore/f9e3bcee6be231d4565812231ebdf4058ebe4c04/ProgrammersGuideExamples/chap_config_examples.py", "visit_date": "2023-07-21T21:42:13.315837", "added": "2024-11-19T01:06:05.187541+00:00", "created": "2023-06-28T11:26:48", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
/** * (C) Copyright 2020-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ #ifndef __TELEMETRY_CONSUMER_H__ #define __TELEMETRY_CONSUMER_H__ #include <gurt/telemetry_common.h> /* Developer facing client API to read data */ char *d_tm_get_name(struct d_tm_context *ctx, struct d_tm_node_t *node); int d_tm_get_counter(struct d_tm_context *ctx, uint64_t *val, struct d_tm_node_t *node); int d_tm_get_timestamp(struct d_tm_context *ctx, time_t *val, struct d_tm_node_t *node); int d_tm_get_timer_snapshot(struct d_tm_context *ctx, struct timespec *tms, struct d_tm_node_t *node); int d_tm_get_gauge(struct d_tm_context *ctx, uint64_t *val, struct d_tm_stats_t *stats, struct d_tm_node_t *node); int d_tm_get_duration(struct d_tm_context *ctx, struct timespec *tms, struct d_tm_stats_t *stats, struct d_tm_node_t *node); int d_tm_get_metadata(struct d_tm_context *ctx, char **desc, char **units, struct d_tm_node_t *node); int d_tm_get_num_buckets(struct d_tm_context *ctx, struct d_tm_histogram_t *histogram, struct d_tm_node_t *node); int d_tm_get_bucket_range(struct d_tm_context *ctx, struct d_tm_bucket_t *bucket, int bucket_id, struct d_tm_node_t *node); /* Developer facing client API to discover topology and manage results */ struct d_tm_context *d_tm_open(int id); void d_tm_close(struct d_tm_context **ctx); void d_tm_gc_ctx(struct d_tm_context *ctx); void *d_tm_conv_ptr(struct d_tm_context *ctx, struct d_tm_node_t *node, void *ptr); struct d_tm_node_t *d_tm_get_root(struct d_tm_context *ctx); struct d_tm_node_t *d_tm_get_child(struct d_tm_context *ctx, struct d_tm_node_t *node); struct d_tm_node_t *d_tm_get_sibling(struct d_tm_context *ctx, struct d_tm_node_t *node); struct d_tm_node_t *d_tm_find_metric(struct d_tm_context *ctx, char *path); uint64_t d_tm_count_metrics(struct d_tm_context *ctx, struct d_tm_node_t *node, int d_tm_type); int d_tm_list(struct d_tm_context *ctx, struct d_tm_nodeList_t **head, struct d_tm_node_t *node, int d_tm_type); int d_tm_list_subdirs(struct d_tm_context *ctx, struct d_tm_nodeList_t **head, struct d_tm_node_t *node, uint64_t *node_count, int max_depth); void d_tm_iterate(struct d_tm_context *ctx, struct d_tm_node_t *node, int level, int filter, char *path, int format, int opt_fields, uint32_t ops, FILE *stream); void d_tm_print_node(struct d_tm_context *ctx, struct d_tm_node_t *node, int level, char *name, int format, int opt_fields, FILE *stream); void d_tm_print_field_descriptors(int opt_fields, FILE *stream); void d_tm_print_counter(uint64_t val, char *name, int format, char *units, int opt_fields, FILE *stream); void d_tm_print_timestamp(time_t *clk, char *name, int format, int opt_fields, FILE *stream); void d_tm_print_timer_snapshot(struct timespec *tms, char *name, int tm_type, int format, int opt_fields, FILE *stream); void d_tm_print_duration(struct timespec *tms, struct d_tm_stats_t *stats, char *name, int tm_type, int format, int opt_fields, FILE *stream); void d_tm_print_gauge(uint64_t val, struct d_tm_stats_t *stats, char *name, int format, char *units, int opt_fields, FILE *stream); void d_tm_print_metadata(char *desc, char *units, int format, FILE *stream); int d_tm_clock_id(int clk_id); char *d_tm_clock_string(int clk_id); #endif /* __TELEMETRY_CONSUMER_H__ */
e0b498fc271dc55233d03155964804a3c4f1b5b4
{ "blob_id": "e0b498fc271dc55233d03155964804a3c4f1b5b4", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T16:38:00", "content_id": "f0b1d706be718df7cbd62e82574e0d09a2a21e18", "detected_licenses": [ "BSD-2-Clause", "BSD-2-Clause-Patent" ], "directory_id": "1efd2de8bf77ec00eb2fcaf5749278495946d920", "extension": "h", "filename": "telemetry_consumer.h", "fork_events_count": 300, "gha_created_at": "2016-09-27T19:21:29", "gha_event_created_at": "2023-09-14T18:55:15", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 69390670, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3467, "license": "BSD-2-Clause,BSD-2-Clause-Patent", "license_type": "permissive", "path": "/src/include/gurt/telemetry_consumer.h", "provenance": "stack-edu-0000.json.gz:483000", "repo_name": "daos-stack/daos", "revision_date": "2023-08-31T16:38:00", "revision_id": "ed5eed5df43a68571afe123132a743824c02637a", "snapshot_id": "6f55bf3061fd830d5b8d28506e1295e2d3a27c38", "src_encoding": "UTF-8", "star_events_count": 631, "url": "https://raw.githubusercontent.com/daos-stack/daos/ed5eed5df43a68571afe123132a743824c02637a/src/include/gurt/telemetry_consumer.h", "visit_date": "2023-08-31T21:43:37.606145", "added": "2024-11-18T23:51:33.615519+00:00", "created": "2023-08-31T16:38:00", "int_score": 2, "score": 2, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
#!/usr/bin/env python3 # coding: utf-8 __version__='0.0.1' symb = u"\u26A0" import sys sys.dont_write_bytecode = True import logging logstream = sys.stdout logfile = False logger = None from GeneTree.timer import Timer from GeneTree import create_tree from GeneTree import matrice from GeneTree import clean_name from GeneTree import cli class MyFormatter(logging.Formatter): info_fmt = '> %(msg)s' dbg_fmt = 'DEBUG: %(module)s: %(lineno)d: %(msg)s' crit_fmt = '# CRITICAL: %(msg)s' warn_fmt = f'{symb} Warning: %(msg)s' def __init__(self, fmt='%(levelno)s: %(msg)s'): super().__init__(fmt, datefmt=None, style='%') def format(self, record): orig = self._style._fmt if record.levelno == logging.DEBUG: self._style._fmt = MyFormatter.dbg_fmt elif record.levelno == logging.INFO: self._style._fmt = MyFormatter.info_fmt elif record.levelno == logging.CRITICAL: self._style._fmt = MyFormatter.crit_fmt elif record.levelno == logging.WARNING: self._style._fmt = MyFormatter.warn_fmt res = logging.Formatter.format(self, record) self._style._fmt = orig return res def setup_logger(name, log_s, log_f): l = logging.getLogger(name) l.setLevel(logging.DEBUG) formatter = MyFormatter() if log_f: fileHandler = logging.FileHandler(log_f, mode="w") fileHandler.setFormatter(formatter) l.addHandler(fileHandler) if log_s: streamHandler = logging.StreamHandler(logstream) streamHandler.setFormatter(formatter) l.addHandler(streamHandler) def info(msg: str) -> None: logger.info(msg) def warn(msg: str) -> None: logger.warning(msg) def crit(msg: str, code: int) -> None: logger.critical(msg) sys.exit(code) def err(msg: str) -> None: logger.error(msg)
4c97b1c4a366c9e6eaffe65c95afb7069b13c231
{ "blob_id": "4c97b1c4a366c9e6eaffe65c95afb7069b13c231", "branch_name": "refs/heads/master", "committer_date": "2021-08-18T15:11:22", "content_id": "257581965694c1e0fe7c80e7bae5fc711bfc4f6c", "detected_licenses": [ "MIT" ], "directory_id": "6c5125625b908a683070fa2db704275ab8bd8444", "extension": "py", "filename": "__init__.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 282912700, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1908, "license": "MIT", "license_type": "permissive", "path": "/GeneTree/__init__.py", "provenance": "stack-edu-0062.json.gz:598262", "repo_name": "gsiekaniec/GeneTree", "revision_date": "2021-08-18T15:11:22", "revision_id": "a098a64117dbe8ebd6d84c3fdd184df9f93f5480", "snapshot_id": "fde87226adb84ef35fee010328429fd34db5491c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gsiekaniec/GeneTree/a098a64117dbe8ebd6d84c3fdd184df9f93f5480/GeneTree/__init__.py", "visit_date": "2023-07-20T03:49:29.362901", "added": "2024-11-18T21:14:32.054463+00:00", "created": "2021-08-18T15:11:22", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Expression formula(string $expression) */ class Expression extends WizardAbstract implements WizardInterface { /** * @var string */ protected $expression; public function __construct(string $cellRange) { parent::__construct($cellRange); } public function expression(string $expression): self { $expression = $this->validateOperand($expression, Wizard::VALUE_TYPE_FORMULA); $this->expression = $expression; return $this; } public function getConditional(): Conditional { $expression = $this->adjustConditionsForCellReferences([$this->expression]); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_EXPRESSION); $conditional->setConditions($expression); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_EXPRESSION) { throw new Exception('Conditional is not an Expression CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->expression = self::reverseAdjustCellRef((string) ($conditional->getConditions()[0]), $cellRange); return $wizard; } /** * @param string $methodName * @param mixed[] $arguments */ public function __call($methodName, $arguments): self { if ($methodName !== 'formula') { throw new Exception('Invalid Operation for Expression CF Rule Wizard'); } // Scrutinizer ignores its own recommendation //$this->expression(/** @scrutinizer ignore-type */ ...$arguments); $this->expression($arguments[0]); return $this; } }
4cda88112457e17f1818ee401eb8b039822ff8c2
{ "blob_id": "4cda88112457e17f1818ee401eb8b039822ff8c2", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T01:46:02", "content_id": "e6d29f7be9b17bb92c33918e024e2f131a3fc537", "detected_licenses": [ "MIT" ], "directory_id": "7a3d640158101168494a319ac27696033d5aa5c2", "extension": "php", "filename": "Expression.php", "fork_events_count": 3722, "gha_created_at": "2016-06-19T16:58:48", "gha_event_created_at": "2023-09-14T14:49:51", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 61490598, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2295, "license": "MIT", "license_type": "permissive", "path": "/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php", "provenance": "stack-edu-0050.json.gz:226619", "repo_name": "PHPOffice/PhpSpreadsheet", "revision_date": "2023-08-30T16:36:28", "revision_id": "6edc552013d9e20438dd8bcf4b259887ebf81795", "snapshot_id": "cd2a6aa46248f4d07b8e6eb5b386f064eb659faa", "src_encoding": "UTF-8", "star_events_count": 13089, "url": "https://raw.githubusercontent.com/PHPOffice/PhpSpreadsheet/6edc552013d9e20438dd8bcf4b259887ebf81795/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php", "visit_date": "2023-09-01T11:39:05.605583", "added": "2024-11-18T23:55:27.974798+00:00", "created": "2023-08-30T16:36:28", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
import React from "react"; import Joi from "joi-browser"; import pic from "./logo.jpg"; import Form from "./common/form.jsx"; import Logo from "./logo.jsx"; import TaskList from "./taskList.jsx"; import "./login.css"; import { Route } from "react-router-dom"; import { login, checkSession } from "../services/authService"; class Login extends Form { state = { data: { username: "", password: "", }, errors: {}, }; schema = { username: Joi.string().required().label("Username"), password: Joi.string().required().label("Password"), }; doSubmit = async () => { //call the server // await // await checkSession() try { console.log("do submit"); let res = await login(this.state.data.username, this.state.data.password); console.log("res: ", res); console.log(res.status == 200); console.log("res: ", res.body); if (res.status == 200) { let member = await res.json(); console.log("member"); console.log(member); localStorage.setItem("memberId", member._id); localStorage.setItem("teamId", member.teamId); localStorage.setItem("companyId", member.companyId); localStorage.setItem("rank", member.rank); this.props.history.push("/taskList"); } // checkSession(); } catch (error) { console.log(error); } }; componentDidMount() { } render() { return ( <div className="row"> {/* placeholder for logo */} <div className="col"> <Logo Logo={pic} /> </div> <div className="col-5"> <h1>Welcome to Devflow</h1> <form onSubmit={this.handleSubmit}> {this.renderInput("username", "Username", "text")} {this.renderInput("password", "Password", "password")} <br></br> {this.renderButton("submit", "Login")}{" "} {this.renderButton("button", "Forget Password")} </form> <br></br> <a href="./register" className="btn btn-primary btn-lg " tabIndex="-1" role="button" aria-disabled="false" > Register </a> </div> <div className="col-1"></div> </div> ); } } export default Login;
ed734a149eab2f9575961eebd6f5ea3710b12583
{ "blob_id": "ed734a149eab2f9575961eebd6f5ea3710b12583", "branch_name": "refs/heads/master", "committer_date": "2021-07-23T11:02:04", "content_id": "354f97eebedbdf501c8374ec5d6c26e3bfcd81b1", "detected_licenses": [ "MIT" ], "directory_id": "d446a04b044b2c395b552e066bd5a430d312e2fb", "extension": "jsx", "filename": "login.jsx", "fork_events_count": 0, "gha_created_at": "2020-10-20T17:54:36", "gha_event_created_at": "2020-11-30T02:36:10", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 305790629, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2335, "license": "MIT", "license_type": "permissive", "path": "/devflow/src/components/login.jsx", "provenance": "stack-edu-0033.json.gz:187422", "repo_name": "troyyxk/devflow", "revision_date": "2021-07-23T11:02:04", "revision_id": "8f2170c74e4f05f2fc7ef471a11598c0bced70ea", "snapshot_id": "4799c468be2010de65d809b0b816a92fcf61324b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/troyyxk/devflow/8f2170c74e4f05f2fc7ef471a11598c0bced70ea/devflow/src/components/login.jsx", "visit_date": "2023-06-28T22:35:34.762418", "added": "2024-11-18T22:29:25.175415+00:00", "created": "2021-07-23T11:02:04", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
 #include <iostream> #include <mutex> #include "RingBuffer.hpp" RingBuffer::AlignedAllocator alloc; int main() { std::mutex mtx; std::condition_variable cond; std::atomic<int> finished(0); auto cosumeList = std::initializer_list<RingBuffer::Int>({1}); auto ringBuf = RingBuffer::CreateRingBuffer<int, RingBuffer::SingleProducer>(128, &alloc, cosumeList); std::thread t1{ [&] { auto& pdr = ringBuf.GetProducer(); for (int i = 0; i < 10000; i++) { ringBuf.Produce(i); } finished.fetch_add(1); cond.notify_all(); } }; std::thread t2{ [&] { auto csm = ringBuf.GetConsumer(); int n = 0; while (n < 9999) { csm.GetNext(n); } finished.fetch_add(1); cond.notify_all(); } }; t1.detach(); t2.detach(); std::unique_lock<std::mutex> lock{ mtx }; cond.wait(lock, [&] { return finished >= 2; }); std::cout << "Test OK!\n"; }
befa4e6063356baf124d9ba211e40522807ad9b6
{ "blob_id": "befa4e6063356baf124d9ba211e40522807ad9b6", "branch_name": "refs/heads/master", "committer_date": "2020-09-21T04:24:57", "content_id": "3cdeeb60cb7d6f9618acd4373a32fe58e73cb63a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a24712a6ca2515ab842f2cb215ddfc00b1415709", "extension": "cpp", "filename": "TestRingBuffer.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 297226549, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1004, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/TestRingBuffer.cpp", "provenance": "stack-edu-0003.json.gz:453068", "repo_name": "daipech/MiniRingBuffer", "revision_date": "2020-09-21T04:24:57", "revision_id": "26e4ea1cdfa38ef36da5fb9db7facf2de5982773", "snapshot_id": "245dc24f169cbca7ce6b9d15d6db66cbc91c8430", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daipech/MiniRingBuffer/26e4ea1cdfa38ef36da5fb9db7facf2de5982773/TestRingBuffer.cpp", "visit_date": "2022-12-17T14:34:29.747960", "added": "2024-11-18T21:48:21.307450+00:00", "created": "2020-09-21T04:24:57", "int_score": 3, "score": 2.828125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
### [CVE-2013-5961](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-5961) ![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue) ![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue) ![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen) ### Description Unrestricted file upload vulnerability in lazyseo.php in the Lazy SEO plugin 1.1.9 for WordPress allows remote attackers to execute arbitrary PHP code by uploading a PHP file, then accessing it via a direct request to the file in lazy-seo/. ### POC #### Reference - http://packetstormsecurity.com/files/123349 #### Github No PoCs found on GitHub currently.
54235a91109ed3751d549756ab04f0cef659320d
{ "blob_id": "54235a91109ed3751d549756ab04f0cef659320d", "branch_name": "refs/heads/main", "committer_date": "2023-08-22T10:57:28", "content_id": "7943bb4a907ba804b335893fe1265bfdd15547b2", "detected_licenses": [ "MIT" ], "directory_id": "9b96a77fdd7eeba74a3d66d09eb8ebbf28b7b8b9", "extension": "md", "filename": "CVE-2013-5961.md", "fork_events_count": 647, "gha_created_at": "2022-01-31T13:23:51", "gha_event_created_at": "2023-05-24T04:54:19", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 454015416, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 704, "license": "MIT", "license_type": "permissive", "path": "/2013/CVE-2013-5961.md", "provenance": "stack-edu-markdown-0017.json.gz:61501", "repo_name": "trickest/cve", "revision_date": "2023-08-22T10:57:28", "revision_id": "193d43877d4d88120833461ebab51acc2e5e37f0", "snapshot_id": "2d5fdbb47e0baf6ce74e016190dec666cdfd9bfe", "src_encoding": "UTF-8", "star_events_count": 5091, "url": "https://raw.githubusercontent.com/trickest/cve/193d43877d4d88120833461ebab51acc2e5e37f0/2013/CVE-2013-5961.md", "visit_date": "2023-08-22T19:53:39.850122", "added": "2024-11-18T22:33:34.250130+00:00", "created": "2023-08-22T10:57:28", "int_score": 3, "score": 3.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0017.json.gz" }
package com.apress.prospring5.ch3; //The instantiation of the abstract class is supported only when using Lookup Method Injection, //in which Spring will use CGLIB to generate a subclass of the AbstractLookupDemoBean class that overrides the method dynamically. //The first part of the displayInfo() method creates two local variables of Singer type and assigns them each a value by calling //getMySinger() on the bean passed to it. Using these two variables, it writes a message to the console indicating whether the //two references point to the same object. public abstract class AbstractLookupDemoBean implements DemoBean { public abstract Singer getMySinger(); @Override public void doSomething() { getMySinger().sing(); } }
942e5b7d55c971f6288cd0b6c1eca19626502790
{ "blob_id": "942e5b7d55c971f6288cd0b6c1eca19626502790", "branch_name": "refs/heads/master", "committer_date": "2023-08-09T19:47:15", "content_id": "1a5b280094b60bff74c0b2b001dc38091cf17e41", "detected_licenses": [ "Apache-2.0" ], "directory_id": "72e1e90dd8e1e43bad4a6ba46a44d1f30aa76fe6", "extension": "java", "filename": "AbstractLookupDemoBean.java", "fork_events_count": 0, "gha_created_at": "2019-12-25T22:27:59", "gha_event_created_at": "2023-02-08T19:49:02", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 230160136, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 760, "license": "Apache-2.0", "license_type": "permissive", "path": "/java/spring/pro-spring-5/pro-spring-5-chapter03-introducing-ioc-di-spring/pro-spring-5-chapter03-part10-method-injection/src/main/java/com/apress/prospring5/ch3/AbstractLookupDemoBean.java", "provenance": "stack-edu-0022.json.gz:597404", "repo_name": "fernando-romulo-silva/myStudies", "revision_date": "2023-08-09T19:47:15", "revision_id": "aa8867cda5edd54348f59583555b1f8fff3cd6b3", "snapshot_id": "bfdf9f02778d2f4993999f0ffc0ddd0066ec41b4", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/fernando-romulo-silva/myStudies/aa8867cda5edd54348f59583555b1f8fff3cd6b3/java/spring/pro-spring-5/pro-spring-5-chapter03-introducing-ioc-di-spring/pro-spring-5-chapter03-part10-method-injection/src/main/java/com/apress/prospring5/ch3/AbstractLookupDemoBean.java", "visit_date": "2023-08-16T17:18:50.665674", "added": "2024-11-19T02:17:13.189330+00:00", "created": "2023-08-09T19:47:15", "int_score": 3, "score": 3.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
#ifndef GITTEH_COMMIT_H #define GITTEH_COMMIT_H #include "gitteh.h" #include "ts_objectwrap.h" namespace gitteh { class Repository; class Commit : public ThreadSafeObjectWrap { public: static Persistent<FunctionTemplate> constructor_template; static void Init(Handle<Object>); Commit(); ~Commit(); void setOwner(void*); Repository *repository_; git_commit *commit_; protected: static Handle<Value> New(const Arguments&); static Handle<Value> GetTree(const Arguments&); static Handle<Value> SetTree(const Arguments&); static Handle<Value> AddParent(const Arguments&); static Handle<Value> GetParent(const Arguments&); static Handle<Value> Save(const Arguments&); void processInitData(void *data); void* loadInitData(); int parentCount_; private: static int EIO_AddParent(eio_req*); static int EIO_AfterAddParent(eio_req*); static int EIO_GetParent(eio_req*); static int EIO_AfterGetParent(eio_req*); static int EIO_GetTree(eio_req*); static int EIO_AfterGetTree(eio_req*); static int EIO_SetTree(eio_req*); static int EIO_AfterSetTree(eio_req*); static int EIO_Save(eio_req*); static int EIO_AfterSave(eio_req*); }; } // namespace gitteh #endif // GITTEH_COMMIT_H
4effd3edad4f2769987b8adea3c76b11260db8c7
{ "blob_id": "4effd3edad4f2769987b8adea3c76b11260db8c7", "branch_name": "refs/heads/master", "committer_date": "2011-04-07T14:25:55", "content_id": "58855be6b9b4c71e25597c462e5f140f6d5f9642", "detected_licenses": [ "MIT" ], "directory_id": "8e57c99bb848871e6e65a70315fb1ead3f45f3d1", "extension": "h", "filename": "commit.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1582625, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1205, "license": "MIT", "license_type": "permissive", "path": "/src/commit.h", "provenance": "stack-edu-0002.json.gz:614887", "repo_name": "milani/node-gitteh", "revision_date": "2011-04-07T14:25:55", "revision_id": "1a74cd8b3be2ba6fababad29044bb4b151f2b936", "snapshot_id": "0ef1a0edac3559c0baddcbf897474cb05921443f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/milani/node-gitteh/1a74cd8b3be2ba6fababad29044bb4b151f2b936/src/commit.h", "visit_date": "2021-01-24T05:06:43.132289", "added": "2024-11-18T22:48:01.707775+00:00", "created": "2011-04-07T14:25:55", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
//@@author theJrLinguist package seedu.address.logic.commands.eventcommands; import static java.util.Objects.requireNonNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.testutil.TypicalEvents.getEmptyAddressBook; import static seedu.address.testutil.TypicalPersons.ALICE; import java.util.ArrayList; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.ModelStub; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.commands.exceptions.NoEventSelectedException; import seedu.address.logic.commands.exceptions.NoUserLoggedInException; import seedu.address.model.AddressBook; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.UserPrefs; import seedu.address.model.event.Event; import seedu.address.model.person.Person; import seedu.address.testutil.EventBuilder; public class AddEventCommandTest { private static final CommandHistory EMPTY_COMMAND_HISTORY = new CommandHistory(); @Rule public ExpectedException thrown = ExpectedException.none(); private CommandHistory commandHistory = new CommandHistory(); @Test public void constructor_nullEvent_throwsNullPointerException() { thrown.expect(NullPointerException.class); new AddEventCommand(null); } @Test public void execute_eventAcceptedByModel_addSuccessful() throws Exception { AddEventCommandTest.ModelStubAcceptingEventAdded modelStub = new AddEventCommandTest.ModelStubAcceptingEventAdded(); Event validEvent = new EventBuilder().build(); modelStub.setCurrentUser(ALICE); CommandResult commandResult = new AddEventCommand(validEvent).execute(modelStub, commandHistory); assertEquals(String.format(AddEventCommand.MESSAGE_SUCCESS, validEvent), commandResult.feedbackToUser); assertEquals(Arrays.asList(validEvent), modelStub.eventsAdded); } @Test public void execute_duplicateEvent_throwsCommandException() throws Exception { Event validEvent = new EventBuilder().build(); AddEventCommand addEventCommand = new AddEventCommand(validEvent); ModelStub modelStub = new AddEventCommandTest.ModelStubWithEvent(validEvent); thrown.expect(CommandException.class); thrown.expectMessage(AddEventCommand.MESSAGE_DUPLICATE_EVENT); addEventCommand.execute(modelStub, commandHistory); } @Test public void execute_noUser_throwsCommandException() throws Exception { Model model = new ModelManager(getEmptyAddressBook(), new UserPrefs()); Event validEvent = new EventBuilder().build(); thrown.expect(CommandException.class); thrown.expectMessage(Messages.MESSAGE_NO_USER_LOGGED_IN); new AddEventCommand(validEvent).execute(model, commandHistory); } @Test public void equals() { Event tutorial = new EventBuilder().withName("Tutorial").build(); Event meeting = new EventBuilder().withName("Meeting").build(); AddEventCommand addTutorialCommand = new AddEventCommand(tutorial); AddEventCommand addMeetingCommand = new AddEventCommand(meeting); // same object -> returns true assertTrue(addTutorialCommand.equals(addTutorialCommand)); // same values -> returns true AddEventCommand addTutorialCommandCopy = new AddEventCommand(tutorial); assertTrue(addTutorialCommand.equals(addTutorialCommandCopy)); // different types -> returns false assertFalse(addTutorialCommand.equals(1)); // null -> returns false assertFalse(addTutorialCommand.equals(null)); // different person -> returns false assertFalse(addTutorialCommand.equals(addMeetingCommand)); } /** * A Model stub that contains a single event. */ private class ModelStubWithEvent extends ModelStub { private final Event event; ModelStubWithEvent(Event event) { requireNonNull(event); this.event = event; } @Override public boolean hasEvent(Event event) { requireNonNull(event); return this.event.isSameEvent(event); } } /** * A Model stub that always accept the event being added. */ private class ModelStubAcceptingEventAdded extends ModelStub { final ArrayList<Event> eventsAdded = new ArrayList<>(); private Person currentUser = null; private Event currentEvent; @Override public int getNumEvents() { return eventsAdded.size(); } @Override public Event getEvent(Index index) { return eventsAdded.get(index.getZeroBased()); } @Override public boolean hasEvent(Event event) { requireNonNull(event); return eventsAdded.stream().anyMatch(event::isSameEvent); } @Override public void addEvent(Event event) { requireNonNull(event); eventsAdded.add(event); } @Override public void commitAddressBook() { // called by {@code AddCommand#execute()} } @Override public ReadOnlyAddressBook getAddressBook() { return new AddressBook(); } @Override public void setCurrentUser(Person person) { currentUser = person; } @Override public Person getCurrentUser() throws NoUserLoggedInException { if (currentUser == null) { throw new NoUserLoggedInException(); } return currentUser; } public void setSelectedEvent(Event currentEvent) { this.currentEvent = currentEvent; } public Event getSelectedEvent() throws NoEventSelectedException { if (currentEvent == null) { throw new NoEventSelectedException(); } return currentEvent; } } }
2d4598c06f7913f637e57c3d9c6a9ff2bc20e7e6
{ "blob_id": "2d4598c06f7913f637e57c3d9c6a9ff2bc20e7e6", "branch_name": "refs/heads/master", "committer_date": "2018-11-15T12:23:23", "content_id": "17880dfb2231f3068c3322ad9db6ffebd5570091", "detected_licenses": [ "MIT" ], "directory_id": "a745045fc5341ad865ffb7e06f156ffdbc022bd1", "extension": "java", "filename": "AddEventCommandTest.java", "fork_events_count": 4, "gha_created_at": "2018-09-05T00:16:52", "gha_event_created_at": "2018-11-12T14:17:53", "gha_language": "Java", "gha_license_id": "NOASSERTION", "github_id": 147435723, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6455, "license": "MIT", "license_type": "permissive", "path": "/src/test/java/seedu/address/logic/commands/eventcommands/AddEventCommandTest.java", "provenance": "stack-edu-0026.json.gz:445968", "repo_name": "CS2103-AY1819S1-W10-3/main", "revision_date": "2018-11-15T12:23:23", "revision_id": "5bae4c9df68ae44f8a87554ec75608388d0966c7", "snapshot_id": "dcab4f69efd4c3f2781ec4e6931e26a601df39e8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CS2103-AY1819S1-W10-3/main/5bae4c9df68ae44f8a87554ec75608388d0966c7/src/test/java/seedu/address/logic/commands/eventcommands/AddEventCommandTest.java", "visit_date": "2020-03-28T00:38:23.883143", "added": "2024-11-18T21:54:43.600127+00:00", "created": "2018-11-15T12:23:23", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz" }
<?php use Workerman\Worker; require_once __DIR__ . '/Workerman-master/Autoloader.php'; require_once __DIR__ . '/vendor/autoload.php'; $worker = new Worker('tcp://0.0.0.0:8585'); $worker->onWorkerStart = function($worker) { // 将db实例存储在全局变量中(也可以存储在某类的静态成员中) global $db; $db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', 'jiangbowen', 'test'); }; $worker->onMessage = function($connection, $data) { // 通过全局变量获得db实例 global $db; // 执行SQL $all_tables = $db->query("SELECT * FROM `user` WHERE id= {$data}"); $connection->send(json_encode($all_tables)); }; // 运行worker Worker::runAll(); ?>
69fc117c3b6f0c67ff1be5dd2a3e7dc63b2b3229
{ "blob_id": "69fc117c3b6f0c67ff1be5dd2a3e7dc63b2b3229", "branch_name": "refs/heads/master", "committer_date": "2019-10-15T14:23:26", "content_id": "bae6ced769b416a2fcef54e9297c1629173b24d5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e502c748746dd654b15ab40668b8e1c2628affb5", "extension": "php", "filename": "mysql.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 215067315, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 735, "license": "Apache-2.0", "license_type": "permissive", "path": "/public/mysql.php", "provenance": "stack-edu-0050.json.gz:242370", "repo_name": "jiangbowen1995/thinkphp5", "revision_date": "2019-10-15T14:23:26", "revision_id": "29ed0cbc0fc80e33d771a031c2aad5c5f3bbcdd3", "snapshot_id": "3593ca5657ab74faacf86a2deb362a3f059dd2b1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jiangbowen1995/thinkphp5/29ed0cbc0fc80e33d771a031c2aad5c5f3bbcdd3/public/mysql.php", "visit_date": "2020-08-14T00:53:39.927101", "added": "2024-11-19T02:44:54.123994+00:00", "created": "2019-10-15T14:23:26", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
export default StyledAutoCompleteContainer; declare function StyledAutoCompleteContainer({ cx, innerRef, children, ...props }: { [x: string]: any; cx: any; innerRef: any; children: any; }): import("@emotion/react/jsx-runtime").JSX.Element; declare namespace StyledAutoCompleteContainer { namespace propTypes { const cx: PropTypes.Validator<(...args: any[]) => any>; const children: PropTypes.Validator<string | number | boolean | {} | PropTypes.ReactElementLike | PropTypes.ReactNodeArray>; const innerRef: PropTypes.Validator<(...args: any[]) => any>; } } import PropTypes from "prop-types";
0493a4a8c86dc3eff4d7a7b3d46d6dddd20aa30f
{ "blob_id": "0493a4a8c86dc3eff4d7a7b3d46d6dddd20aa30f", "branch_name": "refs/heads/master", "committer_date": "2022-06-07T22:02:35", "content_id": "91a7ad529b5a6ca0aea4fab26426c6b7e6f1f81d", "detected_licenses": [ "MIT" ], "directory_id": "4e35049ab3206e439312ce55bcfdcf2058074dbd", "extension": "ts", "filename": "StyledAutoCompleteContainer.d.ts", "fork_events_count": 4, "gha_created_at": "2018-09-28T18:47:58", "gha_event_created_at": "2023-01-09T15:02:13", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 150782142, "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 641, "license": "MIT", "license_type": "permissive", "path": "/dist/AutoComplete/StyledAutoCompleteContainer.d.ts", "provenance": "stack-edu-0075.json.gz:1020402", "repo_name": "CatchRelease/arbor", "revision_date": "2022-06-07T22:02:35", "revision_id": "40b10a8e9a616b5fcafee67fbbe2ae93a7bce673", "snapshot_id": "b3dd4feba669c4e5491ba7a3de0cd3e976c7e9b6", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/CatchRelease/arbor/40b10a8e9a616b5fcafee67fbbe2ae93a7bce673/dist/AutoComplete/StyledAutoCompleteContainer.d.ts", "visit_date": "2023-01-20T00:44:29.835639", "added": "2024-11-19T02:17:07.152253+00:00", "created": "2022-06-07T22:02:35", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
package gamemanager; import game.GestionJuegos; import game.IGestionJuegos; import game.ITriquiGame; import game.TriquiGame; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class TriquiServer{ /** *Método local que no puede se invocado de manera remota. *Las principales funciones de este método son: * -Crear e instalar un security manager. determina los permisos de * operación de aplicaciones de diferentes maquinas virtuales. Si no está * Implementada. RMI no descargará clases diferentes al classpath. * -Hacer los objetos remotos disponibles para los clientes. */ public static void main(String[] args) { // Creación del securuty manager. /*if (System.getSecurityManager()==null){ System.setSecurityManager(new SecurityManager()); }*/ try { //Se crea un nombre para el objeto String name = "gestor"; String gameName = "game"; //Hace los objetos disponibles para los clientes IGestionJuegos gestor = new GestionJuegos(); ITriquiGame game = new TriquiGame(); //Crea los stub IGestionJuegos stub = (IGestionJuegos) UnicastRemoteObject.exportObject(gestor, 0); ITriquiGame stub2 = (ITriquiGame)UnicastRemoteObject.exportObject(game, 0); //Se agrega el nombre del RMI Registry en el servidor Registry registry = LocateRegistry.getRegistry(); /*Hace una referencia al localhost registry y el default registry port que es 1099*/ registry.rebind(name, stub); registry.rebind(gameName, stub2); /*La invocación del rebind hace una llamada remota al RMI Registry en el localhost. Por razones de seguridad una aplicación solo puede Hacer bind, rebind y unbind referencias de objetos remotos con un registry corriendo en el mismo host.*/ System.out.println("gestor y game publicados"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
373ee2f333ff01bd3177092fbfb26cffbba7246e
{ "blob_id": "373ee2f333ff01bd3177092fbfb26cffbba7246e", "branch_name": "refs/heads/master", "committer_date": "2016-03-16T03:56:43", "content_id": "ba98532b9a99a66b7ef4c6a90f50b244d4bb89ff", "detected_licenses": [ "MIT" ], "directory_id": "91225d89bc1c2cb530ee9094613e18de954f5179", "extension": "java", "filename": "TriquiServer.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 9289587, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1973, "license": "MIT", "license_type": "permissive", "path": "/gamemanager/TriquiServer.java", "provenance": "stack-edu-0019.json.gz:878772", "repo_name": "jyodroid/TriquiRMI", "revision_date": "2016-03-16T03:56:43", "revision_id": "d27a78d3a1be585703ea0e0cdbe9c5c3825e0106", "snapshot_id": "f1ff4147fc2d139f678cf4c4e1ec4938b5d6c2d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jyodroid/TriquiRMI/d27a78d3a1be585703ea0e0cdbe9c5c3825e0106/gamemanager/TriquiServer.java", "visit_date": "2021-01-21T21:39:49.036860", "added": "2024-11-19T01:31:10.906520+00:00", "created": "2016-03-16T03:56:43", "int_score": 3, "score": 3.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz" }
/** * @param arr: an array of non-negative integers * @return: minimum number of elements */ const minElements = function (arr) { arr.sort((a,b)=>b-a); let sum = 0; let rest = 0; for(let i=0;i<arr.length;i++){ rest += arr[i]; } for(let i=0;i<arr.length;i++){ sum += arr[i]; rest -= arr[i]; if(sum>rest){ return i+1; } } return 0; }
f10c245f26cb4b3dfac03f794c4799a2c1521582
{ "blob_id": "f10c245f26cb4b3dfac03f794c4799a2c1521582", "branch_name": "refs/heads/master", "committer_date": "2020-07-19T02:18:11", "content_id": "a59182677c599476d9c61b94e217c05fd828a667", "detected_licenses": [ "MIT" ], "directory_id": "f91a6210ae2688ddcb08ef36b9393366f94d62b4", "extension": "js", "filename": "0761.smallest-subset.js", "fork_events_count": 1, "gha_created_at": "2020-07-25T08:42:37", "gha_event_created_at": "2020-07-25T08:42:38", "gha_language": null, "gha_license_id": "MIT", "github_id": 282405375, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 419, "license": "MIT", "license_type": "permissive", "path": "/javascript/0761.smallest-subset.js", "provenance": "stack-edu-0035.json.gz:557207", "repo_name": "Ubastic/lintcode", "revision_date": "2020-07-19T02:18:11", "revision_id": "9f600eece075410221a24859331a810503c76014", "snapshot_id": "242bef06db8f420a71ba68d1781ed21b8bda2b28", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Ubastic/lintcode/9f600eece075410221a24859331a810503c76014/javascript/0761.smallest-subset.js", "visit_date": "2022-11-06T22:54:18.983213", "added": "2024-11-19T00:01:40.691668+00:00", "created": "2020-07-19T02:18:11", "int_score": 3, "score": 3.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
// 头部选择部分 (function(){ var HeadCon = document.getElementById('header_con'), SeleIn = HeadCon.querySelectorAll('.select_input'), SeleNow = HeadCon.querySelectorAll('.select_now'), SeleAll = HeadCon.querySelectorAll('.select_all'); var Arr = []; // 定义一个用来存放选择对象的数组 for(var i = 0; i < SeleIn.length; i++){ SeleNow[i].index = i; // 点击框时选项的显示和消失 SeleNow[i].onmousedown = function(){ var _this = this; if(this.isDown = !this.isDown){ SeleAll[this.index].style.display = "block"; } else { SeleAll[this.index].style.display = "none"; } } // 选取all_sec对象存入数组 Arr[i] = SeleAll[i].querySelectorAll('.all_sec'); // 每个对象点击时的函数 for(var t = 0; t < Arr[i].length; t++){ Arr[i][t].index = i; Arr[i][t].onmousedown = function(){ SeleNow[this.index].innerHTML = this.innerHTML; SeleAll[this.index].style.display = "none"; SeleNow[this.index].isDown = false; } } } })();
b51b613070341e285423350aed3271a604c171e0
{ "blob_id": "b51b613070341e285423350aed3271a604c171e0", "branch_name": "refs/heads/master", "committer_date": "2017-08-29T07:06:53", "content_id": "77586f1c17b535219a15d6eec59db2593187dca8", "detected_licenses": [ "MIT" ], "directory_id": "732941b20fe515b58ee102768b73433742a264b9", "extension": "js", "filename": "show.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": 1230, "license": "MIT", "license_type": "permissive", "path": "/src/main/resources/static/js/show.js", "provenance": "stack-edu-0043.json.gz:268093", "repo_name": "cj1224149316/village1.0", "revision_date": "2017-08-29T07:06:53", "revision_id": "91fdfebeb9bb0e1ecd84c471f9b1f7a1ff41633f", "snapshot_id": "17ed53446640adb6bb3e10cebcbeea39aa697df6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cj1224149316/village1.0/91fdfebeb9bb0e1ecd84c471f9b1f7a1ff41633f/src/main/resources/static/js/show.js", "visit_date": "2021-06-23T11:12:51.901259", "added": "2024-11-18T21:00:46.618788+00:00", "created": "2017-08-29T07:06:53", "int_score": 3, "score": 2.8125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
# libsite-showcase *Obsolete experimental module* Drupal Module to populate blocks with content from across GW Libraries content. Currently pulling in content from the GW Exhibits site (Omeka) and DCAAP Tumblr account. These blocks are designed to be used in the new 'extended' regions of the main page as showcase content. Styling for the blocks is in the Libsite7 theme css and only applies to the those regions. The Tumblr block will need the $consumerKey value to be set (with the account's Consumer Key).
5bfa3c97f1b6a87718ca210a497e14fb8fa19212
{ "blob_id": "5bfa3c97f1b6a87718ca210a497e14fb8fa19212", "branch_name": "refs/heads/master", "committer_date": "2017-04-04T16:51:42", "content_id": "16617ac583dac739500c1242cac598a8719e8b12", "detected_licenses": [ "MIT" ], "directory_id": "63af866254fe925a08812317305534b5e02ce510", "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": 37338410, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 515, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0000.json.gz:272672", "repo_name": "gwu-libraries/libsite-showcase", "revision_date": "2017-04-04T16:51:42", "revision_id": "f356c02226e1887d1ad72ceeb7a391927ac74d38", "snapshot_id": "ef99bc48e5e1184c024132d3902135a660b392aa", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gwu-libraries/libsite-showcase/f356c02226e1887d1ad72ceeb7a391927ac74d38/README.md", "visit_date": "2021-01-17T14:41:16.511793", "added": "2024-11-19T00:33:15.884464+00:00", "created": "2017-04-04T16:51:42", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz" }
package com.gainmatrix.lib.business.exception; /** * Исключение сигнализирующее о проблеме взаимодействия внутри системы */ public class SystemIntegrityException extends RuntimeException { public SystemIntegrityException(String msg) { super(msg); } public SystemIntegrityException(String msg, Throwable cause) { super(msg, cause); } }
8d1a25407e683f8a975458eea524b4cbf8853ed5
{ "blob_id": "8d1a25407e683f8a975458eea524b4cbf8853ed5", "branch_name": "refs/heads/master", "committer_date": "2015-09-30T15:29:44", "content_id": "f0c380faa2ba1cacab9061d6fdacd22883e9b499", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6511f9cd8fbd37499294e5a9f50a4bc73b75ed8e", "extension": "java", "filename": "SystemIntegrityException.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41808921, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 434, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/lib-beans/src/main/java/com/gainmatrix/lib/business/exception/SystemIntegrityException.java", "provenance": "stack-edu-0023.json.gz:300258", "repo_name": "mazurkin/gainmatrix", "revision_date": "2015-09-30T15:29:44", "revision_id": "296766e8516035275287954ffe85dcecbcd9bebe", "snapshot_id": "736cce1e97d83c987ac0a4fab96bd5ac31cba952", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mazurkin/gainmatrix/296766e8516035275287954ffe85dcecbcd9bebe/lib/lib-beans/src/main/java/com/gainmatrix/lib/business/exception/SystemIntegrityException.java", "visit_date": "2021-03-12T23:39:23.105356", "added": "2024-11-18T23:29:54.492472+00:00", "created": "2015-09-30T15:29:44", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
<?php declare(strict_types=1); namespace App\Traits; trait ElasticsearchSnapshotModelTrait { private ?array $indices = null; private ?bool $ignoreUnavailable = null; private ?bool $partial = null; private ?bool $includeGlobalState = null; public function getIndices(): ?array { return $this->indices; } public function setIndices(?array $indices): self { $this->indices = $indices; return $this; } public function getIgnoreUnavailable(): ?bool { return $this->ignoreUnavailable; } public function setIgnoreUnavailable(?bool $ignoreUnavailable): self { $this->ignoreUnavailable = $ignoreUnavailable; return $this; } public function getPartial(): ?bool { return $this->partial; } public function setPartial(?bool $partial): self { $this->partial = $partial; return $this; } public function getIncludeGlobalState(): ?bool { return $this->includeGlobalState; } public function setIncludeGlobalState(?bool $includeGlobalState): self { $this->includeGlobalState = $includeGlobalState; return $this; } }
fda63922f92c96aed0bd888da30f6fc359853df5
{ "blob_id": "fda63922f92c96aed0bd888da30f6fc359853df5", "branch_name": "refs/heads/main", "committer_date": "2023-06-03T05:40:49", "content_id": "0da7994bf4d21e25b7e304b11e735e360765eb9a", "detected_licenses": [ "MIT" ], "directory_id": "ac101a95d02d7707b384c67016fc9521e3045a35", "extension": "php", "filename": "ElasticsearchSnapshotModelTrait.php", "fork_events_count": 10, "gha_created_at": "2020-03-21T20:15:44", "gha_event_created_at": "2023-09-03T08:14:41", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 249053358, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1223, "license": "MIT", "license_type": "permissive", "path": "/src/Traits/ElasticsearchSnapshotModelTrait.php", "provenance": "stack-edu-0048.json.gz:70841", "repo_name": "stephanediondev/elasticsearch-admin", "revision_date": "2023-06-03T05:40:49", "revision_id": "31d62676264b478a7f601ed6e3e665b7cebfc575", "snapshot_id": "5cfc5362af78130460e025949d9a80374930659e", "src_encoding": "UTF-8", "star_events_count": 86, "url": "https://raw.githubusercontent.com/stephanediondev/elasticsearch-admin/31d62676264b478a7f601ed6e3e665b7cebfc575/src/Traits/ElasticsearchSnapshotModelTrait.php", "visit_date": "2023-06-17T23:40:19.577941", "added": "2024-11-18T21:31:44.793968+00:00", "created": "2023-06-03T05:40:49", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
import { mount } from '@vue/test-utils' import { BButtonGroup } from './button-group' describe('button-group', () => { it('has expected default structure', async () => { const wrapper = mount(BButtonGroup) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group') expect(wrapper.classes().length).toBe(1) expect(wrapper.attributes('role')).toBeDefined() expect(wrapper.attributes('role')).toBe('group') expect(wrapper.text()).toBe('') wrapper.destroy() }) it('should render default slot', async () => { const wrapper = mount(BButtonGroup, { slots: { default: '<span>foobar</span>' } }) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group') expect(wrapper.classes().length).toBe(1) expect(wrapper.attributes('role')).toBeDefined() expect(wrapper.attributes('role')).toBe('group') expect(wrapper.find('span').exists()).toBe(true) expect(wrapper.text()).toBe('foobar') wrapper.destroy() }) it('should apply vertical class', async () => { const wrapper = mount(BButtonGroup, { propsData: { vertical: true } }) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group-vertical') expect(wrapper.classes()).not.toContain('btn-group') expect(wrapper.classes().length).toBe(1) wrapper.destroy() }) it('should apply size class', async () => { const wrapper = mount(BButtonGroup, { propsData: { size: 'sm' } }) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group') expect(wrapper.classes()).toContain('btn-group-sm') expect(wrapper.classes().length).toBe(2) wrapper.destroy() }) it('should apply size class when vertical', async () => { const wrapper = mount(BButtonGroup, { propsData: { size: 'sm', vertical: true } }) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group-sm') expect(wrapper.classes()).toContain('btn-group-vertical') expect(wrapper.classes()).not.toContain('btn-group') expect(wrapper.classes().length).toBe(2) wrapper.destroy() }) it('has custom role when aria-role prop set', async () => { const wrapper = mount(BButtonGroup, { propsData: { ariaRole: 'foobar' } }) expect(wrapper.element.tagName).toBe('DIV') expect(wrapper.classes()).toContain('btn-group') expect(wrapper.classes().length).toBe(1) expect(wrapper.attributes('role')).toBeDefined() expect(wrapper.attributes('role')).toBe('foobar') wrapper.destroy() }) })
ec8410cf1d3cd7bdd4ba3992624542cca5dd86fa
{ "blob_id": "ec8410cf1d3cd7bdd4ba3992624542cca5dd86fa", "branch_name": "refs/heads/dev", "committer_date": "2023-07-28T00:24:13", "content_id": "9406313bbfcd2a6eb109f00ca6171e233365ad55", "detected_licenses": [ "MIT" ], "directory_id": "4b7feb42365d59907db58b914d3e55093bceb598", "extension": "js", "filename": "button-group.spec.js", "fork_events_count": 2680, "gha_created_at": "2016-10-08T15:59:35", "gha_event_created_at": "2023-08-10T09:00:21", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 70342215, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2759, "license": "MIT", "license_type": "permissive", "path": "/src/components/button-group/button-group.spec.js", "provenance": "stack-edu-0032.json.gz:369549", "repo_name": "bootstrap-vue/bootstrap-vue", "revision_date": "2023-07-28T00:24:13", "revision_id": "5173dd19f6f46dc9d125cd7233fb59ccd2ef9296", "snapshot_id": "86cda16c64c9e4a042cb34b6ea80536def51190f", "src_encoding": "UTF-8", "star_events_count": 16001, "url": "https://raw.githubusercontent.com/bootstrap-vue/bootstrap-vue/5173dd19f6f46dc9d125cd7233fb59ccd2ef9296/src/components/button-group/button-group.spec.js", "visit_date": "2023-08-03T04:11:27.247324", "added": "2024-11-18T23:09:36.124689+00:00", "created": "2023-07-28T00:24:13", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
using System; namespace Paillave.Etl.TextFile { public class FlatFileNoFieldDeserializeException : Exception { public int SourceColumnIndex { get; } public string TargetPropertyName { get; } public FlatFileNoFieldDeserializeException(int sourceColumnIndex, string targetPropertyName, Exception innerException) : base($"could not get value to deserialize in source column {sourceColumnIndex} for target property {targetPropertyName}", innerException) { this.SourceColumnIndex = sourceColumnIndex; this.TargetPropertyName = targetPropertyName; } } }
39066096c194a87663bb69abe0f793e3c6d97165
{ "blob_id": "39066096c194a87663bb69abe0f793e3c6d97165", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T10:07:48", "content_id": "bdadcb0d869fc13066434850e693d5518d7bfc74", "detected_licenses": [ "MIT" ], "directory_id": "f20c0a071060cbe129d4e395481d7c761ccb30fa", "extension": "cs", "filename": "FlatFileNoFieldDeserializeException.cs", "fork_events_count": 70, "gha_created_at": "2018-06-23T07:43:55", "gha_event_created_at": "2023-09-11T06:58:15", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 138381746, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 624, "license": "MIT", "license_type": "permissive", "path": "/src/Paillave.Etl.TextFile/FlatFileNoFieldDeserializeException.cs", "provenance": "stack-edu-0011.json.gz:833993", "repo_name": "paillave/Etl.Net", "revision_date": "2023-07-07T10:07:48", "revision_id": "eb84958ccb454989caffbd6eac392dfbf48805b5", "snapshot_id": "e381d640b3f1c495e1be0056d4b7dd9d4685b3dc", "src_encoding": "UTF-8", "star_events_count": 516, "url": "https://raw.githubusercontent.com/paillave/Etl.Net/eb84958ccb454989caffbd6eac392dfbf48805b5/src/Paillave.Etl.TextFile/FlatFileNoFieldDeserializeException.cs", "visit_date": "2023-08-04T23:51:22.380280", "added": "2024-11-18T22:59:25.032176+00:00", "created": "2023-07-07T10:07:48", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
# createmasks stage import argparse from ast import Num from functools import partial from pathlib import Path from typing import Iterable, List, Optional, TypeVar, Union import psutil from pygeos.set_operations import union import geopandas as gpd import numpy as np import pandas as pd import rioxarray import xarray as xr from shapely.geometry import Polygon from tqdm import tqdm from tqdm.contrib.concurrent import process_map def make_poly(coords: pd.Series) -> Polygon: """Create Shapely polygon (a tile boundary) from x1,y1 and x2,y2 coordinates""" xs = [coords[v] for v in "x1,x1,x2,x2,x1".split(",")] ys = [coords[v] for v in "y1,y2,y2,y1,y1".split(",")] return Polygon(zip(xs, ys)) def _identify_empty(tile: Union[Path, str]) -> bool: """Helper func for exclude_nodata_tiles""" with xr.open_rasterio(tile).sel(band=1) as t: # original check # status = True if t.max().values - t.min().values > 0 else False # check 2 (edge tiles with all white/ black are also detected) return False if np.isin(t, [0, 255]).all() else True def exclude_nodata_tiles( path: Iterable[Union[Path, str]], tiles_df: gpd.GeoDataFrame, workers: int, ) -> gpd.GeoDataFrame: """Identify tiles that only contain NoData (in parallel)""" print(f"WORKERS: {workers}") tile_names = sorted([Path(p) if isinstance(p, str) else p for p in path]) results = process_map(_identify_empty, tile_names, max_workers=workers, chunksize=1) valid_d = dict([(t.name, r) for t, r in zip(tile_names, results)]) tiles_df["status"] = tiles_df.filename.map(valid_d) # limit tiles to those with actual data (and delete status column afterwards) return tiles_df[tiles_df.status == 1].drop("status", axis=1) def create_tile_grid_gdf(path: Union[Path, str], crs: str) -> gpd.GeoDataFrame: """Convert gdal_tile split info file into geopandas dataframe""" tiles_df = pd.read_csv(path, sep=";", header=None) tiles_df.columns = ["filename", "x1", "x2", "y1", "y2"] tiles_df["geometry"] = tiles_df.apply(make_poly, axis=1) tiles_df = tiles_df.drop(["x1", "x2", "y1", "y2"], axis=1) tiles_gpd = gpd.GeoDataFrame(tiles_df, crs=crs, geometry=tiles_df.geometry) return tiles_gpd def split_groundtruth_data_by_tiles( groundtruth: gpd.GeoDataFrame, tiles_df: gpd.GeoDataFrame ) -> gpd.GeoDataFrame: """Split the oberserved dead tree areas into tile segments for faster downstream processing""" union_gpd = gpd.overlay(tiles_df, groundtruth, how="intersection") train_files = list(sorted(union_gpd.filename.value_counts().keys())) tiles_with_groundtruth = tiles_df[tiles_df.filename.isin(train_files)] return tiles_with_groundtruth, union_gpd # union_gpd[union_gpd.id == 2] def _mask_tile( tile_filename: str, *, groundtruth_df: gpd.GeoDataFrame, crs: str, inpath: Path, outpath: Path, simple: bool = False, ) -> float: image_tile_path = inpath / tile_filename mask_tile_path = outpath / tile_filename with rioxarray.open_rasterio( image_tile_path, chunks={"band": 4, "x": 256, "y": 256} ) as tile: mask_orig = xr.ones_like(tile.load().sel(band=1, drop=True), dtype="uint8") mask_orig.rio.set_crs(crs) selection = groundtruth_df.loc[groundtruth_df.filename == tile_filename] if simple: # just use the geometry for clipping (single-class) mask = mask_orig.rio.clip( selection.geometry, crs, drop=False, invert=False, all_touched=True, from_disk=True, ) else: # use type col from shapefile to create (multi-)classification masks classes = [0, 1, 2] # 0: non-class, 1: coniferous, 2: broadleaf selection.loc[:, "type"] = pd.to_numeric(selection["type"]) masks = [mask_orig * 0] for c in classes[1:]: gdf = selection.loc[selection["type"] == c, :] if len(gdf) > 0: mask = mask_orig.rio.clip( gdf.geometry, crs, drop=False, invert=False, all_touched=True, from_disk=True, ) else: mask = mask_orig * 0 masks.append(mask) mask = xr.concat(masks, pd.Index(classes, name="classes")).argmax( dim="classes" ) mask.astype("uint8").rio.to_raster(mask_tile_path, tiled=True) mask_sum = np.count_nonzero(mask.values) # just for checks return mask_sum def create_tile_mask_geotiffs( tiles_df_train: gpd.GeoDataFrame, workers: int, **kwargs ) -> None: """Create binary mask geotiffs""" process_map( partial(_mask_tile, **kwargs), tiles_df_train.filename.values, max_workers=workers, chunksize=1, ) def create_masks( indir: Path, outdir: Path, shpfile: Path, shpfile_ns: Optional[Path], workers: int, ) -> None: """ Stage 1: produce masks for training tiles """ # load domain shape files and use its crs for the entire script groundtruth = gpd.read_file(shpfile) crs = groundtruth.crs # reference crs tiles_df = create_tile_grid_gdf(indir / "locations.csv", crs) tiles_df = exclude_nodata_tiles( sorted(indir.glob("*.tif")), tiles_df, workers, ) print(f"len2: {len(tiles_df)}") tiles_df.to_file("locations.shp") tiles_df_train, groundtruth_df = split_groundtruth_data_by_tiles( groundtruth, tiles_df ) create_tile_mask_geotiffs( tiles_df_train, workers, groundtruth_df=groundtruth_df, crs=crs, inpath=indir, outpath=outdir, ) if shpfile_ns: outpath = outdir.parent / (outdir.name + ".neg_sample") outpath.mkdir(parents=True, exist_ok=True) groundtruth_ns = gpd.read_file(shpfile_ns) tiles_df_train_ns, groundtruth_ns_df = split_groundtruth_data_by_tiles( groundtruth_ns, tiles_df ) # make sure we don't use tiles from original tiles_df_train # print(f'Size tiles_df_train_ns (A) {len(tiles_df_train_ns)}') tiles_df_train_ns = tiles_df_train_ns.loc[ ~tiles_df_train_ns.filename.isin(tiles_df_train.filename) ] # print(f'Size tiles_df_train_ns (B) {len(tiles_df_train_ns)}') create_tile_mask_geotiffs( tiles_df_train_ns, workers, groundtruth_df=groundtruth_ns_df, crs=crs, inpath=indir, outpath=outdir.parent / (outdir.name + ".neg_sample"), simple=True, ) def main(): parser = argparse.ArgumentParser() parser.add_argument("indir", type=Path) parser.add_argument("outdir", type=Path) parser.add_argument("shpfile", type=Path) num_cores = psutil.cpu_count(logical=False) parser.add_argument( "--workers", dest="workers", type=int, default=num_cores, help="number of workers for parallel execution [def: %(default)s]", ) parser.add_argument( "--negativesample", dest="shpfile_ns", type=Path, default=None, help="shapefile with non-deadtree samples to create additional training tiles", ) args = parser.parse_args() Path(args.outdir).mkdir(parents=True, exist_ok=True) create_masks( args.indir, args.outdir, args.shpfile, args.shpfile_ns, args.workers, ) if __name__ == "__main__": main()
56f2ed832074c3a77ade85c16b90e8ae33853f58
{ "blob_id": "56f2ed832074c3a77ade85c16b90e8ae33853f58", "branch_name": "refs/heads/main", "committer_date": "2021-10-06T14:19:26", "content_id": "7e86a3ada860d9c9404496ae861dba0d7cc6a59a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "28040ff2e38f4206c1d66a11cf1463cec80efff6", "extension": "py", "filename": "createmasks.py", "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": "Python", "length_bytes": 7826, "license": "Apache-2.0", "license_type": "permissive", "path": "/scripts/createmasks.py", "provenance": "stack-edu-0061.json.gz:448568", "repo_name": "selschwarz/deadtrees", "revision_date": "2021-10-06T14:19:26", "revision_id": "c7a25e50c995da1e68b4310a26fc768bb9a49cbb", "snapshot_id": "ca796f789541828b49eeb2e11ecd50cfc53c4e91", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/selschwarz/deadtrees/c7a25e50c995da1e68b4310a26fc768bb9a49cbb/scripts/createmasks.py", "visit_date": "2023-09-04T08:12:19.951387", "added": "2024-11-19T01:17:15.698333+00:00", "created": "2021-10-06T14:19:26", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz" }
package com.ilearnrw.common.security.users.services; /* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */ import java.util.List; import com.ilearnrw.common.security.users.model.Classroom; import com.ilearnrw.common.security.users.model.School; import com.ilearnrw.common.security.users.model.StudentDetails; import com.ilearnrw.common.security.users.model.User; public interface StudentDetailsService { public StudentDetails getStudentDetails(User student); public int insertData(StudentDetails user); public void updateData(StudentDetails user); public void deleteData(int id); public List<Classroom> getClassRooms(School school); public List<School> getSchools(); public List<User> getStudentsFromClassRoom(Classroom classroom); public Classroom getStudentClassroom(User student); public School getStudentSchool(User student); }
58d71a310622e0d70e95cd5f1c6adf1776422c4f
{ "blob_id": "58d71a310622e0d70e95cd5f1c6adf1776422c4f", "branch_name": "refs/heads/master", "committer_date": "2015-07-22T10:07:05", "content_id": "5256d17689400b1db00e0607b42d156e4ee102aa", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "208148fdb754cbc49ae57529772721c7f5742930", "extension": "java", "filename": "StudentDetailsService.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13671951, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 904, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/main/java/com/ilearnrw/common/security/users/services/StudentDetailsService.java", "provenance": "stack-edu-0027.json.gz:713600", "repo_name": "mpakarlsson/ilearnrw-service", "revision_date": "2015-07-22T10:07:05", "revision_id": "3d2e47f2967a99e7ea9ded2b9aa2a929f40d4fa0", "snapshot_id": "2fdc24e640936ccca892c6962b98f6f7203b9835", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mpakarlsson/ilearnrw-service/3d2e47f2967a99e7ea9ded2b9aa2a929f40d4fa0/src/main/java/com/ilearnrw/common/security/users/services/StudentDetailsService.java", "visit_date": "2021-01-18T20:40:29.269784", "added": "2024-11-18T22:23:22.635306+00:00", "created": "2015-07-22T10:07:05", "int_score": 2, "score": 2.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
public class Student { public int studentID; public String studentName; public String address; public void showStudentInfo(){ System.out.println(studentID + "학번의 이름은"+ studentName + "이고, 주소는 " + address + "입니다."); } public String getStudentName(){ return studentName; } public void setStudentName(String name){ studentName = name; } }
fa17deadc0fb7fb81fbc87c443a483938e0785c7
{ "blob_id": "fa17deadc0fb7fb81fbc87c443a483938e0785c7", "branch_name": "refs/heads/main", "committer_date": "2021-09-12T14:47:05", "content_id": "b9b8a51288dba63efab9201b0776f58215347821", "detected_licenses": [ "MIT" ], "directory_id": "71dee2aa905853d57ead296d8103b9433a7cbaad", "extension": "java", "filename": "Student.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 392212760, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 427, "license": "MIT", "license_type": "permissive", "path": "/java/Student.java", "provenance": "stack-edu-0031.json.gz:613072", "repo_name": "kimkh0930/practice", "revision_date": "2021-09-12T14:47:05", "revision_id": "82ddd450bf65de01865c26790a6e728840b2ccbe", "snapshot_id": "4924726cf3c62cd4a17ed6005cdcb22c228aeebd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kimkh0930/practice/82ddd450bf65de01865c26790a6e728840b2ccbe/java/Student.java", "visit_date": "2023-08-15T10:09:23.687583", "added": "2024-11-18T21:51:11.955832+00:00", "created": "2021-09-12T14:47:05", "int_score": 3, "score": 3.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
const { wsUrl } = window.env; function WebSocketTest() { const shopName = document.querySelector('#shopName').value; if (!shopName) { alert('请输入店铺名'); return; } const ws = new WebSocket(wsUrl); const msgWrapper = document.getElementById('message-wrapper'); let pingTimer = null; ws.onopen = function ({ data }) { ws.send(`${shopName};online`); const p = document.createElement('p'); p.innerText = '商家:' + shopName + ' 开始营业'; msgWrapper.appendChild(p); pingTimer = setInterval(() => { ws.send('ping'); }, 5000); }; // 接收到服务器消息后的回调函数 ws.onmessage = function ({ data }) { const p = document.createElement('p'); const res = JSON.parse(data); if (res.data.indexOf('ping') === -1) { if (res.data.indexOf('order') !== -1) { p.innerText = '-------- \n' + res.data; } else { p.innerText = '收到消息:' + res.data; } msgWrapper.appendChild(p); } }; ws.onclose = function () { const p = document.createElement('p'); p.innerText = '连接已关闭...'; msgWrapper.appendChild(p); }; }
fc6e0160286351a848fb0e6c5b0dc44c71856049
{ "blob_id": "fc6e0160286351a848fb0e6c5b0dc44c71856049", "branch_name": "refs/heads/master", "committer_date": "2020-12-24T08:48:12", "content_id": "560d1294fe3220125bf367d1bee9d99466e00467", "detected_licenses": [ "MIT" ], "directory_id": "3f6938d9fd93eb2c77f2cba8a875f75f304a82a9", "extension": "js", "filename": "shop.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 307988637, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1167, "license": "MIT", "license_type": "permissive", "path": "/website/js/shop.js", "provenance": "stack-edu-0038.json.gz:667524", "repo_name": "serverless-plus/serverless-order-system", "revision_date": "2020-12-24T08:48:12", "revision_id": "58872b2acda78c1bed198dc4579d02b95c49e392", "snapshot_id": "d0e85f9d8e6822cfd2947b95fc84f63fa2d0b3a6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/serverless-plus/serverless-order-system/58872b2acda78c1bed198dc4579d02b95c49e392/website/js/shop.js", "visit_date": "2023-02-04T18:10:30.385164", "added": "2024-11-19T00:15:42.264222+00:00", "created": "2020-12-24T08:48:12", "int_score": 3, "score": 2.546875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class P01InsertionSort { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] input = reader.readLine().split(" "); int[] arr = new int[input.length]; for (int i = 0; i < input.length; i++) { arr[i] = Integer.parseInt(input[i]); } long start = System.nanoTime(); sort(arr, input.length-1 ); StringBuilder output = new StringBuilder(); for (int i = 0; i < arr.length; i++) { output.append(arr[i] + " "); } System.out.println(output); long elapsedTime = System.nanoTime() - start; System.out.println(elapsedTime); } private static void sort(int[] arr, int n) { if (n > 0) { sort(arr, n - 1); int x = arr[n]; int j = n - 1; while (j >= 0 && arr[j] > x) { arr[j + 1] = arr[j--]; } arr[j + 1] = x; } } }
6e79b651ec219ccd880105e190887607f27f1d9c
{ "blob_id": "6e79b651ec219ccd880105e190887607f27f1d9c", "branch_name": "refs/heads/master", "committer_date": "2018-04-22T18:19:58", "content_id": "1302b6e6aa5655ef0dfd70a8f076058f56a74844", "detected_licenses": [ "MIT" ], "directory_id": "fca29d54905a2edd7fd4db82500bba9c43701966", "extension": "java", "filename": "P01InsertionSort.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 78928699, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1146, "license": "MIT", "license_type": "permissive", "path": "/Algorithms/02.SortingAndSearchingExercise/src/P01InsertionSort.java", "provenance": "stack-edu-0028.json.gz:825492", "repo_name": "yangra/SoftUni", "revision_date": "2018-04-22T18:19:58", "revision_id": "2fe8ac059fe398f8bf229200c5406840f026fb88", "snapshot_id": "4046bd28e445f6cef98d2ee31179ba22892e6589", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yangra/SoftUni/2fe8ac059fe398f8bf229200c5406840f026fb88/Algorithms/02.SortingAndSearchingExercise/src/P01InsertionSort.java", "visit_date": "2021-01-13T15:16:53.303291", "added": "2024-11-18T23:05:39.280808+00:00", "created": "2018-04-22T18:19:58", "int_score": 4, "score": 3.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
<?php /** * Rating DataTable * * @package Gofer * @subpackage DataTable * @category Rating * @author Trioangle Product Team * @version 1.7 * @link http://trioangle.com */ namespace App\DataTables; use App\Models\Rating; use Yajra\Datatables\Services\DataTable; use Auth; class RatingDataTable extends DataTable { // protected $printPreview = 'path-to-print-preview-view'; protected $exportColumns = ['id','rider_name','driver_name','car_name','rider_rading','driver_rading','driver_name','rider_comments','driver_comments', 'status']; /** * Display ajax response. * * @return \Illuminate\Http\JsonResponse */ public function ajax() { $rating = $this->query(); return $this->datatables ->of($rating) ->make(true); } /** * Get the query object to be processed by datatables. * * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder */ public function query() { $rating = Rating:: where(function($query) { //If login user is company then get that company driver ratings only if(LOGIN_USER_TYPE=='company') { $query->whereHas('driver',function($q1){ $q1->where('company_id',Auth::guard('company')->user()->id); }); } }) ->join('users', function($join) { $join->on('users.id', '=', 'rating.user_id'); }) ->join('trips', function($join) { $join->on('trips.id', '=', 'rating.trip_id'); }) ->join('car_type', function($join) { $join->on('car_type.id', '=', 'trips.car_id'); }) ->leftJoin('users as u', function($join) { $join->on('u.id', '=', 'rating.driver_id'); }) ->leftJoin('companies', function($join) { $join->on('u.company_id', '=', 'companies.id'); }) ->select(['rating.id as id', 'u.first_name as driver_name', 'users.first_name as rider_name', 'car_type.car_name as car_name','rating.rider_rating as rider_rating', 'rating.driver_rating as driver_rading','rating.rider_comments as rider_comments', 'rating.driver_comments as driver_comments','trips.created_at as date','rating.*','companies.name as driver_company_name']); return $this->applyScopes($rating); } /** * Optional method if you want to use html builder. * * @return \yajra\Datatables\Html\Builder */ public function html() { $company_columns = array(); if(LOGIN_USER_TYPE == 'admin') { $company_columns = array( ['data' => 'driver_company_name', 'name' => 'companies.name', 'title' => 'Company Name'] ); } return $this->builder() ->addColumn(['data' => 'trip_id', 'name' => 'trip_id', 'title' => 'Trip Number']) ->addColumn(['data' => 'date', 'name' => 'trips.created_at', 'title' => 'Trip Date']) ->addColumn(['data' => 'driver_name', 'name' => 'u.first_name', 'title' => 'Driver Name']) ->addColumn(['data' => 'rider_name', 'name' => 'users.first_name', 'title' => 'Rider Name']) ->Columns($company_columns) ->addColumn(['data' => 'car_name', 'name' => 'car_name', 'title' => 'Car name']) ->addColumn(['data' => 'driver_rating', 'name' => 'driver_rating', 'title' => 'Driver Rating']) ->addColumn(['data' => 'rider_rating', 'name' => 'rider_rating', 'title' => 'Rider Rating']) ->addColumn(['data' => 'rider_comments', 'name' => 'rider_comments', 'title' => 'Rider Comments']) ->addColumn(['data' => 'driver_comments', 'name' => 'driver_comments', 'title' => 'Driver Comments']) ->parameters([ 'dom' => 'lBfrtip', 'buttons' => [], 'order' => [0, 'desc'], ]); } }
4c09fa0e02dc776ab10b9d230b594801b03a3849
{ "blob_id": "4c09fa0e02dc776ab10b9d230b594801b03a3849", "branch_name": "refs/heads/master", "committer_date": "2019-11-13T19:17:09", "content_id": "5f73f096e561b0ed1db1d2e13dd4c61e230e3083", "detected_licenses": [ "MIT" ], "directory_id": "af855166b71aab13c714559959d2fdb765a55ffa", "extension": "php", "filename": "RatingDataTable.php", "fork_events_count": 0, "gha_created_at": "2019-11-13T19:00:11", "gha_event_created_at": "2019-11-13T19:00:12", "gha_language": null, "gha_license_id": "MIT", "github_id": 221530969, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4325, "license": "MIT", "license_type": "permissive", "path": "/app/DataTables/RatingDataTable.php", "provenance": "stack-edu-0054.json.gz:539920", "repo_name": "Famzy/citikab-android-web", "revision_date": "2019-11-13T19:17:09", "revision_id": "7384cd1588126a5f64d5c60c1e94680baae8fadd", "snapshot_id": "8c56b5873faa21b29d05c2edd485e9bb49841f99", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Famzy/citikab-android-web/7384cd1588126a5f64d5c60c1e94680baae8fadd/app/DataTables/RatingDataTable.php", "visit_date": "2020-09-09T18:42:57.087276", "added": "2024-11-18T22:13:09.769949+00:00", "created": "2019-11-13T19:17:09", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
# Coding Assessment ![MIT license badge](https://img.shields.io/badge/license-MIT-green) ## Description A timed, interactive quiz application testing for basic JavaScript knowledge ##### Homescreen ![Homescreen Screenshot](./assets/images/screenshot.png) ##### Question Example ![Question Example Screenshot](./assets/images/screenshot2.png) ##### Game Over ![Game Over Screenshot](./assets/images/screenshot3.png) ##### High Scores ![High Scores Screenshot](./assets/images/screenshot4.png) Visit site [here](https://christopherconcannon.github.io/coding-assessment/) ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Technologies](#technologies) * [Contributing](#contributing) * [Testing](#testing) * [Questions](#questions) ## Installation Clone project to a directory on your local machine and cd into coding-assessment directory. ## Usage Open index.html file in browser of your choice. Push button to start quiz and countdown. Select the best answer to the questions. If you answer incorrectly your time will be reduced by 10 seconds. Your score will be the amount of time you have remaining at the end of the test. You may then enter your initials to display in the high score list. Good luck. ## License This project is covered under the MIT license ## Technologies HTML5, CSS3, JavaScript ## Contributing To see the guidelines adopted for contributing to this project, please view the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.txt) ## Testing Tests coming soon ## Questions Visit me at GitHub [christopherConcannon](https://github.com/christopherConcannon) If you have any questions or would like to contact me, please email me at [cmcon<EMAIL_ADDRESS>
c33cc3b96794576bfe4c94310f86d033b80413cb
{ "blob_id": "c33cc3b96794576bfe4c94310f86d033b80413cb", "branch_name": "refs/heads/master", "committer_date": "2020-12-03T19:26:52", "content_id": "885ec50c683b5b34a0c49c45b4aee1835c8925b8", "detected_licenses": [ "MIT" ], "directory_id": "16c872c4fa70dae5754156cc979bde9a78bfe84e", "extension": "md", "filename": "README.md", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 270847084, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1838, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0012.json.gz:226614", "repo_name": "christopherConcannon/coding-assessment", "revision_date": "2020-12-03T19:26:52", "revision_id": "8c1181b0286d5a198533b68eb124219f1f47ae62", "snapshot_id": "30d9be290de3bb64bb9e329cc24436f512ff0892", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/christopherConcannon/coding-assessment/8c1181b0286d5a198533b68eb124219f1f47ae62/README.md", "visit_date": "2023-01-22T22:15:36.439070", "added": "2024-11-19T00:29:18.997358+00:00", "created": "2020-12-03T19:26:52", "int_score": 3, "score": 3.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz" }
package consensus import ( "math/rand" "testing" "github.com/axiom-org/axiom/util" ) // Simulate the sending of messages from source to target func chainSend(source *Chain, target *Chain) { if source == target { return } messages := source.OutgoingMessages() for _, message := range messages { m := util.EncodeThenDecodeMessage(message) response, ok := target.Handle(source.publicKey.String(), m) if ok { _, ok := source.Handle(target.publicKey.String(), response) if ok { util.Logger.Fatal("infinite response loop") } } } } // Makes a cluster of chains that requires a consensus of more than two thirds. func chainCluster(size int) []*Chain { qs, names := MakeTestQuorumSlice(size) chains := []*Chain{} for i, name := range names { vs := NewTestValueStore(i) chains = append(chains, NewEmptyChain(name, qs, vs)) } return chains } // checkProgress checks that blocks match up to and including limit. // it errors if there is any disagreement in externalized values. func checkProgress(chains []*Chain, limit int, t *testing.T) { first := chains[0] for i := 1; i < len(chains); i++ { chain := chains[i] for j := 1; j <= limit; j++ { // Check that this chain agrees with the first one for slot j blockValue := chain.history[j].X firstValue := first.history[j].X if blockValue != firstValue { util.Logger.Printf("%s externalized %+v for slot %d", first.publicKey, firstValue, j) util.Logger.Printf("%s externalized %+v for slot %d", chain.publicKey, blockValue, j) t.Fatal("this cannot be") } } } } // progress returns the number of blocks that all of these chains have externalized func progress(chains []*Chain) int { minSlot := chains[0].current.slot for i := 1; i < len(chains); i++ { if chains[i].current.slot < minSlot { minSlot = chains[i].current.slot } } return minSlot - 1 } func chainFuzzTest(chains []*Chain, seed int64, t *testing.T) { limit := 10 rand.Seed(seed ^ 46372837824) util.Logger.Printf("fuzz testing chains with seed %d", seed) for i := 1; i <= 10000; i++ { j := rand.Intn(len(chains)) k := rand.Intn(len(chains)) chainSend(chains[j], chains[k]) if progress(chains) >= limit { break } if i%1000 == 0 { util.Logger.Printf("done round: %d ************************************", i) } } if progress(chains) < limit { LogChains(chains) t.Fatalf("with seed %d, we only externalized %d blocks", seed, progress(chains)) } checkProgress(chains, 10, t) } // Should work to 10k func TestChainFullCluster(t *testing.T) { var i int64 for i = 0; i < util.GetTestLoopLength(10, 10000); i++ { c := chainCluster(4) chainFuzzTest(c, i, t) } } // Should work to 10k func TestChainOneNodeKnockedOut(t *testing.T) { var i int64 for i = 0; i < util.GetTestLoopLength(10, 10000); i++ { c := chainCluster(4) knockout := c[0:3] chainFuzzTest(knockout, i, t) } }
406aa98e4fb115b99d317f5e893a0244ebd97ed9
{ "blob_id": "406aa98e4fb115b99d317f5e893a0244ebd97ed9", "branch_name": "refs/heads/master", "committer_date": "2019-06-04T18:22:58", "content_id": "21e3bd0fcfe7c01d08b077d81b5230eb322e5b3f", "detected_licenses": [ "MIT" ], "directory_id": "45d26ec5e83cefa95746c495b156346abebee2bd", "extension": "go", "filename": "chain_test.go", "fork_events_count": 0, "gha_created_at": "2019-06-06T04:12:46", "gha_event_created_at": "2019-06-06T04:12:46", "gha_language": null, "gha_license_id": "MIT", "github_id": 190512487, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2917, "license": "MIT", "license_type": "permissive", "path": "/consensus/chain_test.go", "provenance": "stack-edu-0018.json.gz:553637", "repo_name": "stephensong/axiom", "revision_date": "2019-06-04T18:22:58", "revision_id": "b03bfd7d577242210cc17327dbc5c38d03504409", "snapshot_id": "835b132b90261d8fb7f5d2bc0a869e41e3b4bdd5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/stephensong/axiom/b03bfd7d577242210cc17327dbc5c38d03504409/consensus/chain_test.go", "visit_date": "2020-05-31T22:04:24.509750", "added": "2024-11-18T18:48:16.574548+00:00", "created": "2019-06-04T18:22:58", "int_score": 3, "score": 2.828125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
-- +migrate Up ALTER TABLE user_contact_methods ADD UNIQUE(name, type, user_id); ALTER TABLE user_contact_methods ADD UNIQUE(type, value); ALTER TABLE user_contact_methods ALTER id SET DEFAULT gen_random_uuid(); -- +migrate Down ALTER TABLE user_contact_methods DROP CONSTRAINT UNIQUE(name, type, user_id); ALTER TABLE user_contact_methods DROP CONSTRAINT UNIQUE(type, value); ALTER TABLE user_contact_methods ALTER id DROP DEFAULT;
8e3a98009392c313ef05c68202a64a60af2ff2da
{ "blob_id": "8e3a98009392c313ef05c68202a64a60af2ff2da", "branch_name": "refs/heads/master", "committer_date": "2023-08-22T17:27:43", "content_id": "1022da450e255994b7469d8ec1593eff25487ce6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "61c2bb82208278bc5bdb3f3cb5dda5cde60664d1", "extension": "sql", "filename": "20170620104459-contact-constraints.sql", "fork_events_count": 239, "gha_created_at": "2019-05-24T16:46:20", "gha_event_created_at": "2023-09-14T16:51:32", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 188457198, "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 437, "license": "Apache-2.0", "license_type": "permissive", "path": "/migrate/migrations/20170620104459-contact-constraints.sql", "provenance": "stack-edu-0070.json.gz:342950", "repo_name": "target/goalert", "revision_date": "2023-08-22T17:27:43", "revision_id": "f783576ae8ba986ab1bade3a1bfec95f54c4d972", "snapshot_id": "c9b176655b647889fd416d2180cc8389587b27e4", "src_encoding": "UTF-8", "star_events_count": 1996, "url": "https://raw.githubusercontent.com/target/goalert/f783576ae8ba986ab1bade3a1bfec95f54c4d972/migrate/migrations/20170620104459-contact-constraints.sql", "visit_date": "2023-08-22T17:42:14.271611", "added": "2024-11-18T19:16:18.087363+00:00", "created": "2023-08-22T17:27:43", "int_score": 3, "score": 2.84375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
# ring-gravity A numerical Saturn's ring gravitational model including C/D/B/A ringlet ## equipotential surface of B/A ![avatar](images/ring-grav.png)
371fd1b139c86c70ffbf893e062794fc319c5239
{ "blob_id": "371fd1b139c86c70ffbf893e062794fc319c5239", "branch_name": "refs/heads/master", "committer_date": "2018-03-25T07:24:54", "content_id": "715166ea58cbb42f67e6976d091ec78e351ae2d3", "detected_licenses": [ "MIT" ], "directory_id": "b8610920eb5191fe6fc4ad6fe8a6229edf916aa1", "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": 118231072, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 154, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0007.json.gz:63971", "repo_name": "jnnccc/ring-gravity", "revision_date": "2018-03-25T07:24:54", "revision_id": "e326c3507a872f507443f1523051e0ebe6f24a5e", "snapshot_id": "499f922205018e5e3721eb8443ce67ad028bef82", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jnnccc/ring-gravity/e326c3507a872f507443f1523051e0ebe6f24a5e/README.md", "visit_date": "2021-05-10T21:31:53.345074", "added": "2024-11-18T22:20:12.710331+00:00", "created": "2018-03-25T07:24:54", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
#!/bin/bash echo "Building binary" export GO111MODULE=on echo "Pulling Latest commit" git remote set-url origin [email protected]:corneredrat/kubectl-which-node.git git pull -f echo "Getting latest commitid" commitid=$(git log --format="%H" -n 1) echo "Latest comit : $commitid" echo "Downloading packages" go mod vendor echo "Building binary" go build -mod=vendor -v main.go if [ $? != 0 ]; then echo "Build failed, exiting." echo "If problem persists, raise an issue at : https://github.com/corneredrat/kubectl-which-node/issues" exit fi echo "Installing" sudo cp main ./bin/kubectl-which-node sudo mv main /usr/bin/kubectl-which-node echo "...Done."
0a7112eaaee014b963dc7a49f14375aa96824241
{ "blob_id": "0a7112eaaee014b963dc7a49f14375aa96824241", "branch_name": "refs/heads/master", "committer_date": "2020-12-09T07:48:03", "content_id": "d2ae4987ec92ef00aaf052ef7f6946ffaad98f47", "detected_licenses": [ "Apache-2.0" ], "directory_id": "067e385b3ddccaa5d29f1e668b2fc6e766af9bf0", "extension": "", "filename": "build", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 279848104, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 664, "license": "Apache-2.0", "license_type": "permissive", "path": "/build", "provenance": "stack-edu-0069.json.gz:1063165", "repo_name": "corneredrat/kubectl-which-node", "revision_date": "2020-12-09T07:48:03", "revision_id": "3d5ea3e6a3be31de6d3619af2a2b1f6fb84e1d4b", "snapshot_id": "8f8fe2b7fe03645f60abceb0509a780e6c45e714", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/corneredrat/kubectl-which-node/3d5ea3e6a3be31de6d3619af2a2b1f6fb84e1d4b/build", "visit_date": "2023-01-31T07:10:41.004227", "added": "2024-11-18T20:58:35.032999+00:00", "created": "2020-12-09T07:48:03", "int_score": 3, "score": 3.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
/* Copyright 2013 Rene Nowak 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 at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.json; import at.ac.tuwien.infosys.jcloudscale.datastore.api.DatastoreException; import at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.TypeAdapter; import at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.TypeMetadata; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; public class JsonLongTypeAdapter implements TypeAdapter<Long, JsonElement> { @Override public JsonElement serialize(Long object, TypeMetadata<JsonElement> typeMetadata) { return new JsonPrimitive(object); } @Override public Long deserialize(JsonElement element, TypeMetadata<JsonElement> typeMetadata) { JsonPrimitive jsonPrimitive = (JsonPrimitive) element; if(!jsonPrimitive.isNumber()) { throw new DatastoreException("Invalid value for long type."); } return jsonPrimitive.getAsLong(); } }
b54b2e4af1b36fdc5c08f9b864fb7c76b1f1a115
{ "blob_id": "b54b2e4af1b36fdc5c08f9b864fb7c76b1f1a115", "branch_name": "refs/heads/master", "committer_date": "2014-05-02T15:14:56", "content_id": "2ee861c7892e3d3af8f3961dcb903421240507ca", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7a983e2a9c1c21ba8afb1c61e41dd6b4c921819a", "extension": "java", "filename": "JsonLongTypeAdapter.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": 1532, "license": "Apache-2.0", "license_type": "permissive", "path": "/ext/DataStoreLib/src/main/java/at/ac/tuwien/infosys/jcloudscale/datastore/mapping/type/json/JsonLongTypeAdapter.java", "provenance": "stack-edu-0026.json.gz:160073", "repo_name": "zhengt/jcloudscale", "revision_date": "2014-05-02T15:14:56", "revision_id": "294e829b9a5c02bdd54139110b30aa9be160eabe", "snapshot_id": "0cf5e5761192ce0d9444065ca5076cd253f26cd6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zhengt/jcloudscale/294e829b9a5c02bdd54139110b30aa9be160eabe/ext/DataStoreLib/src/main/java/at/ac/tuwien/infosys/jcloudscale/datastore/mapping/type/json/JsonLongTypeAdapter.java", "visit_date": "2021-01-17T21:14:09.886106", "added": "2024-11-19T00:31:11.682108+00:00", "created": "2014-05-02T15:14:56", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz" }