text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using AcgViewer.Tools; namespace AcgViewer { /// <summary> /// ImgShow.xaml 的交互逻辑 /// </summary> public partial class ImgShow : UserControl { private double _imgWidth; private double _imgHight; private string _imgUrl; private int _imgID; public ImgShow(string imgUrl,int imgID,Double imgWidth, Double imgHight) { InitializeComponent(); _imgWidth = imgWidth; _imgHight = imgHight; _imgUrl = imgUrl; _imgID = imgID; try { LoadPreview(imgUrl, imgID); }catch(Exception e) { LoadingTextBlock.Text = e.Message + "\n点击重试"; ExcepitonLog.WriteLog(e); LoadingTextBlock.MouseLeftButtonUp += LoadingTextBlock_MouseLeftButtonUp; } } private void LoadingTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { try { LoadPreview(_imgUrl, _imgID); } catch { MainWindow.dataLib.ImgsItemSourse.Remove(this); } } /// <summary> /// 加载预览图 /// </summary> /// <param name="imgUrl">URL</param> /// <param name="imgID">ID</param> private async void LoadPreview(string imgUrl, int imgID) { Img.Width = _imgWidth; Img.Height = _imgHight; MainWindow.dataLib.ImgsItemSourse.Add(this); Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\cache\\" + MainWindow.dataLib.SiteName); string imgPath = Directory.GetCurrentDirectory() + "\\" + string.Format("cache\\{0}\\{1}_preview{2}", MainWindow.dataLib.SiteName, imgID,System.IO.Path.GetExtension(imgUrl)); //if (File.Exists(imgPath)) //{ // File.Delete(imgPath); //} await Download.DownloadFile(imgUrl, imgPath,false, 5000); await Task.Run(() => { Img.Dispatcher.BeginInvoke(new Action(() => { LoadingTextBlock.Visibility = Visibility.Collapsed; using (BinaryReader binReader = new BinaryReader(File.Open(imgPath, FileMode.Open))) { FileInfo fileInfo = new FileInfo(imgPath); byte[] bytes = binReader.ReadBytes((int)fileInfo.Length); binReader.Close(); BitmapImage bi = new BitmapImage(); try { bi.BeginInit(); bi.StreamSource = new MemoryStream(bytes); bi.EndInit(); } catch { MainWindow.dataLib.ImgsItemSourse.Remove(this); //throw new Exception("图片加载错误"); } Img.Source = bi; } } )); }); } } }
fffe909a0781f331932af13bba55b53cb84acf49
{ "blob_id": "fffe909a0781f331932af13bba55b53cb84acf49", "branch_name": "refs/heads/master", "committer_date": "2019-09-20T02:26:28", "content_id": "9fb76f52f56712b22986d7478cf47cec961c76c6", "detected_licenses": [ "MIT" ], "directory_id": "89eea5afe241cd55e23994ad94a7cd791caf382e", "extension": "cs", "filename": "ImgShow.xaml.cs", "fork_events_count": 1, "gha_created_at": "2019-07-30T09:36:14", "gha_event_created_at": "2022-12-07T20:28:55", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 199621430, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3724, "license": "MIT", "license_type": "permissive", "path": "/AcgViewer/ImgShow.xaml.cs", "provenance": "stack-edu-0012.json.gz:882911", "repo_name": "YukiCoco/AcgViewer", "revision_date": "2019-09-20T02:26:28", "revision_id": "353553ae04a9227f682220692937e8bb29c64bae", "snapshot_id": "7675e0b6dace05786073509a77161c84d04e4ba0", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/YukiCoco/AcgViewer/353553ae04a9227f682220692937e8bb29c64bae/AcgViewer/ImgShow.xaml.cs", "visit_date": "2022-12-09T10:03:31.163430", "added": "2024-11-18T23:55:04.149180+00:00", "created": "2019-09-20T02:26:28", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
<?php namespace EmailMarketing\Services; use EmailMarketing\Message\Request; use EmailMarketing\Message\Uri; use Psr\Http\Client\ClientInterface; class AbstractService { protected $httpClient; protected $configuration; public function __construct(ClientInterface $httpClient, ConfigurationInterface $configuration) { $this->httpClient = $httpClient; $this->configuration = $configuration; } public function send(Request $request, $options = []) { if ($headers = $this->configuration->getDefaultHeaders()) { foreach ($headers as $key => $value) { $request = $request->withHeader($key, $value); } } if (! $request->getUri()->getHost()) { $baseUrl = $this->configuration->getBaseUrl(); $uriPath = $baseUrl.'/'.ltrim($request->getUri(), '/'); $request = $request->withUri(new Uri($uriPath)); } if (isset($options['beforeSend'])) { if (is_callable($options['beforeSend'])) { $options['beforeSend']($request); } } $sendRequest = $this->httpClient->sendRequest($request); return $sendRequest; } public function sendRequest($request) { # code... } }
e90448c0b8dacc92fa21a18086f0200038cee9b9
{ "blob_id": "e90448c0b8dacc92fa21a18086f0200038cee9b9", "branch_name": "refs/heads/main", "committer_date": "2021-03-24T17:15:14", "content_id": "c377a369ee15a65c3ae7615a641f01f2d573625b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f4a9ed967d0690fcdc26d705f346c52a0f373203", "extension": "php", "filename": "AbstractService.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 351152667, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1302, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/Services/AbstractService.php", "provenance": "stack-edu-0046.json.gz:533432", "repo_name": "rafirandoni/email-marketing-php", "revision_date": "2021-03-24T17:15:14", "revision_id": "a0e7b1002a234362339d1d57fe0fa3f823b955b8", "snapshot_id": "ef8d486160dadf71e1685113f361353fa50a0897", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rafirandoni/email-marketing-php/a0e7b1002a234362339d1d57fe0fa3f823b955b8/src/Services/AbstractService.php", "visit_date": "2023-03-28T17:16:59.038249", "added": "2024-11-18T22:35:33.567859+00:00", "created": "2021-03-24T17:15:14", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz" }
using System; using System.Collections.Generic; namespace DependencyInjection.Container.Contract { public interface IDiContainer : IDisposable { IEnumerable<T> ResolveAll<T>(); T Resolve<T>(); dynamic Resolve(Type type); void RegisterType<TType, TClass>() where TClass : TType; void RegisterType<TType, TClass>(string name) where TClass : TType; void RegisterTypeAsSingleton<TType, TClass>() where TClass : TType; void RegisterTypeAsSingleton<TType, TClass>(string name) where TClass : TType; void RegisterInstance<T>(T impl); void RegisterInstance<T>(T impl, string name); void RegisterTypeIfNotSet<TType, TClass>() where TClass : TType; void RegisterTypeIfNotSet<TType, TClass>(string name) where TClass : TType; void RegisterTypeAsSingletonIfNotSet<TType, TClass>() where TClass : TType; void RegisterTypeAsSingletonIfNotSet<TType, TClass>(string name) where TClass : TType; void RegisterInstanceIfNotSet<T>(T impl); void RegisterInstanceIfNotSet<T>(T impl, string name); IDiContainer CreateChildContainer(); bool IsRegistered<T>(); bool IsRegistered(Type type); bool IsRegistered<T>(string name); } }
fb8348ff3631c04ca436ca10b2a77224b15e5e46
{ "blob_id": "fb8348ff3631c04ca436ca10b2a77224b15e5e46", "branch_name": "refs/heads/master", "committer_date": "2018-11-08T22:02:02", "content_id": "258e103a95712a1a4954f9101d4bf3b0cbc8df17", "detected_licenses": [ "MIT" ], "directory_id": "a66e632057c116c492290f22362c96a21f6884ba", "extension": "cs", "filename": "IDiContainer.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 49233100, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1287, "license": "MIT", "license_type": "permissive", "path": "/src/di/Container/Contract/IDiContainer.cs", "provenance": "stack-edu-0013.json.gz:798251", "repo_name": "dreanor/Library", "revision_date": "2018-11-08T22:02:02", "revision_id": "0f608f0ea4556a204dd76ee89bc894d19c95d40d", "snapshot_id": "efef3de979e54239d57cf1c5de6df7fce44adc3d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dreanor/Library/0f608f0ea4556a204dd76ee89bc894d19c95d40d/src/di/Container/Contract/IDiContainer.cs", "visit_date": "2021-01-10T12:22:42.459885", "added": "2024-11-19T01:49:23.577551+00:00", "created": "2018-11-08T22:02:02", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
import { Thread } from "./Thread"; export class Threads { private readonly threads: Thread[]; constructor(threads: Thread[]) { this.threads = threads; } get titles() { return this.threads.map((thread) => thread.title); } all() { return this.threads; } title(title: string) { return this.threads.find((thread) => thread.title === title) as Thread; } datId(datId: string) { return this.threads.find((thread) => thread.datId === datId) as Thread; } datName(datName: string) { return this.threads.find((thread) => thread.datName === datName) as Thread; } searchByTitle(title: string | RegExp) { return this.threads.filter((thread) => thread.title && thread.title.match(title)); } }
63b50fb915c827b6665aa41e006fedf33a644b0e
{ "blob_id": "63b50fb915c827b6665aa41e006fedf33a644b0e", "branch_name": "refs/heads/master", "committer_date": "2018-05-24T08:51:57", "content_id": "cd200aa01629441f98c58ee428253b0f8f33a2b0", "detected_licenses": [ "MIT" ], "directory_id": "c256c3adcee5dc357a0212b7c0975331161b3636", "extension": "ts", "filename": "Threads.ts", "fork_events_count": 2, "gha_created_at": "2017-12-09T15:34:05", "gha_event_created_at": "2020-05-20T20:53:37", "gha_language": "TypeScript", "gha_license_id": null, "github_id": 113680074, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 790, "license": "MIT", "license_type": "permissive", "path": "/src/Threads.ts", "provenance": "stack-edu-0076.json.gz:246256", "repo_name": "Narazaka/2ch-fetcher", "revision_date": "2018-05-24T08:51:57", "revision_id": "4132c9d9e318166b9d6c60bfb43e292e486f179b", "snapshot_id": "641e07eaab52aea41403eb521672ed6b0ba8594a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Narazaka/2ch-fetcher/4132c9d9e318166b9d6c60bfb43e292e486f179b/src/Threads.ts", "visit_date": "2022-07-29T16:44:28.437907", "added": "2024-11-18T22:56:21.596727+00:00", "created": "2018-05-24T08:51:57", "int_score": 3, "score": 3.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz" }
import unittest from mock import patch from empiar_depositor.empiar_depositor import EmpiarDepositor from empiar_depositor.tests.testutils import capture, EmpiarDepositorTest missing_id_json_str = b'{\n "DATA_TYPE": "transfer_result",\n "code": "Accepted",\n "message": "The transfer has ' \ b'been accepted and a task has been created and queued for execution",\n "request_id": "abc",' \ b'\n "resource": "/transfer",\n "submission_id": "Task123",\n "task_link": {\n ' \ b'"DATA_TYPE": "link",\n "href": "task/Task123?format=json",\n "rel": "related",\n ' \ b'"resource": "task",\n "title": "related task"\n }\n}' class TestGlobusUpload(EmpiarDepositorTest): @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_failed_init_stdout(self, mock_popen): mock_popen.return_value.communicate.return_value = ("Task ID: 123", "") mock_popen.return_value.returncode = 1 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") with capture(emp_dep.globus_upload) as output: self.assertTrue('Globus transfer initiation was not successful. Return code:' in output) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_failed_init_return(self, mock_popen): mock_popen.return_value.communicate.return_value = (None, None) mock_popen.return_value.returncode = 1 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") c = emp_dep.globus_upload() self.assertEqual(c, 1) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_invalid_json_stdout(self, mock_popen): mock_popen.return_value.communicate.return_value = (b'The transfer has been accepted and a task has been ' b'created and queued for execution. Task ID: 123', None) mock_popen.return_value.returncode = 0 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") c = emp_dep.globus_upload() self.assertEqual(c, 1) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_invalid_json_return(self, mock_popen): mock_popen.return_value.communicate.return_value = (b'The transfer has been accepted and a task has been ' b'created and queued for execution. Task ID: 123', None) mock_popen.return_value.returncode = 0 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") with capture(emp_dep.globus_upload) as output: self.assertTrue('Error while processing transfer initiation result - the string does not contain a valid ' 'JSON. Return code' in output) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_missing_id_json_stdout(self, mock_popen): mock_popen.return_value.communicate.return_value = (missing_id_json_str, None) mock_popen.return_value.returncode = 0 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") c = emp_dep.globus_upload() self.assertEqual(c, 1) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_missing_id_json_return(self, mock_popen): mock_popen.return_value.communicate.return_value = (missing_id_json_str, None) mock_popen.return_value.returncode = 0 emp_dep = EmpiarDepositor("ABC123", self.json_path, "globus_obj", "", "globusid", {"is_dir": False, "obj_name": "globus_obj"}, entry_id=1, entry_directory="entry_dir") with capture(emp_dep.globus_upload) as output: self.assertTrue('Globus JSON transfer initiation result does not have a valid structure of ' 'JSON[\'task_id\']. Return code:' in output) @patch('empiar_depositor.empiar_depositor.subprocess.Popen') def test_failed_wait_upload(self, mock_popen): mock_popen.return_value.communicate.return_value = ("Waiting", None) mock_popen.return_value.stdout.readline.return_value = b'' mock_popen.return_value.returncode = 1 task_id = "Task123" c = EmpiarDepositor.globus_upload_wait(task_id) self.assertEqual(c, 1) if __name__ == '__main__': unittest.main()
d45302e08200f396e8d306feb47abed6d2a58f8b
{ "blob_id": "d45302e08200f396e8d306feb47abed6d2a58f8b", "branch_name": "refs/heads/master", "committer_date": "2023-08-16T10:37:10", "content_id": "667768fd976664dbab98db0261ccdc9b3bc2db55", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ecf1cdb9f7a59e13ed33062187dc57e6f221a9ce", "extension": "py", "filename": "test_globus_upload.py", "fork_events_count": 3, "gha_created_at": "2018-06-01T08:56:18", "gha_event_created_at": "2023-08-11T16:41:55", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 135693799, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5126, "license": "Apache-2.0", "license_type": "permissive", "path": "/empiar_depositor/tests/test_globus_upload.py", "provenance": "stack-edu-0055.json.gz:575553", "repo_name": "emdb-empiar/empiar-depositor", "revision_date": "2023-08-16T10:37:10", "revision_id": "8f46851083df44251ff53f5be44b585a6a1648d6", "snapshot_id": "e86d159a3c6e869cf77b8dfe28c8d936293e5e56", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/emdb-empiar/empiar-depositor/8f46851083df44251ff53f5be44b585a6a1648d6/empiar_depositor/tests/test_globus_upload.py", "visit_date": "2023-08-17T05:02:22.990765", "added": "2024-11-19T01:29:20.899458+00:00", "created": "2023-08-16T10:37:10", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz" }
import { Tracker, Position } from '../../src/core/state/trace' function createTrackerInstance (): Tracker { const tracker = Tracker() tracker.push({ x: 0, y: 0, time: 0 } as Position) tracker.push({ x: 1, y: 1, time: 5 } as Position) tracker.push({ x: 3, y: 4, time: 10 } as Position) return tracker } describe('Trace', () => { test('init', () => { const tracker = createTrackerInstance() expect(tracker.getDuration()).toEqual(10) expect(tracker.getOffset()).toEqual({ x: 3, y: 4 }) expect(tracker.vector()).toEqual({ x: 2, y: 3, velocityX: 0.4, velocityY: 0.6, angle: Math.atan2(3, 2) * 180 / Math.PI }) }) test('clear', () => { const tracker = createTrackerInstance() expect(tracker.getLogs()).toEqual([ { x: 0, y: 0, time: 0 }, { x: 1, y: 1, time: 5 }, { x: 3, y: 4, time: 10 } ]) tracker.clear() expect(tracker.getLogs()).toEqual([]) }) test('click action (only one log data)', () => { const tracker = Tracker() tracker.push({ x: 0, y: 0, time: 0 } as Position) expect(tracker.getDuration()).toEqual(0) expect(tracker.getOffset()).toEqual({ x: 0, y: 0 }) expect(tracker.vector()).toEqual({ x: 0, y: 0, velocityX: 0, velocityY: 0, angle: 0 }) }) })
c5c6cd5f8f211db2840ca76d525a257cb793ccdf
{ "blob_id": "c5c6cd5f8f211db2840ca76d525a257cb793ccdf", "branch_name": "refs/heads/dev", "committer_date": "2022-01-29T14:40:31", "content_id": "e40e72bfa006ae62a371914085295d21d155b157", "detected_licenses": [ "MIT" ], "directory_id": "71d20c30bed1031413efcbea3028742ec7c583be", "extension": "ts", "filename": "trace.spec.ts", "fork_events_count": 58, "gha_created_at": "2019-10-14T03:36:02", "gha_event_created_at": "2023-07-11T18:33:54", "gha_language": "TypeScript", "gha_license_id": null, "github_id": 214941058, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1870, "license": "MIT", "license_type": "permissive", "path": "/packages/tiny-swiper/__test__/unit/trace.spec.ts", "provenance": "stack-edu-0074.json.gz:708698", "repo_name": "joe223/tiny-swiper", "revision_date": "2022-01-29T14:40:31", "revision_id": "aca4f989fa75ec9907b99fcbbfcd10cf99893339", "snapshot_id": "285c98f63924d39732c734925f2fb74a564fcd3b", "src_encoding": "UTF-8", "star_events_count": 1315, "url": "https://raw.githubusercontent.com/joe223/tiny-swiper/aca4f989fa75ec9907b99fcbbfcd10cf99893339/packages/tiny-swiper/__test__/unit/trace.spec.ts", "visit_date": "2023-08-21T07:53:58.909199", "added": "2024-11-18T22:05:09.718017+00:00", "created": "2022-01-29T14:40:31", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
# Misabot <p align="center"> <img src="./web/src/assets/logo.png" align="center" /> <p align="center" style="font-size: 20px; padding: 0 20%;"> Play Music in Discord </p> </p> ## Invite Misabot Meet Misabot [here](https://misabotapp.herokuapp.com). ## Docs | ID | Name | Description | Usage | |----|------------------|-----------------------------------------|-----------------------------------------------------------| | 1 | !play | Plays a song or playlist on Youtube with the given name or url | !play {link/query} | | 2 | !soundcloud, !sc | Plays a song or playlist on SoundCloud with the given name or url | !soundcloud or !sc {link/query} | | 3 | !pause | Pause current song | !pause | | 4 | !resume | Resume current song | !resume | | 5 | !skip, !fs | Skip current song | !skip or !fs | | 6 | !stop | Stop and leave audio channel | !stop | | 7 | !nowplaying, !np | Get current song info | !nowplaying or !np | | 8 | !loop | Loop current song | !loop | | 9 | !queue | View songs in queue | !queue | | 10 | !select | Select song by position in queue | !select {position} | | 11 | !remove | Remove song by position in queue | !remove or !rm {position} | ## Guide Guide to build Misabot [here](https://viblo.asia/p/tao-mot-discord-bot-phat-nhac-don-gian-bang-nodejs-typescript-va-deploy-len-heroku-Qbq5QE935D8). ## License [MIT](https://choosealicense.com/licenses/mit/)
0132419923f23db4481ee80cdcbe28e819b85dbd
{ "blob_id": "0132419923f23db4481ee80cdcbe28e819b85dbd", "branch_name": "refs/heads/master", "committer_date": "2021-06-22T03:06:01", "content_id": "a9191103df3ef0406dd0e0f9fdea2551a9a7cc5e", "detected_licenses": [ "MIT" ], "directory_id": "a1642efc9bd2fa2b51f4d3a07a386ab44e09eb9d", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2151, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0005.json.gz:152955", "repo_name": "aleixespagaro/bot-tu", "revision_date": "2021-06-22T03:06:01", "revision_id": "7a5d0c5a1e9ad3684c370a9a71cacdb01ae23c90", "snapshot_id": "a436ea92aa873fafe6f1d61a631caa37f970d205", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aleixespagaro/bot-tu/7a5d0c5a1e9ad3684c370a9a71cacdb01ae23c90/README.md", "visit_date": "2023-06-02T00:46:14.278447", "added": "2024-11-18T22:17:22.815798+00:00", "created": "2021-06-22T03:06:01", "int_score": 3, "score": 2.90625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0005.json.gz" }
<?php namespace Arcanesoft\Seo\Http\Routes\Admin; use Arcanedev\Support\Routing\RouteRegistrar; use Arcanesoft\Seo\Models\Redirect; /** * Class RedirectsRoutes * * @package Arcanesoft\Seo\Http\Routes\Admin * @author ARCANEDEV <arcanedev.maroc@gmail.com> */ class RedirectsRoutes extends RouteRegistrar { /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * Register the bindings. */ public static function bindings() { $registrar = new static; $registrar->bind('seo_redirect', function ($id) { return Redirect::query()->findOrFail($id); }); } /** * Define the routes for the application. */ public function map() { $this->prefix('redirects')->name('redirects.')->group(function () { $this->get('/', 'RedirectsController@index') ->name('index'); // admin::seo.redirects.index $this->get('create', 'RedirectsController@create') ->name('create'); // admin::seo.redirects.create $this->post('store', 'RedirectsController@store') ->name('store'); // admin::seo.redirects.store $this->prefix('{seo_redirect}')->group(function () { $this->get('/', 'RedirectsController@show') ->name('show'); // admin::seo.redirects.show $this->get('edit', 'RedirectsController@edit') ->name('edit'); // admin::seo.redirects.edit $this->put('update', 'RedirectsController@update') ->name('update'); // admin::seo.redirects.update $this->delete('delete', 'RedirectsController@delete') ->middleware('ajax') ->name('delete'); // admin::seo.redirects.delete }); }); } }
fcc27cc02a8705cbbee548402ef8a06c55104256
{ "blob_id": "fcc27cc02a8705cbbee548402ef8a06c55104256", "branch_name": "refs/heads/master", "committer_date": "2017-09-08T16:28:45", "content_id": "0b772b6354c58a8129c3565698f264d82b2f8235", "detected_licenses": [ "MIT" ], "directory_id": "3c41809364d65478156e84082b4aa7991153311b", "extension": "php", "filename": "RedirectsRoutes.php", "fork_events_count": 0, "gha_created_at": "2016-01-27T18:14:28", "gha_event_created_at": "2017-09-08T16:28:46", "gha_language": "PHP", "gha_license_id": null, "github_id": 50527623, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1977, "license": "MIT", "license_type": "permissive", "path": "/src/Http/Routes/Admin/RedirectsRoutes.php", "provenance": "stack-edu-0053.json.gz:362271", "repo_name": "ARCANESOFT/SEO", "revision_date": "2017-09-08T16:28:45", "revision_id": "ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2", "snapshot_id": "674c8e95ce19720caef3cd9351d5eaa7d6864c45", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ARCANESOFT/SEO/ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2/src/Http/Routes/Admin/RedirectsRoutes.php", "visit_date": "2021-07-04T22:20:54.216775", "added": "2024-11-19T01:06:08.981055+00:00", "created": "2017-09-08T16:28:45", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
import {MathQuestionData} from "../questiondata" class MathQuestionDataGenerator { static getRandomInt(max: number) { return Math.floor(Math.random() * Math.floor(max)); } static getRandomRange(min: number, max: number, exclude: Array<number> = []) { var k = MathQuestionDataGenerator.getRandomInt(max - min) + min while (exclude.includes(k)) { k = MathQuestionDataGenerator.getRandomInt(max - min) + min } return k } static generate_basic_plus(): MathQuestionData { var a = MathQuestionDataGenerator.getRandomInt(10); var b = MathQuestionDataGenerator.getRandomInt(10); return new MathQuestionData("計算せよ", "", String(a) + "+" + String(b), String(a + b)) } static generate_basic_minus(): MathQuestionData { var a = MathQuestionDataGenerator.getRandomInt(10); var b = MathQuestionDataGenerator.getRandomInt(10); return new MathQuestionData("計算せよ", "",String(a) + "-" + String(b), String(a - b)) } static generate_basic_mul(): MathQuestionData { var a = MathQuestionDataGenerator.getRandomInt(10); var b = MathQuestionDataGenerator.getRandomInt(10); return new MathQuestionData("計算せよ", "",String(a) + "\\times" + String(b), String(a * b)) } static generate_basic_div(): MathQuestionData { var a = MathQuestionDataGenerator.getRandomInt(9); var b = MathQuestionDataGenerator.getRandomInt(9); a += 1 b += 1 var k = a * b return new MathQuestionData("計算せよ", "",String(k) + "\\div" + String(b), String(a)) } static _quadraticequation_text(a: number, b: number, c: number) { var text = "" if (a !== 1) { if (a === -1) { text += "-" } else { text += String(a) } } text += "x^2" if (b !== 0) { if (b > 0) { text += "+" } if (b !== 1) { if (b === -1) { text += "-" } else { text += String(b) } } text += "x" } if (c > 0) { text += "+" } text += String(c) return text } static _linerequation_text(a: number, b: number) { var text = "" if (a !== 0) { if (a !== 1) { if (a === -1) { text += "-" } else { text += String(a) } } text += "x" } if (b > 0) { text += "+" } text += String(b) return text } static generate_basic_quadraticequation(): MathQuestionData { var x1 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var x2 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var b = x1 + x2 var c = x1 * x2 var text = MathQuestionDataGenerator._quadraticequation_text(1, b, c) text += "=0" var answer = "x=" + String(-x1) if (x1 !== x2) { answer += ", " + String(-x2) } return new MathQuestionData( "次の方程式を解け", "", text, answer ) } static generate_basic_quadraticequation_extract(): MathQuestionData { var x1 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var x2 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var x3 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var x4 = MathQuestionDataGenerator.getRandomRange(-9, 9, [0]); var text = "(" + MathQuestionDataGenerator._linerequation_text(x1, x2) + ")" text += "(" + MathQuestionDataGenerator._linerequation_text(x3, x4) + ")" var a = (x1 * x3) var b = (x1 * x4 + x2 * x3) var c = (x2 * x4) return new MathQuestionData("展開せよ", "", text, MathQuestionDataGenerator._quadraticequation_text(a, b, c)) } static generate_basic_sin(): MathQuestionData { var text = "sin 30^{o}" var ans = "\\frac{1}{2}" return new MathQuestionData("単位円上での値を書け", "", text, ans ) } } export {MathQuestionDataGenerator}
4afa1c034baba257e24f4e0d13e27bd381844365
{ "blob_id": "4afa1c034baba257e24f4e0d13e27bd381844365", "branch_name": "refs/heads/master", "committer_date": "2020-05-27T00:02:04", "content_id": "0dddd1a20748d1e5fd4066d71e4284d965ae7d23", "detected_licenses": [ "MIT" ], "directory_id": "d5abce30948e15d2ff6f0306b5ad62d842f7417d", "extension": "ts", "filename": "mathQuestionGenerator.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 262597615, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4488, "license": "MIT", "license_type": "permissive", "path": "/src/questsions/math/mathQuestionGenerator.ts", "provenance": "stack-edu-0074.json.gz:282484", "repo_name": "mitsuo0114/tenarai", "revision_date": "2020-05-27T00:02:04", "revision_id": "3fefd1d634982e70e1d10779a668c9cddb1e3b34", "snapshot_id": "1842557a5774360e67f426c6ee8f2275f8902019", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mitsuo0114/tenarai/3fefd1d634982e70e1d10779a668c9cddb1e3b34/src/questsions/math/mathQuestionGenerator.ts", "visit_date": "2022-10-08T14:41:46.001333", "added": "2024-11-18T21:55:03.584431+00:00", "created": "2020-05-27T00:02:04", "int_score": 3, "score": 3.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
<?php declare(strict_types=1); namespace WeChatPay\Tests\OpenAPI\V2\Secapi\Mch; use const DIRECTORY_SEPARATOR; use function basename; use function dirname; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\LazyOpenStream; use GuzzleHttp\Psr7\Utils; use GuzzleHttp\Psr7\MultipartStream; use Psr\Http\Message\ResponseInterface; use WeChatPay\Builder; use WeChatPay\Crypto\Hash; use WeChatPay\Formatter; use WeChatPay\Transformer; use WeChatPay\ClientDecoratorInterface; use PHPUnit\Framework\TestCase; class UploadmediaTest extends TestCase { /** @var MockHandler $mock */ private $mock; private function guzzleMockStack(): HandlerStack { $this->mock = new MockHandler(); return HandlerStack::create($this->mock); } /** * @param string $mchid * @param string $secret * @return array{\WeChatPay\BuilderChainable,HandlerStack} */ private function prepareEnvironment(string $mchid, string $secret): array { $instance = Builder::factory([ 'mchid' => $mchid, 'serial' => 'nop', 'privateKey' => 'any', 'certs' => ['any' => null], 'secret' => $secret, 'handler' => $this->guzzleMockStack(), ]); /** @var HandlerStack $stack */ $stack = $instance->getDriver()->select(ClientDecoratorInterface::XML_BASED)->getConfig('handler'); $stack = clone $stack; $stack->remove('transform_request'); $endpoint = $instance->chain('v2/secapi/mch/uploadmedia'); return [$endpoint, $stack]; } /** * @return array<string,array{string,string,MultipartStream,ResponseInterface}> */ public function mockRequestsDataProvider(): array { $mchid = '1230000109'; $secret = Formatter::nonce(32); $data = [ 'media_id' => Formatter::nonce(107), 'return_code' => 'SUCCESS', 'return_msg' => 'OK', 'result_code' => 'SUCCESS', ]; $data['sign'] = Hash::sign(Hash::ALGO_MD5, Formatter::queryStringLike(Formatter::ksort($data)), $secret); $logo = dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'logo.png'; $media = new LazyOpenStream($logo, 'rb'); $formDataStructure = ['mch_id' => $mchid, 'media_hash' => Utils::hash($media, 'md5'),]; $formDataStructure['sign'] = Hash::sign(Hash::ALGO_MD5, Formatter::queryStringLike(Formatter::ksort($formDataStructure)), $secret); $elements = [['name' => 'media', 'contents' => $media, 'filename' => basename($logo),]]; foreach($formDataStructure as $key => $value) { $elements[] = ['name' => $key, 'contents' => $value]; } $body = new MultipartStream($elements); return [ 'return_code=SUCCESS' => [$mchid, $secret, $body, new Response(200, [], Transformer::toXml($data))], ]; } /** * @dataProvider mockRequestsDataProvider * @param string $mchid * @param string $secret * @param MultipartStream $body * @param ResponseInterface $respondor */ public function testPost(string $mchid, string $secret, MultipartStream $body, ResponseInterface $respondor): void { [$endpoint, $stack] = $this->prepareEnvironment($mchid, $secret); $this->mock->reset(); $this->mock->append($respondor); // yes, start with `@` to prevent the internal `E_USER_DEPRECATED` $res = @$endpoint->post([ 'body' => $body, 'handler' => $stack, // 'ssl_key' => 'file:///path/to/apiclient_key.pem', // 'cert' => 'file:///path/to/apiclient_cert.pem', ]); self::responseAssertion($res); } /** * @param ResponseInterface $response */ private static function responseAssertion(ResponseInterface $response): void { $txt = (string) $response->getBody(); $array = Transformer::toArray($txt); static::assertArrayHasKey('sign', $array); static::assertArrayHasKey('media_id', $array); static::assertArrayHasKey('return_code', $array); static::assertArrayHasKey('result_code', $array); } /** * @dataProvider mockRequestsDataProvider * @param string $mchid * @param string $secret * @param MultipartStream $body * @param ResponseInterface $respondor */ public function testPostAsync(string $mchid, string $secret, MultipartStream $body, ResponseInterface $respondor): void { [$endpoint, $stack] = $this->prepareEnvironment($mchid, $secret); $this->mock->reset(); $this->mock->append($respondor); // yes, start with `@` to prevent the internal `E_USER_DEPRECATED` @$endpoint->postAsync([ 'body' => $body, 'handler' => $stack, // 'ssl_key' => 'file:///path/to/apiclient_key.pem', // 'cert' => 'file:///path/to/apiclient_cert.pem', ])->then(static function(ResponseInterface $res) { self::responseAssertion($res); })->wait(); } }
10fb67b14380c688c0a8ebcce9aca9afd4bae26a
{ "blob_id": "10fb67b14380c688c0a8ebcce9aca9afd4bae26a", "branch_name": "refs/heads/main", "committer_date": "2021-11-08T08:09:05", "content_id": "5aab308f70b985ff84f79183afcfc32583dcd1e6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a62286e93f845fb5973489b9516ec75515085cfe", "extension": "php", "filename": "UploadmediaTest.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": 5231, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/OpenAPI/V2/Secapi/Mch/UploadmediaTest.php", "provenance": "stack-edu-0047.json.gz:683575", "repo_name": "wangbenphp/wechatpay-php", "revision_date": "2021-11-08T08:09:05", "revision_id": "51e5050a76332f1506d26e997b9ac29c0e8a09ab", "snapshot_id": "56303d2775efec6d83f2abe32c8f1ceab783d8fc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wangbenphp/wechatpay-php/51e5050a76332f1506d26e997b9ac29c0e8a09ab/tests/OpenAPI/V2/Secapi/Mch/UploadmediaTest.php", "visit_date": "2023-09-03T00:55:58.197932", "added": "2024-11-19T02:32:19.289446+00:00", "created": "2021-11-08T08:09:05", "int_score": 2, "score": 2.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
# Sourcetrail Extenstion for VS Code This extension enables VS Code to communicate with [Sourcetrail](http://sourcetrail.com) ## Links * Project Home, News: [www.sourcetrail.com](https://www.sourcetrail.com/) * Documentation: [www.sourcetrail.com/documentation](https://www.sourcetrail.com/documentation/#VsCode) * Download, Reviews: [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=astallinger.sourcetrail) * Code, Issues: [GitHub](http://github.com/CoatiSoftware/vsce-sourcetrail.git) ## Features > Settings for the Plugin ![Settings](images/vsce-sourcetrail1.png) > Send Location from VS Code to Sourcetrail via context menu ![Context](images/vsce-sourcetrail2.png) > Display if the plugin is connected to Sourcetrail. Sourcetrail will be displayed if the TCP Server is running. ![Statusbar](images/vsce-sourcetrail3.png) ## Requirements Plugin and Sourcetrail should be able to communicate over TCP ## Extension Settings This extension contributes the following settings: * `sourcetrail.pluginPort`: port VS Code listens to * `sourcetrail.sourcetrailPort`: port Sourcetrail listens to * `sourcetrail.ip`: TCP server ip address * `sourcetrail.startServerAtStartup`: set to `true` to start the TCP listener at VS Code startup
6230351ad2b8524fe7525f470d6870d7e5ed3366
{ "blob_id": "6230351ad2b8524fe7525f470d6870d7e5ed3366", "branch_name": "refs/heads/master", "committer_date": "2020-02-24T15:12:50", "content_id": "30cce96832f856f922b1cb88af6aa3556a44455e", "detected_licenses": [ "MIT" ], "directory_id": "80bbb4c1a52a1390b500f3c42799b7643a3b56db", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1272, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0007.json.gz:231997", "repo_name": "lxngoddess5321/vsce-sourcetrail", "revision_date": "2020-02-24T15:12:50", "revision_id": "97ba7e5b63d96d1b553e725a070cfc2b4c21d23f", "snapshot_id": "f0771716f7bec882f9481a85bf1301e8cfa7a2dd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lxngoddess5321/vsce-sourcetrail/97ba7e5b63d96d1b553e725a070cfc2b4c21d23f/README.md", "visit_date": "2022-04-07T16:45:05.256715", "added": "2024-11-18T23:30:02.362279+00:00", "created": "2020-02-24T15:12:50", "int_score": 3, "score": 3.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
import femto.Game; import femto.input.Button; import femto.mode.HiRes16Color; import femto.palette.UltimaViSharpX68000; import femto.font.FontC64; import audio.Hurt; import sprites.Loot; import sprites.Magnet; import managers.SaveManager; import managers.SectorZoneManager; import managers.EndlessSaveManager; /** * Globals contains all of the globally used variables as well as * a couple of useful helper methods. * */ class Globals { //TODO: I find it incredibly annoying to have the Bot's "hurt" variable here. static final Hurt pain = new Hurt(2); static final SaveManager saveManager = new SaveManager(); // Initialize only in endless mode static EndlessSaveManager endlessSaveManager; static final HiRes16Color screen = new HiRes16Color(UltimaViSharpX68000.palette(), FontC64.font()); static final Loot loot = new Loot(); static final Magnet mag = new Magnet(); static int ZONE = 0, SECTOR = 0, t = 100; static int score = 0, kills = 0; static int shield = 100, hurt = 0, hit = 0, shots = 0; static boolean createItemDrop = false; static float itemX = 0, itemY = 0; static final String PRESS_C_TRANSPORT = "[C] - Transport"; static boolean endlessUnlocked, endless; static void initEndlessMode(){ ZONE = 0; endlessSaveManager = new EndlessSaveManager(); endless = true; shield = 100; score = 0; endlessSaveManager.highScore = 0; endlessSaveManager.rate = 1; endlessSaveManager.refresh = 50; endlessSaveManager.currency = 0; endlessSaveManager.magnet = 0; endlessSaveManager.charge = 1; endlessSaveManager.damage = 2; endlessSaveManager.saveCookie(); } /** * Takes two square objects and checks if they intersect, given x,y and size * The boxing shape is always a square */ public static boolean boundingBox(float x1, float y1, float s1, float x2, float y2, float s2){ return (x1 < x2 + s2 && x1 + s1 > x2 && y1 < y2 + s2 && y1 + s1 > y2); } public static boolean checkHitBot(float vx, float vy, int vSize, float bx, float by, int bSize){ if(boundingBox(vx, vy, vSize, bx, by, bSize)){ if(hurt == 0){ pain.play(); hurt = 50; return true; } } return false; } /** * When an enemy is destroyed, this is called to create an item drop and to update variables */ public static void updateKills(float x, float y){ kills++; score += 10; itemX = x; itemY = y; createItemDrop = true; } public static void reset(){ kills = 0; hit = 0; shots = 0; score = 0; SECTOR = 0; } public static void newGame(){ saveManager.started = true; endlessUnlocked = false; saveManager.firstZoneClear = false; saveManager.secondZoneClear = false; saveManager.thirdZoneClear = false; saveManager.fourthZoneClear = false; saveManager.rate = 1; saveManager.refresh = 50; saveManager.currency = 0; saveManager.magnet = 0.0f; saveManager.charge = 1; saveManager.damage = 2; saveManager.saveCookie(); System.out.println("New game"); } /** * When a ZONE is cleared, we calculate the accuracy to display on the results view. * This will also be used to determine acheivments */ public static int getAccuracy() { if(hit == 0) return 0; if(shots == 0) return 0; return Math.abs(hit * 100 / shots); } /** * drawHud displays the top progress bar indicators for shield/threats/boss health * as well as displaying the Score, currency and current ZONE:SECTOR. * */ static void drawHud(int threatWidth){ // Fill rects for the top and bottom sections screen.fillRect(0, 0, 220, 16, 3); screen.fillRect(0, 162, 140, 16, 3); // Bot Shield screen.drawRect(6, 0, 80, 6, 0); screen.fillRect(8, 2, 78, 4, 2); // bot shield screen.fillRect(8, 2, (int)(shield * 78 / 100), 4, 15); // Blast charge box screen.drawRect(6, 10, 70, 4, 0); screen.fillRect(8, 12, 68, 2, 2); // The blast charge fill is rendered in BlastManager:L85 // NormalSector draws the sector total. // Boss Blast charge box if(SECTOR != 8){ screen.drawRect(144, 10, 70, 4, 0); screen.fillRect(146, 12, 68, 2, 2); } //Threats or Boss Shield screen.drawRect(134, 0, 80, 6, 0); screen.fillRect(136, 2, 78, 4, 2); // threats health screen.fillRect(214-threatWidth, 2, threatWidth, 4, 8); // Zone : SECTOR screen.setTextPosition(98, 3); screen.setTextColor(0); screen.print(ZONE + ":" + SECTOR); // Mini Fragments (currency) if(SECTOR != 4 && SECTOR != 8){ loot.play(); loot.draw(screen, 6, 164); // Currency drawn on NormalSector // screen.setTextPosition(16, 164); // screen.print("x"+saveManager.currency); // Magnet if(endless){ if(endlessSaveManager.magnet > 0.0f){ mag.idle(); mag.draw(screen, 120, 164); screen.setTextPosition(130, 164); screen.print((int)(endlessSaveManager.magnet*100) + "%"); } }else{ if(saveManager.magnet > 0.0f){ mag.idle(); mag.draw(screen, 120, 164); screen.setTextPosition(130, 164); screen.print((int)(saveManager.magnet*100) + "%"); } } } } static void drawGrid(){ screen.drawRect(6, 17, 208, 144, 12, true); } static void drawCleared(boolean boss){ screen.setTextColor(12); screen.fillRect(0, 160, 220, 20, 3); screen.setTextPosition(0, 167); screen.print(PRESS_C_TRANSPORT); if(t < 50){ int x = screen.textWidth(PRESS_C_TRANSPORT); if(t < 4) screen.drawRect(x, 166, 5, 9, 12); else screen.fillRect(x, 166, 5, 9, 12); } t--; if(t == 0){ t = 100; } if(Button.C.justPressed()){ SECTOR++; if(endless && boss){ score += 500 + (ZONE * 50); } Game.changeState(new Shop()); } } }
6a13283c2e38be11bd9bc0a99dabe4f2038e6e9f
{ "blob_id": "6a13283c2e38be11bd9bc0a99dabe4f2038e6e9f", "branch_name": "refs/heads/master", "committer_date": "2021-03-17T20:14:44", "content_id": "30ae9c139be64837f5b516c85ba41f25e11a10ac", "detected_licenses": [ "MIT" ], "directory_id": "fe57960860a1e2f41b3933a0466a7c129ffaa37d", "extension": "java", "filename": "Globals.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 186501282, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6698, "license": "MIT", "license_type": "permissive", "path": "/Globals.java", "provenance": "stack-edu-0028.json.gz:134770", "repo_name": "Torbuntu/VirusBuster_Pokitto", "revision_date": "2021-03-17T20:14:44", "revision_id": "8429d6535e040a9169d640a15c492e044b79600d", "snapshot_id": "75e8bd08ab2cc17e17176b3a4fc8f85a6966bd7a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Torbuntu/VirusBuster_Pokitto/8429d6535e040a9169d640a15c492e044b79600d/Globals.java", "visit_date": "2023-03-20T21:32:22.029585", "added": "2024-11-19T00:03:23.503153+00:00", "created": "2021-03-17T20:14:44", "int_score": 3, "score": 2.546875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
package bof; public class Demo6 extends Worker { private static SmallObject<Integer> createFoo(int i) { return new SmallObject<>(i); } @Override protected void doWork() { for (int i = 0; i < 1000 * 1000 * 10; i++) { SmallObject<Integer> fi = createFoo(i); SmallObject<SmallObject<Integer>> ff = new SmallObject<>(fi); } } }
d18c980a0592c2712335dbe67f8ae770d186275a
{ "blob_id": "d18c980a0592c2712335dbe67f8ae770d186275a", "branch_name": "refs/heads/master", "committer_date": "2018-08-31T17:09:03", "content_id": "2170a0480e65340c646d4911aa10251d18643452", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9a521af8f0346d9210c1054715966b0d251267cc", "extension": "java", "filename": "Demo6.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 145188832, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 389, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/bof/Demo6.java", "provenance": "stack-edu-0028.json.gz:22285", "repo_name": "iceboundrock/escape-analysis-demo", "revision_date": "2018-08-31T17:09:03", "revision_id": "9b2dc3b18f72a0fc212f02aff5b9027f17a87a7f", "snapshot_id": "1f0e2b61973d424ca80dd2c88b0b7e84316ec976", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iceboundrock/escape-analysis-demo/9b2dc3b18f72a0fc212f02aff5b9027f17a87a7f/src/main/java/bof/Demo6.java", "visit_date": "2020-03-26T17:57:12.053418", "added": "2024-11-18T22:04:20.883932+00:00", "created": "2018-08-31T17:09:03", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
# # オープニング処理. # https://docs.openmv.io/library/omv.image.html#image.image.open # http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html#opening # ################################################## # import ################################################## import lcd import sensor ################################################## # initialize ################################################## # LCDを初期化 lcd.init() # LCDの方向を設定 lcd.direction(lcd.YX_LRUD) # カメラを初期化 sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.run(1) ################################################## # main ################################################## while True: # カメラ画像を取得 img = sensor.snapshot() # オープニング処理 img.open(3) # 画像をLCDに描画 lcd.display(img)
fc57d07dcd2714da9c34d798b6f879ef19dc77d3
{ "blob_id": "fc57d07dcd2714da9c34d798b6f879ef19dc77d3", "branch_name": "refs/heads/master", "committer_date": "2020-04-01T10:41:17", "content_id": "e4c95369fdf5cc72607db6f285a9b538598127f0", "detected_licenses": [ "MIT" ], "directory_id": "4935470fa763f85fa3d63a0aa28f91d8929871a7", "extension": "py", "filename": "open.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": 1011, "license": "MIT", "license_type": "permissive", "path": "/machine_vision/open.py", "provenance": "stack-edu-0059.json.gz:584524", "repo_name": "reltkaine/M5stickV-playground", "revision_date": "2020-04-01T10:41:17", "revision_id": "9c1447078bebb279684bf9fc4b485c1aae1c8b12", "snapshot_id": "57a087bb5ec995492e6393ebf03df93938f3e96f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reltkaine/M5stickV-playground/9c1447078bebb279684bf9fc4b485c1aae1c8b12/machine_vision/open.py", "visit_date": "2023-07-03T02:04:01.476886", "added": "2024-11-18T18:15:58.061483+00:00", "created": "2020-04-01T10:41:17", "int_score": 3, "score": 2.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
# QuoteJar QuoteJar let's you easily store the cute things your kids say (or the awful things your enemies say), including the date quoted and the age the child (or enemy) was when quoted. ## Usage To install from the command line: gem install 'quotejar' Once installed, in IRB enter "require 'quotejar'", and then enter "start". You will be prompted to enter a child's name. If you have entered information for this childed previously, you will be prompted to enter a new quote or list all quotes saved for that child. If the child has not been stored previously, you will be prompted to save the child by entering the child's birthday, and then will be able to enter new quotes. Creating a new child will create a .yaml file to store that child's name, birthday and quotes. Creating new entries for an existing child will update that child's .yaml file. Note: The .yaml file will be created in the directory where you have started your IRB session. Make sure you use the same directory each time if you want to load previously create .yaml files. If you get booted out of the program during an IRB session, typing 'start' will begin QuoteJar again. ## Features To Come - Ability to search quotes by date or age - Better tests - User to specify where to store .yaml files for each child ## Contributing 1. Fork it ( https://github.com/jtrudell/quotejar/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
26820edda412989e4396dc9135f3e4a1f81f3190
{ "blob_id": "26820edda412989e4396dc9135f3e4a1f81f3190", "branch_name": "refs/heads/master", "committer_date": "2015-06-09T02:03:50", "content_id": "271fbe90add964187bf829a14ea8a18b4373ff6e", "detected_licenses": [ "MIT" ], "directory_id": "434a3d45ca2be20827fd7e2867c889f1c71da5bb", "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": 37088988, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1584, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0013.json.gz:336042", "repo_name": "jtrudell/quotejar", "revision_date": "2015-06-09T02:03:50", "revision_id": "18098b835158faabc8c7e3ef14bafe8ca86af1a9", "snapshot_id": "32dfd6982b36bbf17e8e21c9f9a4ee41441a0b09", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jtrudell/quotejar/18098b835158faabc8c7e3ef14bafe8ca86af1a9/README.md", "visit_date": "2016-09-05T17:32:57.853982", "added": "2024-11-19T00:28:43.300063+00:00", "created": "2015-06-09T02:03:50", "int_score": 3, "score": 3.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz" }
#!/bin/bash # Script to initialize moloch, add a user, and run the services ESURL=elasticsearch-master ADMINPASSWORD=Sealingtech echo INIT | /data/moloch/db/db.pl http://$ESURL:9200 init /data/moloch/bin/moloch_add_user.sh admin "Admin User" $ADMINPASSWORD --admin /data/moloch/bin/moloch_update_geo.sh chmod a+rwx /data/moloch/raw /data/moloch/logs echo "Starting Moloch capture and viewer..." /data/moloch/bin/moloch_config_interfaces.sh # ===== Uncomment for packetcapture on the master server ===== # #cd /data/moloch #nohup /data/moloch/bin/moloch-capture -c /data/moloch/etc/config.ini >> /data/moloch/logs/capture.log 2>&1 & # ============================================================ # cd /data/moloch/viewer /data/moloch/bin/node viewer.js -c /data/moloch/etc/config.ini >> /data/moloch/logs/viewer.log 2>&1
25cd7d98c067125da3e7df3a99332aeb539e53fd
{ "blob_id": "25cd7d98c067125da3e7df3a99332aeb539e53fd", "branch_name": "refs/heads/master", "committer_date": "2018-07-18T19:30:06", "content_id": "84e378bf95edb1c8b1c9c4cc0d4fa4f4b87bf368", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5aaf581dbd76d4e95630d4d8bce093c78249040f", "extension": "sh", "filename": "startmoloch.sh", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120018239, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 824, "license": "Apache-2.0", "license_type": "permissive", "path": "/OLD/updatedfiles/containers/master/Moloch/startmoloch.sh", "provenance": "stack-edu-0069.json.gz:330590", "repo_name": "miked235/EDCOP-TOOLS", "revision_date": "2018-07-18T19:30:06", "revision_id": "5678adf3ee8be5f89555574bc430b88c665d6e91", "snapshot_id": "5305fe3dd82e2cbafc893be365d2ac5c718d38fe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/miked235/EDCOP-TOOLS/5678adf3ee8be5f89555574bc430b88c665d6e91/OLD/updatedfiles/containers/master/Moloch/startmoloch.sh", "visit_date": "2020-03-18T22:16:09.495508", "added": "2024-11-18T21:48:49.095842+00:00", "created": "2018-07-18T19:30:06", "int_score": 3, "score": 2.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
#include "Chapter1Helper.h" #include <iostream> using namespace std; void Chapter1Helper::RunExercise1() { // 1.1 Display Welcome to C++, Welcome to CS, and Programming is Fun cout << "Welcome to C++!" << endl; cout << "Welcome to Computer Science!" << endl; cout << "Programming is fun" << endl; } void Chapter1Helper::RunExercise2() { // 1.2 Display Welcome to C++ 5 times PrintMessage(5); } void Chapter1Helper::RunExercise3() { // 1.3 Program to Display pattern cout << " CCCC + +" << endl; cout << " C + +" << endl; cout << "C +++++++ +++++++" << endl; cout << " C + +" << endl; cout << " CCCC + +" << endl; } void Chapter1Helper::RunExercise4() { // 1.4 Print a table cout << "a a^2 a^3" << endl; cout << "1 1 1" << endl; cout << "2 4 8" << endl; cout << "3 9 27" << endl; cout << "4 16 64" << endl; } void Chapter1Helper::RunExercise5() { // 1.5 Write a program that displays math result cout << (9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5) << endl; } void Chapter1Helper::RunExercise6() { // 1.6 summation of 1+2+3+4+5+6+7+8+9 PrintSummation(9); } void Chapter1Helper::RunExercise7() { // 1.7 Approximating pi cout << 4 * (1.0 - 1.0 / 3.0 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11 + 1.0 / 13) << endl; } void Chapter1Helper::PrintMessage(int num) { for (int i = 0; i < num; i++) { cout << "Welcome to C++!" << endl; } } void Chapter1Helper::PrintSummation(int num) { int sum = 0; for (int i = 1; i < num + 1; i++) { sum = sum + i; } cout << sum << endl; }
ea7fe954209c71187f75ba195ec950e5c7d23d8d
{ "blob_id": "ea7fe954209c71187f75ba195ec950e5c7d23d8d", "branch_name": "refs/heads/main", "committer_date": "2021-06-11T00:31:35", "content_id": "fb875d0663df0842904ce2ae81d77705f08f3188", "detected_licenses": [ "MIT" ], "directory_id": "1925daf0738339b4f9f19745e01c893610e839c3", "extension": "cpp", "filename": "Chapter1Helper.cpp", "fork_events_count": 0, "gha_created_at": "2020-10-12T00:15:34", "gha_event_created_at": "2021-06-06T03:32:54", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 303236966, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1721, "license": "MIT", "license_type": "permissive", "path": "/cppLearningExercises/Chapter1Helper.cpp", "provenance": "stack-edu-0006.json.gz:201835", "repo_name": "QueeniePun/cppLearningExercises", "revision_date": "2021-06-11T00:31:35", "revision_id": "4c4181573d1b7de9f67acdea1b0fd6d2245b8806", "snapshot_id": "dd6e6830b3004737e7e8efc4333560c53b28809f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/QueeniePun/cppLearningExercises/4c4181573d1b7de9f67acdea1b0fd6d2245b8806/cppLearningExercises/Chapter1Helper.cpp", "visit_date": "2023-05-28T08:52:25.478879", "added": "2024-11-18T22:05:06.813201+00:00", "created": "2021-06-11T00:31:35", "int_score": 4, "score": 3.546875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
// for ( n of nums ) for( n in nums ) 차이 알기 const numbers = [ 10, 20, 30, 40, 50 ]; for( let number of numbers ) { console.log( number ); } const doggy = { name: '멍멍이', sound: '멍멍', age: 2 }; // console.log( Object.entries( doggy ) ); // console.log( Object.keys( doggy ) ); // console.log( Object.values( doggy ) ); for ( let key in doggy ) { console.log( `${key} : ${doggy[key]}` ); console.log( key + ' : ' + doggy[key] ); } // for( let key of doggy ) { // console.log( key ); // }
777e070a9b451a186b0e8b3cbcc0b4a3c86c14f3
{ "blob_id": "777e070a9b451a186b0e8b3cbcc0b4a3c86c14f3", "branch_name": "refs/heads/master", "committer_date": "2020-01-10T06:39:31", "content_id": "4127fccb2da1aa464555f0dba1e3038f64fa46d3", "detected_licenses": [ "MIT" ], "directory_id": "0f94ebbee84cda7e8f87c2369ee48280dc144752", "extension": "js", "filename": "forofforin.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 218939145, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 540, "license": "MIT", "license_type": "permissive", "path": "/JavaScript/basics/forofforin.js", "provenance": "stack-edu-0043.json.gz:381456", "repo_name": "zionhan/TIL", "revision_date": "2020-01-10T06:39:31", "revision_id": "2b74bf3f977ead3432bde64e9826f505af58de26", "snapshot_id": "8def3247a8534bc5cb9e01bf1f793ad1a115bf5d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zionhan/TIL/2b74bf3f977ead3432bde64e9826f505af58de26/JavaScript/basics/forofforin.js", "visit_date": "2020-09-01T10:22:36.341420", "added": "2024-11-19T01:47:11.797761+00:00", "created": "2020-01-10T06:39:31", "int_score": 4, "score": 3.921875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
<?php //Clase : PROFESOR_Controller //Creado el : 27-09-2019 //Creado por: 70ky5e //Descripcion: Funciona como intermediario Vista-Modelo (pide los datos al modelo y los devuelve de nuevo a la vista). Se encarga de controlar las interacciones del usuario en la vista. //------------------------------------------------------- session_start(); //solicito trabajar con la session include '../Functions/Authentication.php'; //Si no está autentificado, redirige al index.php if (!IsAuthenticated()){ header('Location:../index.php'); } include '../Model/PROFESOR_Model.php'; include '../View/PROFESOR_SHOWALL_View.php'; include '../View/PROFESOR_SEARCH_View.php'; include '../View/PROFESOR_ADD_View.php'; include '../View/PROFESOR_EDIT_View.php'; include '../View/PROFESOR_DELETE_View.php'; include '../View/PROFESOR_SHOWCURRENT_View.php'; include '../View/MESSAGE_View.php'; // la función get_data_form() recoge los valores que vienen del formulario por medio de post y la action a realizar, crea una instancia USUARIOS y la devuelve function get_data_form(){ $DNI = $_POST['DNI'];//recojo la variable DNI $NOMBREPROFESOR = $_POST['NOMBREPROFESOR'];//recojo la variable NOMBREPROFESOR $APELLIDOSPROFESOR = $_POST['APELLIDOSPROFESOR'];//recojo la variable APELLIDOSPROFESOR $AREAPROFESOR = $_POST['AREAPROFESOR'];//recojo la variable AREAPROFESOR $DEPARTAMENTOPROFESOR = $_POST['DEPARTAMENTOPROFESOR'];//recojo la variable DEPARTAMENTOPROFESOR //creamos el modelo con los datos que recojimos anteriormente y lo guardamos en la variable profesor $PROFESOR = new PROFESOR_Model($DNI,$NOMBREPROFESOR,$APELLIDOSPROFESOR,$AREAPROFESOR,$DEPARTAMENTOPROFESOR); return $PROFESOR; } // sino existe la variable action la crea vacia para no tener error de undefined index if (!isset($_REQUEST['action'])){ $_REQUEST['action'] = ''; } // En funcion del action realizamos las acciones necesarias switch ($_REQUEST['action']){ case 'ADD': //si no nos llegan los datos por post if (!$_POST){ // se incoca la vista de add de usuarios new PROFESOR_ADD();//invoca la vista de add } else{//si nos llegan los datos por post $PROFESOR = get_data_form(); //se recogen los datos del formulario $respuesta = $PROFESOR->ADD();//se añaden los datos y se guardan en la variable respuesta new MESSAGE($respuesta, '../Controller/PROFESOR_Controller.php'); //se genera un mensaje con la respuesta } break; case 'DELETE': if (!$_POST){ //nos llega el id a eliminar por get $PROFESOR = new PROFESOR_Model($_REQUEST['DNI'],'','','','');//creamos el objeto $valores = $PROFESOR->RellenaDatos(); ////recogemos los datos en la variable valores new PROFESOR_DELETE($valores); //se le muestra al usuario los valores de la tupla para que confirme el borrado mediante un form que no permite modificar las variables } else{ // llegan los datos confirmados por post y se eliminan $PROFESOR = get_data_form();//se recogen los datos del formulario $respuesta = $PROFESOR->DELETE();//se eliminan y se guarda en la variable respuesta new MESSAGE($respuesta, '../Controller/PROFESOR_Controller.php');//se genera un mensaje con la respuesta } break; case 'EDIT': //si no nos llegan los datos por post if (!$_POST){ //nos llega el usuario a editar por get $PROFESOR = new PROFESOR_Model($_REQUEST['DNI'],'','','',''); // Creo el objeto $valores = $PROFESOR->RellenaDatos(); // obtengo todos los datos de la tupla //si hay valores if (is_array($valores)) { new PROFESOR_EDIT($valores); //invoco la vista de edit con los datos //precargados }else //si no hay valores { new MESSAGE($valores, '../Controller/PROFESOR_Controller.php');//se genera un mensaje con la respuesta } } else{//si nos llegan los datos por post $PROFESOR = get_data_form(); //recojo los valores del formulario $respuesta = $PROFESOR->EDIT(); // update en la bd en la bd new MESSAGE($respuesta, '../Controller/PROFESOR_Controller.php');//se genera un mensaje con la respuesta } break; case 'SEARCH': //si no nos llegan los datos por post if (!$_POST){//nos llega el profesor a buscar por get new PROFESOR_SEARCH();//invocamos la busqueda } else{//si nos llegan los datos por post $PROFESOR = get_data_form();//recojo los valores del formulario $datos = $PROFESOR->SEARCH();//buscamos los datos $lista = array('NOMBREPROFESOR','APELLIDOSPROFESOR');//guardamos los datos new PROFESOR_SHOWALL($lista, $datos, '../index.php');//mostramos los datos } break; case 'SHOWCURRENT': $PROFESOR = new PROFESOR_Model($_REQUEST['DNI'],'','','','');//invocamos el modelo $valores = $PROFESOR->RellenaDatos();//recojemos los datos new PROFESOR_SHOWCURRENT($valores);//mostramos los valores break; //SHOWALL default: //si no nos llegan los datos por post if (!$_POST){//nos llega el profesor a mostrar por get $PROFESOR = new PROFESOR_Model('','','','','');//creamos el objeto } //si no nos llegan los datos por post else{ $PROFESOR = get_data_form();//recojo los valores del formulario } $datos = $PROFESOR->SEARCH();//buscamos los datos $lista = array('NOMBREPROFESOR','APELLIDOSPROFESOR');//guardamos los datos en la variable lista new PROFESOR_SHOWALL($lista, $datos);//mostramos los datos } ?>
1801625fb1b06dffa69c8e7d8bd758993fbd9cf9
{ "blob_id": "1801625fb1b06dffa69c8e7d8bd758993fbd9cf9", "branch_name": "refs/heads/main", "committer_date": "2020-11-10T16:01:36", "content_id": "75bc77dfdae7c3df235604fc96d94a2a9f216bbc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a1834ce6049f42703990c3a1f4baa9187fbf6607", "extension": "php", "filename": "PROFESOR_Controller.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 311702570, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5584, "license": "Apache-2.0", "license_type": "permissive", "path": "/Controller/PROFESOR_Controller.php", "provenance": "stack-edu-0053.json.gz:701029", "repo_name": "99PabloGG/Web-GestionCentroEducativo", "revision_date": "2020-11-10T16:01:36", "revision_id": "6ad86f55e89eaf05a3f737bc00e596090ebe169e", "snapshot_id": "039c29d23a66892c58f43a8c831f632a8ce2b3b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/99PabloGG/Web-GestionCentroEducativo/6ad86f55e89eaf05a3f737bc00e596090ebe169e/Controller/PROFESOR_Controller.php", "visit_date": "2023-01-11T21:05:57.157699", "added": "2024-11-18T21:50:55.418480+00:00", "created": "2020-11-10T16:01:36", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
async def prepareMiddleware(app, handler): async def middleware(req): # Get peer information peername = req.transport.get_extra_info("peername") if peername is not None: req["host"] = peername[0] # Fetch a database connection from the pool async with app["pool"].acquire() as conn: req["db"] = conn try: res = await handler(req) except Exception as e: raise e return res return middleware
e2efc2821ea6c25597ffaaa6ad8f7062b0a36ed6
{ "blob_id": "e2efc2821ea6c25597ffaaa6ad8f7062b0a36ed6", "branch_name": "refs/heads/master", "committer_date": "2016-08-29T16:46:03", "content_id": "ac6629ae2a5b5642a5108ab8688a72d3a93aa24d", "detected_licenses": [ "MIT" ], "directory_id": "fb91244befcdd7168494ce663bfd3027d4a4dda7", "extension": "py", "filename": "prep.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 64784278, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license": "MIT", "license_type": "permissive", "path": "/aiotpt/prep.py", "provenance": "stack-edu-0054.json.gz:594044", "repo_name": "nucular/aiotpt", "revision_date": "2016-08-29T16:46:03", "revision_id": "0f4b3cdc9b857ca7f4bd58ef9585d01928301018", "snapshot_id": "f9685adbd130d2aa859768a5c4ff3f8d40027021", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nucular/aiotpt/0f4b3cdc9b857ca7f4bd58ef9585d01928301018/aiotpt/prep.py", "visit_date": "2020-04-06T07:01:46.718068", "added": "2024-11-18T21:49:28.630349+00:00", "created": "2016-08-29T16:46:03", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
exports.createWin4 = function(){ var win4 = Titanium.UI.createWindow({ title:String.format(L('Tab_'), '4'), backgroundColor:'green' }); //scrollableView var view1 = Titanium.UI.createView({ backgroundColor: 'red', }); var view2 = Titanium.UI.createView({ backgroundColor: 'blue', }); var view3 = Titanium.UI.createView({ backgroundColor: 'green', }); var view4 = Titanium.UI.createView({ backgroundColor: 'black', }); var label01 = Titanium.UI.createLabel({ color: '#999', backgroundColor: 'transparent', text: 'View1\nSwipe and Scrool', font:{fontSize: 20,fontFamily:'Helvetica Neue'}, textAlign: 'center', }); var label02 = Titanium.UI.createLabel({ color: '#999', backgroundColor: 'transparent', text: 'View2\nSwipe and Scrool', font:{fontSize: 20,fontFamily:'Helvetica Neue'}, textAlign: 'center', }); var label03 = Titanium.UI.createLabel({ color: '#999', backgroundColor: 'transparent', text: 'View3\nSwipe and Scrool', font:{fontSize: 20,fontFamily:'Helvetica Neue'}, textAlign: 'center', }); var label04 = Titanium.UI.createLabel({ color: '#999', backgroundColor: 'transparent', text: 'View4\nSwipe and Scrool', font:{fontSize: 20,fontFamily:'Helvetica Neue'}, textAlign: 'center', }); view1.add(label01); view2.add(label02); view3.add(label03); view4.add(label04); // 上記のviewを配列としてviewsプロパティに引き渡します。 var scrollView = Titanium.UI.createScrollableView({ views: [view1,view2,view3,view4], showPagingControl: true, pagingControlHeight: 30, maxZoomScale: 2.0 }); // スクロールビューを配置する win4.add(scrollView); var b1 = Titanium.UI.createButton({title:L('Back')}); var b2 = Titanium.UI.createButton({title:L('Next')}); win4.LeftNavButton = b1; win4.RightNavButton = b2; b1.addEventListener('click', function(){ tabGroup.activeTab = tabGroup.tabs[2]; }); b2.addEventListener('click', function(e){ tabGroup.activeTab = tabGroup.tabs[4]; }); return win4; };
a731648bd692bb64be4f9a27de6d01a8e616319f
{ "blob_id": "a731648bd692bb64be4f9a27de6d01a8e616319f", "branch_name": "refs/heads/master", "committer_date": "2014-08-02T21:34:43", "content_id": "2e51b691ceca9bb2b15eced6da2bab10d2610783", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a3d82ea7d883464564ab4f29da78061b60dd7142", "extension": "js", "filename": "win4.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": 2079, "license": "Apache-2.0", "license_type": "permissive", "path": "/demoapp/Resources/ui/win4.js", "provenance": "stack-edu-0034.json.gz:702104", "repo_name": "nspenchan/Titanium_Studio_Workspace", "revision_date": "2014-08-02T21:34:43", "revision_id": "510fa03c336a204bbe7dd848a2889bef0f198050", "snapshot_id": "0b7dce6501e5a93563d6e63435059a56843ca649", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nspenchan/Titanium_Studio_Workspace/510fa03c336a204bbe7dd848a2889bef0f198050/demoapp/Resources/ui/win4.js", "visit_date": "2020-06-04T05:12:14.967469", "added": "2024-11-18T19:13:45.374891+00:00", "created": "2014-08-02T21:34:43", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz" }
#!/bin/bash # Take in yaml as argument hyaml=$1 # If no yaml input, exit without any further output if [ -z ${hyaml} ]; then exit 0 fi # Convert file to base 64 base64 $hyaml
592ba51a97c620ec1ffb366b87363921eee8628f
{ "blob_id": "592ba51a97c620ec1ffb366b87363921eee8628f", "branch_name": "refs/heads/master", "committer_date": "2016-11-12T21:25:08", "content_id": "b946ac73aa737a82b89409c741f182be9e16ac2f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d2cb7211c440f530d54ca7aef215ecba9b8af14e", "extension": "sh", "filename": "hiera.sh", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 51278947, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 180, "license": "Apache-2.0", "license_type": "permissive", "path": "/hiera.sh", "provenance": "stack-edu-0070.json.gz:129902", "repo_name": "bryantrobbins/standard-aws", "revision_date": "2016-11-12T21:25:08", "revision_id": "33b5f1a02f0f3313ac726e91b6cdc1af199ee751", "snapshot_id": "e16a7e31e5e06d8eb3ce64d611f5dfd0503e4a89", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bryantrobbins/standard-aws/33b5f1a02f0f3313ac726e91b6cdc1af199ee751/hiera.sh", "visit_date": "2021-01-10T14:23:55.007601", "added": "2024-11-19T00:41:28.646909+00:00", "created": "2016-11-12T21:25:08", "int_score": 3, "score": 3.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
using System; namespace Confluxx.StringFlection { public static class ObjectStringFlector { public static object GetValue(object source, string path) { return GetValue(source, path, 0); } private static object GetValue(object source, string path, int startIndex) { if (path[startIndex] == '[') { var indexedProperty = GetValueByIndex(source, path, startIndex); var closingBracketIndex = path.IndexOf(']', startIndex); if (closingBracketIndex < path.Length - 1) { return GetValue(indexedProperty, path, closingBracketIndex + 1); } return indexedProperty; } if (path[startIndex] == '.') { startIndex++; } var sourceType = source.GetType(); var boundaryIndex = path.IndexOfAny(BoundaryStartChars, startIndex); var currentPropertyName = boundaryIndex > -1 ? path.Substring(startIndex, boundaryIndex - startIndex) : path.Substring(startIndex); var propertyInfo = sourceType.GetProperty(currentPropertyName); if (propertyInfo == null) { throw new Exception(); } var currentProperty = propertyInfo.GetValue(source, null); if (currentPropertyName.Length + startIndex == path.Length) { return currentProperty; } return GetValue(currentProperty, path, boundaryIndex); } private static object GetValueByIndex(object source, string path, int startIndex) { var sourceType = source.GetType(); var boundaryEndIndex = path.IndexOf(']', startIndex); var indexString = path.Substring(startIndex + 1, boundaryEndIndex - startIndex - 1); if (sourceType.IsArray) { return ((Array) source).GetValue(int.Parse(indexString)); } if (sourceType == typeof(string)) { return ((string) source)[int.Parse(indexString)]; } var index = indexString.IndexOfAny(StringBoundaryChars) == 0 ? new object[] { indexString.Trim(StringBoundaryChars) } : new object[] {int.Parse(indexString)}; var propertyInfo = sourceType.GetProperty("Item"); if (propertyInfo == null) { throw new Exception(); } return propertyInfo.GetValue(source, index); } private static readonly Char[] BoundaryStartChars = new[] { '.', '[' }; private static readonly Char[] StringBoundaryChars = new [] {'\'', '"'}; } }
f0dd5c83a902b5b9169309b8dadff060810a3098
{ "blob_id": "f0dd5c83a902b5b9169309b8dadff060810a3098", "branch_name": "refs/heads/master", "committer_date": "2016-07-30T21:22:47", "content_id": "2fabb55508e61c05cd3fb3a60bf531b8912088c1", "detected_licenses": [ "MIT" ], "directory_id": "d80ceb851c4263b60dd56e211d044f2c28ba587a", "extension": "cs", "filename": "ObjectStringFlector.cs", "fork_events_count": 0, "gha_created_at": "2014-01-24T19:39:59", "gha_event_created_at": "2014-01-26T12:20:26", "gha_language": "C#", "gha_license_id": null, "github_id": 16214796, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2320, "license": "MIT", "license_type": "permissive", "path": "/StringFlection/ObjectStringFlector.cs", "provenance": "stack-edu-0014.json.gz:171184", "repo_name": "nsteenbock/StringFlection", "revision_date": "2016-07-30T21:22:47", "revision_id": "b6f9ac26acf4b4f579ec9b0350b5972e0baf6ee4", "snapshot_id": "3c84dc002519b0fd990e9e657a64b1a8bda82c3b", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/nsteenbock/StringFlection/b6f9ac26acf4b4f579ec9b0350b5972e0baf6ee4/StringFlection/ObjectStringFlector.cs", "visit_date": "2020-12-22T23:30:48.302189", "added": "2024-11-19T02:14:35.690962+00:00", "created": "2016-07-30T21:22:47", "int_score": 3, "score": 3.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDirectorsTitles extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('directors_titles', function(Blueprint $table) { $table->Bigincrements('id'); $table->bigInteger('director_id')->unsigned(); $table->bigInteger('title_id')->unsigned(); $table->timestamp('created_at')->default( DB::raw('CURRENT_TIMESTAMP') ); $table->timestamp('updated_at')->nullable(); $table->engine = 'InnoDB'; $table->unique(array('director_id','title_id'), 'director_title_unique'); $table->foreign('title_id')->references('id')->on('titles')->onDelete('cascade'); $table->foreign('director_id')->references('id')->on('directors')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('directors_titles'); } }
0e030cd6b68173fa99664462e62409dc551cb002
{ "blob_id": "0e030cd6b68173fa99664462e62409dc551cb002", "branch_name": "refs/heads/master", "committer_date": "2014-03-31T07:55:31", "content_id": "e53088284104a78c7d9887e3cf3c092e925776d7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1669e7d8e5ba83e6f84a273b820d359a23156f06", "extension": "php", "filename": "2013_12_07_105239_create_directors_titles.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 18284664, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1009, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/database/migrations/2013_12_07_105239_create_directors_titles.php", "provenance": "stack-edu-0053.json.gz:284488", "repo_name": "romeoinbar/MDTB", "revision_date": "2014-03-31T07:55:31", "revision_id": "02e39faf2281a0b18d6fcc7ee5b0d6c0bea52751", "snapshot_id": "ff72c83e12aad4e8d4079df03a5eda88715a4a4d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/romeoinbar/MDTB/02e39faf2281a0b18d6fcc7ee5b0d6c0bea52751/app/database/migrations/2013_12_07_105239_create_directors_titles.php", "visit_date": "2020-05-17T15:22:35.500976", "added": "2024-11-18T21:59:08.570778+00:00", "created": "2014-03-31T07:55:31", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
// Copyright 2016 The Bazel Authors. 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. package com.google.devtools.build.lib.bazel.repository.downloader; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.io.ByteStreams; import com.google.common.net.MediaType; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; /** * Represents a connection over HTTP. */ class HttpConnection implements Closeable { private static final int MAX_REDIRECTS = 20; private final InputStream inputStream; private final int contentLength; private HttpConnection(InputStream inputStream, int contentLength) { this.inputStream = inputStream; this.contentLength = contentLength; } public InputStream getInputStream() { return inputStream; } /** * @return The length of the response, or -1 if unknown. */ public int getContentLength() { return contentLength; } @Override public void close() throws IOException { inputStream.close(); } private static int parseContentLength(HttpURLConnection connection) { String length; try { length = connection.getHeaderField("Content-Length"); if (length == null) { return -1; } return Integer.parseInt(length); } catch (NumberFormatException e) { return -1; } } public static HttpConnection createAndConnect(URL url, Map<String, String> clientEnv) throws IOException { int retries = MAX_REDIRECTS; Proxy proxy = ProxyHelper.createProxyIfNeeded(url.toString(), clientEnv); do { HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); try { connection.connect(); } catch (IllegalArgumentException e) { throw new IOException("Failed to connect to " + url + " : " + e.getMessage(), e); } int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_OK: return new HttpConnection(connection.getInputStream(), parseContentLength(connection)); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: url = tryGetLocation(statusCode, connection); connection.disconnect(); break; case -1: throw new IOException("An HTTP error occured"); default: throw new IOException(String.format("%s %s: %s", connection.getResponseCode(), connection.getResponseMessage(), readBody(connection))); } } while (retries-- > 0); throw new IOException("Maximum redirects (" + MAX_REDIRECTS + ") exceeded"); } private static URL tryGetLocation(int statusCode, HttpURLConnection connection) throws IOException { String newLocation = connection.getHeaderField("Location"); if (newLocation == null) { throw new IOException( "Remote returned " + statusCode + " but did not return location header."); } URL newUrl; try { newUrl = new URL(newLocation); } catch (MalformedURLException e) { throw new IOException("Remote returned invalid location header: " + newLocation); } String newProtocol = newUrl.getProtocol(); if (!("http".equals(newProtocol) || "https".equals(newProtocol))) { throw new IOException( "Remote returned invalid location header: " + newLocation); } return newUrl; } /** * Attempts to detect the encoding the HTTP reponse is using. * * <p>This attempts to read the Content-Encoding header, then the Content-Type header, * then just falls back to UTF-8.</p> * * @throws IOException If something goes wrong (the encoding isn't parsable or is, but isn't * supported by the system). */ @VisibleForTesting static Charset getEncoding(HttpURLConnection connection) throws IOException { String encoding = connection.getContentEncoding(); if (encoding != null) { if (Charset.availableCharsets().containsKey(encoding)) { try { return Charset.forName(encoding); } catch (IllegalArgumentException | UnsupportedOperationException e) { throw new IOException( "Got invalid encoding from " + connection.getURL() + ": " + encoding); } } else { throw new IOException( "Got unavailable encoding from " + connection.getURL() + ": " + encoding); } } encoding = connection.getContentType(); if (encoding == null) { return StandardCharsets.UTF_8; } try { MediaType mediaType = MediaType.parse(encoding); if (mediaType == null) { return StandardCharsets.UTF_8; } Optional<Charset> charset = mediaType.charset(); if (charset.isPresent()) { return charset.get(); } } catch (IllegalArgumentException | IllegalStateException e) { throw new IOException( "Got invalid encoding from " + connection.getURL() + ": " + encoding); } return StandardCharsets.UTF_8; } private static String readBody(HttpURLConnection connection) throws IOException { InputStream errorStream = connection.getErrorStream(); Charset encoding = getEncoding(connection); if (errorStream != null) { return new String(ByteStreams.toByteArray(errorStream), encoding); } InputStream responseStream = connection.getInputStream(); if (responseStream != null) { return new String(ByteStreams.toByteArray(responseStream), encoding); } return null; } }
7b05d4f1438caf111727f5729077bdc1002e06fc
{ "blob_id": "7b05d4f1438caf111727f5729077bdc1002e06fc", "branch_name": "refs/heads/master", "committer_date": "2016-07-14T11:13:00", "content_id": "7005fbbd8d5d78ffe1bb36001043db29bc1f29d1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "23ef5e365496b0b82d566dbb80ea9f0c1140546e", "extension": "java", "filename": "HttpConnection.java", "fork_events_count": 10, "gha_created_at": "2016-07-14T16:30:40", "gha_event_created_at": "2016-07-14T16:30:41", "gha_language": null, "gha_license_id": null, "github_id": 63352564, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6353, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnection.java", "provenance": "stack-edu-0024.json.gz:327345", "repo_name": "ibmsoe/bazel", "revision_date": "2016-07-14T00:09:52", "revision_id": "102841908e9753d128c0341eb2292f3df1e8cd04", "snapshot_id": "dbce1c0b71f58b4590fa84bc86d7b99808a81c80", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/ibmsoe/bazel/102841908e9753d128c0341eb2292f3df1e8cd04/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnection.java", "visit_date": "2021-01-24T00:19:04.109853", "added": "2024-11-19T01:46:36.333089+00:00", "created": "2016-07-14T00:09:52", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
const antlr4 = require('antlr4/index') const iStar2Lexer = require('./iStar2Lexer') const iStar2Parser = require('./iStar2Parser') const fs = require('fs') const { Visitor, layout } = require('./Visitor'); function levelChild(goalmodel, actor) { var n = actor.nodes.length var levels = [] var ops = [] for (i in actor.nodes) { levels[actor.nodes[i].id] = 0 ops[actor.nodes[i].id] = "" } var level = 0 do { var counted = 0; for (l in goalmodel.links) { var link = goalmodel.links[l] if ((link.type.substring(6).toLowerCase() == "andrefinementlink" || link.type.substring(6).toLowerCase() == "orrefinementlink")) { if (levels[link.target] == level) { if (link.type.substring(6).toLowerCase() == "andrefinementlink") { ops[link.target] = "&" } else { ops[link.target] = "|" } levels[link.source] = level + 1; counted++; } } } level++; } while (counted > 0); for (i in actor.nodes) { actor.nodes[i].level = levels[actor.nodes[i].id] actor.nodes[i].op = ops[actor.nodes[i].id] } return level } /** * Append contribute links to the source node, and identify the target node using its lineno instead of its id * @param {*} goalmodel * @param {*} linenos * @param {*} lines */ function contributionLinks(goalmodel, linenos, lines) { for (l in goalmodel.links) { link = goalmodel.links[l] if (link.type.substring(6).toLowerCase() == "contributionlink") { var label = "" if (link.label == "help") label = "+" if (link.label == "hurt") label = "-" if (link.label == "make") label = "++" if (link.label == "break") label = "--" source_lineno = linenos[link.source] if (source_lineno != null) { target_lineno = linenos[link.target] lines[source_lineno] += " " + label + target_lineno } } else if (link.type.substring(6).toLowerCase() == "neededbylink") { var label = "-o" source_lineno = linenos[link.source] if (source_lineno != null) { target_lineno = linenos[link.target] lines[source_lineno] += " " + label + target_lineno } } else if (link.type.substring(6).toLowerCase() == "qualificationlink") { var label = "~~" source_lineno = linenos[link.source] if (source_lineno != null) { target_lineno = linenos[link.target] lines[source_lineno] += " " + label + target_lineno } } } for (d in goalmodel.dependencies) { dependency = goalmodel.dependencies[d] source_lineno = linenos[dependency.source] target_lineno = linenos[dependency.target] dependency_lineno = linenos[dependency.id] if (source_lineno != null) { lines[source_lineno] += " " + "~>" + dependency_lineno } if (target_lineno != null) { lines[dependency_lineno] += " " + "~>" + target_lineno } else if (source_lineno == null) { delete lines[dependency_lineno] } } } function pad(pad, str, padLeft) { if (typeof str === 'undefined') return pad; if (padLeft) { return (pad + str).slice(-pad.length); } else { return (str + pad).substring(0, pad.length); } } function enumerate_children(goalmodel, node, lines, linenos, lineno) { var text = "" for (var i = 0; i < node.level + 1; i++) text += " " text += "" + lineno + (goalmodel.display != null && goalmodel.display[node.id] != null && goalmodel.display[node.id].backgroundColor != null && goalmodel.display[node.id].backgroundColor != "CCFACD" ? " " + toCompletion(goalmodel.display[node.id].backgroundColor) : "") + " " + node.type.substring(6).toLowerCase() + " {" + node.text.replace(/}/g, "\\}") + "} " + ((node.customProperties != null && node.customProperties.Description != null && node.customProperties.Description != "") ? " {" + node.customProperties.Description.replace(/}/g, "\\}") + "}" : "") + (goalmodel.diagram.selected_actor != null || goalmodel.diagram.layout ? "" : ("@" + node.x + "," + node.y)); // don't print the location if the actor is selected if (node.op != "") { text += " " + node.op } linenos[node.id] = lineno nodes[node.id] = node lines[lineno++] = text for (l in goalmodel.links) { var link = goalmodel.links[l] if ((link.type.substring(6).toLowerCase() == "andrefinementlink" || link.type.substring(6).toLowerCase() == "orrefinementlink")) { if (link.target == node.id) { var child = nodes[link.source] lineno = enumerate_children(goalmodel, child, lines, linenos, lineno) } } } return lineno } var storedColors = null function RGBfromYUV(y, u, v) { var r = y + 1.4075 * (v - 128); var g = y - 0.3455 * (u - 128) - (0.7169 * (v - 128)); var b = y + 1.7790 * (u - 128); r = Math.floor(r); g = Math.floor(g); b = Math.floor(b); r = (r < 0) ? 0 : r; r = (r > 255) ? 255 : r; g = (g < 0) ? 0 : g; g = (g > 255) ? 255 : g; b = (b < 0) ? 0 : b; b = (b > 255) ? 255 : b; r = r.toString(16); g = g.toString(16); b = b.toString(16); if (r.length < 2) { r = "0" + r; } if (g.length < 2) { g = "0" + g; } if (b.length < 2) { b = "0" + b; } return r + g + b; } function toColor(percentage) { var Y = 128 var U = 0 var V = 256 * (100 - percentage) / 100.0 return RGBfromYUV(Y, U, V) } /** * First convert hex color into RGB numbers, then convert RGB numbers into YUV numbers, and * finally return (1-U)*100 as the indicator to the percentage of progress till completion * @param {*} hex */ function toCompletion(hex) { if (storedColors == null) { storedColors = {} for (var i = 0; i <= 100; i++) { storedColors[toColor(i)] = i } } // console.log(hex) // var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); // if (result!=null) { // var r = parseInt(result[1], 16) // var g = parseInt(result[2], 16) // var b = parseInt(result[3], 16) // console.log(r + " " + g + " " + b) // var y, u, v; // y = r * .299000 + g * .587000 + b * .114000 // u = r * -.168736 + g * -.331264 + b * .500000 // v = r * .500000 + g * -.418688 + b * -.081312 // y = Math.floor(y); // u = Math.floor(u); // v = Math.floor(v); // console.log(y + " " + u + " " + v) // } var hex = hex.substring(1) var percentage = storedColors[hex] if (percentage == null) { return "" } return percentage + "%" } function convert_json_to_istar2(model, output_filename) { lines = [] lineno = 0 var goalmodel = JSON.parse(model) if (goalmodel.diagram != null && goalmodel.diagram.name != null) { lines[lineno++] = "{" + goalmodel.diagram.name + "}" + "{" + goalmodel.diagram.customProperties.Description + "}" } else { lineno++ } linenos = [] nodes = [] intention2actor = {} if (goalmodel.diagram.selected_actor != null) { goalmodel.diagram.layout = true } for (a in goalmodel.actors) { var actor = goalmodel.actors[a] if (goalmodel.diagram != null && goalmodel.diagram.selected_actor != null && actor.id != goalmodel.diagram.selected_actor) continue if (actor.type.startsWith("istar.")) { linenos[actor.id] = lineno nodes[actor.id] = actor actor.lineno = lineno lines[lineno] = "" + lineno + ((goalmodel.diagram != null && goalmodel.diagram.selected_actor != null) ? (" " + actor.layout) : ((goalmodel.display != null && goalmodel.display[actor.id] != null && goalmodel.display[actor.id].collapsed == false) ? " " + actor.layout : "")) + (goalmodel.display != null && goalmodel.display[actor.id] != null && goalmodel.display[actor.id].backgroundColor != null ? " " + toCompletion(goalmodel.display[actor.id].backgroundColor) : "") + " " + actor.type.substring(6).toLowerCase() + " {" + actor.text.replace(/}/g, "\\}") + "} " + ((actor.customProperties != null && actor.customProperties.Description != null && actor.customProperties.Description != "") ? " {" + actor.customProperties.Description.replace(/}/g, "\\}") + "}" : "") + (goalmodel.diagram.layout ? "" : ("@" + actor.x + "," + actor.y + " ")) lineno++ var L = levelChild(goalmodel, actor) for (n in actor.nodes) { var node = actor.nodes[n] nodes[node.id] = node intention2actor[node.id] = actor.id } for (n in actor.nodes) { var node = actor.nodes[n] if (node.level == 0) { lineno = enumerate_children(goalmodel, node, lines, linenos, lineno) } } } } for (d in goalmodel.dependencies) { dependency = goalmodel.dependencies[d] type = dependency.type.substring(6).toLowerCase(); text = "" + lineno + " " + type + " {" + dependency.text.replace(/}/g, "\\}") + "} " + ((dependency.customProperties != null && dependency.customProperties.Description != null && dependency.customProperties.Description != "") ? " {" + dependency.customProperties.Description.replace(/}/g, "\\}") + "}" : "") + (goalmodel.diagram.layout ? "" : ("@" + dependency.x + "," + dependency.y + " ")) linenos[dependency.id] = lineno nodes[dependency.id] = dependency lines[lineno++] = text } contributionLinks(goalmodel, linenos, lines) if (output_filename != null) { try { fs.writeFileSync(output_filename, lines.join('\n') + '\n', { mode: 0o755 }); } catch (err) { } } else { console.log(lines.join('\n') + '\n') } } function convert_istart2_to_goalmodel(tree, parser) { var visitor = new Visitor(); return visitor.start(tree); } function load_istar2(input) { const chars = new antlr4.InputStream(input); const lexer = new iStar2Lexer.iStar2Lexer(chars); lexer.strictMode = false; // do not use js strictMode const tokens = new antlr4.CommonTokenStream(lexer); const parser = new iStar2Parser.iStar2Parser(tokens); const tree = parser.file_input(); var goalModel = convert_istart2_to_goalmodel(tree, parser); var model = {} model.actors = goalModel.actors model.links = goalModel.links model.dependencies = goalModel.dependencies model.display = goalModel.display // model.actors.forEach(function(a) { // a.nodes.forEach(function (n) { // console.log(model.display[n.id]) // }) // }) model.diagram = goalModel.diagram return model } function save_istar2(goalmodel, output_file) { convert_json_to_istar2(goalmodel, output_file) } function merge_istar2(goalmodel, input) { var model = load_istar2(input) model.actors.forEach(function (a) { // appending the actor var found = false goalmodel.actors.forEach(function (a0) { if (a0.text == a.text) { found = true; } }) if (!found) { goalmodel.actors[goalmodel.actors.length] = a if (goalmodel.display != null) { goalmodel.display[a.id] = model.display[a.id] a.nodes.forEach(function (n) { goalmodel.display[n.id] = model.display[n.id] }) } } }); model.links.forEach(function (l) { goalmodel.links[goalmodel.links.length] = l if (goalmodel.display != null) goalmodel.display[l.id] = model.display[l.id] }); model.dependencies.forEach(function (d) { var found = false goalmodel.dependencies.forEach(function (d0) { if (d0.text == d.text) { if (d0.source == null && d.source != null) { d0.source = d.source; } if (d0.target == null && d.target != null) { d0.target = d.target; } if (d.source == null && d0.source != null) { d.source = d0.source; } if (d.target == null && d0.target != null) { d.target = d0.target; } if (d.source == d0.source && d.target == d0.target) { found = true; // redundant } } }); if (!found) { goalmodel.dependencies[goalmodel.dependencies.length] = d if (goalmodel.display != null) goalmodel.display[d.id] = model.display[d.id] } }); layout(goalmodel) if (goalmodel.display == null) { goalmodel.display = model.display } if (goalmodel.diagram == null) { goalmodel.diagram = model.diagram } if (goalmodel.diagram.name == null && model.digram != null) { goalmodel.diagram.name = model.diagram.name } if (goalmodel.diagram.customProperties == null && model.diagram != null && model.diagram.customProperties != null) { goalmodel.diagram.customProperties = model.diagram.customProperties } return goalmodel } module.exports = { load_istar2, save_istar2, merge_istar2 };
a0ecad994ea4088db46124e896ee4202e26103eb
{ "blob_id": "a0ecad994ea4088db46124e896ee4202e26103eb", "branch_name": "refs/heads/master", "committer_date": "2020-08-16T21:03:47", "content_id": "e1722aa86b076d4bc6aa51ba8b6144c80ccb16af", "detected_licenses": [ "MIT" ], "directory_id": "d40bb1a3d1be6b577782c5a2f9be3f54dc680357", "extension": "js", "filename": "index.js", "fork_events_count": 0, "gha_created_at": "2020-08-15T11:26:44", "gha_event_created_at": "2020-08-15T11:26:45", "gha_language": null, "gha_license_id": "MIT", "github_id": 287733309, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12010, "license": "MIT", "license_type": "permissive", "path": "/tool/istar2/index.js", "provenance": "stack-edu-0040.json.gz:90875", "repo_name": "yijunyu/piStar", "revision_date": "2020-08-16T21:03:47", "revision_id": "0a2b5f40b2f28e116fd667cbf66ae5b25e9548ec", "snapshot_id": "4c35f11003faa03bcd223764db5a48c454380909", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yijunyu/piStar/0a2b5f40b2f28e116fd667cbf66ae5b25e9548ec/tool/istar2/index.js", "visit_date": "2022-11-30T18:47:29.240234", "added": "2024-11-18T19:02:22.734839+00:00", "created": "2020-08-16T21:03:47", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
import * as util from 'util' import { BlenderCollection, Indexable } from '../../collection' import { BlenderInterop } from '../../../worker/interop' import { PythonInterop } from '../../../python/interop' import { AnimViz } from './AnimViz' import { BoneGroups } from './BoneGroups' import { BoneGroup } from './BoneGroup' import { PoseBone } from './PoseBone' import { IKParam } from './IKParam' /** * Pose * * https://docs.blender.org/api/current/bpy.types.Pose.html */ export class Pose { constructor(public interop: BlenderInterop, public accessor: string) { } /** * Animation data for this data-block * @desc AnimViz, (readonly, never None) */ public get animation_visualization(): AnimViz { return PythonInterop.getClass(this.interop, `${this.accessor}.animation_visualization`, AnimViz) } /** * Groups of the bones * @desc BoneGroups bpy_prop_collection of BoneGroup, (readonly) */ public get bone_groups(): BlenderCollection<BoneGroup> & Indexable<BoneGroup> & BoneGroups { return BlenderCollection.createSpecialized(this.interop, `${this.accessor}.bone_groups`, BoneGroups, BoneGroup) } /** * Individual pose bones for the armature * @desc bpy_prop_collection of PoseBone, (readonly) */ public get bones(): BlenderCollection<PoseBone> & Indexable<PoseBone> { return BlenderCollection.createGeneric(this.interop, `${this.accessor}.bones`, PoseBone) } /** * Parameters for IK solver * @desc IKParam, (readonly) */ public get ik_param(): IKParam { return PythonInterop.getClass(this.interop, `${this.accessor}.ik_param`, IKParam) } /** * Selection of IK solver for IK chain * @desc enum in ['LEGACY', 'ITASC'], default 'LEGACY' */ public get ik_solver(): 'LEGACY' | 'ITASC' { return PythonInterop.getEnum(this.interop, `${this.accessor}.ik_solver`) } /** * Add temporary IK constraints while grabbing bones in Pose Mode * @desc boolean, default False */ public get use_auto_ik(): boolean { return PythonInterop.getBoolean(this.interop, `${this.accessor}.use_auto_ik`) } /** * Apply relative transformations in X-mirror mode (not supported with Auto IK) * @desc boolean, default False */ public get use_mirror_relative(): boolean { return PythonInterop.getBoolean(this.interop, `${this.accessor}.use_mirror_relative`) } /** * Apply changes to matching bone on opposite side of X-Axis * @desc boolean, default False */ public get use_mirror_x(): boolean { return PythonInterop.getBoolean(this.interop, `${this.accessor}.use_mirror_x`) } /** * Selection of IK solver for IK chain * @desc enum in ['LEGACY', 'ITASC'], default 'LEGACY' */ public set ik_solver(value: 'LEGACY' | 'ITASC') { PythonInterop.setEnum(this.interop, `${this.accessor}.ik_solver`, value) } /** * Add temporary IK constraints while grabbing bones in Pose Mode * @desc boolean, default False */ public set use_auto_ik(value: boolean) { PythonInterop.setBoolean(this.interop, `${this.accessor}.use_auto_ik`, value) } /** * Apply relative transformations in X-mirror mode (not supported with Auto IK) * @desc boolean, default False */ public set use_mirror_relative(value: boolean) { PythonInterop.setBoolean(this.interop, `${this.accessor}.use_mirror_relative`, value) } /** * Apply changes to matching bone on opposite side of X-Axis * @desc boolean, default False */ public set use_mirror_x(value: boolean) { PythonInterop.setBoolean(this.interop, `${this.accessor}.use_mirror_x`, value) } [util.inspect.custom]() { return this.accessor } }
f497d3508de3059394ed5d8d9e82dfb03aad1b99
{ "blob_id": "f497d3508de3059394ed5d8d9e82dfb03aad1b99", "branch_name": "refs/heads/master", "committer_date": "2020-11-15T15:58:55", "content_id": "34c8e064c111df555ba5df88d8a451f9c68d90a1", "detected_licenses": [ "MIT" ], "directory_id": "a7de5d4bedef5b5974c70f10ad74e60b6dd710e3", "extension": "ts", "filename": "Pose.ts", "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": "TypeScript", "length_bytes": 3876, "license": "MIT", "license_type": "permissive", "path": "/src/blender/bpy/types/Pose.ts", "provenance": "stack-edu-0074.json.gz:72461", "repo_name": "prafulrana/blender-node", "revision_date": "2020-11-15T15:58:55", "revision_id": "f7aa8b7287139020a213d8277ab28e26da994e10", "snapshot_id": "407899e06bb5cd9659b1b3eba8d13f9103e81714", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/prafulrana/blender-node/f7aa8b7287139020a213d8277ab28e26da994e10/src/blender/bpy/types/Pose.ts", "visit_date": "2023-04-20T15:18:33.177383", "added": "2024-11-18T21:05:35.276418+00:00", "created": "2020-11-15T15:58:55", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
<?php namespace API\Service\Factory; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Authentication\AuthenticationService; use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter; class AuthenticationServiceFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter'); $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user', 'username', 'password', 'MD5(?) AND status = "active"'); return new AuthenticationService( $serviceLocator->get('API\Service\AuthenticationStorage'), $dbTableAuthAdapter ); } }
4d8848b723c2fc572a2f7127cd35a97b187e19b8
{ "blob_id": "4d8848b723c2fc572a2f7127cd35a97b187e19b8", "branch_name": "refs/heads/master", "committer_date": "2015-08-01T19:59:31", "content_id": "1432739ffc85783a7a4b3ebf937a70a504dbc13b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b5acf89c482bbfc60bd56e866329f3372dc3af7d", "extension": "php", "filename": "AuthenticationServiceFactory.php", "fork_events_count": 0, "gha_created_at": "2014-09-12T18:17:57", "gha_event_created_at": "2014-12-29T18:19:39", "gha_language": "PHP", "gha_license_id": null, "github_id": 23971540, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 698, "license": "Apache-2.0", "license_type": "permissive", "path": "/zend/module/API/src/API/Service/Factory/AuthenticationServiceFactory.php", "provenance": "stack-edu-0047.json.gz:496602", "repo_name": "imrannaqvi/roach", "revision_date": "2015-08-01T19:59:31", "revision_id": "dd5ca0f7088af6baa80acb67b5030cb5956f3a02", "snapshot_id": "b5f2e7413dc288393dfd15b97b669494be35be3c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/imrannaqvi/roach/dd5ca0f7088af6baa80acb67b5030cb5956f3a02/zend/module/API/src/API/Service/Factory/AuthenticationServiceFactory.php", "visit_date": "2021-01-01T05:34:49.541255", "added": "2024-11-19T02:46:12.949318+00:00", "created": "2015-08-01T19:59:31", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
package com.jd.binlog.inter.work; import com.jd.binlog.dbsync.LogPosition; import com.jd.binlog.exception.BinlogException; import java.io.IOException; import java.util.Map; /** * work interface * <p> * Created by pengan on 17-5-2. */ public interface IBinlogWorker { int PACKET_HEAD_SIZE = 4; int MAX_PACKET_SIZE = 16 * 1024 * 1024; int THROTTLE_QUEUE_SIZE = 64; Object object = new Object(); /** * startWorking */ void startWorking(); // startWorking /** * close worker and handler and all * * @return */ boolean close(); // close work /** * 是否已经关闭 * * @return */ boolean isClosed(); /** * 获取最新的binlog 位置 并删除已经过期的节点 * <p> * 只会找到最新的commit位置push 到zk * <p> * ----------------------| |--------------------| |--------------------| * node1.isCommit = true | -> | node2.isCommit=true| -> |node3.isCommit=false| ... * ----------------------| |--------------------| |--------------------| * <p> * 返回 node2 * * @return */ LogPosition getLatestLogPosWithRm(); /** * 只是读取最新的binlog offset 原理同 * * @func: getLatestLogPosWithRm * <p> * 但是不删除log-position */ LogPosition getLatestLogPos(); /** * 处理异常: * <p> * 所有异常: 仅仅是退出leader 不关闭leaderSelector 因为dump会重试 * * @param exp */ void handleException(BinlogException exp); // handle binlog exception /** * 处理 error 异常 * * @param exp */ void handleError(Throwable exp); // handle any other error /** * 删除 binlog position in queue * * @param target */ void removeLogPosition(LogPosition target); /** * keep dump data on worker thread */ void keepDump(); /** * monitor including: delay and start time and etc any what you want */ Map<String, Object> monitor(); }
970bfd3cc8042ea2a147ededbf96d0bf2c004158
{ "blob_id": "970bfd3cc8042ea2a147ededbf96d0bf2c004158", "branch_name": "refs/heads/master", "committer_date": "2022-09-26T07:33:29", "content_id": "45c750b822851321a176e006222a2ac958d2a329", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c93f82f3389edb4e5840d146e150bf829d063ba1", "extension": "java", "filename": "IBinlogWorker.java", "fork_events_count": 27, "gha_created_at": "2019-05-03T06:28:37", "gha_event_created_at": "2023-05-12T01:21:51", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 184708656, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2104, "license": "Apache-2.0", "license_type": "permissive", "path": "/binlake-wave/binlake-wave.interface/src/main/java/com/jd/binlog/inter/work/IBinlogWorker.java", "provenance": "stack-edu-0027.json.gz:606463", "repo_name": "jd-tiger/binlake", "revision_date": "2022-09-26T07:33:29", "revision_id": "462e4e5ebcc55c4d473c3bef9831126dbe3c148c", "snapshot_id": "87c14e476c299000eba6f99de1ade10af4ee2a66", "src_encoding": "UTF-8", "star_events_count": 93, "url": "https://raw.githubusercontent.com/jd-tiger/binlake/462e4e5ebcc55c4d473c3bef9831126dbe3c148c/binlake-wave/binlake-wave.interface/src/main/java/com/jd/binlog/inter/work/IBinlogWorker.java", "visit_date": "2022-10-05T03:30:17.306219", "added": "2024-11-19T02:42:05.655268+00:00", "created": "2022-09-26T07:33:29", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
## `ern run-container-pipeline` #### Description - This command can be used to run a local pre-generated Container through a Container pipeline _(aribtrary sequence of transformers & publishers)_ #### Syntax `ern run-container-pipeline` **Options** `--containerPath` - The local file system path to the directory containing the Container to run through the pipeline. - **Default** If this option is not provided, the command will look for a Container in the default platform directory `~/.ern/containergen/out/[platform]`. `--pipeline` - Path to the JSON file containing the pipeline configuration. - Can either be a local file system path to the JSON file, or a path to a JSON file stored in the cauldron _(for example cauldron://config/my-pipeline.json for a my-pipeline.json file stored in config directory in the cauldron)_ `--platform` - Specify the native platform of the target Container (`android` or `ios`) - This option is required, there is no default. `--version/-v` - Specify the Container version to use for publication. - The version will be ignored if the pipeline is only composed of transformers. - Defaults to `1.0.0`. #### Remarks Refer to [container publication] and [container integration] documentation for more details regarding the structure of the JSON pertaining to pipeline configuration. [container publication]: ../platform-parts/container/container-publication.md [container integration]: ../platform-parts/container/container-integration.md
6bba362a1a4e41fdb3d4eccc0be83f452b7fcf31
{ "blob_id": "6bba362a1a4e41fdb3d4eccc0be83f452b7fcf31", "branch_name": "refs/heads/master", "committer_date": "2021-05-25T15:21:40", "content_id": "9b25718bf4129aadd19d016664691c5a1ab708f4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0b43c20a78bcfb513fe3468fc1ef01881d1f7b8b", "extension": "md", "filename": "run-container-pipeline.md", "fork_events_count": 1, "gha_created_at": "2017-09-25T19:33:42", "gha_event_created_at": "2017-09-25T23:40:46", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 104793496, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1489, "license": "Apache-2.0", "license_type": "permissive", "path": "/docs/cli/run-container-pipeline.md", "provenance": "stack-edu-markdown-0002.json.gz:113109", "repo_name": "belemaire/electrode-native", "revision_date": "2021-05-24T18:28:29", "revision_id": "7a74d4bd5d65fcd395210983104ecec31dbadbaf", "snapshot_id": "be2663ca8cdf5e9bad3ab7c5f910376f13da0cc8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/belemaire/electrode-native/7a74d4bd5d65fcd395210983104ecec31dbadbaf/docs/cli/run-container-pipeline.md", "visit_date": "2021-07-25T20:11:51.807004", "added": "2024-11-18T22:19:44.947016+00:00", "created": "2021-05-24T18:28:29", "int_score": 4, "score": 3.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
import Transformable, { TransformProp } from './core/Transformable'; import { AnimationEasing } from './animation/easing'; import Animator from './animation/Animator'; import { ZRenderType } from './zrender'; import { Dictionary, ElementEventName, ZRRawEvent, BuiltinTextPosition, MapToType } from './core/types'; import Path from './graphic/Path'; import BoundingRect, { RectLike } from './core/BoundingRect'; import Eventful from './core/Eventful'; import ZRText from './graphic/Text'; import { TextPositionCalculationResult } from './contain/text'; import Polyline from './graphic/shape/Polyline'; import Group from './graphic/Group'; import Point from './core/Point'; export interface ElementAnimateConfig { duration?: number; delay?: number; easing?: AnimationEasing; during?: (percent: number) => void; done?: Function; aborted?: Function; scope?: string; force?: boolean; additive?: boolean; setToFinal?: boolean; } export interface ElementTextConfig { position?: BuiltinTextPosition | (number | string)[]; rotation?: number; layoutRect?: RectLike; offset?: number[]; origin?: (number | string)[] | 'center'; distance?: number; local?: boolean; insideFill?: string; insideStroke?: string; outsideFill?: string; outsideStroke?: string; inside?: boolean; } export interface ElementTextGuideLineConfig { anchor?: Point; showAbove?: boolean; candidates?: ('left' | 'top' | 'right' | 'bottom')[]; } export interface ElementEvent { type: ElementEventName; event: ZRRawEvent; target: Element; topTarget: Element; cancelBubble: boolean; offsetX: number; offsetY: number; gestureEvent: string; pinchX: number; pinchY: number; pinchScale: number; wheelDelta: number; zrByTouch: boolean; which: number; stop: (this: ElementEvent) => void; } export declare type ElementEventCallback<Ctx, Impl> = (this: CbThis<Ctx, Impl>, e: ElementEvent) => boolean | void; declare type CbThis<Ctx, Impl> = unknown extends Ctx ? Impl : Ctx; interface ElementEventHandlerProps { onclick: ElementEventCallback<unknown, unknown>; ondblclick: ElementEventCallback<unknown, unknown>; onmouseover: ElementEventCallback<unknown, unknown>; onmouseout: ElementEventCallback<unknown, unknown>; onmousemove: ElementEventCallback<unknown, unknown>; onmousewheel: ElementEventCallback<unknown, unknown>; onmousedown: ElementEventCallback<unknown, unknown>; onmouseup: ElementEventCallback<unknown, unknown>; oncontextmenu: ElementEventCallback<unknown, unknown>; ondrag: ElementEventCallback<unknown, unknown>; ondragstart: ElementEventCallback<unknown, unknown>; ondragend: ElementEventCallback<unknown, unknown>; ondragenter: ElementEventCallback<unknown, unknown>; ondragleave: ElementEventCallback<unknown, unknown>; ondragover: ElementEventCallback<unknown, unknown>; ondrop: ElementEventCallback<unknown, unknown>; } export interface ElementProps extends Partial<ElementEventHandlerProps>, Partial<Pick<Transformable, TransformProp>> { name?: string; ignore?: boolean; isGroup?: boolean; draggable?: boolean | 'horizontal' | 'vertical'; silent?: boolean; ignoreClip?: boolean; globalScaleRatio?: number; textConfig?: ElementTextConfig; textContent?: ZRText; clipPath?: Path; drift?: Element['drift']; extra?: Dictionary<unknown>; anid?: string; } export declare const PRESERVED_NORMAL_STATE = "__zr_normal__"; declare const PRIMARY_STATES_KEYS: ["x" | "y" | "originX" | "originY" | "anchorX" | "anchorY" | "rotation" | "scaleX" | "scaleY" | "skewX" | "skewY", "ignore"]; export declare type ElementStatePropNames = (typeof PRIMARY_STATES_KEYS)[number] | 'textConfig'; export declare type ElementState = Pick<ElementProps, ElementStatePropNames> & ElementCommonState; export declare type ElementCommonState = { hoverLayer?: boolean; }; export declare type ElementCalculateTextPosition = (out: TextPositionCalculationResult, style: ElementTextConfig, rect: RectLike) => TextPositionCalculationResult; interface Element<Props extends ElementProps = ElementProps> extends Transformable, Eventful<{ [key in ElementEventName]: (e: ElementEvent) => void | boolean; } & { [key in string]: (...args: any) => void | boolean; }>, ElementEventHandlerProps { } declare class Element<Props extends ElementProps = ElementProps> { id: number; type: string; name: string; ignore: boolean; silent: boolean; isGroup: boolean; draggable: boolean | 'horizontal' | 'vertical'; dragging: boolean; parent: Group; animators: Animator<any>[]; ignoreClip: boolean; __hostTarget: Element; __zr: ZRenderType; __dirty: number; __isRendered: boolean; __inHover: boolean; private _clipPath?; private _textContent?; private _textGuide?; textConfig?: ElementTextConfig; textGuideLineConfig?: ElementTextGuideLineConfig; anid: string; extra: Dictionary<unknown>; currentStates?: string[]; prevStates?: string[]; states: Dictionary<ElementState>; stateTransition: ElementAnimateConfig; stateProxy?: (stateName: string, targetStates?: string[]) => ElementState; protected _normalState: ElementState; private _innerTextDefaultStyle; constructor(props?: Props); protected _init(props?: Props): void; drift(dx: number, dy: number, e?: ElementEvent): void; beforeUpdate(): void; afterUpdate(): void; update(): void; updateInnerText(forceUpdate?: boolean): void; protected canBeInsideText(): boolean; protected getInsideTextFill(): string | undefined; protected getInsideTextStroke(textFill: string): string | undefined; protected getOutsideFill(): string | undefined; protected getOutsideStroke(textFill: string): string; traverse<Context>(cb: (this: Context, el: Element<Props>) => void, context?: Context): void; protected attrKV(key: string, value: unknown): void; hide(): void; show(): void; attr(keyOrObj: Props): this; attr<T extends keyof Props>(keyOrObj: T, value: Props[T]): this; saveCurrentToNormalState(toState: ElementState): void; protected _innerSaveToNormal(toState: ElementState): void; protected _savePrimaryToNormal(toState: Dictionary<any>, normalState: Dictionary<any>, primaryKeys: readonly string[]): void; hasState(): boolean; getState(name: string): ElementState; ensureState(name: string): ElementState; clearStates(noAnimation?: boolean): void; useState(stateName: string, keepCurrentStates?: boolean, noAnimation?: boolean, forceUseHoverLayer?: boolean): ElementState; useStates(states: string[], noAnimation?: boolean, forceUseHoverLayer?: boolean): void; private _updateAnimationTargets; removeState(state: string): void; replaceState(oldState: string, newState: string, forceAdd: boolean): void; toggleState(state: string, enable: boolean): void; protected _mergeStates(states: ElementState[]): ElementState; protected _applyStateObj(stateName: string, state: ElementState, normalState: ElementState, keepCurrentStates: boolean, transition: boolean, animationCfg: ElementAnimateConfig): void; private _attachComponent; private _detachComponent; getClipPath(): Path<import("./graphic/Path").PathProps>; setClipPath(clipPath: Path): void; removeClipPath(): void; getTextContent(): ZRText; setTextContent(textEl: ZRText): void; setTextConfig(cfg: ElementTextConfig): void; removeTextConfig(): void; removeTextContent(): void; getTextGuideLine(): Polyline; setTextGuideLine(guideLine: Polyline): void; removeTextGuideLine(): void; markRedraw(): void; dirty(): void; private _toggleHoverLayerFlag; addSelfToZr(zr: ZRenderType): void; removeSelfFromZr(zr: ZRenderType): void; animate(key?: string, loop?: boolean, allowDiscreteAnimation?: boolean): Animator<any>; addAnimator(animator: Animator<any>, key: string): void; updateDuringAnimation(key: string): void; stopAnimation(scope?: string, forwardToLast?: boolean): this; animateTo(target: Props, cfg?: ElementAnimateConfig, animationProps?: MapToType<Props, boolean>): void; animateFrom(target: Props, cfg: ElementAnimateConfig, animationProps?: MapToType<Props, boolean>): void; protected _transitionState(stateName: string, target: Props, cfg?: ElementAnimateConfig, animationProps?: MapToType<Props, boolean>): void; getBoundingRect(): BoundingRect; getPaintRect(): BoundingRect; calculateTextPosition: ElementCalculateTextPosition; protected static initDefaultProps: void; } export default Element;
03a8bc4731fbc10e0c49aca708ed7a326cf19d7a
{ "blob_id": "03a8bc4731fbc10e0c49aca708ed7a326cf19d7a", "branch_name": "refs/heads/master", "committer_date": "2023-02-25T14:14:40", "content_id": "c3cb018bc777f49d84d3e8aa5c6471b8dd169fc8", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "8ca9fe48cd97f155a4560ab6990f4c6f4124bd0d", "extension": "ts", "filename": "Element.d.ts", "fork_events_count": 3, "gha_created_at": "2017-03-07T13:51:38", "gha_event_created_at": "2023-07-20T06:49:10", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 84204626, "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 8769, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/chart_renderer/node_modules/zrender/lib/Element.d.ts", "provenance": "stack-edu-0072.json.gz:591659", "repo_name": "adityaU/AfterGlow", "revision_date": "2023-02-25T14:14:40", "revision_id": "fac35a2d7ff2e1c9ddde239d5ab5b7b5b4458f3a", "snapshot_id": "a414c1b3dd8bd81285c4021bb1bae62e7fb011ee", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/adityaU/AfterGlow/fac35a2d7ff2e1c9ddde239d5ab5b7b5b4458f3a/chart_renderer/node_modules/zrender/lib/Element.d.ts", "visit_date": "2023-08-01T04:04:48.904497", "added": "2024-11-18T23:03:46.511363+00:00", "created": "2023-02-25T14:14:40", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
<?php /** * Copyright © Vaimo Group. All rights reserved. * See LICENSE_VAIMO.txt for license details. */ namespace Vaimo\ComposerChangelogs\Data; class Changelog { /** * @var \Composer\Package\PackageInterface */ private $package; /** * @var array */ private $changelog; /** * @param \Composer\Package\PackageInterface $package * @param array $changelog */ public function __construct( \Composer\Package\PackageInterface $package, array $changelog ) { $this->package = $package; $this->changelog = $changelog; } public function getOwner() { return $this->package; } public function getReleases() { return $this->changelog; } }
652a168c8bee19af08a6c75fb994f056b5a9b6e8
{ "blob_id": "652a168c8bee19af08a6c75fb994f056b5a9b6e8", "branch_name": "refs/heads/master", "committer_date": "2022-04-21T13:51:42", "content_id": "1499979006e7d710baaad0a002c771af1938b5b2", "detected_licenses": [ "MIT" ], "directory_id": "988f65a3633e9ccf0017b04b18dd4dcbacee5284", "extension": "php", "filename": "Changelog.php", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 143271201, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 784, "license": "MIT", "license_type": "permissive", "path": "/src/Data/Changelog.php", "provenance": "stack-edu-0053.json.gz:582591", "repo_name": "vaimo/composer-changelogs", "revision_date": "2022-04-21T13:51:42", "revision_id": "1ba3f11ca922fc0e9e5de00395166150d9263da4", "snapshot_id": "72ed179889ead3ef82334a5b50481b90d4481635", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/vaimo/composer-changelogs/1ba3f11ca922fc0e9e5de00395166150d9263da4/src/Data/Changelog.php", "visit_date": "2022-12-06T00:12:17.285766", "added": "2024-11-18T22:33:30.440105+00:00", "created": "2022-04-21T13:51:42", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
#include "font_library.h" #include "engine/core/log/Log.h" namespace Echo { FontLibrary::FontLibrary() { FT_Error result = FT_Init_FreeType(&m_library); if(result!=FT_Err_Ok) { EchoLogError("UiModule FreeType init failed."); } } FontLibrary::~FontLibrary() { EchoSafeDeleteContainer(m_fontFaces, FontFace); } FontLibrary* FontLibrary::instance() { static FontLibrary* inst = EchoNew(FontLibrary); return inst; } FontGlyph* FontLibrary::getFontGlyph(i32 charCode, const ResourcePath& fontPath, i32 fontSize) { FontFace* fontFace = loadFace( fontPath.getPath().c_str()); if(fontFace) { return fontFace->getGlyph(charCode, fontSize); } return nullptr; } FontFace* FontLibrary::loadFace(const char* filePath) { // if exist, return it for(FontFace* fontFace : m_fontFaces) { if(fontFace->getFile()==filePath) return fontFace; } // create new FontFace* face = EchoNew(FontFace(m_library, filePath)); m_fontFaces.emplace_back(face); return face; } bool FontLibrary::unloadFace(const char* filePath) { return true; } }
17c36996b579205009d8e1e884e49c4676403dd7
{ "blob_id": "17c36996b579205009d8e1e884e49c4676403dd7", "branch_name": "refs/heads/master", "committer_date": "2023-08-11T18:10:35", "content_id": "c98afbfb4a7cafc72233d997afe9ae18a960d40f", "detected_licenses": [ "MIT" ], "directory_id": "31f5cddb9885fc03b5c05fba5f9727b2f775cf47", "extension": "cpp", "filename": "font_library.cpp", "fork_events_count": 102, "gha_created_at": "2018-03-10T04:07:35", "gha_event_created_at": "2021-06-11T14:29:03", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 124620874, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1333, "license": "MIT", "license_type": "permissive", "path": "/engine/modules/ui/font/font_library.cpp", "provenance": "stack-edu-0004.json.gz:241194", "repo_name": "timi-liuliang/echo", "revision_date": "2023-08-11T18:10:35", "revision_id": "d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24", "snapshot_id": "2935a34b80b598eeb2c2039d686a15d42907d6f7", "src_encoding": "UTF-8", "star_events_count": 822, "url": "https://raw.githubusercontent.com/timi-liuliang/echo/d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24/engine/modules/ui/font/font_library.cpp", "visit_date": "2023-08-17T05:35:08.104918", "added": "2024-11-18T22:40:50.523150+00:00", "created": "2023-08-11T18:10:35", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
# bamazon ## Overview In this activity, you'll be creating an Amazon-like storefront with the MySQL skills you learned this week. The app will take in orders from customers and deplete stock from the store's inventory. As a bonus task, you can program your app to track product sales across your store's departments and then provide a summary of the highest-grossing departments in the store. Make sure you save and require the MySQL and Inquirer npm packages in your homework files--your app will need them for data input and storage. ## Instructions **CHALLENGE #1: Customer View** 1. Create a MySQL Database called Bamazon. 2. Then create a table inside of that database called products. 3. The products table should have each of the following columns: * id (unique id for each product) * product_name (Name of product) * department_name * product_price (cost to customer) * inventory (how much of the product is available in stores) 4. Populate this database with around 10 different products (i.e. insert "mock" data rows into this database and table). 5. Then create a Node application called bamazonCustomer.js. Running this application will first display all of the items available for sale. Include the ids, names, and prices of products for sale. 6. The app should then prompt users with two messages: * The first should ask them the ID of the product they would like to buy. * The second message should ask how many units of the product they would like to buy. 7. Once the customer has placed the order, your application should check if your store has enough of the product to meet the customer's request. * if not, the app should log a phase like Insufficient quantity!, and then prevent the order from going through. 8. However, if your store does have enough of the product, you should fulfill the cutomer's order. * This means updating the SQL database to reflect the remaining quantity. * Once the update goes through, show the customer the total cost of their purchase. ## Technologies Used: * npm packages - mysql and inquirer * mySQL * Node.js * JavsScript ##Screencapture ![Bamazon](capture.png) Image is not showing, please view "capture" image in origin master ##Problems The bulk of my application works. There is one glitch when reprompting, which is regardless if you want to continue you shopping you have to continue. Other problems while recreating this application included minimal mistakes such as forgetting closing curly braces, misspelled words, and not calling on functions. ##Authors Stefani Krautstrunk
b0b2f65c1ccd5bc5e5b6e10f8e40305bcc103243
{ "blob_id": "b0b2f65c1ccd5bc5e5b6e10f8e40305bcc103243", "branch_name": "refs/heads/master", "committer_date": "2018-07-28T16:52:14", "content_id": "bddec55491118fe4bfbebdfac59b61555cfc8958", "detected_licenses": [ "MIT" ], "directory_id": "99399bedbdf40cbb5c0aeefe754db0d8ded74d6d", "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": 141932160, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2608, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0002.json.gz:125744", "repo_name": "stefaniiik/bamazon", "revision_date": "2018-07-28T16:52:14", "revision_id": "dced4660b8bb0a97c125ce9ee2b0f336b801b8d4", "snapshot_id": "5661ad7600ec6326ea4ab8e3bc60c0e3e36d470c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/stefaniiik/bamazon/dced4660b8bb0a97c125ce9ee2b0f336b801b8d4/README.md", "visit_date": "2020-03-23T18:47:48.325427", "added": "2024-11-18T23:39:28.777747+00:00", "created": "2018-07-28T16:52:14", "int_score": 3, "score": 3.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
CREATE DATABASE bankanalyzer CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE USER 'bankanalyzer' IDENTIFIED BY 'sonar'; GRANT ALL ON bankanalyzer.* TO `bankanalyzer`@`%` IDENTIFIED BY `sonar`; GRANT ALL ON bankanalyzer.* TO `bankanalyzer`@`localhost` IDENTIFIED BY `sonar`; FLUSH PRIVILEGES;
63353e602540efb3312321e1e88040cc0cd1ab7b
{ "blob_id": "63353e602540efb3312321e1e88040cc0cd1ab7b", "branch_name": "refs/heads/master", "committer_date": "2021-06-09T12:41:36", "content_id": "655ed0fda513a2238259983374e1b0d137442239", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fb47a020703f5ad11898205cbbbd7ff872f795c3", "extension": "sql", "filename": "mysql-create-user.sql", "fork_events_count": 1, "gha_created_at": "2015-09-08T21:19:45", "gha_event_created_at": "2022-02-01T00:57:33", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 42139601, "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 295, "license": "Apache-2.0", "license_type": "permissive", "path": "/ba-services/ba-services-rest-impl-jaxrs/src/integration-test/data/mysql-create-user.sql", "provenance": "stack-edu-0070.json.gz:454605", "repo_name": "marcomaccio/bankanalyzer-he", "revision_date": "2021-06-09T12:41:36", "revision_id": "da8c04455591f2667d6c35ba35bd202befc32fdc", "snapshot_id": "b1b033069105143d5c10ae7c21d8e3c0a47be444", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/marcomaccio/bankanalyzer-he/da8c04455591f2667d6c35ba35bd202befc32fdc/ba-services/ba-services-rest-impl-jaxrs/src/integration-test/data/mysql-create-user.sql", "visit_date": "2022-07-10T19:40:33.716750", "added": "2024-11-18T21:42:51.765233+00:00", "created": "2021-06-09T12:41:36", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router-dom'; import PropTypes from 'prop-types'; import {logoutRequest} from '../../actions/loginActions'; import './Navbar.css'; class NavigationBar extends Component { static propTypes = { userLogin: PropTypes.object.isRequired, logoutRequest: PropTypes.func.isRequired }; logoutRequest = (e) => { e.preventDefault(); this.props.logoutRequest(); }; render() { const {isAuthenticated, user} = this.props.userLogin; const userLinks = ( <div className="container"> <Link className="navbar-brand" to="/">A站</Link> <ul className="navbar-nav mr-auto"> <li className="nav-item dropdown"> <a className="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> 上传资源 </a> <ul className="dropdown-menu"> <li> <Link className="nav-link dropdown-item" to="/allWebResources/upload">全网上传</Link> </li> <li> <Link className="nav-link dropdown-item" to="/resources/upload">本站上传</Link> </li> </ul> </li> <li className="nav-item"> <Link className="nav-link" to="/myWallet">我的钱包</Link> </li> </ul> <ul className="navbar-nav mt-md-0"> <li className="nav-item"> <Link className="nav-link" to="">Welcome {user.username}</Link> </li> <li className="nav-item"> <Link className="nav-link" to="" onClick={this.logoutRequest}>退出</Link> </li> </ul> </div> ); const guestLinks = ( <div className="container"> <Link className="navbar-brand" to="/">A站</Link> <ul className="navbar-nav mr-auto"> <li className="nav-item dropdown"> <a className="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> 上传资源 </a> <ul className="dropdown-menu"> <li> <Link className="nav-link dropdown-item" to="/allWebResources/upload">全网上传</Link> </li> <li> <Link className="nav-link dropdown-item" to="/resources/upload">本站上传</Link> </li> </ul> </li> </ul> <ul className="navbar-nav mt-md-0"> <li className="nav-item"> <Link className="nav-link" to="/login">登录</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/signup">注册</Link> </li> </ul> </div> ); return ( <nav className="navbar navbar-expand-lg mb-3"> {isAuthenticated ? userLinks : guestLinks} </nav> ); } } const mapStateToProps = (state) => { return { userLogin: state.userLogin } }; export default connect(mapStateToProps, {logoutRequest})(NavigationBar);
c947dade6a59fb19dec10a94fed5741c5de41781
{ "blob_id": "c947dade6a59fb19dec10a94fed5741c5de41781", "branch_name": "refs/heads/master", "committer_date": "2020-06-06T12:28:24", "content_id": "743af969c2e3532ee72193ee79f32f1a1357151f", "detected_licenses": [ "MIT" ], "directory_id": "e1eef177ecce772d35731cdbc0da3c414f99a3f1", "extension": "js", "filename": "NavigationBar.js", "fork_events_count": 0, "gha_created_at": "2018-08-16T15:48:12", "gha_event_created_at": "2020-06-06T12:28:25", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 145008975, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3860, "license": "MIT", "license_type": "permissive", "path": "/client/src/components/navPage/NavigationBar.js", "provenance": "stack-edu-0039.json.gz:90997", "repo_name": "Messi-Q/Resource-CI", "revision_date": "2020-06-06T12:28:24", "revision_id": "909a4a5b0515b9e43f7498a66b69ee744979457c", "snapshot_id": "6adfd84a8505449fc8221d190a27fc771c627444", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Messi-Q/Resource-CI/909a4a5b0515b9e43f7498a66b69ee744979457c/client/src/components/navPage/NavigationBar.js", "visit_date": "2021-07-11T20:23:28.795320", "added": "2024-11-18T18:52:23.677890+00:00", "created": "2020-06-06T12:28:24", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
--- title: "Tutorial Vazirani: Classical proofs of quantumness (Chair: Gorjan Alagic)" format: tutorial speakers: - vazirani videoId: "YHOm4dZOE2s" presentation: "/slides/QCrypt2021TutorialVazirani.pdf" draft: false --- Abstract: In this tutorial I will explain the fundamental principles behind the use of trapdoor claw-free functions to build a qubit certification test, which allows a classical verifier to reach into a quantum computer's Hilbert space, and enforce a qubit structure in it. I will discuss how this leads to protocols for proofs of quantumness, certified randomness and verification of quantum computations. I will also describe refinements of these techniques for improving the efficiency of the protocols. <!-- fields to use above: --> <!-- videoId: "Vfl9pPh6ipI" --> <!-- presentation: "/slides/invited-MargaridaPereira.pdf" -->
4524bbcec416ac66ea400d0829b00310d17c153d
{ "blob_id": "4524bbcec416ac66ea400d0829b00310d17c153d", "branch_name": "refs/heads/master", "committer_date": "2021-09-19T12:14:48", "content_id": "1042c63780c55346d3a3198a1c660d0981096b01", "detected_licenses": [ "MIT" ], "directory_id": "815e631f262cf7d4ae27a58c90b07c7523cf3dc3", "extension": "md", "filename": "tutorial_vazirani.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 854, "license": "MIT", "license_type": "permissive", "path": "/content/sessions/tutorial_vazirani.md", "provenance": "stack-edu-markdown-0007.json.gz:108073", "repo_name": "passerchell/website-parctice_2022", "revision_date": "2021-09-19T12:14:48", "revision_id": "e6c5b13e681150bda20e855cd8748a75abebe11d", "snapshot_id": "c1a79b0935b0e49e128a23fa6eb460bea50ea730", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/passerchell/website-parctice_2022/e6c5b13e681150bda20e855cd8748a75abebe11d/content/sessions/tutorial_vazirani.md", "visit_date": "2023-08-05T21:37:49.652987", "added": "2024-11-18T22:24:02.864252+00:00", "created": "2021-09-19T12:14:48", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
const { assert, refute } = require('@sinonjs/referee'); const Map = require('./../solutions/22/map.js'); describe('Day 22 Map class', () => { const depth = 510; const target = { x: 10, y: 10 }; const start = { x: 0, y: 0 }; const map = new Map(depth, target, start); describe('Geologic index tests', () => { // At 0,0, the geologic index is 0. The erosion level is (0 + 510) % 20183 = 510. The type is 510 % 3 = 0, rocky. it('should calculate 0 for 0,0', () => { const actual = map.calcGeologicIndex(0, 0); assert.equals(actual, 0); }); // At 1,0, because the Y coordinate is 0, the geologic index is 1 * 16807 = 16807. The erosion level is (16807 + 510) % 20183 = 17317. The type is 17317 % 3 = 1, wet. it('should calculate 16807 for 1,0', () => { const actual = map.calcGeologicIndex(1, 0); assert.equals(actual, 16807); }); // At 0,1, because the X coordinate is 0, the geologic index is 1 * 48271 = 48271. it('should calculate 48271 for 0,1', () => { const actual = map.calcGeologicIndex(0, 1); assert.equals(actual, 48271); }); // At 1,1, neither coordinate is 0 and it is not the coordinate of the target, so the geologic index is the erosion level of 0,1 (8415) times the erosion level of 1,0 (17317), 8415 * 17317 = 145722555. The erosion level is (145722555 + 510) % 20183 = 1805. The type is 1805 % 3 = 2, narrow. it('should calculate 145722555 for 1,1', () => { const actual = map.calcGeologicIndex(1, 1); assert.equals(actual, 145722555); }); }); describe('Erosion level calculation', () => { // At 1,0, The erosion level is (16807 + 510) % 20183 = 17317 it('should calculate 17317 for 1,0', () => { const actual = map.calcErosionLevel(1, 0); assert.equals(actual, 17317); }); }); describe('Risk level tests', () => { it('should choose rocky for 0,0', () => { const actual = map.determineRiskLevel(0, 0); assert.equals(actual, 0); }); it('should choose wet for 1,0', () => { const actual = map.determineRiskLevel(1, 0); assert.equals(actual, 1); }); // At 0,1, because the X coordinate is 0, the geologic index is 1 * 48271 = 48271. The erosion level is (48271 + 510) % 20183 = 8415. The type is 8415 % 3 = 0, rocky. it('should choose rocky for 0,1', () => { const actual = map.determineRiskLevel(0, 1); assert.equals(actual, 0); }); // At 1,1, neither coordinate is 0 and it is not the coordinate of the target, so the geologic index is the erosion level of 0,1 (8415) times the erosion level of 1,0 (17317), 8415 * 17317 = 145722555. The erosion level is (145722555 + 510) % 20183 = 1805. The type is 1805 % 3 = 2, narrow. it('should choose narrow for 1,1', () => { const actual = map.determineRiskLevel(1, 1); assert.equals(actual, 2); }); }); // At 10,10, because they are the target's coordinates, the geologic index is 0. The erosion level is (0 + 510) % 20183 = 510. The type is 510 % 3 = 0, rocky. // Drawing this same cave system with rocky as ., wet as =, narrow as |, the mouth as M, the target as T, with 0,0 in the top-left corner, X increasing to the right, and Y increasing downward, the top-left corner of the map looks like this: // M=.|=.|.|=.|=|=. // .|=|=|||..|.=... // .==|....||=..|== // =.|....|.==.|==. // =|..==...=.|==.. // =||.=.=||=|=..|= // |.=.===|||..=..| // |..==||=.|==|=== // .=..===..=|.|||. // .======|||=|=.|= // .===|=|===T===|| // =|||...|==..|=.| // =.=|=.=..=.||==| // ||=|=...|==.=|== // |=.=||===.|||=== // ||.|==.|.|.||=|| // Before you go in, you should determine the risk level of the area. For the the rectangle that has a top-left corner of region 0,0 and a bottom-right corner of the region containing the target, add up the risk level of each individual region: 0 for rocky regions, 1 for wet regions, and 2 for narrow regions. // In the cave system above, because the mouth is at 0,0 and the target is at 10,10, adding up the risk level of all regions with an X coordinate from 0 to 10 and a Y coordinate from 0 to 10, this total is 114. });
b0f3163d191ae05cb2215b98b55d5bf5274c2675
{ "blob_id": "b0f3163d191ae05cb2215b98b55d5bf5274c2675", "branch_name": "refs/heads/master", "committer_date": "2020-03-14T01:31:48", "content_id": "f03f78771974d5a95bd4771c4cd85d6d86ab6b71", "detected_licenses": [ "MIT" ], "directory_id": "274559cb2e041cff17a63ccaac5ecc026ca377cf", "extension": "js", "filename": "22-map-test.js", "fork_events_count": 0, "gha_created_at": "2018-11-30T14:27:13", "gha_event_created_at": "2022-02-11T13:44:58", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 159834747, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4193, "license": "MIT", "license_type": "permissive", "path": "/test/22-map-test.js", "provenance": "stack-edu-0039.json.gz:511334", "repo_name": "gundelsby/aoc2018", "revision_date": "2020-03-14T01:31:48", "revision_id": "9f6058fb7766a24707b0e41be69f90a9f383a40c", "snapshot_id": "7d09540d345c596424b27435fc43ac621fdc4188", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gundelsby/aoc2018/9f6058fb7766a24707b0e41be69f90a9f383a40c/test/22-map-test.js", "visit_date": "2022-02-18T08:45:17.797874", "added": "2024-11-19T02:34:23.643239+00:00", "created": "2020-03-14T01:31:48", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
--- title: "Multi-Speaker Localization using Convolutional Neural Network Trained with Noise" date: 2017-12-01 publishDate: 2020-04-11T03:59:53.707653Z authors: ["S. Chakrabarty", "E. A. P. Habets"] publication_types: ["1"] abstract: "" featured: false publication: "*ML4Audio Worskhop at NeurIPS*" # Project tag projects: - asl image: caption: DOA Estimates focal_point: "" preview_only: false links: - icon: twitter icon_pack: fab name: Follow url: https://twitter.com/sch_bty - icon: github icon_pack: fab name: Model url: https://github.com/Soumitro-Chakrabarty/Single-speaker-localization url_code: "" url_pdf: "https://arxiv.org/pdf/1712.04276.pdf" url_slides: "https://www.audiolabs-erlangen.de/content/05-fau/assistant/00-chakrabarty/01-publications/2017NIPS/17_NIPS_presentation.pdf" url_video: "" ---
cf96ce390b65215f91c3626aa8ecdc1e0b3e3f1f
{ "blob_id": "cf96ce390b65215f91c3626aa8ecdc1e0b3e3f1f", "branch_name": "refs/heads/master", "committer_date": "2023-08-02T11:46:45", "content_id": "0300fdee1771ed5925be93b9bef9c9da121f53e6", "detected_licenses": [ "MIT" ], "directory_id": "7d71065bdc6582c03f0502ed518e98219e1b68f8", "extension": "md", "filename": "index.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 252923399, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 834, "license": "MIT", "license_type": "permissive", "path": "/content/publication/chakrabarty-2017-b/index.md", "provenance": "stack-edu-markdown-0007.json.gz:335786", "repo_name": "Soumitro-Chakrabarty/academic-kickstart", "revision_date": "2023-08-02T11:46:45", "revision_id": "92581462e62849102ecd1ce2e2cbbd40c625d03a", "snapshot_id": "21c0b128582a3c1070f03f2898ef162283eddfc1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Soumitro-Chakrabarty/academic-kickstart/92581462e62849102ecd1ce2e2cbbd40c625d03a/content/publication/chakrabarty-2017-b/index.md", "visit_date": "2023-08-29T07:48:52.508226", "added": "2024-11-19T01:39:20.565580+00:00", "created": "2023-08-02T11:46:45", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
using MagusCharacterGenerator.GameSystem.Magic; using Mtf.Languages; namespace MagusCharacterGenerator.Qualifications.Magic { class BardMagic : Sorcery { //ManaPoints = IQ 10 feletti része. public override string ToString() => Lng.Elem("Bard magic"); } }
1a40a31559a1adde2baf36942849af0e5bcb6385
{ "blob_id": "1a40a31559a1adde2baf36942849af0e5bcb6385", "branch_name": "refs/heads/main", "committer_date": "2021-10-31T00:20:17", "content_id": "227cedc8b41a3daea00238a7e6d4b85642c43c69", "detected_licenses": [ "MIT" ], "directory_id": "b00048bc5556c7b5812907017e7eb321a0241be2", "extension": "cs", "filename": "BardMagic.cs", "fork_events_count": 0, "gha_created_at": "2019-04-22T16:01:06", "gha_event_created_at": "2022-12-08T06:15:17", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 182821404, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 301, "license": "MIT", "license_type": "permissive", "path": "/MagusCharacterGenerator/Qualifications/Magic/BardMagic.cs", "provenance": "stack-edu-0009.json.gz:123855", "repo_name": "Mortens4444/MagusCharacterGenerator", "revision_date": "2021-10-31T00:20:17", "revision_id": "d86c867a9cb672de5ee75cd9591c3f3d5d5ad8e4", "snapshot_id": "2beab381d960c61702efb7504599d2dae72028d4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Mortens4444/MagusCharacterGenerator/d86c867a9cb672de5ee75cd9591c3f3d5d5ad8e4/MagusCharacterGenerator/Qualifications/Magic/BardMagic.cs", "visit_date": "2022-12-10T13:50:31.437774", "added": "2024-11-19T03:02:51.958065+00:00", "created": "2021-10-31T00:20:17", "int_score": 2, "score": 2, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
<?php namespace app\index\controller; use think\Controller; use think\Session; use think\Cookie; use think\Db; use app\index\model\Sms as SmsModel; class Login extends Controller{ public function login() { if(Cookie::has('username')&&Cookie::has('password')) { $curr_username = Cookie::get('username'); $curr_password = Cookie::get('password'); $curr_user = Db::query('select password,user_id from yyd_users where username ="'.$curr_username.'"'); if($curr_user) { $curr_user = $curr_user['0']; if ($curr_password == $curr_user['password']) { Session::set('userid', $curr_user['user_id']); Cookie::set('username', $curr_username, 3600 * 48); Cookie::set('password', $curr_password, 3600 * 48); $url = "/index/index/index"; $this->redirect($url); } else { return $this->fetch(); } } } //哪个页面跳过来的 $from = ''; if (isset($_SERVER['HTTP_REFERER'])) { $from = $_SERVER['HTTP_REFERER']; } $this->assign('from',$from); return $this->fetch(); } public function zhuce() { return $this->fetch(); } public function set_password() { $userid = Session::get('userid'); $phone=''; if(!empty($userid)){ $res = Db::query('select phone from yyd_users_info WHERE user_id = "'.$userid.'"'); $phone = $res['0']['phone']; } $this->assign('phone',$phone); return $this->fetch(); } public function dozuce() { $username = input('username'); $phone = input('phone'); $verifycode = input('verifycode'); $password = input('password'); $consistent_user = Db::query('select 1 from yyd_users where username ="'.$username.'"'); $consistent_userinfo = Db::query('select 1 from yyd_users_info where phone ="'.$phone.'"'); if(!empty($consistent_user)||!empty($consistent_userinfo)){ echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('已注册可直接登录');parent.location.href='/index/login/login'; </script>"; return; } $res = Db::query('select * from yyd_approve_smslog where phone ="'.$phone.'"order by addtime DESC limit 1'); if(empty($res)){ echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('注册失败');parent.location.href='/index/login/login'; </script>"; return; } if($res['0']['code']==$verifycode){ Db::query('insert into yyd_users (username,password) VALUE ("'.$username.'","'.md5($password).'")'); $result = Db::query('select last_insert_id()'); $user_id = $result['0']['last_insert_id()']; Db::query('insert into yyd_users_info (user_id,phone) VALUE ("'.$user_id.'","'.$phone.'")'); Session::set('userid',$user_id); $url = '/index/index/index'; $this->redirect($url); } } public function doreset(){ $smsmodle = new SmsModel; $phonenum = input('phone'); $captcha = input('verifycode'); $user_password= input('password'); $consistent_users = Db::query('SELECT * from yyd_users_info where phone ="'.$phonenum.'"'); $consistent_users = $consistent_users['0']; $consistent_sms = $smsmodle::get(['phone' => $phonenum]); if($captcha==$consistent_sms['code']){ if(!empty($consistent_users)){ $userid = $consistent_users['user_id']; $passwordmd5 = md5($user_password); $res = Db::query('update yyd_users set password ="'.$passwordmd5.'"where user_id ="'.$userid.'"'); echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('修改成功');parent.location.href='/index/login/login'; </script>"; return; }else{ echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('该手机还没注册');parent.location.href='/index/login/zhuce'; </script>"; return; } }else{ echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('验证码错误');parent.location.href='/index/login/set_password'; </script>"; return; } } public function dologin(){ $username = input('username'); $from = input('from'); $url = '/index/index/index'; if(!empty($from)){ $url = $from; } $consistent_user = Db::query('select * from yyd_users where username ="'.$username.'"'); if(!empty($consistent_user)){ $consistent_user = $consistent_user['0']; if(md5(input('password'))==$consistent_user['password']) { Session::set('userid',$consistent_user['user_id']); Cookie::set('username',$consistent_user['username'],3600*48); Cookie::set('password',$consistent_user['password'],3600*48); $this->redirect($url); return; }else{ echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('密码错误');parent.location.href='/index/login/login'; </script>"; return; } } echo "<script charset='utf-8' language='javascript' type='text/javascript' > alert('用户名未注册');parent.location.href='/index/login/login'; </script>"; return; } public function isnewusername(){ $isnewname = input('username'); $consistent_user = Db::query('select 1 from yyd_users where username ="'.$isnewname.'"'); if(empty($consistent_user)){ echo json_encode(array("code" => 0, "msg" => '用户名可用')); die; }else{ echo json_encode(array("code" => 1, "msg" => '用户名已注册')); die; } } //发送短信 public function sendsms() { $data['tel'] = input('tel'); $sms = new SmsModel; if (Session::get('smscode_time') + 60 > strtotime(date("Y-m-d H:i:s")) && Session::get('smscode_phone') == $data['tel']) { echo json_encode(array("code" => 0, "msg" => '请过1分钟后再申请')); die; } else if (empty($data['tel'])) { echo json_encode(array("code" => 0, "msg" => '手机号不能为空')); die; } else { if ($sms->check_phonenum($data['tel'])) { $smsdata = array(); Session::set('smscode_time', strtotime(date("Y-m-d H:i:s"))); Session::set('smscode_othertime', ('smscode_time') - strtotime(date("Y-m-d H:i:s"))); Session::set('smscode_phone', $data['tel']); //发送信息给客户 $smsdata['phone'] = $data['tel']; $smsdata['status'] = 1; $smsdata['type'] = 1; $smsdata['code'] = rand(100000, 999999); $smsdata['contents'] = "验证码:" . $smsdata['code'] . "。您正在进行手机注册操作,请不要把验证码泄露给任何人。【91众筹】"; $smsresult = $sms->SendSMS($smsdata); // if ($smsresult > 0) { echo json_encode(array("code" => 1, "msg" => '验证短信已发送,请查收!')); $newsms['phone'] = $data['tel']; $newsms['contents'] = $smsdata['contents']; $newsms['addtime'] = time(); $newsms['code'] = $smsdata['code']; //添加或更新该数据 $curr_sms = $sms->where('phone', $data['tel'])->find(); if (!empty($curr_sms)) { $newsms['id'] = $curr_sms['id']; $sms->update($newsms); } else { $sms->save($newsms); } return; } else { Session::set('smscode_username', ""); Session::set('smscode_time', Session::get('smscode_time') - 120); echo json_encode(array("code" => 0, "msg" => '验证短信发送失败,请联系客服!')); return; } } else { echo json_encode(array("code" => 0, "msg" => '手机号码格式不正确')); die; } } } public function quit(){ Session::set('userid',''); Session::set('accountInfo',''); Cookie::set('username','',60); Cookie::set('password','',60); $url = '/index/login/login'; $this->redirect($url); } }
4421167e502f2f373d93e1216eeefa2191b92c4f
{ "blob_id": "4421167e502f2f373d93e1216eeefa2191b92c4f", "branch_name": "refs/heads/master", "committer_date": "2017-02-15T09:09:40", "content_id": "735b78b34f52d3c6285bb9bee465c6c6d5c6a576", "detected_licenses": [ "Apache-2.0" ], "directory_id": "51b41a01e5b204a25dab2ef67ac912e7a2dd445b", "extension": "php", "filename": "Login.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 78906112, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9574, "license": "Apache-2.0", "license_type": "permissive", "path": "/application/index/controller/Login.php", "provenance": "stack-edu-0048.json.gz:827047", "repo_name": "mayingbing/zhongchou", "revision_date": "2017-02-15T09:09:40", "revision_id": "ec213ab146389829b1c763cc80d6f9de3f0b335d", "snapshot_id": "029890122dff219625bdca8eb9343ddfe100678f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mayingbing/zhongchou/ec213ab146389829b1c763cc80d6f9de3f0b335d/application/index/controller/Login.php", "visit_date": "2021-01-13T15:10:30.547025", "added": "2024-11-18T21:50:52.479933+00:00", "created": "2017-02-15T09:09:40", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
package com.seachangesimulations.platform.dao; import java.util.List; import com.seachangesimulations.platform.rpimobjects.Message; /** * This Database Access Object (DAO) Interface is the contract that any supporting persistence layer must meet to * function correctly in this software. * */ public interface MessageDao extends BaseDao<Message> { /** Returns messages sent to the user based on their unique user id. */ List<Message> getPlayersPersonalMessages(Long personId, Long rpimId, Long lastMessageReceived); /** Returns messages sent to the user based on the role they are playing id. */ List<Message> getPlayersRoleMessages(Long actorId, Long rpimId, Long lastMessageReceived); }
5fc309c12d8795257de23842c910fe7dbd8aa880
{ "blob_id": "5fc309c12d8795257de23842c910fe7dbd8aa880", "branch_name": "refs/heads/master", "committer_date": "2018-03-24T00:29:19", "content_id": "8d5a3425758cb710a678aadb28b1ce4ea752b537", "detected_licenses": [ "MIT" ], "directory_id": "83e901e214c44d63f7d79809354febbb154ba174", "extension": "java", "filename": "MessageDao.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 12821879, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 713, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/com/seachangesimulations/platform/dao/MessageDao.java", "provenance": "stack-edu-0025.json.gz:511158", "repo_name": "skipcole/SeaChangePlatform", "revision_date": "2018-03-24T00:29:19", "revision_id": "55b3493e778f18d19dda04b56d6a224e7ecd57df", "snapshot_id": "e71688d8d154a79022c45c83817dc6dbcb89ed97", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/skipcole/SeaChangePlatform/55b3493e778f18d19dda04b56d6a224e7ecd57df/src/main/java/com/seachangesimulations/platform/dao/MessageDao.java", "visit_date": "2021-05-15T01:25:16.388760", "added": "2024-11-19T02:21:25.552746+00:00", "created": "2018-03-24T00:29:19", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
// // SecondOnboardingScreen.swift // Granite(Revisited) // // Created by Matthew Harrilal on 5/28/19. // Copyright © 2019 Matthew Harrilal. All rights reserved. // import Foundation import UIKit class SecondOnboardingScreen: UIView { @IBOutlet weak var preferredLanguageLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! lazy var transitionButton = createTouchableBounceButton(withText: "Next") lazy var languageSet = Set<String>() var languagesArray: [(UIImage, String)] = [(#imageLiteral(resourceName: "javascript"), "Javascript"), (#imageLiteral(resourceName: "go"), "Golang"), (#imageLiteral(resourceName: "python"), "Python"), (#imageLiteral(resourceName: "ruby"),"Ruby"), (#imageLiteral(resourceName: "c"), "C++"), (#imageLiteral(resourceName: "java"), "Java"), (#imageLiteral(resourceName: "rust"), "Rust"), (#imageLiteral(resourceName: "php"), "PHP"), (#imageLiteral(resourceName: "swift"), "Swift") ] var selectedLanguagesClosure: ((Set<String>) -> Void)? override init(frame: CGRect) { super.init(frame: frame) // commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { commonInit() } fileprivate func commonInit() { Bundle.main.loadNibNamed("SecondOnboardingScreen", owner: self, options: nil) collectionView.dataSource = self collectionView.delegate = self collectionView.register(LanguagesCollectionViewCell.self, forCellWithReuseIdentifier: "cell") collectionView.alpha = 1.0 preferredLanguageLabel.alpha = 1.0 descriptionLabel.alpha = 1.0 preferredLanguageLabel.font = UIFont.bold(size: 20) descriptionLabel.font = UIFont.regular(size: 15) self.transitionButton.alpha = 1.0 addSubviews(views: preferredLanguageLabel, descriptionLabel, collectionView) collectionView?.contentInset = UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 16) collectionView.anchor(top: self.descriptionLabel.bottomAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor, padding: .init(top: 0, left: 10, bottom: -10, right: -10)) } }
2b5f3d933de8816846c9093fba5e00ab0eccff91
{ "blob_id": "2b5f3d933de8816846c9093fba5e00ab0eccff91", "branch_name": "refs/heads/master", "committer_date": "2019-09-27T21:27:25", "content_id": "bc63458c24474b1c6996913591e208a70d976501", "detected_licenses": [ "MIT" ], "directory_id": "2617a8f8ebb78afb06a16ae2203644836d90db3a", "extension": "swift", "filename": "SecondOnboardingScreen.swift", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 177221493, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 2351, "license": "MIT", "license_type": "permissive", "path": "/Granite(Revisited)/Views/SecondOnboardingScreen.swift", "provenance": "stack-edu-0072.json.gz:155922", "repo_name": "matthewharrilal/Granite-Cont", "revision_date": "2019-09-27T21:27:25", "revision_id": "9391b218719013aa6ddd359a8e69048ed564d17f", "snapshot_id": "1bf3843a080cc093f0c1d0d86852c3b8d3286c29", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matthewharrilal/Granite-Cont/9391b218719013aa6ddd359a8e69048ed564d17f/Granite(Revisited)/Views/SecondOnboardingScreen.swift", "visit_date": "2020-05-01T02:33:57.918894", "added": "2024-11-18T23:43:01.401452+00:00", "created": "2019-09-27T21:27:25", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
import React from "react" import { graphql } from "gatsby" import SEO from "../components/seo" import ProductForm from "../components/productForm" import { Image, Grid, Container } from "semantic-ui-react" import Layout from "../components/layout" const PartTemplate = ({ data }) => { const product = data.shopifyProduct return ( <Layout> <Container className="main-container"> <SEO title={product.title} description={product.description} /> <Grid columns={2}> <Grid.Column> {product.images.map(image => ( <Image src={image.originalSrc} key={image.id} alt={product.title} /> ))} </Grid.Column> <Grid.Column> <h1>{product.title}</h1> <div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }} /> <ProductForm product={product} /> </Grid.Column> </Grid> </Container> </Layout> ) } export const partQuery = graphql` query($handle: String!) { shopifyProduct(handle: { eq: $handle }) { id title handle productType description descriptionHtml shopifyId options { id name values } variants { id title price availableForSale shopifyId selectedOptions { name value } } priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } } images { originalSrc id localFile { childImageSharp { fluid(maxWidth: 910) { ...GatsbyImageSharpFluid_withWebp_tracedSVG } } } } } } ` export default PartTemplate
9a6df52b6fc2b07db2e3b426f18939dabb133489
{ "blob_id": "9a6df52b6fc2b07db2e3b426f18939dabb133489", "branch_name": "refs/heads/master", "committer_date": "2020-05-27T04:10:06", "content_id": "8d760828ffb6e1631eafc0fbbbab69b86e1dc26c", "detected_licenses": [ "MIT" ], "directory_id": "e1ea6943fbbe45073d4b63d02b2c7955c44cc153", "extension": "js", "filename": "part.js", "fork_events_count": 0, "gha_created_at": "2019-09-19T15:31:50", "gha_event_created_at": "2023-06-10T00:43:22", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 209588948, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1946, "license": "MIT", "license_type": "permissive", "path": "/src/templates/part.js", "provenance": "stack-edu-0038.json.gz:746243", "repo_name": "lewiscam/recovered_energy", "revision_date": "2020-05-27T04:10:06", "revision_id": "9f0cc68f49dec1a124f51f84756beeaa33944705", "snapshot_id": "0c1ea7aba46b5e4e5b914e78a99d904f69e03ca4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lewiscam/recovered_energy/9f0cc68f49dec1a124f51f84756beeaa33944705/src/templates/part.js", "visit_date": "2023-06-23T02:21:11.100009", "added": "2024-11-19T00:14:05.453533+00:00", "created": "2020-05-27T04:10:06", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
package com.example.extensions; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @ControllerAdvice public class ExceptionHandlers extends ResponseEntityExceptionHandler{ // @ExceptionHandler(MaxUploadSizeExceededException.class) // public ModelAndView handleMaxSizeFileException(MultipartException multiException, HttpEntity<String> req , ResponseEntity<String> response ) { // ModelAndView modelAndView = new ModelAndView("file"); // modelAndView.getModel().put("message", "File too large!"); // return modelAndView; // } @ExceptionHandler(MultipartException.class) public String handleLargeFileError(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", "Error: Uploaded file size exceeds limit (5MB)"); return "redirect:/upload"; } }
dde5da1545a94f1b94109e5de8ea0a3726ffeaa6
{ "blob_id": "dde5da1545a94f1b94109e5de8ea0a3726ffeaa6", "branch_name": "refs/heads/master", "committer_date": "2019-08-31T05:55:19", "content_id": "f312e77149059ca04922e6063b7674a0ccfc1106", "detected_licenses": [ "MIT" ], "directory_id": "523dd803cc5df6f3eccc59114883de5d2a0bdb75", "extension": "java", "filename": "ExceptionHandlers.java", "fork_events_count": 0, "gha_created_at": "2019-04-01T01:35:57", "gha_event_created_at": "2022-11-28T22:21:31", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 178764596, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1163, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/com/example/extensions/ExceptionHandlers.java", "provenance": "stack-edu-0025.json.gz:372141", "repo_name": "nuzzz/ConspecDashboard", "revision_date": "2019-08-31T05:55:19", "revision_id": "6c24674a1a391c9979da804cf2857d34f95218c8", "snapshot_id": "c21b7f057053f2b824548e34f82a1b5c7a092826", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nuzzz/ConspecDashboard/6c24674a1a391c9979da804cf2857d34f95218c8/src/main/java/com/example/extensions/ExceptionHandlers.java", "visit_date": "2022-12-12T00:01:23.961226", "added": "2024-11-18T22:58:37.969375+00:00", "created": "2019-08-31T05:55:19", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011, 2012 VMware, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package org.zmail.soap.mail.message; import com.google.common.base.Objects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.zmail.common.soap.MailConstants; import org.zmail.soap.mail.type.DocumentSpec; import org.zmail.soap.json.jackson.annotate.ZmailUniqueElement; /** * @zm-api-command-auth-required true * @zm-api-command-admin-auth-required false * @zm-api-command-description Save Document * <br /> * <br /> * One mechanism for Creating and updating a Document is: * <ol> * <li> Use FileUploadServlet to upload the document * <li> Call SaveDocumentRequest using the upload-id returned from FileUploadServlet. * </ol> * A Document represents a file. A file can be created by uploading to FileUploadServlet. Or it can refer to an * attachment of an existing message. * <br /> * <br /> * Documents are versioned. The server maintains the metadata of each version, such as by who and when the version * was edited, and the fragment. * <br /> * <br /> * When updating an existing Document, the client must supply the id of Document, and the last known version of the * document in the 'ver' attribute. This is used to prevent blindly overwriting someone else's change made after * the version this update was based upon. The update will succeed only when the last known version supplied by the * client matches the current version of the item identified by item-id. * <br /> * <br /> * Saving a new document, as opposed to adding a revision of existing document, should leave the id and ver fields * empty in the request. Then the server checks and see if the named document already exists, if so returns an error. * <br /> * <br /> * The request should contain either an <b>&lt;upload></b> element or a <b>&lt;msg></b> element, but not both. * When <b>&lt;upload></b> is used, the document should first be uploaded to FileUploadServlet, and then use the * upload-id from the FileUploadResponse. * <br /> * When <b>&lt;m></b> is used, the document is retrieved from an existing message in the mailbox, identified by the * msg-id and part-id. The content of the document can be inlined in the <b>&lt;content></b> element. * The content can come from another document / revision specified in the <b>&lt;doc></b> sub element. * <br /> * Examples: * <br /> * <br /> * Saving a new document: * <pre> * &lt;SaveDocumentRequest xmlns:ns0="urn:zmailMail"> * &lt;doc> * &lt;upload id="18baa043-394f-42ae-be8a-110b279cb696:cc2f2fdf-7957-4412-aa83-6433662ce5d0"/> * &lt;/doc> * &lt;/SaveDocumentRequest> * * &lt;SaveDocumentResponse xmlns:ns0="urn:zmailMail"> * &lt;doc ver="1" id="574" name="PICT0370.JPG"/> * &lt;/SaveDocumentResponse> * </pre> * Updating an existing document * <pre> * &lt;SaveDocumentRequest xmlns:ns0="urn:zmailMail"> * &lt;doc ver="1" id="574" desc="rev 2.0"> * &lt;upload id="18baa043-394f-42ae-be8a-110b279cb696:fcb572ce-2a81-4ad3-b55b-cb998c47b416"/> * &lt;/doc> * &lt;/SaveDocumentRequest> * * &lt;SaveDocumentResponse xmlns:ns0="urn:zmailMail"> * &lt;doc ver="2" id="574" name="PICT0370.JPG"/> * &lt;/SaveDocumentResponse> * </pre> */ @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name=MailConstants.E_SAVE_DOCUMENT_REQUEST) public class SaveDocumentRequest { /** * @zm-api-field-description Document specification */ @ZmailUniqueElement @XmlElement(name=MailConstants.E_DOC /* doc */, required=true) private DocumentSpec doc; public SaveDocumentRequest() { } public void setDoc(DocumentSpec doc) { this.doc = doc; } public DocumentSpec getDoc() { return doc; } public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) { return helper .add("doc", doc); } @Override public String toString() { return addToStringInfo(Objects.toStringHelper(this)).toString(); } }
35ce439140d764cb15af7560b090798c8d630652
{ "blob_id": "35ce439140d764cb15af7560b090798c8d630652", "branch_name": "refs/heads/master", "committer_date": "2013-10-22T12:48:43", "content_id": "7343adc73b87d8d7393c3d019b540da80f8058a7", "detected_licenses": [ "MIT" ], "directory_id": "82eba08b9a7ee1bd1a5f83c3176bf3c0826a3a32", "extension": "java", "filename": "SaveDocumentRequest.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": 4655, "license": "MIT", "license_type": "permissive", "path": "/ZmailSoap/src/java/org/zmail/soap/mail/message/SaveDocumentRequest.java", "provenance": "stack-edu-0024.json.gz:858841", "repo_name": "keramist/zmailserver", "revision_date": "2013-10-21T11:27:05", "revision_id": "762642b77c8f559a57e93c9f89b1473d6858c159", "snapshot_id": "d01187fb6086bf3784fe180bea2e1c0854c83f3f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/keramist/zmailserver/762642b77c8f559a57e93c9f89b1473d6858c159/ZmailSoap/src/java/org/zmail/soap/mail/message/SaveDocumentRequest.java", "visit_date": "2021-01-21T05:56:25.642425", "added": "2024-11-19T01:31:23.900909+00:00", "created": "2013-10-21T11:27:05", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
/* * 프로그래밍 연습 final project * PHONE BOOK * 151008 정승미 * * - instructions- * PHONE_BOOK.txt파일이 이미 생성 되어 있을경우, 파일에서 이름과 전화번호 데이터를 읽어들인 후 메뉴 실행 * 1. insert mode: 이름과 전화번호 저장. 한번에 하나씩 저장가능 * 2. delete mode: 이름, 혹은 전화번호(전체 전화번호 혹은 가운데 네자리, 끝 네자리로 검색 가능)로 지울 item을 찾아서 지움 * 3. modify mode: 이름, 혹은 전화번호(전체 전화번호 혹은 가운데 네자리, 끝 네자리로 검색 가능)로 수정할 item을 찾아서 수정 * 이름을 수정하고 싶을 경우 이름으로 검색 해야하고, 전화번호를 수정하고 싶을 경우 전화번호로 검색 해야함 * 4. search mode: 이름, 혹은 전화번호(전체 전화번호 혹은 가운데 네자리, 끝 네자리로 검색 가능)로 검색 * 5. print mode: 전체 전화번호부 출력 * 6. quit: 전화번호부 종료 및 전화번호부 .txt파일 생성(파일이름: PHONE_BOOK.txt) * */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct person { char name[20]; char phoneNum[20]; }Person; void insertMode(Person**, int); void deleteMode(Person**, int*); void modifyMode(Person**, int); void searchMode(Person**, int); void printMode(Person**, int); void writeTofile(Person**,int); int fopenCheck(FILE*); int getPhonebookData(Person**); int searchByName(Person**, int, char*); int searchByPartialPnum(Person**, int, char*); int searchByPnum(Person**, int, char*);
688caabd89b20ade508855d0c8763cd156d0581d
{ "blob_id": "688caabd89b20ade508855d0c8763cd156d0581d", "branch_name": "refs/heads/master", "committer_date": "2015-06-24T15:14:38", "content_id": "911f432f76b8786eeab36f6de326b27401e3cbd0", "detected_licenses": [ "MIT" ], "directory_id": "b904b66bfaacbfd8bdfb7e2fc45c7cf094df6802", "extension": "h", "filename": "phoneBook.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 34119350, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1677, "license": "MIT", "license_type": "permissive", "path": "/PLinC/phoneBook/phoneBook.h", "provenance": "stack-edu-0001.json.gz:53378", "repo_name": "miyaeyo/1stSemester-nhnnext", "revision_date": "2015-06-24T15:14:38", "revision_id": "418b0ae4d611730dcc783c124da98df8bec47637", "snapshot_id": "659ed9060c41ddcf9890f08f09d63efe0fa82321", "src_encoding": "UHC", "star_events_count": 1, "url": "https://raw.githubusercontent.com/miyaeyo/1stSemester-nhnnext/418b0ae4d611730dcc783c124da98df8bec47637/PLinC/phoneBook/phoneBook.h", "visit_date": "2016-09-06T13:01:02.310768", "added": "2024-11-19T02:37:40.660469+00:00", "created": "2015-06-24T15:14:38", "int_score": 3, "score": 2.625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
#pragma once #include <vector> #include "Constants.hpp" #include "MotionControl.hpp" #include "Node.hpp" /** * Handles motion control for all robots. Calling this once will run motion * control on all robots. */ class MotionControlNode : public Node { public: explicit MotionControlNode(Context* context); void run() override; private: Context* _context; std::vector<std::optional<MotionControl>> _controllers; };
ab63744883dba91e804f15e21da49e6d97893fbe
{ "blob_id": "ab63744883dba91e804f15e21da49e6d97893fbe", "branch_name": "refs/heads/master", "committer_date": "2019-09-23T13:19:08", "content_id": "26f0de87998a24f6d5f47a3f142c27711b841721", "detected_licenses": [ "Apache-2.0" ], "directory_id": "307dd911353916538743bc59726d13fb0d309fae", "extension": "hpp", "filename": "MotionControlNode.hpp", "fork_events_count": 0, "gha_created_at": "2019-09-24T23:38:32", "gha_event_created_at": "2019-09-24T23:38:32", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 210716189, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license": "Apache-2.0", "license_type": "permissive", "path": "/soccer/motion/MotionControlNode.hpp", "provenance": "stack-edu-0006.json.gz:309863", "repo_name": "bulanov416/robocup-software", "revision_date": "2019-09-23T13:19:08", "revision_id": "4043a7f9590d02f617d8e9a762697e4aaa27f1a6", "snapshot_id": "d92c4a49c2498aec869501bc63efb2618ea67a22", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bulanov416/robocup-software/4043a7f9590d02f617d8e9a762697e4aaa27f1a6/soccer/motion/MotionControlNode.hpp", "visit_date": "2020-07-31T19:25:07.546735", "added": "2024-11-18T23:05:18.887814+00:00", "created": "2019-09-23T13:19:08", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
<?php function loadClass($classname) { if(file_exists('../models/'. $classname.'.php')) { require '../models/'. $classname.'.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('loadClass'); session_start(); if (isset($_SESSION['name'])) { }else { header('location: inscriptionLog.php'); } // Connexion à la base de données $db = Database::DB(); $userManager = new UserManager($db); $bookManager = new BookManager($db); //Suppression d'un utilisateur if(isset($_POST['delete'])){ if(isset($_POST['id']) && !empty($_POST['id'])){ $id = (int) $_POST['id']; $userManager->deleteUser($id); } } $users = $userManager->getUsersByLastname(); include "../views/usersListView.php"; ?>
82978c9d899832a1bce9a8359a5dc13bc8fcc93b
{ "blob_id": "82978c9d899832a1bce9a8359a5dc13bc8fcc93b", "branch_name": "refs/heads/master", "committer_date": "2019-08-30T12:05:44", "content_id": "a8a44d3541d68fa732dd0aa263d93d8cf6c33cd4", "detected_licenses": [ "MIT" ], "directory_id": "fcdbeb143dc1c5ce93554885cc5b2cbca0c6118f", "extension": "php", "filename": "usersList.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 197378856, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 821, "license": "MIT", "license_type": "permissive", "path": "/controllers/usersList.php", "provenance": "stack-edu-0048.json.gz:925909", "repo_name": "jeancharlesgraillot/biblio_app", "revision_date": "2019-08-30T12:05:44", "revision_id": "88d5bcf2f1a5690c594cbbae2d66005feabf0fc7", "snapshot_id": "7f7eac2fd76ad7793af920568dceec70b446899a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jeancharlesgraillot/biblio_app/88d5bcf2f1a5690c594cbbae2d66005feabf0fc7/controllers/usersList.php", "visit_date": "2020-07-14T18:27:56.600244", "added": "2024-11-19T00:51:16.543179+00:00", "created": "2019-08-30T12:05:44", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
class Measured::UnitSystemBuilder def initialize @units = [] end def unit(unit_name, aliases: [], value: nil) @units << build_unit(unit_name, aliases: aliases, value: value) nil end def build Measured::UnitSystem.new(@units) end private def build_unit(name, aliases: [], value: nil) unit = Measured::Unit.new(name, aliases: aliases, value: value) check_for_duplicate_unit_names!(unit) unit end def check_for_duplicate_unit_names!(unit) names = @units.flat_map(&:names) if names.any? { |name| unit.names.include?(name) } raise Measured::UnitError, "Unit #{unit.name} has already been added." end end end
02cc576d0163d8500fe05ac1373e14d23be47221
{ "blob_id": "02cc576d0163d8500fe05ac1373e14d23be47221", "branch_name": "refs/heads/master", "committer_date": "2017-02-22T22:58:50", "content_id": "2b854d7b54910472ec760c2a5bcd58e13614f33e", "detected_licenses": [ "MIT" ], "directory_id": "383cc0bcc8540427600449211422fe74d36e046f", "extension": "rb", "filename": "unit_system_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": 676, "license": "MIT", "license_type": "permissive", "path": "/lib/measured/unit_system_builder.rb", "provenance": "stack-edu-0066.json.gz:765160", "repo_name": "danielstanojevic/measured", "revision_date": "2017-02-22T22:58:50", "revision_id": "76e7b7276b7cf435b3f7ac4402269b9a60dd9bf9", "snapshot_id": "6b99b547a6eac8ba478a93a79e10167c1e8fde5a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/danielstanojevic/measured/76e7b7276b7cf435b3f7ac4402269b9a60dd9bf9/lib/measured/unit_system_builder.rb", "visit_date": "2021-01-21T10:34:07.018010", "added": "2024-11-19T01:32:40.121519+00:00", "created": "2017-02-22T22:58:50", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
<?php declare(strict_types=1); namespace Osnova\Api\Component\Model; /** * Class EtcControls * @package Osnova\Api\Component\Model */ class EtcControls extends Model { public bool $edit_entry; public bool $pin_content; public bool $unpublish_entry; public bool $ban_subsite; public bool $pin_comment; public bool $remove; public bool $remove_thread; }
bd119e6736a3bb8a0cf91ba07352640e97ee4c1e
{ "blob_id": "bd119e6736a3bb8a0cf91ba07352640e97ee4c1e", "branch_name": "refs/heads/main", "committer_date": "2021-04-18T10:47:38", "content_id": "6d445be9bafc42e256971e72fff6ba078972f7ed", "detected_licenses": [ "MIT" ], "directory_id": "d35b7100c6054eac3cc900740875ce6b7ccd8152", "extension": "php", "filename": "EtcControls.php", "fork_events_count": 0, "gha_created_at": "2021-04-13T20:07:10", "gha_event_created_at": "2021-04-17T10:10:10", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 357675348, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 385, "license": "MIT", "license_type": "permissive", "path": "/src/Component/Model/EtcControls.php", "provenance": "stack-edu-0054.json.gz:89062", "repo_name": "digtyarenko/osnova-php-sdk", "revision_date": "2021-04-18T10:47:38", "revision_id": "38169a18db365ba8a1bc1e161dc794984c55f8d8", "snapshot_id": "f5dde96774ecaed336ac09f7eef6a7414406f597", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/digtyarenko/osnova-php-sdk/38169a18db365ba8a1bc1e161dc794984c55f8d8/src/Component/Model/EtcControls.php", "visit_date": "2023-04-04T06:38:53.063061", "added": "2024-11-18T23:36:45.049658+00:00", "created": "2021-04-18T10:47:38", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
/* Copyright 2019 The Kubernetes Authors. 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 pod import ( "context" "fmt" "time" "github.com/onsi/ginkgo/v2" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/test/e2e/framework" ) const ( // PodDeleteTimeout is how long to wait for a pod to be deleted. PodDeleteTimeout = 5 * time.Minute ) // DeletePodOrFail deletes the pod of the specified namespace and name. Resilient to the pod // not existing. func DeletePodOrFail(ctx context.Context, c clientset.Interface, ns, name string) { ginkgo.By(fmt.Sprintf("Deleting pod %s in namespace %s", name, ns)) err := c.CoreV1().Pods(ns).Delete(ctx, name, metav1.DeleteOptions{}) if err != nil && apierrors.IsNotFound(err) { return } expectNoError(err, "failed to delete pod %s in namespace %s", name, ns) } // DeletePodWithWait deletes the passed-in pod and waits for the pod to be terminated. Resilient to the pod // not existing. func DeletePodWithWait(ctx context.Context, c clientset.Interface, pod *v1.Pod) error { if pod == nil { return nil } return DeletePodWithWaitByName(ctx, c, pod.GetName(), pod.GetNamespace()) } // DeletePodWithWaitByName deletes the named and namespaced pod and waits for the pod to be terminated. Resilient to the pod // not existing. func DeletePodWithWaitByName(ctx context.Context, c clientset.Interface, podName, podNamespace string) error { framework.Logf("Deleting pod %q in namespace %q", podName, podNamespace) err := c.CoreV1().Pods(podNamespace).Delete(ctx, podName, metav1.DeleteOptions{}) if err != nil { if apierrors.IsNotFound(err) { return nil // assume pod was already deleted } return fmt.Errorf("pod Delete API error: %w", err) } framework.Logf("Wait up to %v for pod %q to be fully deleted", PodDeleteTimeout, podName) err = WaitForPodNotFoundInNamespace(ctx, c, podName, podNamespace, PodDeleteTimeout) if err != nil { return fmt.Errorf("pod %q was not deleted: %w", podName, err) } return nil } // DeletePodWithGracePeriod deletes the passed-in pod. Resilient to the pod not existing. func DeletePodWithGracePeriod(ctx context.Context, c clientset.Interface, pod *v1.Pod, grace int64) error { return DeletePodWithGracePeriodByName(ctx, c, pod.GetName(), pod.GetNamespace(), grace) } // DeletePodsWithGracePeriod deletes the passed-in pods. Resilient to the pods not existing. func DeletePodsWithGracePeriod(ctx context.Context, c clientset.Interface, pods []v1.Pod, grace int64) error { for _, pod := range pods { if err := DeletePodWithGracePeriod(ctx, c, &pod, grace); err != nil { return err } } return nil } // DeletePodWithGracePeriodByName deletes a pod by name and namespace. Resilient to the pod not existing. func DeletePodWithGracePeriodByName(ctx context.Context, c clientset.Interface, podName, podNamespace string, grace int64) error { framework.Logf("Deleting pod %q in namespace %q", podName, podNamespace) err := c.CoreV1().Pods(podNamespace).Delete(ctx, podName, *metav1.NewDeleteOptions(grace)) if err != nil { if apierrors.IsNotFound(err) { return nil // assume pod was already deleted } return fmt.Errorf("pod Delete API error: %w", err) } return nil }
91698f8881c61443f58e81505eb444c29adc4060
{ "blob_id": "91698f8881c61443f58e81505eb444c29adc4060", "branch_name": "refs/heads/master", "committer_date": "2023-08-21T18:09:34", "content_id": "360862d34387a6d48627d79cd2b324a85c4235e4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c2e298290aa9d4d0c74482850c0547027d359820", "extension": "go", "filename": "delete.go", "fork_events_count": 43154, "gha_created_at": "2014-06-06T22:56:04", "gha_event_created_at": "2023-09-14T21:45:02", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 20580498, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3808, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/e2e/framework/pod/delete.go", "provenance": "stack-edu-0018.json.gz:42092", "repo_name": "kubernetes/kubernetes", "revision_date": "2023-08-21T18:09:34", "revision_id": "55c86d6ad930d437931079318d740bdf8dac34f0", "snapshot_id": "a3df9e08b5a0d013dcfccfa7cacd6afe39e282df", "src_encoding": "UTF-8", "star_events_count": 101271, "url": "https://raw.githubusercontent.com/kubernetes/kubernetes/55c86d6ad930d437931079318d740bdf8dac34f0/test/e2e/framework/pod/delete.go", "visit_date": "2023-08-21T18:23:51.296777", "added": "2024-11-19T01:40:56.869638+00:00", "created": "2023-08-21T18:09:34", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
using System; namespace Vetores_ex002 { class Program { static void Main(string[] args) { int n; n = int.Parse(Console.ReadLine()); double soma = 0.0; double media; //Criação de um vetor de objetos Product[] vetorProdutos = new Product[n]; for(int i = 0; i < n; i++) { string name = Console.ReadLine(); double price = double.Parse(Console.ReadLine()); //Instanciação automática dos objetos, sem construtores vetorProdutos[i] = new Product {Name = name, Price = price}; } //Acessar um atributo em um vetor de objetos for (int i = 0; i < n; i++) { soma += vetorProdutos[i].Price; } media = soma / n; Console.WriteLine($"Average price: {media}"); } } }
d805b0899eb03d38e4aa34df27b74b9cf1623083
{ "blob_id": "d805b0899eb03d38e4aa34df27b74b9cf1623083", "branch_name": "refs/heads/master", "committer_date": "2021-06-18T13:15:25", "content_id": "588f9c0ae71c9a6193cf02aeb1f12c45387ab32d", "detected_licenses": [ "MIT" ], "directory_id": "5445b876560cee50bf18307f439c5bbcd72d5f78", "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": 369610227, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 962, "license": "MIT", "license_type": "permissive", "path": "/Capitulo 6/Vetores_ex002/Vetores_ex002/Program.cs", "provenance": "stack-edu-0015.json.gz:4639", "repo_name": "GabriellyBailon/CursoCSharp", "revision_date": "2021-06-18T13:15:25", "revision_id": "4ab2f7299ae22a6003e8f6a3ee9ab6574466e5e1", "snapshot_id": "238ea1af131baeedb53985fb3caed1193f30ea0a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GabriellyBailon/CursoCSharp/4ab2f7299ae22a6003e8f6a3ee9ab6574466e5e1/Capitulo 6/Vetores_ex002/Vetores_ex002/Program.cs", "visit_date": "2023-05-24T15:43:40.972060", "added": "2024-11-18T22:52:01.496684+00:00", "created": "2021-06-18T13:15:25", "int_score": 4, "score": 3.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz" }
#!/bin/bash function main() { for FILE in "$@"; do local UNUSED_SYMBOLS=() for SYMBOL in $(find_imported_symbols < "$FILE"); do local COUNT=$(one_expression_per_line < "$FILE" | \ grep -vE '^\s*import\s+[a-zA-Z0-9_.]+\s*:' | \ grep -cE "\b$SYMBOL\b") if (( COUNT == 0 )); then UNUSED_SYMBOLS+=( $SYMBOL ) fi done if (( ${#UNUSED_SYMBOLS[*]} > 0 )); then local OLD_IFS="$IFS"; IFS="|" echo "$FILE: \b(${UNUSED_SYMBOLS[*]})\b" IFS="$OLD_IFS" fi done } function find_imported_symbols() { one_expression_per_line | \ grep -E '^\s*import\s+[a-zA-Z0-9_.]+\s*:' | \ tr ',;' ' ' | \ sed -r '{ s/^.*:// s/=\s*\S+//g }' } function one_expression_per_line() { tr '\n' ' ' | \ tr ';' '\n' | \ sed -r 's/\bimport\b/\nimport/g' } main "$@"
50ecfe5ea1430f6a4bcfc6dfe3251fa275e5710b
{ "blob_id": "50ecfe5ea1430f6a4bcfc6dfe3251fa275e5710b", "branch_name": "refs/heads/master", "committer_date": "2018-08-08T13:46:57", "content_id": "bf02fe3ce2012034c1b5b9b12b33d2f2fcb60367", "detected_licenses": [ "MIT" ], "directory_id": "2c5ebe0955168be702e2829c67806313dc3002a6", "extension": "sh", "filename": ".unused-imports.sh", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 125883419, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 982, "license": "MIT", "license_type": "permissive", "path": "/.unused-imports.sh", "provenance": "stack-edu-0069.json.gz:842252", "repo_name": "a-ludi/djunctor", "revision_date": "2018-08-08T13:46:57", "revision_id": "47c388ad1c5884b538253dce9f1645c003493503", "snapshot_id": "f5dce463588f97c4a7dbfff4b38e4f7c3e39503d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/a-ludi/djunctor/47c388ad1c5884b538253dce9f1645c003493503/.unused-imports.sh", "visit_date": "2021-04-12T03:22:39.154466", "added": "2024-11-19T01:15:39.245718+00:00", "created": "2018-08-08T13:46:57", "int_score": 4, "score": 3.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
<?php namespace Bundle\DoctrineUserBundle\Tests\Command; use Bundle\DoctrineUserBundle\Test\WebTestCase; use Bundle\DoctrineUserBundle\Model\User; use Bundle\DoctrineUserBundle\Command\CreateUserCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Output\Output; use Symfony\Component\Console\Tester\ApplicationTester; class CreateUserCommandTest extends WebTestCase { public function testUserCreation() { $kernel = $this->createKernel(); $command = new CreateUserCommand(); $application = new Application($kernel); $application->setAutoExit(false); $tester = new ApplicationTester($application); $username = 'test_username'; $password = 'test_password'; $email = 'test_email@email.org'; $tester->run(array( 'command' => $command->getFullName(), 'username' => $username, 'password' => $password, 'email' => $email, ), array('interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE)); $userRepo = $this->getService('doctrine_user.repository.user'); $user = $userRepo->findOneByUsername($username); $this->assertTrue($user instanceof User); $this->assertTrue($user->checkPassword($password)); $this->assertEquals($email, $user->getEmail()); $userRepo->getObjectManager()->remove($user); $userRepo->getObjectManager()->flush(); } public function testUserCreationWithOptions() { $kernel = $this->createKernel(); $command = new CreateUserCommand(); $application = new Application($kernel); $application->setAutoExit(false); $tester = new ApplicationTester($application); $username = 'test_username'; $password = 'test_password'; $email = 'test_email@email.org'; $tester->run(array( 'command' => $command->getFullName(), 'username' => $username, 'password' => $password, 'email' => $email, '--inactive' => true, '--super-admin' => true ), array('interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE)); $userRepo = $this->getService('doctrine_user.repository.user'); $user = $userRepo->findOneByUsername($username); $this->assertTrue($user instanceof User); $this->assertTrue($user->checkPassword($password)); $this->assertEquals($email, $user->getEmail()); $this->assertFalse($user->getIsActive()); $this->assertTrue($user->getIsSuperAdmin()); $userRepo->getObjectManager()->remove($user); $userRepo->getObjectManager()->flush(); } public function tearDown() { $repo = $this->getService('doctrine_user.repository.user'); $om = $repo->getObjectManager(); if ($user = $repo->findOneByUsername('test_username')) { $om->remove($user); } $om->flush(); } }
d6b98a83607314adac9059bf97c82fcdfcb417af
{ "blob_id": "d6b98a83607314adac9059bf97c82fcdfcb417af", "branch_name": "refs/heads/master", "committer_date": "2010-12-02T16:47:27", "content_id": "06d4be516afc423b513d6923f353085170dc6c40", "detected_licenses": [ "MIT" ], "directory_id": "9d56c55ff18241930ded911378a72de053af58f8", "extension": "php", "filename": "CreateUserCommandTest.php", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1132479, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3071, "license": "MIT", "license_type": "permissive", "path": "/Tests/Command/CreateUserCommandTest.php", "provenance": "stack-edu-0048.json.gz:301368", "repo_name": "dunglas/DoctrineUserBundle", "revision_date": "2010-12-02T16:47:27", "revision_id": "ec3e5687e1e4724306b285471a6da9f6eb3043dc", "snapshot_id": "1f1d5b8735a910f2b7bed15c1929ba43c4d60f38", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dunglas/DoctrineUserBundle/ec3e5687e1e4724306b285471a6da9f6eb3043dc/Tests/Command/CreateUserCommandTest.php", "visit_date": "2021-01-17T21:49:11.788460", "added": "2024-11-19T02:45:03.799651+00:00", "created": "2010-12-02T16:47:27", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
public struct Amount { let subtotalIva: Double let subtotalIva0: Double let iva: Double public init(subtotalIva: Double, subtotalIva0: Double, iva: Double) { self.subtotalIva = subtotalIva self.subtotalIva0 = subtotalIva0 self.iva = iva } }
523de4e8da83ad985ae97464627a5e6e0afaa3c7
{ "blob_id": "523de4e8da83ad985ae97464627a5e6e0afaa3c7", "branch_name": "refs/heads/master", "committer_date": "2022-12-20T19:30:25", "content_id": "1b7fb302254796a52a410196217f3f55bae28752", "detected_licenses": [ "MIT" ], "directory_id": "1685ecf6723bf3020492676113af896c771436db", "extension": "swift", "filename": "Amount.swift", "fork_events_count": 5, "gha_created_at": "2016-09-29T21:22:25", "gha_event_created_at": "2022-12-22T22:17:15", "gha_language": "Swift", "gha_license_id": "MIT", "github_id": 69608978, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 295, "license": "MIT", "license_type": "permissive", "path": "/Example/Pods/Kushki/Kushki/Classes/Struct/Amount.swift", "provenance": "stack-edu-0071.json.gz:689985", "repo_name": "Kushki/kushki-ios", "revision_date": "2022-12-20T19:30:25", "revision_id": "231a22a4394dd285f1bd53640a7b0ffb2be57742", "snapshot_id": "f20f0717f98f0fcb3ace80499cc4ce9e13a15f8c", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Kushki/kushki-ios/231a22a4394dd285f1bd53640a7b0ffb2be57742/Example/Pods/Kushki/Kushki/Classes/Struct/Amount.swift", "visit_date": "2022-12-29T22:32:26.384431", "added": "2024-11-18T20:46:57.711016+00:00", "created": "2022-12-20T19:30:25", "int_score": 3, "score": 2.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz" }
import random import numpy as np class Compose: def __init__(self, transforms, prob=1.): self.transforms = [t for t in transforms if t is not None] self.prob = prob def __call__(self, **data): if random.random() < self.prob: for t in self.transforms: data = t(**data) return data class OneOf: def __init__(self, transforms, prob=.5): self.transforms = transforms self.prob = prob transforms_probs = [t.prob for t in transforms] s = sum(transforms_probs) self.transforms_probs = [t / s for t in transforms_probs] def __call__(self, **data): if random.random() < self.prob: t = np.random.choice(self.transforms, p=self.transforms_probs) t.prob = 1. data = t(**data) return data class OneOrOther: def __init__(self, first, second, prob=.5): self.first = first first.prob = 1. self.second = second second.prob = 1. self.prob = prob def __call__(self, **data): return self.first(**data) if random.random() < self.prob else self.second(**data)
688002a1f514a662da6dc56f5fcdc074969e3e40
{ "blob_id": "688002a1f514a662da6dc56f5fcdc074969e3e40", "branch_name": "refs/heads/master", "committer_date": "2020-05-07T10:33:06", "content_id": "15be97b75ad5f3a6d14f41614cab2a74382b3b34", "detected_licenses": [ "MIT" ], "directory_id": "6c39dedc2162e5a7c4ef23492502402c0730c86a", "extension": "py", "filename": "composition.py", "fork_events_count": 0, "gha_created_at": "2020-04-28T11:01:08", "gha_event_created_at": "2020-04-28T11:01:09", "gha_language": null, "gha_license_id": "MIT", "github_id": 259611745, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1213, "license": "MIT", "license_type": "permissive", "path": "/victor/augmentations/composition.py", "provenance": "stack-edu-0061.json.gz:240134", "repo_name": "AmirShahid/dsb2018_topcoders", "revision_date": "2020-05-07T10:33:06", "revision_id": "1b59c56f9a767def4ae61b10f7d66f324b4660ff", "snapshot_id": "05f8df51fab30081e325250c60d92166db4a4b8c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/AmirShahid/dsb2018_topcoders/1b59c56f9a767def4ae61b10f7d66f324b4660ff/victor/augmentations/composition.py", "visit_date": "2022-06-15T17:01:41.486154", "added": "2024-11-18T20:43:23.448012+00:00", "created": "2020-05-07T10:33:06", "int_score": 3, "score": 3.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz" }
// // XMLPath.swift // SwiftLibXML // // Created by Rene Hexel on 25/03/2016. // Copyright © 2016, 2018, 2020 Rene Hexel. All rights reserved. // #if os(Linux) import Glibc import CLibXML2 #else import Darwin import libxml2 #endif /// /// A wrapper around libxml2 xmlXPathTypePtr /// public struct XMLPath { let xpath: xmlXPathObjectPtr } /// /// Extension to make XMLPath behave like an array /// extension XMLPath: Sequence { public typealias Index = Int public typealias Iterator = AnyIterator<XMLElement> // public typealias SubSequence = Array<XMLElement> var nodeSet: xmlNodeSetPtr? { return xpath.pointee.nodesetval } public var count: Int { return nodeSet != nil ? Int(nodeSet!.pointee.nodeNr) : 0 } public var startIndex: Index { return 0 } public var endIndex: Index { return count } public var first: XMLElement? { guard count > 0 else { return nil } return self.at(index: startIndex) } public var last: XMLElement? { guard count > 0 else { return nil } return self.at(index: endIndex) } public func index(after i: Index) -> Index { return i+1 } public func formIndex(after i: inout Index) { i += 1 } public func at(index i: Index) -> XMLElement { precondition(i >= startIndex) precondition(i < endIndex) return XMLElement(node: nodeSet!.pointee.nodeTab![i]!) } public subscript(position i: Index) -> XMLElement { return at(index: i) } // public subscript(bounds: Range<Index>) -> Array<XMLElement> { // return [] // } /// Returns an iterator over the elements of the XMLPath. public func makeIterator() -> Iterator { var i = 0 return AnyIterator { let j = i guard j < self.count else { return nil } i += 1 return self.at(index: j) } } } extension XMLDocument { /// compile a given XPath for queries public func xpath(_ p: String, namespaces ns: AnySequence<XMLNameSpace> = emptySequence(), defaultPrefix: String = "ns") -> XMLPath? { guard let context = xmlXPathNewContext(xml) else { return nil } defer { xmlXPathFreeContext(context) } ns.forEach { xmlXPathRegisterNs(context, $0.prefix ?? defaultPrefix, $0.href ?? "") } return xpath(p, context: context) } /// compile a given XPath for queries public func xpath(_ p: String, namespaces ns: [(prefix: String, href: String)]) -> XMLPath? { guard let context = xmlXPathNewContext(xml) else { return nil } defer { xmlXPathFreeContext(context) } ns.forEach { xmlXPathRegisterNs(context, $0.prefix, $0.href) } return xpath(p, context: context) } /// compile an xpath for queries with a given context public func xpath(_ p: String, context: xmlXPathContextPtr) -> XMLPath? { guard let xmlXPath = xmlXPathEvalExpression(p, context) else { return nil } return XMLPath(xpath: xmlXPath) } }
9744702b2660682751e2d3aaa838775366fa7ec9
{ "blob_id": "9744702b2660682751e2d3aaa838775366fa7ec9", "branch_name": "refs/heads/main", "committer_date": "2021-03-06T16:01:40", "content_id": "6059a62bbb7f377bc711d0c93ff6418223cc5b8f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "fb51e8a575bd3937cdf5608fd8508792d9592586", "extension": "swift", "filename": "XMLPath.swift", "fork_events_count": 0, "gha_created_at": "2021-03-06T15:54:39", "gha_event_created_at": "2021-03-06T15:54:39", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 345132834, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3027, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Sources/SwiftLibXML/XMLPath.swift", "provenance": "stack-edu-0071.json.gz:52304", "repo_name": "mikolasstuchlik/SwiftLibXML", "revision_date": "2021-03-06T16:01:40", "revision_id": "e08a46045a71136c11e8f41259d65e05b61e7ae0", "snapshot_id": "460ae4d5e31716a841c12fd05073c282699cc617", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mikolasstuchlik/SwiftLibXML/e08a46045a71136c11e8f41259d65e05b61e7ae0/Sources/SwiftLibXML/XMLPath.swift", "visit_date": "2023-03-21T15:28:35.311355", "added": "2024-11-18T21:24:03.781614+00:00", "created": "2021-03-06T16:01:40", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz" }
import { ConfluenceRawApi } from '../src/raw'; import { ConfluenceConfig } from '../src/config'; describe('ConfluenceRawApi', () => { let config; let api; const params = { one: '2', three: 4 }; beforeEach(() => { config = new ConfluenceConfig('http://www.test.de', 'tom', 'secret'); config.setPretend(true); api = new ConfluenceRawApi(config); }); describe('create instance', () => { test('with missing configuration', () => { let caughtError; let unexpectedApi; try { unexpectedApi = new ConfluenceRawApi(undefined); } catch (error) { caughtError = error; } expect(caughtError).not.toBeUndefined(); expect(unexpectedApi).toBeUndefined(); }); test('with invalid configuration', () => { config.url = undefined; let caughtError; let unexpectedApi; try { unexpectedApi = new ConfluenceRawApi(config); } catch (error) { caughtError = error; } expect(caughtError).not.toBeUndefined(); expect(unexpectedApi).toBeUndefined(); }); test('with valid configuration', () => { expect(new ConfluenceRawApi(config)).not.toBeUndefined(); }); }); describe('get()', () => { test('without parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content `; api.get('content', undefined, (command) => { expect(command).toMatch('--request GET'); expect(command).toMatch(expectedUrl); expect(command).toContainHeaders(config.requestHeaders); }); }); test('with parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content?one=2&three=4 `; api.get('content', params, (command) => { expect(command).toMatch('--request GET'); expect(command).toMatch(expectedUrl); expect(command).toContainHeaders(config.requestHeaders); }); }); }); describe('post()', () => { const data = { hello: 'world', some: { any: 'thing', more: { number: 34 } }, items: [ 'one', 'two' ] }; test('without data', () => { let caughtError; try { api.post('content/123', undefined, undefined); } catch (error) { caughtError = error; } expect(caughtError).not.toBeUndefined(); }); test('without parameters', () => { const expectedUrl = `--data ${JSON.stringify(data)} `; api.post('content/123', undefined, data, (command) => { expect(command).toMatch('--request POST'); expect(command).toMatch(`--url ${config.apiUrl}/content/123 `); expect(command).toMatch(expectedUrl); expect(command).toMatch('--header Content-Type: application/json'); expect(command).toContainHeaders(config.requestHeaders); }); }); test('with parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123?one=2&three=4 `; api.post('content/123', params, data, (command) => { expect(command).toMatch('--request POST'); expect(command).toMatch(expectedUrl); expect(command).toMatch(`--data ${JSON.stringify(data)} `); expect(command).toMatch('--header Content-Type: application/json'); expect(command).toContainHeaders(config.requestHeaders); }); }); }); describe('postFile()', () => { const file = '/Users/home/user/file.txt'; test('without file', () => { let caughtError; try { api.postFile('content/123/attachments', undefined, undefined); } catch (error) { caughtError = error; } expect(caughtError).not.toBeUndefined(); }); test('without parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123/attachments `; api.postFile('content/123/attachments', undefined, file, (command) => { expect(command).toMatch('--request POST'); expect(command).toMatch(expectedUrl); expect(command).toMatch(`--form file=@${file} `); expect(command).toContainHeaders(config.requestHeaders); }); }); test('with parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123/attachments?one=2&three=4 `; api.postFile('content/123/attachments', params, file, (command) => { expect(command).toMatch('--request POST'); expect(command).toMatch(expectedUrl); expect(command).toMatch(`--form file=@${file} `); expect(command).toContainHeaders(config.requestHeaders); }); }); }); describe('put()', () => { const data = { hello: 'world', flagged: true }; test('without data', () => { let caughtError; try { api.put('content/123', undefined, undefined); } catch (error) { caughtError = error; } expect(caughtError).not.toBeUndefined(); }); test('without parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123 `; api.put('content/123', undefined, data, (command) => { expect(command).toMatch('--request PUT'); expect(command).toMatch(expectedUrl); expect(command).toMatch(`--data ${JSON.stringify(data)} `); expect(command).toMatch('--header Content-Type: application/json'); expect(command).toContainHeaders(config.requestHeaders); }); }); test('with parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123?one=2&three=4 `; api.put('content/123', params, data, (command) => { expect(command).toMatch('--request PUT'); expect(command).toMatch(expectedUrl); expect(command).toMatch(`--data ${JSON.stringify(data)} `); expect(command).toMatch('--header Content-Type: application/json'); expect(command).toContainHeaders(config.requestHeaders); }); }); }); describe('delete()', () => { test('without parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123 `; api.delete('content/123', undefined, (command) => { expect(command).toMatch('--request DELETE'); expect(command).toMatch(expectedUrl); expect(command).toContainHeaders(config.requestHeaders); }); }); test('with parameters', () => { const expectedUrl = `--url ${config.apiUrl}/content/123?one=2&three=4 `; api.delete('content/123', params, (command) => { expect(command).toMatch('--request DELETE'); expect(command).toMatch(expectedUrl); expect(command).toContainHeaders(config.requestHeaders); }); }); }); describe('evaluatingCallback()', () => { beforeEach(() => { config.setPretend(false); }); test('with pretend mode', () => { config.setPretend(true); const meta = { cmd: 'curl', args: [ '--request', 'GET', '--url', 'http://www.test.de/rest/api/content' ] }; api.evaluatingCallback(undefined, undefined, meta, (error, response) => { expect(error).toBe('curl --request GET --url http://www.test.de/rest/api/content'); expect(response).toBeUndefined(); }); }); test('with error', () => { const errorMessage = 'Some error message'; const responseData = '{some:data}'; api.evaluatingCallback(errorMessage, responseData, undefined, (error, response) => { expect(error).toBe(errorMessage); expect(response).toBeUndefined(); }); }); test('with invalid response', () => { const responseData = '<html><body>Error 403</body></html>'; api.evaluatingCallback(undefined, responseData, undefined, (error, response) => { expect(error).toBe(responseData); expect(response).toBeUndefined(); }); }); test('with response containing invalid statuscode', () => { const responseData = '{statusCode:502}'; api.evaluatingCallback(undefined, responseData, undefined, (error, response) => { expect(error).toBe(responseData); expect(response).toBeUndefined(); }); }); test('with valid response', () => { const responseData = { hello: 'world', one: 2, three: { text: 'something', items: [ 'one', 'two' ], flag: true } }; api.evaluatingCallback(undefined, JSON.stringify(responseData), undefined, (error, response) => { expect(error).toBeUndefined(); expect(response).toEqual(responseData); } ); }); }); });
f1354f10a2fbec387f28271a3f2cecdb95460f9a
{ "blob_id": "f1354f10a2fbec387f28271a3f2cecdb95460f9a", "branch_name": "refs/heads/master", "committer_date": "2018-06-12T11:53:21", "content_id": "f8b93ae1c3665129b18b3bf83a46aa7fee1b5814", "detected_licenses": [ "MIT" ], "directory_id": "483c4c4039005bae702be6fa626fe1f49a312205", "extension": "js", "filename": "raw-test.js", "fork_events_count": 0, "gha_created_at": "2018-02-16T08:05:39", "gha_event_created_at": "2018-06-12T11:43:59", "gha_language": null, "gha_license_id": "MIT", "github_id": 121727147, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10193, "license": "MIT", "license_type": "permissive", "path": "/test/raw-test.js", "provenance": "stack-edu-0036.json.gz:539538", "repo_name": "milltree/confluence-curlapi", "revision_date": "2018-06-12T11:53:21", "revision_id": "49a9fdec47f73bee78c19685c3a4fe9882ddb6c1", "snapshot_id": "5e3835bb89ab4ec808b3eea3fe478d1257092e70", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/milltree/confluence-curlapi/49a9fdec47f73bee78c19685c3a4fe9882ddb6c1/test/raw-test.js", "visit_date": "2021-04-29T12:20:42.242053", "added": "2024-11-18T23:38:15.476610+00:00", "created": "2018-06-12T11:53:21", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
#!/usr/bin/env python3 import argparse import psycopg2 import sys import time if __name__ == '__main__': arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--db_host', required=True) arg_parser.add_argument('--db_port', required=True) arg_parser.add_argument('--db_user', required=True) arg_parser.add_argument('--db_password', required=True) arg_parser.add_argument('--timeout', type=int, default=5) args = arg_parser.parse_args() start_time = time.time() while (time.time() - start_time) < args.timeout: try: conn = psycopg2.connect(user=args.db_user, host=args.db_host, port=args.db_port, password=args.db_password, dbname='postgres') error = '' break except psycopg2.OperationalError as e: error = e else: conn.close() time.sleep(1) if error: print("Database connection failure: %s" % error, file=sys.stderr) sys.exit(1)
2a017a33b45bb511148c1a623ab9dd3124b62ecb
{ "blob_id": "2a017a33b45bb511148c1a623ab9dd3124b62ecb", "branch_name": "refs/heads/master", "committer_date": "2023-08-17T05:41:21", "content_id": "7996397418175daed81e1e9dd211618eb103fd98", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a8b96689030fc41e4271311e8e44e7e78550750c", "extension": "py", "filename": "wait-for-psql.py", "fork_events_count": 367, "gha_created_at": "2017-02-06T23:48:15", "gha_event_created_at": "2023-09-14T14:26:59", "gha_language": "Shell", "gha_license_id": "Apache-2.0", "github_id": 81145663, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license": "Apache-2.0", "license_type": "permissive", "path": "/o/odoo/Dockerfiles/16.0_debian_bullseye/wait-for-psql.py", "provenance": "stack-edu-0055.json.gz:401942", "repo_name": "ppc64le/build-scripts", "revision_date": "2023-08-17T05:41:21", "revision_id": "e10ab4c8d10b591fd23151bfe7a4f5921f45b59c", "snapshot_id": "f7dd7f660fb447ecab7e3464fa7ba83c743ef785", "src_encoding": "UTF-8", "star_events_count": 79, "url": "https://raw.githubusercontent.com/ppc64le/build-scripts/e10ab4c8d10b591fd23151bfe7a4f5921f45b59c/o/odoo/Dockerfiles/16.0_debian_bullseye/wait-for-psql.py", "visit_date": "2023-08-21T12:54:56.145453", "added": "2024-11-19T02:31:52.348750+00:00", "created": "2023-08-17T05:41:21", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz" }
// @flow import { INIT_SEARCH, INIT_UPDATE_STATS, UPDATE_STATS, INIT_REORDER_STATS } from './actionTypes'; /** * Starts a search by criteria. * * @param {string} criteria - The search criteria. * @returns {Object} */ export function initSearch(criteria: string) { return { type: INIT_SEARCH, criteria }; } /** * Gets the new stats and triggers update. * * @param {Function} getSpeakerStats - Function to get the speaker stats. * @returns {Object} */ export function initUpdateStats(getSpeakerStats: Function) { return { type: INIT_UPDATE_STATS, getSpeakerStats }; } /** * Updates the stats with new stats. * * @param {Object} stats - The new stats. * @returns {Object} */ export function updateStats(stats: Object) { return { type: UPDATE_STATS, stats }; } /** * Initiates reordering of the stats. * * @returns {Object} */ export function initReorderStats() { return { type: INIT_REORDER_STATS }; }
d3cf474279efc4183e75b12b7c9e3d3d1a1f9b4a
{ "blob_id": "d3cf474279efc4183e75b12b7c9e3d3d1a1f9b4a", "branch_name": "refs/heads/master", "committer_date": "2021-09-15T16:29:46", "content_id": "381d5da627958c01495bd5e114f12fb6e776e313", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "aa1bb7b9e18a8a5bff9c9af4615d5d0e508584aa", "extension": "js", "filename": "actions.js", "fork_events_count": 0, "gha_created_at": "2021-09-15T17:39:29", "gha_event_created_at": "2021-09-15T17:39:30", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 406868864, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1027, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/react/features/speaker-stats/actions.js", "provenance": "stack-edu-0032.json.gz:549500", "repo_name": "pc-beast/jitsi-meet", "revision_date": "2021-09-15T15:59:06", "revision_id": "042a2cb447bd9ff39ab3904e493952787bd30924", "snapshot_id": "0962d2ae20a9e8e9548d723047575cd92cba9466", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/pc-beast/jitsi-meet/042a2cb447bd9ff39ab3904e493952787bd30924/react/features/speaker-stats/actions.js", "visit_date": "2023-08-15T10:09:13.502307", "added": "2024-11-18T23:59:43.614850+00:00", "created": "2021-09-15T15:59:06", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
#encoding=utf-8 ''' Step4: transform the triples and represent entity, type and predicate with id ''' eid = {} tid = {} pid = {} with open('entity id file here','r') as e: for line in e: dub = line[:-1].split('\t') eid[dub[0]] = dub[1] with open('type id file here','r') as t: for line in t: dub = line[:-1].split('\t') tid[dub[0]] = dub[1] with open('predicate id file here','r') as p: for line in p: dub = line[:-1].split('\t') pid[dub[0]] = dub[1] print("%d %d %d"%(len(eid),len(tid),len(pid))) rt = open("output triple file here",'w') with open('input triple file here','r') as f: i = 1; for line in f: tri = line[:-2].split('\t') if tri[1] == '<type>': if not tid.has_key(tri[2]): tid[tri[2]] = '-1' try: rt.write("%s\t%s\t%s\n"%(eid[tri[0]],pid[tri[1]],tid[tri[2]])) except KeyError: print(line) print(i) else: if tri[2][0]=='"': try: rt.write("%s\t%s\t-1\n"%(eid[tri[0]],pid[tri[1]])) except KeyError: print(line) print(i) else: try: rt.write("%s\t%s\t%s\n"%(eid[tri[0]],pid[tri[1]],eid[tri[2]])) except KeyError: print(line) print(i)
8a8bb5b18d639d7074e783639ccd9c3d8df556a7
{ "blob_id": "8a8bb5b18d639d7074e783639ccd9c3d8df556a7", "branch_name": "refs/heads/master", "committer_date": "2022-07-20T01:38:38", "content_id": "a4cc2d25d8e93096dc56e34ac83202a3f7156ce8", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "61b9b7a6017066cd45f4d8a446c5c79a11c31361", "extension": "py", "filename": "step4_triple_to_number.py", "fork_events_count": 104, "gha_created_at": "2018-12-13T14:25:35", "gha_event_created_at": "2018-12-25T09:51:53", "gha_language": "Java", "gha_license_id": "BSD-3-Clause", "github_id": 161650285, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1209, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/genrate_fragments/step4_triple_to_number.py", "provenance": "stack-edu-0062.json.gz:114366", "repo_name": "pkumod/gAnswer", "revision_date": "2022-07-20T01:38:38", "revision_id": "6d37bc2cdbbaf88823d948a019507c94132deca8", "snapshot_id": "33a44c437951fb7ca4343ee7eb59d35b64dbb5c3", "src_encoding": "UTF-8", "star_events_count": 372, "url": "https://raw.githubusercontent.com/pkumod/gAnswer/6d37bc2cdbbaf88823d948a019507c94132deca8/genrate_fragments/step4_triple_to_number.py", "visit_date": "2022-08-02T23:50:33.047136", "added": "2024-11-19T03:22:45.540017+00:00", "created": "2022-07-20T01:38:38", "int_score": 3, "score": 2.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
#ifndef lint static const char RCSid[] = "$Id: rholo2.c,v 3.30 2018/10/05 19:19:16 greg Exp $"; #endif /* * Rtrace support routines for holodeck rendering */ #include <time.h> #include "rholo.h" #include "paths.h" #include "random.h" VIEWPOINT myeye; /* target view position */ struct gclim { HOLO *hp; /* holodeck pointer */ GCOORD gc; /* grid cell */ FVECT egp; /* eye grid point */ double erg2; /* mean square eye grid range */ double gmin[2], gmax[2]; /* grid coordinate limits */ }; /* a grid coordinate range */ static void initeyelim(struct gclim *gcl, HOLO *hp, GCOORD *gc); static void groweyelim(struct gclim *gcl, GCOORD *gc, double r0, double r1, int tight); static int clipeyelim(short rrng[2][2], struct gclim *gcl); static void initeyelim( /* initialize grid coordinate limits */ struct gclim *gcl, HOLO *hp, GCOORD *gc ) { RREAL *v; int i; if (hp != NULL) { hdgrid(gcl->egp, gcl->hp = hp, myeye.vpt); gcl->erg2 = 0; for (i = 0, v = hp->wg[0]; i < 3; i++, v += 3) gcl->erg2 += DOT(v,v); gcl->erg2 *= (1./3.) * myeye.rng*myeye.rng; } if (gc != NULL) gcl->gc = *gc; gcl->gmin[0] = gcl->gmin[1] = FHUGE; gcl->gmax[0] = gcl->gmax[1] = -FHUGE; } static void groweyelim( /* grow grid limits about eye point */ struct gclim *gcl, GCOORD *gc, double r0, double r1, int tight ) { FVECT gp, ab; double ab2, od, cfact; double sqcoef[3], ctcoef[3], licoef[3], cnst; int gw, gi[2]; double wallpos, a, b, c, d, e, f; double root[2], yex; int n, i, j, nex; /* point/view cone */ i = gc->w>>1; gp[i] = gc->w&1 ? gcl->hp->grid[i] : 0; gp[hdwg0[gc->w]] = gc->i[0] + r0; gp[hdwg1[gc->w]] = gc->i[1] + r1; VSUB(ab, gcl->egp, gp); ab2 = DOT(ab, ab); gw = gcl->gc.w>>1; if ((i==gw ? ab[gw]*ab[gw] : ab2) <= gcl->erg2 + FTINY) { gcl->gmin[0] = gcl->gmin[1] = -FHUGE; gcl->gmax[0] = gcl->gmax[1] = FHUGE; return; /* too close (to wall) */ } ab2 = 1./ab2; /* 1/norm2(ab) */ od = DOT(gp, ab); /* origin dot direction */ cfact = 1./(1. - ab2*gcl->erg2); /* tan^2 + 1 of cone angle */ for (i = 0; i < 3; i++) { /* compute cone equation */ sqcoef[i] = ab[i]*ab[i]*cfact*ab2 - 1.; ctcoef[i] = 2.*ab[i]*ab[(i+1)%3]*cfact*ab2; licoef[i] = 2.*(gp[i] - ab[i]*cfact*od*ab2); } cnst = cfact*od*od*ab2 - DOT(gp,gp); /* * CONE: sqcoef[0]*x*x + sqcoef[1]*y*y + sqcoef[2]*z*z * + ctcoef[0]*x*y + ctcoef[1]*y*z + ctcoef[2]*z*x * + licoef[0]*x + licoef[1]*y + licoef[2]*z + cnst == 0 */ /* equation for conic section in plane */ gi[0] = hdwg0[gcl->gc.w]; gi[1] = hdwg1[gcl->gc.w]; wallpos = gcl->gc.w&1 ? gcl->hp->grid[gw] : 0; a = sqcoef[gi[0]]; /* x2 */ b = ctcoef[gi[0]]; /* xy */ c = sqcoef[gi[1]]; /* y2 */ d = ctcoef[gw]*wallpos + licoef[gi[0]]; /* x */ e = ctcoef[gi[1]]*wallpos + licoef[gi[1]]; /* y */ f = wallpos*(wallpos*sqcoef[gw] + licoef[gw]) + cnst; for (i = 0; i < 2; i++) { if (i) { /* swap x and y coefficients */ double t; t = a; a = c; c = t; t = d; d = e; e = t; } nex = 0; /* check global extrema */ n = quadratic(root, a*(4.*a*c-b*b), 2.*a*(2.*c*d-b*e), d*(c*d-b*e) + f*b*b); while (n-- > 0) { if (gc->w>>1 == gi[i] && (gc->w&1) ^ (root[n] < gp[gc->w>>1])) { if (gc->w&1) gcl->gmin[i] = -FHUGE; else gcl->gmax[i] = FHUGE; nex++; continue; /* hyperbolic */ } if (tight) { yex = (-2.*a*root[n] - d)/b; if (yex < gcl->gc.i[1-i] || yex > gcl->gc.i[1-i]+1) continue; /* outside cell */ } if (root[n] < gcl->gmin[i]) gcl->gmin[i] = root[n]; if (root[n] > gcl->gmax[i]) gcl->gmax[i] = root[n]; nex++; } /* check local extrema */ for (j = nex < 2 ? 2 : 0; j--; ) { yex = gcl->gc.i[1-i] + j; n = quadratic(root, a, b*yex+d, yex*(yex*c+e)+f); while (n-- > 0) { if (gc->w>>1 == gi[i] && (gc->w&1) ^ (root[n] < gp[gc->w>>1])) continue; if (root[n] < gcl->gmin[i]) gcl->gmin[i] = root[n]; if (root[n] > gcl->gmax[i]) gcl->gmax[i] = root[n]; } } } } static int clipeyelim( /* clip eye limits to grid cell */ short rrng[2][2], struct gclim *gcl ) { int incell = 1; int i; for (i = 0; i < 2; i++) { if (gcl->gmin[i] < gcl->gc.i[i]) gcl->gmin[i] = gcl->gc.i[i]; if (gcl->gmax[i] > gcl->gc.i[i]+1) gcl->gmax[i] = gcl->gc.i[i]+1; if (gcl->gmax[i] > gcl->gmin[i]) { rrng[i][0] = 256.*(gcl->gmin[i] - gcl->gc.i[i]) + (1.-FTINY); rrng[i][1] = 256.*(gcl->gmax[i] - gcl->gc.i[i]) + (1.-FTINY) - rrng[i][0]; } else rrng[i][0] = rrng[i][1] = 0; incell &= rrng[i][1] > 0; } return(incell); } void packrays( /* pack ray origins and directions */ float *rod, PACKET *p ) { #if 0 double dist2sum = 0.; FVECT vt; #endif int nretries = p->nr + 2; struct gclim eyelim; short rrng0[2][2], rrng1[2][2]; int useyelim; GCOORD gc[2]; FVECT ro, rd; double d; int i; if (!hdbcoord(gc, hdlist[p->hd], p->bi)) error(CONSISTENCY, "bad beam index in packrays"); if ((useyelim = myeye.rng > FTINY)) { initeyelim(&eyelim, hdlist[p->hd], gc); groweyelim(&eyelim, gc+1, 0., 0., 0); groweyelim(&eyelim, gc+1, 1., 1., 0); useyelim = clipeyelim(rrng0, &eyelim); #ifdef DEBUG if (!useyelim) error(WARNING, "no eye overlap in packrays"); #endif } for (i = 0; i < p->nr; i++) { retry: if (useyelim) { initeyelim(&eyelim, NULL, gc+1); p->ra[i].r[0][0] = (int)(frandom()*rrng0[0][1]) + rrng0[0][0]; p->ra[i].r[0][1] = (int)(frandom()*rrng0[1][1]) + rrng0[1][0]; groweyelim(&eyelim, gc, (1./256.)*(p->ra[i].r[0][0]+.5), (1./256.)*(p->ra[i].r[0][1]+.5), 1); if (!clipeyelim(rrng1, &eyelim)) { useyelim = nretries-- > 0; #ifdef DEBUG if (!useyelim) error(WARNING, "exceeded retry limit in packrays"); #endif goto retry; } p->ra[i].r[1][0] = (int)(frandom()*rrng1[0][1]) + rrng1[0][0]; p->ra[i].r[1][1] = (int)(frandom()*rrng1[1][1]) + rrng1[1][0]; } else { p->ra[i].r[0][0] = frandom() * 256.; p->ra[i].r[0][1] = frandom() * 256.; p->ra[i].r[1][0] = frandom() * 256.; p->ra[i].r[1][1] = frandom() * 256.; } d = hdray(ro, rd, hdlist[p->hd], gc, p->ra[i].r); #if 0 VSUM(vt, ro, rd, d); dist2sum += dist2line(myeye.vpt, ro, vt); #endif if (p->offset != NULL) { if (!vdef(OBSTRUCTIONS)) d *= frandom(); /* random offset */ VSUM(ro, ro, rd, d); /* advance ray */ p->offset[i] = d; } VCOPY(rod, ro); rod += 3; VCOPY(rod, rd); rod += 3; } #if 0 fprintf(stderr, "%f RMS (%d retries)\t", sqrt(dist2sum/p->nr), p->nr + 2 - nretries); #endif } void donerays( /* encode finished ray computations */ PACKET *p, float *rvl ) { double d; int i; for (i = 0; i < p->nr; i++) { setcolr(p->ra[i].v, rvl[0], rvl[1], rvl[2]); d = rvl[3]; if (p->offset != NULL) d += p->offset[i]; p->ra[i].d = hdcode(hdlist[p->hd], d); rvl += 4; } p->nc += p->nr; } int done_rtrace(void) /* clean up and close rtrace calculation */ { int status; /* already closed? */ if (!nprocs) return(0); /* flush beam queue */ done_packets(flush_queue()); /* sync holodeck */ hdsync(NULL, 1); /* close rtrace */ if ((status = end_rtrace())) error(WARNING, "bad exit status from rtrace"); if (vdef(REPORT)) { /* report time */ eputs("rtrace process closed\n"); report(0); } return(status); /* return status */ } void new_rtrace(void) /* restart rtrace calculation */ { char combuf[128]; if (nprocs > 0) /* already running? */ return; starttime = time(NULL); /* reset start time and counts */ npacksdone = nraysdone = 0L; if (vdef(TIME)) /* reset end time */ endtime = starttime + vflt(TIME)*3600. + .5; if (vdef(RIF)) { /* rerun rad to update octree */ sprintf(combuf, "rad -v 0 -s -w %s", vval(RIF)); if (system(combuf)) error(WARNING, "error running rad"); } if (start_rtrace() < 1) /* start rtrace */ error(WARNING, "cannot restart rtrace"); else if (vdef(REPORT)) { eputs("rtrace process restarted\n"); report(0); } } int getradfile(void) /* run rad and get needed variables */ { static short mvar[] = {OCTREE,EYESEP,-1}; static char tf1[] = TEMPLATE; char tf2[64]; char combuf[256]; char *pippt = NULL; int i; char *cp; /* check if rad file specified */ if (!vdef(RIF)) return(0); /* create rad command */ mktemp(tf1); sprintf(tf2, "%s.rif", tf1); sprintf(combuf, "rad -v 0 -s -e -w %s OPTFILE=%s | egrep '^[ \t]*(NOMATCH", vval(RIF), tf1); cp = combuf; while (*cp){ if (*cp == '|') pippt = cp; cp++; } /* match unset variables */ for (i = 0; mvar[i] >= 0; i++) if (!vdef(mvar[i])) { *cp++ = '|'; strcpy(cp, vnam(mvar[i])); while (*cp) cp++; pippt = NULL; } if (pippt != NULL) strcpy(pippt, "> " NULL_DEVICE); /* nothing to match */ else sprintf(cp, ")[ \t]*=' > %s", tf2); #ifdef DEBUG wputs(combuf); wputs("\n"); #endif system(combuf); /* ignore exit code */ if (pippt == NULL) { loadvars(tf2); /* load variables */ unlink(tf2); } /* get rtrace options */ rtargc += wordfile(rtargv+rtargc, MAXRTARGC-rtargc, tf1); unlink(tf1); /* clean up */ return(1); } void report( /* report progress so far */ time_t t ) { static time_t seconds2go = 1000000; if (t == 0L) t = time(NULL); sprintf(errmsg, "%ld packets (%ld rays) done after %.2f hours\n", npacksdone, nraysdone, (t-starttime)/3600.); eputs(errmsg); if (seconds2go == 1000000) seconds2go = vdef(REPORT) ? (long)(vflt(REPORT)*60. + .5) : 0L; if (seconds2go) reporttime = t + seconds2go; }
b5235e9d4cee584759917ff90df2edf23d6be0f7
{ "blob_id": "b5235e9d4cee584759917ff90df2edf23d6be0f7", "branch_name": "refs/heads/master", "committer_date": "2021-12-18T00:43:56", "content_id": "9cef2ed23e55e9192b981d21c2c55e8bdbedb6f7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "3f55217e912141e04815bc8bcb6fbd5638d0896e", "extension": "c", "filename": "rholo2.c", "fork_events_count": 68, "gha_created_at": "2013-02-15T00:47:56", "gha_event_created_at": "2019-06-06T19:57:11", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8210805, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9577, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/hd/rholo2.c", "provenance": "stack-edu-0001.json.gz:186657", "repo_name": "NREL/Radiance", "revision_date": "2021-12-18T00:43:56", "revision_id": "2fcca99ace2f2435f32a09525ad31f2b3be3c1bc", "snapshot_id": "bfbb93c99d86368ad0f27052a2a5504aeced47f8", "src_encoding": "UTF-8", "star_events_count": 164, "url": "https://raw.githubusercontent.com/NREL/Radiance/2fcca99ace2f2435f32a09525ad31f2b3be3c1bc/src/hd/rholo2.c", "visit_date": "2021-12-26T12:42:04.586614", "added": "2024-11-18T23:51:49.231207+00:00", "created": "2021-12-18T00:43:56", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
## Simple shelve with Linux file locking Originally published: 2008-12-21 05:50:07 Last updated: 2008-12-21 05:50:07 Author: Michael Ihde The shelve module is a easy way to add persistence to your application via a DBM database. However, if you have multiple reader/writer combination you need to lock the file to prevent corruption. The shelve module itself does not provide locking because it is platform specific. If you only need Linux, this simple module provide an easy way to support locking using dynamically added methods.
9669958b16dbab254c55cbe00d85625d1af92606
{ "blob_id": "9669958b16dbab254c55cbe00d85625d1af92606", "branch_name": "refs/heads/master", "committer_date": "2021-02-24T15:39:59", "content_id": "68c91f1900c96b701832a48bfb0124a2c69dc46d", "detected_licenses": [ "MIT" ], "directory_id": "50008b3b7fb7e14f793e92f5b27bf302112a3cb4", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2021-02-24T11:31:15", "gha_event_created_at": "2021-02-24T15:40:00", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 341878663, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 545, "license": "MIT", "license_type": "permissive", "path": "/recipes/Python/576591_Simple_shelve_Linux_file/README.md", "provenance": "stack-edu-markdown-0011.json.gz:62878", "repo_name": "betty29/code-1", "revision_date": "2021-02-24T15:39:59", "revision_id": "d097ca0ad6a6aee2180d32dce6a3322621f655fd", "snapshot_id": "db56807e19ac9cfe711b41d475a322c168cfdca6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/betty29/code-1/d097ca0ad6a6aee2180d32dce6a3322621f655fd/recipes/Python/576591_Simple_shelve_Linux_file/README.md", "visit_date": "2023-03-14T08:15:47.492844", "added": "2024-11-18T21:31:56.173123+00:00", "created": "2021-02-24T15:39:59", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0011.json.gz" }
// array write operations var mutatorMethods = [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ]; // patches an array so we can listen to write operations var patchArray = module.exports = function(arr) { if (arr._patched) return arr; var patchedArrayProto = [], observers = []; mutatorMethods.forEach(function(methodName) { Object.defineProperty(patchedArrayProto, methodName, { value: method }); function method() { var spliceEquivalent, summary, args, res; args = Array.prototype.slice.call(arguments, 0); // convert the operation into a splice spliceEquivalent = getSpliceEquivalent(this, methodName, args); summary = summariseSpliceOperation(this, spliceEquivalent); // run the intended method res = Array.prototype[methodName].apply(this, args); // call the obersvsers observers.forEach(function(fn) { fn.call(this, summary); }, this); // return the result of the method return res; }; }); if (({}).__proto__) arr.__proto__ = patchedArrayProto; else { mutatorMethods.forEach(function(methodName) { Object.defineProperty(arr, methodName, { value: patchedArrayProto[methodName], configurable: true }); }); } var extras = { _patched: true, observe: function(fn) { if (typeof fn !== "function") throw new Error("Expecting function to observe with."); observers.push(fn); return this; }, stopObserving: function(fn) { var index = observers.indexOf(fn); if (index > -1) observers.splice(index, 1); return this; } }; for (var k in extras) { Object.defineProperty(arr, k, { configurable: false, enumerable: false, value: extras[k], writeable: false }); } return arr; } // converts array write operations into splice equivalent arguments var getSpliceEquivalent = patchArray.getSpliceEquivalent = function ( array, methodName, args ) { switch ( methodName ) { case 'splice': return args; case 'sort': case 'reverse': return null; case 'pop': if ( array.length ) { return [ -1 ]; } return null; case 'push': return [ array.length, 0 ].concat( args ); case 'shift': return [ 0, 1 ]; case 'unshift': return [ 0, 0 ].concat( args ); } } // returns a summary pf how an array will be changed after the splice operation var summariseSpliceOperation = patchArray.summariseSpliceOperation = function ( array, args ) { var index, addedItems, removedItems; if (!args) return null; // figure out where the changes started... index = +( args[0] < 0 ? array.length + args[0] : args[0] ); // ...and how many items were added to or removed from the array addedItems = Math.max( 0, args.length - 2 ); removedItems = ( args[1] !== undefined ? args[1] : array.length - index ); // It's possible to do e.g. [ 1, 2, 3 ].splice( 2, 2 ) - i.e. the second argument // means removing more items from the end of the array than there are. In these // cases we need to curb JavaScript's enthusiasm or we'll get out of sync removedItems = Math.min( removedItems, array.length - index ); return { index: index, added: addedItems, removed: removedItems }; }
93b6910181394588a05a65ad2043ada704d0b96e
{ "blob_id": "93b6910181394588a05a65ad2043ada704d0b96e", "branch_name": "refs/heads/master", "committer_date": "2015-07-07T21:04:57", "content_id": "64ca77f73f51ca64c44369650cb37cc49dd6b243", "detected_licenses": [ "MIT" ], "directory_id": "6ba93bd4e39d90f51a746f09b79d16643b0abeec", "extension": "js", "filename": "index.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 38713978, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3156, "license": "MIT", "license_type": "permissive", "path": "/index.js", "provenance": "stack-edu-0043.json.gz:21526", "repo_name": "tyler-johnson/array-spy", "revision_date": "2015-07-07T21:04:57", "revision_id": "03370c5518d3b1c38fc9d37d98a888a4d44baa34", "snapshot_id": "73bb7807b2921c7c9d4c28b5d8d56c8fed31e3fa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tyler-johnson/array-spy/03370c5518d3b1c38fc9d37d98a888a4d44baa34/index.js", "visit_date": "2021-01-15T12:16:08.222576", "added": "2024-11-19T00:43:35.565611+00:00", "created": "2015-07-07T21:04:57", "int_score": 3, "score": 3.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
<?php namespace App\Repositories; use App\Contracts\Article as ArticleContract; use App\Models\Article; class ArticleRepository extends ModelRepository implements ArticleContract { /** * ArticleRepository constructor. * * @param Article $article */ public function __construct(Article $article) { $this->model = $article; } /** * Обрезать содержание новости. * * @param $articles * * @return Article */ public function cutBody($articles) { foreach ($articles as $article) { $article->body = str_limit($article->body, 300); } return $articles; } /** * Получить видимые новости. * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function getVisibleArticles() { $articles = $this->model->where('visibility', true) ->latest() ->paginate(5); return $this->cutBody($articles); } /** * Получить все новости для администратора. * * @param string $keywords * @param string $field [title, category_id, visibility, favorite] * @param string $direction [asc, desc] * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function getArticlesAdmin($keywords, $field, $direction) { return $this->model->with('category') ->where('title', 'LIKE', '%'.$keywords.'%') ->orderBy($field, $direction) ->paginate(10); } /** * Получить новость. * * @param $id * * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[] */ public function getArticle($id) { return $this->model->with(['category', 'user']) ->find($id); } /** * Получить все новости из категории. * * @param $id * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function getArticlesCategory($id) { $articles = $this->model->where('category_id', $id) ->where('visibility', true) ->latest() ->paginate(5); return $this->cutBody($articles); } /** * Получить последние избранные новости. * * @return Article */ public function getArticlesFavorite() { $articles = $this->model->where('favorite', true) ->where('visibility', true) ->latest() ->limit(5) ->get(); return $this->cutBody($articles); } }
dc22466ce39e0f68e5e77cbd322bcafd01aad1e4
{ "blob_id": "dc22466ce39e0f68e5e77cbd322bcafd01aad1e4", "branch_name": "refs/heads/master", "committer_date": "2017-12-18T11:55:50", "content_id": "7627e4b6762c4b4c7c50b619a468b3b99673e60c", "detected_licenses": [ "MIT" ], "directory_id": "c61460bcb8f88bc8219f127d455610b58799ae0d", "extension": "php", "filename": "ArticleRepository.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": 2799, "license": "MIT", "license_type": "permissive", "path": "/app/Repositories/ArticleRepository.php", "provenance": "stack-edu-0050.json.gz:839862", "repo_name": "deuterium7/laravel-news-app", "revision_date": "2017-12-18T11:55:50", "revision_id": "a484df43ddd97fdd847e9ea6f1f3571372c93525", "snapshot_id": "ce7f9331f76e269a7dd9f4cde4ceeedced9c6612", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/deuterium7/laravel-news-app/a484df43ddd97fdd847e9ea6f1f3571372c93525/app/Repositories/ArticleRepository.php", "visit_date": "2021-08-30T15:13:51.455405", "added": "2024-11-18T21:33:09.189481+00:00", "created": "2017-12-18T11:55:50", "int_score": 3, "score": 2.921875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
const express = require('express'); const uuidv4 = require('uuid/v4'); const { Router } = express; const router = Router(); let mentorList = []; router.get('/mentors', (req, res) => { return res.json(mentorList); }); router.get('/mentors/:id', (req, res) => { const id = req.params.id; const mentor = mentorList.find(mentor => mentor.id === id); if (mentor === undefined) { return res.sendStatus(404); } return res.json(mentor); }); router.post('/mentors', (req, res) => { const mentor = req.body; mentor.id = uuidv4(); mentorList.push(mentor); return res.json(mentor); }); router.put('/mentors/:id', (req, res) => { const mentorId = req.params.id; const newMentor = req.body; const mentor = mentorList.find(mentor => mentor.id === mentorId); mentor.name = newMentor.name; mentor.age = newMentor.age; const newMentorList = mentorList.filter(mentor => mentor.id != mentorId); mentorList = [...newMentorList, mentor]; return res.json(mentor); }); router.delete('/mentors/:id', (req, res) => { const id = req.params.id; const newMentorList = mentorList.filter(mentor => mentor.id != id); return res.sendStatus(204); }); module.exports = router;
f426a4e841b57ae77eaf38f7ca2be91d5fa98ef7
{ "blob_id": "f426a4e841b57ae77eaf38f7ca2be91d5fa98ef7", "branch_name": "refs/heads/master", "committer_date": "2019-10-28T05:11:51", "content_id": "1a181748e7e33006c0488d0022d592f9bea300de", "detected_licenses": [ "MIT" ], "directory_id": "d1902f29f72033acfec495a184138cec2e2b366b", "extension": "js", "filename": "router.js", "fork_events_count": 0, "gha_created_at": "2019-10-19T12:59:52", "gha_event_created_at": "2019-10-19T12:59:52", "gha_language": null, "gha_license_id": "MIT", "github_id": 216206889, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1198, "license": "MIT", "license_type": "permissive", "path": "/server/src/mentors/router.js", "provenance": "stack-edu-0039.json.gz:67914", "repo_name": "Leannelb/coding-ai", "revision_date": "2019-10-28T05:11:51", "revision_id": "f33a8ff506c6720fccf9e20e1e531c36b004c05a", "snapshot_id": "0d5eda78b631cbe376208bef91c5f2d88e8e024c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Leannelb/coding-ai/f33a8ff506c6720fccf9e20e1e531c36b004c05a/server/src/mentors/router.js", "visit_date": "2020-08-21T17:17:40.750946", "added": "2024-11-19T02:04:41.032610+00:00", "created": "2019-10-28T05:11:51", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
/** * Copyright 2021 IBM Corp. * * 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 Foundation class ResponseDataHandler { func parseDataFile(data: Data) { print("In parseDataFile") if let jsonDict = parseJSONData(data: data) { print("In parseDataFile : all fields passed") print("jsonDict is ", jsonDict) } } func parseJSONData(data: Data) -> [String: AnyObject]? { do { let json = try JSONSerialization.jsonObject( with: data, options: .allowFragments) as? [String: AnyObject] return json } catch { print(#function, error) } return nil } }
49beb5906b4b54791ed9dcb0ced42e12c2ebaec9
{ "blob_id": "49beb5906b4b54791ed9dcb0ced42e12c2ebaec9", "branch_name": "refs/heads/master", "committer_date": "2023-09-05T09:27:32", "content_id": "304622cb9fddc67bf50330582a6970702a9e1a07", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5633652def4d36d18578f12791878fdb028db74b", "extension": "swift", "filename": "ResponseDataHandler.swift", "fork_events_count": 147, "gha_created_at": "2019-03-08T11:50:53", "gha_event_created_at": "2023-09-14T07:45:52", "gha_language": "JavaScript", "gha_license_id": "Apache-2.0", "github_id": 174529031, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 1272, "license": "Apache-2.0", "license_type": "permissive", "path": "/Swift-REST/MQSwift/ResponseDataHandler.swift", "provenance": "stack-edu-0072.json.gz:55411", "repo_name": "ibm-messaging/mq-dev-patterns", "revision_date": "2023-09-05T09:27:32", "revision_id": "9b98a8fda42c75268a0d4365bb9d393abdfcf401", "snapshot_id": "584dee06adbf4500c39930f98941b1ffc4cff98d", "src_encoding": "UTF-8", "star_events_count": 149, "url": "https://raw.githubusercontent.com/ibm-messaging/mq-dev-patterns/9b98a8fda42c75268a0d4365bb9d393abdfcf401/Swift-REST/MQSwift/ResponseDataHandler.swift", "visit_date": "2023-09-05T16:50:59.436736", "added": "2024-11-18T23:10:33.712697+00:00", "created": "2023-09-05T09:27:32", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
//=============================================================================== // Microsoft patterns & practices Enterprise Library // Core //=============================================================================== // Copyright © Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== using System; using System.Collections.Generic; using System.Text; using System.Configuration; namespace SiteCore { /// <summary> /// Configuration section for the configuration sources. /// </summary> /// <remarks> /// This configuration must reside in the application's default configuration file. /// </remarks> public class ConfigurationSourceSection : SerializableConfigurationSection { private const string selectedSourceProperty = "selectedSource"; private const string sourcesProperty = "sources"; /// <summary> /// This field supports the Enterprise Library infrastructure and is not intended to be used directly from your code. /// </summary> public const string SectionName = "enterpriseLibrary.ConfigurationSource"; /// <summary> /// Returns the <see cref="ConfigurationSourceSection"/> from the application's default configuration file. /// </summary> /// <returns>The section from the configuration file, or <see langword="null"/> (<b>Nothing</b> in Visual Basic) if the section is not present in the configuration file.</returns> public static ConfigurationSourceSection GetConfigurationSourceSection() { return (ConfigurationSourceSection)ConfigurationManager.GetSection(SectionName); } /// <summary> /// Gets or sets the name for the default configuration source. /// </summary> [ConfigurationProperty(selectedSourceProperty, IsRequired=true)] public string SelectedSource { get { return (string)this[selectedSourceProperty]; } set { this[selectedSourceProperty] = value; } } /// <summary> /// Gets the collection of defined configuration sources. /// </summary> [ConfigurationProperty(sourcesProperty, IsRequired = true)] public NameTypeConfigurationElementCollection<ConfigurationSourceElement> Sources { get { return (NameTypeConfigurationElementCollection<ConfigurationSourceElement>)this[sourcesProperty]; } } } }
07ca4db7660f6c177b6186e91c68c5747ce3aea7
{ "blob_id": "07ca4db7660f6c177b6186e91c68c5747ce3aea7", "branch_name": "refs/heads/master", "committer_date": "2021-05-04T13:41:43", "content_id": "bb7b9c8dbcd9e0b38bf2e0d9e40a10132588b6a6", "detected_licenses": [ "MIT" ], "directory_id": "a61e03922f9b6f028b4b0667850d1387a1b6a92a", "extension": "cs", "filename": "ConfigurationSourceSection.cs", "fork_events_count": 0, "gha_created_at": "2017-10-17T19:02:37", "gha_event_created_at": "2018-09-11T19:31:23", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 107311950, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2795, "license": "MIT", "license_type": "permissive", "path": "/C0DEC0RE/Backup/ConfigurationSourceSection.cs", "provenance": "stack-edu-0012.json.gz:274123", "repo_name": "mmeents/DataMattei", "revision_date": "2021-05-04T13:41:43", "revision_id": "722aa64f6100f70003c6a42cd71e623393afa4eb", "snapshot_id": "2ae5f5af1def3be39395d87f4b1cdf3045f57f5b", "src_encoding": "WINDOWS-1252", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mmeents/DataMattei/722aa64f6100f70003c6a42cd71e623393afa4eb/C0DEC0RE/Backup/ConfigurationSourceSection.cs", "visit_date": "2021-06-06T13:24:37.788858", "added": "2024-11-18T23:24:32.732493+00:00", "created": "2021-05-04T13:41:43", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
# Copyright 2021 @apichick # # 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 apache_beam as beam from apache_beam.transforms.combiners import TopCombineFn from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.transforms.window import SlidingWindows import json def get_tweet_hashtags(tweet): for entity in tweet['entities']['hashtags']: yield '#%s' % entity['text'] def format_message(items): result = {} result['metric'] = 'top10hashtags' result['data'] = [ {'hashtag': item[0], 'ocurrences': item[1]} for item in items] yield json.dumps(result).encode('utf-8') def run(tweets_topic, trends_topic, beam_args): options = PipelineOptions(beam_args, save_main_session=True, streaming=True) with beam.Pipeline(options=options) as pipeline: ( pipeline | 'Read from Pub/Sub' >> beam.io.ReadFromPubSub(topic=tweets_topic) | 'Parse JSON' >> beam.Map(json.loads) | 'Add timestamp' >> beam.Map(lambda item: beam.window.TimestampedValue(item, int(item['timestamp_ms']) / 1000)) | 'Apply sliding window' >> beam.WindowInto(SlidingWindows(300, 60)) | 'Extract hashtags' >> beam.ParDo(get_tweet_hashtags) | 'Transform to key-value pairs' >> beam.Map(lambda hashtag: (hashtag, 1)) | 'Count per key' >> beam.combiners.Count.PerKey() | 'Get top 10 hashtags' >> beam.CombineGlobally(TopCombineFn(n=10, key=lambda item: item[1])).without_defaults() | 'Format' >> beam.ParDo(format_message) | 'Write to Pub/Sub' >> beam.io.WriteToPubSub(topic=trends_topic) )
542806e32968fa942dcc3548b082df9a976a94a6
{ "blob_id": "542806e32968fa942dcc3548b082df9a976a94a6", "branch_name": "refs/heads/main", "committer_date": "2021-08-05T17:32:58", "content_id": "6720a5bd7d46f1e866ce9308c4ec65177127b519", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e0d9f781c5d899d4c0fc7e1ed3175f293a15b023", "extension": "py", "filename": "tweettrends.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": 2161, "license": "Apache-2.0", "license_type": "permissive", "path": "/pipeline/tweettrends.py", "provenance": "stack-edu-0058.json.gz:642394", "repo_name": "direkshan-digital/beam-summit-2021-flex-template", "revision_date": "2021-08-05T12:18:19", "revision_id": "35e027593f14d830a8b279308acaafa7968e705d", "snapshot_id": "5a59c04b66d93fb2d0aa4a4d91c913234a186381", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/direkshan-digital/beam-summit-2021-flex-template/35e027593f14d830a8b279308acaafa7968e705d/pipeline/tweettrends.py", "visit_date": "2023-07-13T00:49:43.857457", "added": "2024-11-19T02:30:39.519696+00:00", "created": "2021-08-05T12:18:19", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
<?php namespace App\Http\Controllers\Backend; use App\Models\Report\Report; use App\Http\Controllers\Controller; /** * Class DashboardController. */ class DashboardController extends Controller { /** * @return \Illuminate\View\View */ public function index() { $reports = Report::latest()->paginate(5); return view('backend.dashboard')->withReports($reports); } }
07e0f4c5b70f3b2629bdcb9ce164508ad54b4bd0
{ "blob_id": "07e0f4c5b70f3b2629bdcb9ce164508ad54b4bd0", "branch_name": "refs/heads/master", "committer_date": "2017-09-13T08:37:09", "content_id": "3a365770e84ae515369b6cf15f4fc3f949f98087", "detected_licenses": [ "MIT" ], "directory_id": "ed4d65b90c8325094f80d3c2d77314607e95dabe", "extension": "php", "filename": "DashboardController.php", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 103113442, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 409, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/Backend/DashboardController.php", "provenance": "stack-edu-0046.json.gz:322325", "repo_name": "hariadi/validworks", "revision_date": "2017-09-13T08:37:09", "revision_id": "1d1836000799c9b65f462472a532383ea0fec90b", "snapshot_id": "e4d287b9f64f77c687f514376efe4108ffa618b0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hariadi/validworks/1d1836000799c9b65f462472a532383ea0fec90b/app/Http/Controllers/Backend/DashboardController.php", "visit_date": "2021-06-26T06:26:04.190758", "added": "2024-11-19T01:05:55.213911+00:00", "created": "2017-09-13T08:37:09", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz" }
#include <cstdio> #include <iostream> int main(){ std::string trip, first, second; getline(std::cin, trip); getline(std::cin, first); getline(std::cin, second); long posF1 = trip.find(first); long posF2 = trip.find(second); while(posF2 != std::string::npos){ long test = trip.find(second, posF2 + 1); if(test != std::string::npos){posF2 = test;} else{break;} }; bool forward = (posF1 != std::string::npos) && (posF2 != std::string::npos) && (posF1 + first.size() - 1 < posF2); std::string retTrip = trip; for(long p = 0; p < trip.size(); p++){retTrip[p] = trip[trip.size() - 1 - p];} long posB1 = retTrip.find(first); long posB2 = retTrip.find(second); while(posB2 != std::string::npos){ long test = retTrip.find(second, posB2 + 1); if(test != std::string::npos){posB2 = test;} else{break;} }; bool backward = (posB1 != std::string::npos) && (posB2 != std::string::npos) && (posB1 + first.size() - 1 < posB2); if(forward && backward){puts("both");} else if(forward && !backward){puts("forward");} else if(!forward && backward){puts("backward");} else {puts("fantasy");} return 0; }
cf6b3e96c6a61175694f1a5121e45e66ed6200fa
{ "blob_id": "cf6b3e96c6a61175694f1a5121e45e66ed6200fa", "branch_name": "refs/heads/master", "committer_date": "2022-10-18T15:38:46", "content_id": "07c6d09775420f704246181e214978b82d26dc65", "detected_licenses": [ "MIT" ], "directory_id": "58a0ba5ee99ec7a0bba36748ba96a557eb798023", "extension": "cpp", "filename": "8A-TrainAndPeter.cpp", "fork_events_count": 54, "gha_created_at": "2019-10-25T15:50:28", "gha_event_created_at": "2022-10-18T15:38:47", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 217567198, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1220, "license": "MIT", "license_type": "permissive", "path": "/CodeForces/Complete/1-99/8A-TrainAndPeter.cpp", "provenance": "stack-edu-0003.json.gz:433803", "repo_name": "adityanjr/code-DS-ALGO", "revision_date": "2022-10-18T15:38:46", "revision_id": "1c104c33d2f56fe671d586b702528a559925f875", "snapshot_id": "5bdd503fb5f70d459c8e9b8e58690f9da159dd53", "src_encoding": "UTF-8", "star_events_count": 40, "url": "https://raw.githubusercontent.com/adityanjr/code-DS-ALGO/1c104c33d2f56fe671d586b702528a559925f875/CodeForces/Complete/1-99/8A-TrainAndPeter.cpp", "visit_date": "2022-10-22T21:22:09.640237", "added": "2024-11-18T22:37:27.725570+00:00", "created": "2022-10-18T15:38:46", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Item extends Model { protected $fillable = ['cordinate_id','category_id','subcategory_id','brand_id','size_id']; /** * このアイテムに紐づく投稿。(Cordinateモデルとの関係を定義) */ public function cordinate() { return $this->belongsTo(Cordinate::class); } /** * このアイテムに紐づくカテゴリ。(Categoryモデルとの関係を定義) */ public function category() { return $this->belongsTo(Category::class); } /** * このアイテムに紐づくサブカテゴリ。(Subategoryモデルとの関係を定義) */ public function subcategory() { return $this->belongsTo(Subcategory::class); } /** * このアイテムに紐づくブランド。(Brandモデルとの関係を定義) */ public function brand() { return $this->belongsTo(Brand::class); } /** * このアイテムに紐づくサイズ。(Sizeモデルとの関係を定義) */ public function size() { return $this->belongsTo(Size::class); } }
b2a8ca85ccf778542aefc27844493a114d6d20b7
{ "blob_id": "b2a8ca85ccf778542aefc27844493a114d6d20b7", "branch_name": "refs/heads/main", "committer_date": "2021-08-08T09:08:26", "content_id": "dd25dea5e0326e9145f180b5edaba8748d5f3b45", "detected_licenses": [ "MIT" ], "directory_id": "01519e1668ae17e2fe6e540728caaa1f15899589", "extension": "php", "filename": "Item.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": 1231, "license": "MIT", "license_type": "permissive", "path": "/app/Item.php", "provenance": "stack-edu-0050.json.gz:48475", "repo_name": "rsasns/mycloset", "revision_date": "2021-08-08T09:08:26", "revision_id": "f5f2eeaba7b28f8040076aeff3d446028919522b", "snapshot_id": "3366b228c881d955f5435361232cb341bff3d1db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rsasns/mycloset/f5f2eeaba7b28f8040076aeff3d446028919522b/app/Item.php", "visit_date": "2023-06-30T12:46:32.528044", "added": "2024-11-19T02:45:03.077102+00:00", "created": "2021-08-08T09:08:26", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
--- title: A common artificial sweetener might be making you fatter and sicker, a new study says author: PipisCrew date: 2020-03-10 categories: [news] toc: true --- From whole grain English muffins to reduced-sugar ketchup, sucralose is found in thousands of baked goods, condiments, syrups and other consumer packaged goods — almost all of them containing carbs. https://www.washingtonpost.com/business/2020/03/10/common-artificial-sweetener-might-be-making-you-fatter-sicker-new-study-says/ origin - https://www.pipiscrew.com/2020/03/a-common-artificial-sweetener-might-be-making-you-fatter-and-sicker-a-new-study-says/ a-common-artificial-sweetener-might-be-making-you-fatter-and-sicker-a-new-study-says
710ce28c21f983c7c383a3664ed6f7d924920ae6
{ "blob_id": "710ce28c21f983c7c383a3664ed6f7d924920ae6", "branch_name": "refs/heads/master", "committer_date": "2020-12-14T20:46:01", "content_id": "5964e1280537cb08ce7a7ac12fc818f711dd7fd9", "detected_licenses": [ "MIT" ], "directory_id": "35f30bbc438b6889c547d72d408ba5bc6c1b5d1c", "extension": "md", "filename": "2020-03-10-a-common-a.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 320619088, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 711, "license": "MIT", "license_type": "permissive", "path": "/_posts/2020-03-10-a-common-a.md", "provenance": "stack-edu-markdown-0002.json.gz:328057", "repo_name": "pipiscrew/pipiscrew.github.io", "revision_date": "2020-12-14T20:46:01", "revision_id": "9d81bd323c800a1bff2b6d26c3ec3eb96fb41004", "snapshot_id": "cbd1628538158a5bed5dcbf6f1c43302fa308ae6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pipiscrew/pipiscrew.github.io/9d81bd323c800a1bff2b6d26c3ec3eb96fb41004/_posts/2020-03-10-a-common-a.md", "visit_date": "2023-01-31T07:57:31.885462", "added": "2024-11-18T22:59:12.365252+00:00", "created": "2020-12-14T20:46:01", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
/* * GridTools * * Copyright (c) 2014-2020, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef INCLUDED_GHEX_TL_SHARED_MESSAGE_BUFFER_HPP #define INCLUDED_GHEX_TL_SHARED_MESSAGE_BUFFER_HPP #include <memory> #include "./message_buffer.hpp" namespace gridtools { namespace ghex { namespace tl { /* A struct that keeps the message with the refcount. The shared message buffer keeps a pointer to a dynamically allocated refcounted_message. That pointer can be shared between many messages. */ template <typename Allocator> struct refcounted_message { using message_type = message_buffer<Allocator>; message_type m_message; int refcount; refcounted_message(size_t capacity, Allocator allc): m_message{std::move(message_type(capacity, allc))}, refcount{1} {} refcounted_message(size_t capacity, size_t size, Allocator allc): m_message{std::move(message_type(capacity, size, allc))}, refcount{1} {} refcounted_message(message_type&& m): m_message{std::move(m)}, refcount{1} {} }; /** The raw shared_message_buffer is a copyable version of message_buffer which internally holds a shared ptr to * a message_buffer instance and forwards all calls to this shared instance (the interface is identical * to message_buffer. * * Compared to the standard shared_message_buffer, here we do not use the shared_ptr, but instead we use * a raw C pointer to refcounted_message. */ template<typename Allocator = std::allocator<unsigned char>> class shared_message_buffer { public: // member types using message_type = message_buffer<Allocator>; using byte = typename message_type::byte; using value_type = typename message_type::value_type; using allocator_type = typename message_type::allocator_type; using pointer = typename message_type::pointer; using const_pointer = typename message_type::const_pointer; using raw_pointer = typename message_type::raw_pointer; using raw_const_pointer = typename message_type::raw_const_pointer; static constexpr bool can_be_shared = true; public: // members // std::shared_ptr<message_type> m_message; refcounted_message<Allocator> *m_sptr; public: // ctors template< typename Alloc = Allocator, typename std::enable_if< std::is_default_constructible<Alloc>::value && !std::is_convertible<Alloc,std::size_t>::value, int>::type = 0> shared_message_buffer(Alloc alloc = Alloc{}) : m_sptr{nullptr} {} template< typename Alloc = Allocator, typename std::enable_if< std::is_default_constructible<Alloc>::value, int>::type = 0> shared_message_buffer(size_t size_, Alloc alloc = Alloc{}){ m_sptr = new refcounted_message<Allocator>(size_,alloc); } template< typename Alloc, typename std::enable_if<!std::is_default_constructible<Alloc>::value, int>::type = 0> shared_message_buffer(size_t size_, Alloc alloc) { m_sptr = new refcounted_message<Allocator>(size_,alloc); } shared_message_buffer(message_type&& m){ m_sptr = new refcounted_message<Allocator>(m); } shared_message_buffer(const shared_message_buffer& other){ m_sptr = other.m_sptr; if(m_sptr) m_sptr->refcount++; } shared_message_buffer(shared_message_buffer&& other){ m_sptr = other.m_sptr; other.m_sptr = nullptr; } shared_message_buffer& operator=(const shared_message_buffer& other){ m_sptr = other.m_sptr; if(m_sptr) m_sptr->refcount++; return *this; } shared_message_buffer& operator=(shared_message_buffer&& other){ m_sptr = other.m_sptr; other.m_sptr = nullptr; return *this; } ~shared_message_buffer(){ if(m_sptr){ if(m_sptr->refcount==0) ERR("inconsistent refcount in shared message"); m_sptr->refcount--; if(m_sptr->refcount==0) { delete m_sptr; m_sptr = nullptr; } } } public: // member functions bool is_shared() const { return use_count() > 1; } auto use_count() const { if(nullptr == m_sptr) return 0; return m_sptr->refcount; } std::size_t size() const noexcept { if(nullptr == m_sptr) return 0; return m_sptr->m_message.size(); } std::size_t capacity() const noexcept { if(nullptr == m_sptr) return 0; return m_sptr->m_message.capacity(); } raw_const_pointer data() const noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.data(); } raw_pointer data() noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.data(); } // template <typename T> // T* data() { return m_message->template data<T>(); } // template <typename T> // const T* data() const { return m_message->template data<T>(); } raw_const_pointer begin() const noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.begin(); } raw_const_pointer end() const noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.end(); } raw_pointer begin() noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.begin(); } raw_pointer end() noexcept { if(nullptr == m_sptr) return nullptr; return m_sptr->m_message.end(); } void reserve(std::size_t n) { if(nullptr == m_sptr) ERR("message is empty"); m_sptr->m_message.reserve(n); } void resize(std::size_t n) { if(nullptr == m_sptr) ERR("message is empty"); m_sptr->m_message.resize(n); } void clear() { if(nullptr == m_sptr) ERR("message is empty"); m_sptr->m_message.clear(); } void swap(shared_message_buffer& other) { std::swap(m_sptr, other.m_sptr); } /* manually decrease the use count. Needed in the UCX communicator */ void release(){ if(nullptr == m_sptr) return; m_sptr->refcount--; if(m_sptr->refcount==0) delete m_sptr; m_sptr = nullptr; } }; template<typename A> void swap(shared_message_buffer<A>& a, shared_message_buffer<A>& b) { a.swap(b); } } // namespace tl } // namespace ghex } // namespace gridtools #endif /* INCLUDED_GHEX_TL_SHARED_MESSAGE_BUFFER_HPP */
4a29fdc5cd0d9dab9f764cc1442029870496c4d9
{ "blob_id": "4a29fdc5cd0d9dab9f764cc1442029870496c4d9", "branch_name": "refs/heads/master", "committer_date": "2020-09-21T13:02:55", "content_id": "bad8fa117c15f83dbd5586c0aa4fba2aca5db6ac", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "2a356e57f313afabd96c10bb6f0f140f0e35d3a4", "extension": "hpp", "filename": "raw_shared_message_buffer.hpp", "fork_events_count": 0, "gha_created_at": "2019-12-10T15:39:46", "gha_event_created_at": "2023-08-07T12:40:16", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 227156498, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7323, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/include/ghex/transport_layer/raw_shared_message_buffer.hpp", "provenance": "stack-edu-0002.json.gz:488248", "repo_name": "boeschf/GHEX", "revision_date": "2020-09-21T13:02:55", "revision_id": "7606d6be813288f2f1efe67c6c8aef8d66e37bd1", "snapshot_id": "56886bc086d14e8832d0d28be49fb650630cecaa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/boeschf/GHEX/7606d6be813288f2f1efe67c6c8aef8d66e37bd1/include/ghex/transport_layer/raw_shared_message_buffer.hpp", "visit_date": "2023-08-15T22:56:19.623959", "added": "2024-11-18T23:05:29.467975+00:00", "created": "2020-09-21T13:02:55", "int_score": 3, "score": 2.578125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
using Newtonsoft.Json.Linq; using Osrs.Data; using Osrs.Net.Http; using Osrs.WellKnown.Projects; using System; using System.Collections.Generic; namespace Pnnl.Oncor.Rest.Projects { internal static class Jsonifier { private const string Dsid = "dsid"; private const string Id = "id"; public static HashSet<CompoundIdentity> ParseIds(string jsonPayload) { try { JArray data = JToken.Parse(jsonPayload) as JArray; if (data!=null) { HashSet<CompoundIdentity> ids = new HashSet<CompoundIdentity>(); CompoundIdentity item; foreach(JToken cur in data) { item = ToId(cur as JObject); if (item != null) ids.Add(item); } return ids; } } catch { } return null; } public static CompoundIdentity ToId(JObject ob) { if (ob!=null) { if (ob[Dsid]!=null && ob[Id]!=null) { JToken d = ob[Dsid]; JToken i = ob[Id]; Guid ds; Guid id; if (Guid.TryParse(d.ToString(), out ds) && Guid.TryParse(i.ToString(), out id)) return new CompoundIdentity(ds, id); } } return null; } public static JToken ParseBody(HttpRequest request) { try { return JToken.Parse(RestUtils.ReadBody(request)); } catch { } return null; } public static JArray ToJson(IEnumerable<Project> projects) { if (projects != null) { JArray o = new JArray(); foreach (Project cur in projects) { if (cur != null) o.Add(ToJson(cur)); } return o; } return null; } public static JArray ToJson(IEnumerable<CompoundIdentity> cids) { if (cids != null) { JArray o = new JArray(); foreach (CompoundIdentity cur in cids) { if (cur != null) o.Add(ToJson(cur)); } return o; } return null; } public static JObject ToJson(Project project) { if (project != null) { JObject o = new JObject(); o.Add(JsonUtils.Id, JsonUtils.ToJson(project.Identity)); o.Add(JsonUtils.Name, project.Name); o.Add(JsonUtils.OwnerId, JsonUtils.ToJson(project.PrincipalOrganization)); o.Add(JsonUtils.ParentId, JsonUtils.ToJson(project.ParentId)); o.Add(JsonUtils.Description, project.Description); o.Add(JsonUtils.Affiliates, JsonUtils.ToJson(project.Affiliates)); return o; } return null; } public static JObject ToJson(CompoundIdentity cid) { if (cid != null) { JObject o = new JObject(); o.Add(JsonUtils.Id, JsonUtils.ToJson(cid)); return o; } return null; } } }
4e1d5b90c48a78a8cc7d728a4efda0ebbd236305
{ "blob_id": "4e1d5b90c48a78a8cc7d728a4efda0ebbd236305", "branch_name": "refs/heads/master", "committer_date": "2018-04-01T12:02:28", "content_id": "da98e4ca06450dc4ccd7671b4db95f31bcb3d7fa", "detected_licenses": [ "Apache-2.0" ], "directory_id": "37259e05f4db7ae3b2e08873fe47f34397bd72eb", "extension": "cs", "filename": "Jsonifier.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 124910225, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3632, "license": "Apache-2.0", "license_type": "permissive", "path": "/OncorDev/Pnnl.Oncor.Rest.Projects/Jsonifier.cs", "provenance": "stack-edu-0011.json.gz:768424", "repo_name": "OSRS/Oncor_Base", "revision_date": "2018-04-01T12:02:28", "revision_id": "13df608e8a4c6ea53fc5937824e9755c89f31aa8", "snapshot_id": "22d59fab8bc059012e572736ab5ff199e21cc3ea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/OSRS/Oncor_Base/13df608e8a4c6ea53fc5937824e9755c89f31aa8/OncorDev/Pnnl.Oncor.Rest.Projects/Jsonifier.cs", "visit_date": "2021-09-10T20:10:24.825322", "added": "2024-11-18T23:01:58.803370+00:00", "created": "2018-04-01T12:02:28", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
import {Component,OnInit,Inject,Input} from '@angular/core'; @Component({ selector: 'join-company', templateUrl: '../../template/message/join-company.component.html' }) export class JoinCompanyComponent implements OnInit { public notificationIn : any; public companyInfo: any; public senderInfo: any; public userInfo: any; public notificationTime: string; public objInfo: any = {}; public notificationInfo:any; public notificationStatus:number; constructor( @Inject('app.config') public appConfig:any, @Inject('date.service') private dateService: any, @Inject('dialog.service') public dialogService: any, @Inject('user-data.service') public userDataService : any, @Inject('company-data.service') public companyDataService : any ) { } //启动 ngOnInit() { this.companyInfo = this.companyDataService.getLocationCompanyIn(); this.userInfo = this.userDataService.getUserIn(); } //父级传入的提示消息 @Input() set setNotification(notification:any) { if(notification) { this.notificationInfo = notification; this.notificationIn = notification.data; this.objInfo = notification.obj; this.senderInfo = notification.obj.senderInfo; this.notificationTime = this.dateService.formatWithTimezone(notification.obj.ts, 'HH:MM'); } } /** * 接受/拒绝dialog */ applyCompanyDialog() { if(!this.notificationIn.handled || this.notificationIn.handled === 0) { this.notificationIn.user_profile_path = this.senderInfo.user_profile_path; this.notificationIn.work_name = this.senderInfo.work_name; this.notificationIn.p_name = this.senderInfo.p_name; let settings = { mode: '1', title: 'LINK TO PARENT', isSimpleContent: false, componentSelector: 'link-to-parent-dialog', componentData: this.notificationIn, buttons: [ { type: 'refuse', btnEvent: 'linkToParentDialogRefuse', mouseEnterEvent: 'linkToParentButDialog', mouseLeaveEvent: 'linkToParentButDialog' }, { type: 'accept', btnEvent: 'linkToParentDialogAccept', mouseEnterEvent: 'linkToParentButDialog', mouseLeaveEvent: 'linkToParentButDialog' } ] }; this.dialogService.openNew(settings); } } }
2aacd6d07f52728e171ad5452a1abeb66073cf39
{ "blob_id": "2aacd6d07f52728e171ad5452a1abeb66073cf39", "branch_name": "refs/heads/master", "committer_date": "2018-08-14T13:42:18", "content_id": "ad0e0dca25bfc34f29546526a59d959830475458", "detected_licenses": [ "MIT" ], "directory_id": "2e1a5640deb992b2a02a3525202bd22464ce7c76", "extension": "ts", "filename": "join-company.component.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 144725500, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2398, "license": "MIT", "license_type": "permissive", "path": "/src/app/notification/components/message/join-company.component.ts", "provenance": "stack-edu-0075.json.gz:836694", "repo_name": "JoyZhou007/Block-bi", "revision_date": "2018-08-14T13:42:18", "revision_id": "2e915cd85695910352446d4707c3808254f56266", "snapshot_id": "048995a367c68fca55d909cff1db8b3a1d249b69", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JoyZhou007/Block-bi/2e915cd85695910352446d4707c3808254f56266/src/app/notification/components/message/join-company.component.ts", "visit_date": "2020-03-26T08:54:44.750006", "added": "2024-11-18T20:59:29.490244+00:00", "created": "2018-08-14T13:42:18", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
package types // import ( // "helputils" // "sysapi" // "strings" // ) // type ProdactConfigurations []ProdactParameters // func (conf ProdactConfigurations) ToString() string { // v := conf // var str []string // for _, params := range v { // d := params // str = append(str, d.ToString()) // } // return "[" + strings.Join(str, " ") + "]" // } // func (fullConf ProdactConfigurations) GetConfiguration(sys *sysapi.System) (ProdactParameters, error) { // isBareMetal := sys.IsBareMetal() // for _, conf := range fullConf { // if conf.SysType == "BM" && isBareMetal { // return conf, nil // } // if conf.SysType == "HCI" && !isBareMetal { // return conf, nil // } // } // panic("Didn't find matching product configuration") // } // type ProdactParameters struct { // SysType string `yaml:"SysType"` // Boundaries ProdactBoundaries `yaml:"Boundaries"` // Timeouts ProdactTimeouts `yaml:"Timeouts"` // } // func (s ProdactParameters) ToString() string { // return "{" + strings.Join(helputils.StructToStrings(s), " ") + "}" // } // type ProdactTimeouts struct { // HaOperations int `yaml:"HaOperations"` //in Minutes // VheadRevive int `yaml:"VheadRevive"` //in Minutes // } // type ProdactBoundaries struct { // MaxFoldersPerCluster int `yaml:"MaxFoldersPerCluster"` // MaxFilesPerFolder int `yaml:"MaxFilesPerFolder"` // } // // type TestsConfigurations map[string]TestParameters // // type TestParameters struct { // // SysType string `yaml:"SysType"` // // Performance Performance `yaml:"Performance"` // // } // // type PerformanceTools struct { // // ErunNumberOfFiles int `yaml:"ErunNumberOfFiles"` // // ErunNumberOfClients int `yaml:"ErunNumberOfClients"` // // } // // type Performance struct { // // InWorkingSet PerformanceTools `yaml:"InWorkingSet"` // // AbovePstore PerformanceTools `yaml:"AbovePstore"` // // AboveDstore PerformanceTools `yaml:"AboveDstore"` // // AboveMD PerformanceTools `yaml:"AboveMD"` // // }
4b3370caf741a2217c5bb1d8a78bc63dc519f9ac
{ "blob_id": "4b3370caf741a2217c5bb1d8a78bc63dc519f9ac", "branch_name": "refs/heads/master", "committer_date": "2022-08-27T15:29:08", "content_id": "134b9ab011971acff8e9bfa98872711c025ca819", "detected_licenses": [ "Apache-2.0" ], "directory_id": "319e2a77db76ae28b1f10e1d808b092eb46243b1", "extension": "go", "filename": "productConfiguration.go", "fork_events_count": 3, "gha_created_at": "2018-11-08T14:52:58", "gha_event_created_at": "2022-03-06T08:22:34", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 156722519, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2032, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/vendor/types/productConfiguration.go", "provenance": "stack-edu-0016.json.gz:464975", "repo_name": "Elastifile/elastifile-provisioner-csi", "revision_date": "2022-08-27T15:29:08", "revision_id": "ac270d827af6c0d3dade7d50d772e8a94cba8cab", "snapshot_id": "056839e3cec154163aeb850da0c93d79a185f5ea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Elastifile/elastifile-provisioner-csi/ac270d827af6c0d3dade7d50d772e8a94cba8cab/src/vendor/types/productConfiguration.go", "visit_date": "2022-11-06T23:58:08.578570", "added": "2024-11-19T03:06:18.585029+00:00", "created": "2022-08-27T15:29:08", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
import csv import matplotlib.pyplot as plt import numpy as np success_rates = [] for file in ["nocomm/no_shared_reward/log0A.csv", "nocomm/no_shared_reward/log1A.csv", "nocomm/shared_reward/log0A.csv", "nocomm/shared_reward/log0B.csv", "comm/2^16/shared_reward/log0E.csv", "comm/2^16/shared_reward/log0.csv", "swobs/2^16/shared_reward/log0F.csv", "swobs/2^16/shared_reward/log0G.csv", "swobs/2^16/switched_reward/log0A.csv", "swobs/2^16/switched_reward/log0B.csv", "swobs/2^16/no_shared_reward/log0.csv", "swobs/2^16/no_shared_reward/log1.csv", "comm/2^16/no_shared_reward/log0.csv", "comm/2^16/no_shared_reward/log1.csv", "swobs/16^4/shared_reward/log0A.csv", "swobs/16^4/shared_reward/log0B.csv", "swobs/16^4/no_shared_reward/log0A.csv", "swobs/16^4/no_shared_reward/log0B.csv", "swobs/1^0/shared_reward/log0A.csv", "swobs/1^0/shared_reward/log0B.csv", "swobs/1^0/no_shared_reward/log0A.csv", "swobs/1^0/no_shared_reward/log0B.csv", "swobs/16^8/tau=0.1/shared_reward/log0A.csv", "swobs/16^8/tau=0.1/shared_reward/log0B.csv", "swobs/16^4/tau=0.1/shared_reward/log0A.csv", "swobs/16^4/tau=0.1/shared_reward/log0B.csv", "swobs/16^4/shared_reward/corr/log0A.csv", "swobs/16^4/shared_reward/corr/log0B.csv"]: with open("logs/plots/" + file, newline='') as csvfile: csvreader = csv.reader(csvfile) success_rate = [] i = 0 for row in csvreader: if i != 0: success_rate.append(float(row[9])) i += 1 success_rates.append(success_rate) #plt.plot(success_rates[0], color='b', label="no communication, no shared reward (2)") #plt.plot(success_rates[1], color='b') #plt.plot(success_rates[2], color='k', label="no communication, shared reward (2)") #plt.plot(success_rates[3], color='k') #plt.plot(success_rates[4], color='g', label="communication, shared reward (2)") #plt.plot(success_rates[5], color='g') #plt.plot(success_rates[10], color='y', label="communication, switched observations, no shared reward (2)") #plt.plot(success_rates[11], color='y') #plt.plot(success_rates[6], color='r', label="communication, switched observations, shared reward (2)") #plt.plot(success_rates[7], color='r') #plt.plot(success_rates[8], color='y', label="switched observations, switched reward (2)") #plt.plot(success_rates[9], color='y') sr = np.asarray(success_rates, dtype=np.float32) #plt.plot((sr[0] +sr[1]) /2, color='y', label=r"no comms, no shared $r$") #plt.plot(1 - (1 - (sr[0] +sr[1])/2)**2, color='b', label=r"no comms, shared $r$ (expected)", alpha=0.25) #plt.plot((sr[2] +sr[3]) /2, color='b', label=r"no comms, shared $r$") #plt.title(r"$|M| = 2^{16}$") #plt.plot((sr[12] +sr[13]) /2, color='m', label=r"comms, no shared $r$") #plt.plot(1 - (1 - (sr[12] +sr[13])/2)**2, color='g', label=r"comms, no shared $r$ (expected)", alpha=0.25) #plt.plot((sr[4] +sr[5]) /2, color='g', label=r"comms, shared $r$") #plt.title(r"$|M| = 2^{16}$") #plt.plot((sr[10]+sr[11])/2, color='c', label=r"comms, switched obs, no shared $r$") #plt.plot(1 - (1 - (sr[10]+sr[11])/2)**2, color='r', label=r"comms, switched obs, shared $r$ (expected)", alpha=0.25) #plt.plot((sr[6] +sr[7]) /2, color='r', label=r"comms, switched obs, shared $r$") #plt.title(r"$|M| = 16^{4}$") #plt.plot((sr[16]+sr[17])/2, color='c', label=r"comms, switched obs, no shared $r$") #plt.plot(1 - (1 - (sr[16]+sr[17])/2)**2, color='r', label=r"comms, switched obs, shared $r$ (expected)", alpha=0.25) #plt.plot((sr[14] +sr[15]) /2, color='r', label=r"comms, switched obs, shared $r$") #plt.plot((sr[20]+sr[21])/2, color='c', label=r"no comms, switched obs, no shared $r$") #plt.plot(1 - (1 - (sr[20]+sr[21])/2)**2, color='r', label=r"no comms, switched obs, shared $r$ (expected)", alpha=0.25) #plt.plot((sr[18] +sr[19]) /2, color='r', label=r"no comms, switched obs, shared $r$") #plt.title(r"$|M| = 16^{8}$, $\tau = 0.1$") #plt.plot((sr[22] +sr[23]) /2, color='r', label=r"comms, switched obs, shared $r$") #plt.title(r"$|M| = 16^{4}$, $\tau = 0.1$") #plt.plot((sr[24] +sr[25]) /2, color='r', label=r"comms, switched obs, shared $r$") plt.title(r"$|M| = 16^{4}$ (corrected)") plt.plot((sr[26] +sr[27]) /2, color='r', label=r"comms, switched obs, shared $r$") plt.ylim(-0.1, 1.1) plt.legend() plt.xlabel("epochs") plt.ylabel(r"success ($r > 0$) rate") plt.show()
1f935dd64fd06bd59c86f0f9b4e5b5d21599c3b8
{ "blob_id": "1f935dd64fd06bd59c86f0f9b4e5b5d21599c3b8", "branch_name": "refs/heads/master", "committer_date": "2019-03-20T02:08:05", "content_id": "bae92c91c26c7e00f6fd88776a3a0ad60175300c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "73d9b76c63c203f9053f676a153353f5f8b4180f", "extension": "py", "filename": "plot.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174381427, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4656, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/scripts/plot.py", "provenance": "stack-edu-0059.json.gz:62314", "repo_name": "taungerine/babyai", "revision_date": "2019-03-20T02:08:05", "revision_id": "2658eaa919721cb9b051477068aef5d7ad9d86ff", "snapshot_id": "cd53c5eb933022a805e9d91b2e0da604fc064971", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/taungerine/babyai/2658eaa919721cb9b051477068aef5d7ad9d86ff/scripts/plot.py", "visit_date": "2020-04-27T13:44:05.663205", "added": "2024-11-18T20:52:25.215647+00:00", "created": "2019-03-20T02:08:05", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
""" This module will contain some util functions that can be used by users """ import hmac import hashlib def is_valid_webhook_request(webhook_token: str, request_body: str, webhook_signature_header: str) -> bool: """This method verifies that requests to your Webhook URL are genuine and from Buycoins. Args: webhook_token: your webhook token request_body: the body of the request webhook_signature_header: the X-Webhook-Signature header from BuyCoins Returns: a Boolean stating whether the request is valid or not """ hmac_request_body = hmac.new(webhook_token.encode(), request_body.encode(), hashlib.sha1) return hmac.compare_digest(hmac_request_body.hexdigest(), webhook_signature_header)
92afe84377a072ddf18d7dbea0eabe916d48321c
{ "blob_id": "92afe84377a072ddf18d7dbea0eabe916d48321c", "branch_name": "refs/heads/main", "committer_date": "2021-02-12T00:40:54", "content_id": "90d84d9b69efa87e21801002114cdf1038366e24", "detected_licenses": [ "MIT" ], "directory_id": "451d25015fc355957e9bcdf582da1523278ecdeb", "extension": "py", "filename": "utils.py", "fork_events_count": 1, "gha_created_at": "2021-01-26T17:53:26", "gha_event_created_at": "2021-02-12T00:40:55", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 333168936, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license": "MIT", "license_type": "permissive", "path": "/buycoins_sdk/commons/utils.py", "provenance": "stack-edu-0060.json.gz:28947", "repo_name": "GoZaddy/buycoins_sdk", "revision_date": "2021-02-12T00:40:54", "revision_id": "404ab183dc9d575d04abc60fa84fb5b1001a97a9", "snapshot_id": "1dd9eebf2560bf829dd47a950a328e1161707d12", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/GoZaddy/buycoins_sdk/404ab183dc9d575d04abc60fa84fb5b1001a97a9/buycoins_sdk/commons/utils.py", "visit_date": "2023-03-01T13:34:21.586309", "added": "2024-11-18T20:57:01.635646+00:00", "created": "2021-02-12T00:40:54", "int_score": 3, "score": 3.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz" }
using Domain.Extensions; using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Domain.UnitTests.Extensions { public class EnumerableExtensionsTests { #region Auxiliary classes public class Type { public int Number { get; set; } } public class TypeA : Type { } public class TypeB : Type { } #endregion public class Intersect { [Fact] public void IntersectOfAllDifferentElements_Should_ReturnEmpty() { // Arrange List<TypeA> list_odd = new() { new() { Number = 1, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 7, }, }; List<TypeB> list_even = new() { new() { Number = 0, }, new() { Number = 2, }, new() { Number = 4, }, new() { Number = 6, }, }; // Act var result_odd_even = list_odd.Intersect(list_even, odd => odd.Number, even => even.Number); var result_even_odd = list_even.Intersect(list_odd, even => even.Number, old => old.Number); // Assert result_odd_even.Should().BeEmpty(); result_even_odd.Should().BeEmpty(); } [Fact] public void IntersectOfElementsInCommon_Should_ReturnCommonElements() { // Arrange List<TypeA> list_a = new() { new() { Number = 1, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 7, }, }; List<TypeB> list_b = new() { new() { Number = 0, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 10, }, }; var expected_intersection_a_b = new List<TypeA>() { list_a[1], list_a[2], }; var expected_intersection_b_a = new List<TypeB>() { list_b[1], list_b[2], }; // Act var result_a_b = list_a.Intersect(list_b, a => a.Number, b => b.Number) .ToList(); var result_b_a = list_b.Intersect(list_a, b => b.Number, a => a.Number) .ToList(); // Assert result_a_b.Should().Equal(expected_intersection_a_b); result_b_a.Should().Equal(expected_intersection_b_a); } [Fact] public void IntersectNullSource_Should_ReturnNull() { // Arrange List<TypeA>? list_a = null; List<TypeB>? list_b = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; // Act var result = list_a?.Intersect(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeNull(); } [Fact] public void IntersectNullTarget_Should_ReturnEmpty() { // Arrange List<TypeA>? list_a = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; ; List<TypeB>? list_b = null; // Act var result = list_a?.Intersect(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeEmpty(); } [Fact] public void IntersectEmptySource_Should_ReturnNull() { // Arrange List<TypeA>? list_a = new(); List<TypeB>? list_b = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; // Act var result = list_a.Intersect(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeEmpty(); } [Fact] public void IntersectEmptyTarget_Should_ReturnEmpty() { // Arrange List<TypeA>? list_a = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; List<TypeB>? list_b = null; // Act var result = list_a?.Intersect(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeEmpty(); } } public class Except { [Fact] public void ExceptOfAllDifferentElements_Should_ReturnSourceEnumeration() { // Arrange List<TypeA> list_odd = new() { new() { Number = 1, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 7, }, }; List<TypeB> list_even = new() { new() { Number = 0, }, new() { Number = 2, }, new() { Number = 4, }, new() { Number = 6, }, }; // Act var result_odd_even = list_odd.Except(list_even, odd => odd.Number, even => even.Number); var result_even_odd = list_even.Except(list_odd, even => even.Number, old => old.Number); // Assert result_odd_even.Should().Equal(list_odd); result_even_odd.Should().Equal(list_even); } [Fact] public void Except_Should_ReturnNotInCommonElements() { // Arrange List<TypeA> list_a = new() { new() { Number = 1, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 7, }, }; List<TypeB> list_b = new() { new() { Number = 0, }, new() { Number = 3, }, new() { Number = 5, }, new() { Number = 10, }, }; var expected_intersection_a_b = new List<TypeA>() { list_a[0], list_a[3], }; var expected_intersection_b_a = new List<TypeB>() { list_b[0], list_b[3], }; // Act var result_a_b = list_a.Except(list_b, a => a.Number, b => b.Number) .ToList(); var result_b_a = list_b.Except(list_a, b => b.Number, a => a.Number) .ToList(); // Assert result_a_b.Should().Equal(expected_intersection_a_b); result_b_a.Should().Equal(expected_intersection_b_a); } [Fact] public void ExceptNullSource_Should_ReturnNull() { // Arrange List<TypeA>? list_a = null; List<TypeB>? list_b = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; // Act var result = list_a?.Except(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeNull(); } [Fact] public void ExceptNullTarget_Should_ReturnSourceEnumeration() { // Arrange List<TypeA>? list_a = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; List<TypeB>? list_b = null; // Act var result = list_a?.Except(list_b, a => a.Number, b => b.Number); // Assert result.Should().Equal(list_a); } [Fact] public void ExceptEmptySource_Should_ReturnEmpty() { // Arrange List<TypeA>? list_a = new(); List<TypeB>? list_b = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; // Act var result = list_a.Except(list_b, a => a.Number, b => b.Number); // Assert result.Should().BeEmpty(); } [Fact] public void ExceptEmptyTarget_Should_ReturnSourceEnumeration() { // Arrange List<TypeA>? list_a = new() { new() { Number = 1 }, new() { Number = 2 }, new() { Number = 3 } }; List<TypeB>? list_b = new(); // Act var result = list_a.Except(list_b, a => a.Number, b => b.Number); // Assert result.Should().Equal(list_a); } } } }
370ee279f1b15ae289c632ca30700629ee30f179
{ "blob_id": "370ee279f1b15ae289c632ca30700629ee30f179", "branch_name": "refs/heads/main", "committer_date": "2021-05-10T20:27:24", "content_id": "9241089997ba9f5ff32ac3d15bc9394b083d2ccb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8fd054f0a08c87e8b810d8a5100974d9eb47045", "extension": "cs", "filename": "EnumerableExtensionsTests.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 363781658, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10093, "license": "Apache-2.0", "license_type": "permissive", "path": "/Tests/Domain.UnitTests/Extensions/EnumerableExtensionsTests.cs", "provenance": "stack-edu-0012.json.gz:303838", "repo_name": "ianleocadio/ProgramaAceleracaoWebAPI", "revision_date": "2021-05-10T20:27:24", "revision_id": "2f69ea3e8c067121b8c36189310031ea15fb7401", "snapshot_id": "0410e9ed6e56eb5373b0a5451733a3e2efe5d336", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ianleocadio/ProgramaAceleracaoWebAPI/2f69ea3e8c067121b8c36189310031ea15fb7401/Tests/Domain.UnitTests/Extensions/EnumerableExtensionsTests.cs", "visit_date": "2023-04-24T12:10:53.549809", "added": "2024-11-19T01:50:01.940015+00:00", "created": "2021-05-10T20:27:24", "int_score": 3, "score": 3.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
from nintendo.nex import backend, authentication, friends, common from nintendo.games import Friends from nintendo import account import logging logging.basicConfig(level=logging.INFO) #Device id can be retrieved with a call to MCP_GetDeviceId on the Wii U #Serial number can be found on the back of the Wii U DEVICE_ID = 12345678 SERIAL_NUMBER = "..." SYSTEM_VERSION = 0x220 REGION = 4 #EUR COUNTRY = "NL" USERNAME = "..." #Nintendo network id PASSWORD = "..." #Nintendo network password api = account.AccountAPI() api.set_device(DEVICE_ID, SERIAL_NUMBER, SYSTEM_VERSION, REGION, COUNTRY) api.set_title(Friends.TITLE_ID_EUR, Friends.LATEST_VERSION) api.login(USERNAME, PASSWORD) pid = api.get_pid(USERNAME) mii = api.get_mii(pid) nex_token = api.get_nex_token(Friends.GAME_SERVER_ID) backend = backend.BackEndClient("friends.cfg") backend.configure(Friends.ACCESS_KEY, Friends.NEX_VERSION) backend.connect(nex_token.host, nex_token.port) login_data = authentication.NintendoLoginData() login_data.token = nex_token.token backend.login( nex_token.username, nex_token.password, None, login_data ) nna_info = friends.NNAInfo() nna_info.principal_info.pid = pid nna_info.principal_info.nnid = USERNAME nna_info.principal_info.mii.name = mii.name nna_info.principal_info.mii.data = mii.data.build() #NintendoPresenceV2 tells the server about your online status, which #game you're currently playing, etc. This will be shown to your friends #in their friend list (unless you disabled this feature). presence = friends.NintendoPresenceV2() client = friends.FriendsClient(backend.secure_client) response = client.get_all_information( nna_info, presence, #Enter your birthday here common.DateTime.make(15, 11, 1999, 0, 0, 0) ) def print_requests(requests): for request in requests: principal_info = request.principal_info message = request.message print("\tWho: %s (%s)" %(principal_info.nnid, principal_info.mii.name)) print("\tMessage:", message.message) if message.game_key.title_id: print("\tGame: %016X (v%i)" %(message.game_key.title_id, message.game_key.title_version)) print("\tSent:", request.sent) print("\tExpires:", message.expires) print("\t" + "-" * 40) print() if response.comment.text: print("Your status message: %s (last changed on %s)" %(response.comment.text, response.comment.changed)) else: print("You don't have a status message") if response.friends: print("Friends:") for friend in response.friends: principal_info = friend.nna_info.principal_info print("\tNNID:", principal_info.nnid) print("\tName:", principal_info.mii.name) presence = friend.presence print("\tOnline:", ["No", "Yes"][presence.is_online]) if presence.game_key.title_id: print("\tPlaying: %016X (v%i)" %(presence.game_key.title_id, presence.game_key.title_version)) if friend.comment.text: print("\tStatus: %s (last changed on %s)" %(friend.comment.text, friend.comment.changed)) print("\tFriend since:", friend.befriended) print("\tLast online:", friend.last_online) print("\t" + "-" * 40) print() else: print("You don't have any friends") if response.sent_requests: print("Friend requests sent:") print_requests(response.sent_requests) else: print("You haven't sent any friend requests") if response.received_requests: print("Friend requests received:") print_requests(response.received_requests) else: print("You haven't received any friend requests") if response.blacklist: print("Blacklist:") for item in response.blacklist: principal_info = item.principal_info print("\tWho: %s (%s)" %(principal_info.nnid, principal_info.mii.name)) if item.game_key.title_id: print("\tGame: %016X (%i)" %(item.game_key.title_id, item.game_key.title_version)) print("\tSince:", item.since) print("\t" + "-" * 40) else: print("You haven't blacklisted any users") backend.close()
e07d0855d6a1c072b0141e254b314b6297dbbe13
{ "blob_id": "e07d0855d6a1c072b0141e254b314b6297dbbe13", "branch_name": "refs/heads/master", "committer_date": "2019-08-29T17:23:46", "content_id": "c0a031438348c028dcd4cd16c5a6f155967e5897", "detected_licenses": [ "MIT" ], "directory_id": "b2b9be47ce8c2cd0985eb39fa4489e149c78a085", "extension": "py", "filename": "example_friend_list.py", "fork_events_count": 3, "gha_created_at": "2019-10-28T20:56:13", "gha_event_created_at": "2019-10-28T20:56:14", "gha_language": null, "gha_license_id": null, "github_id": 218143700, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3869, "license": "MIT", "license_type": "permissive", "path": "/example_friend_list.py", "provenance": "stack-edu-0060.json.gz:131153", "repo_name": "SmmServer/NintendoClients", "revision_date": "2019-08-29T17:23:46", "revision_id": "e1d2fec34e460cd87330a8cc886e54479d701469", "snapshot_id": "9e15801f73d35877b5e3a47830c2a5f2778547ad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SmmServer/NintendoClients/e1d2fec34e460cd87330a8cc886e54479d701469/example_friend_list.py", "visit_date": "2022-09-10T13:06:35.800799", "added": "2024-11-18T21:14:11.129961+00:00", "created": "2019-08-29T17:23:46", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz" }
<?php /** * @package SimpleReservation */ namespace Inc\Pages\Admin; use Inc\Base\BaseController; class AdminEnqueue extends BaseController { function register() { add_action( 'admin_enqueue_scripts', [$this, 'enqueue_admin'] ); } function enqueue_admin() { wp_enqueue_style( 'simple_reservation_style', $this->plugin_url . 'assets/admin/dist/style.min.css' ); wp_enqueue_script( 'simple_reservation_script', $this->plugin_url . 'assets/admin/dist/main.min.js', null, null, true ); } }
806c062575ec45ac82a5c62a00849fea88c76a2c
{ "blob_id": "806c062575ec45ac82a5c62a00849fea88c76a2c", "branch_name": "refs/heads/master", "committer_date": "2018-11-03T13:57:39", "content_id": "41dc9b4e0229e5dce848a5dd6bef750b5ea1972c", "detected_licenses": [ "MIT" ], "directory_id": "00c158ab9c23b0715801a578eff8c332ed935196", "extension": "php", "filename": "AdminEnqueue.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": 532, "license": "MIT", "license_type": "permissive", "path": "/inc/Pages/Admin/AdminEnqueue.php", "provenance": "stack-edu-0046.json.gz:710980", "repo_name": "LucasHild/simple-reservation", "revision_date": "2018-11-03T13:57:39", "revision_id": "480ef9c75793bfe4161e9e67815627ace9b8f6d7", "snapshot_id": "5c66ab4fd8c16c376fe981c2e9446b25491c417c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LucasHild/simple-reservation/480ef9c75793bfe4161e9e67815627ace9b8f6d7/inc/Pages/Admin/AdminEnqueue.php", "visit_date": "2022-05-06T20:28:44.954731", "added": "2024-11-19T02:55:21.447473+00:00", "created": "2018-11-03T13:57:39", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz" }
package com.adriel.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.adriel.utils.Constants; import com.adriel.utils.Redirections; @Controller public class LogoutController { @RequestMapping(value=Constants.LOGOUT, method=RequestMethod.GET) public void logOut(HttpServletRequest req, HttpServletResponse resp) { HttpSession personCurSess = req.getSession(false); if (personCurSess != null) { personCurSess.invalidate(); } Redirections.redirect(req, resp, Constants.INDEX, Constants.INDEX_ERR, Constants.LOGGED_OUT); } }
9f48243072074c2a5fbdc715cfca0a730e31953c
{ "blob_id": "9f48243072074c2a5fbdc715cfca0a730e31953c", "branch_name": "refs/heads/main", "committer_date": "2021-06-02T04:00:43", "content_id": "91ca00199f1e030d88b7a0dc4425d9ca69210865", "detected_licenses": [ "MIT" ], "directory_id": "7adc996743e318a4a6a4f3b0b0fa035c198bec15", "extension": "java", "filename": "LogoutController.java", "fork_events_count": 1, "gha_created_at": "2021-04-25T16:19:51", "gha_event_created_at": "2021-06-02T04:00:44", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 361477947, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 826, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/com/adriel/controller/LogoutController.java", "provenance": "stack-edu-0025.json.gz:313298", "repo_name": "adrielyeung/santa-tracker", "revision_date": "2021-06-02T04:00:43", "revision_id": "38843f088046b5a71963ca1caa2dc94ec890fabd", "snapshot_id": "c54bb829e94a5104b5b06eff80e5df253f25043d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/adrielyeung/santa-tracker/38843f088046b5a71963ca1caa2dc94ec890fabd/src/main/java/com/adriel/controller/LogoutController.java", "visit_date": "2021-06-18T00:37:55.941150", "added": "2024-11-19T00:42:18.304134+00:00", "created": "2021-06-02T04:00:43", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
#!/bin/bash usage="kubectl $(basename "$0") [-h] NAMESPACE NAME kubectl plugin, requires TILLER_NS set before call. Will run helm delete --purge on release associated with pod. Release is acquired from the pod's 'describe' information in the 'tags' section. Examples: kubectl purge my-namespace my-namespace-pod1-123: Purge the release associated with 'my-namespace-pod1-123' pod" while getopts ':h' option; do case "$option" in h) echo "$usage" exit ;; esac done shift $((OPTIND -1)) namespace=$1 name=$2 if [ -z "$TILLER_NS" ]; then echo "Set TILLER_NS environment variable before calling this function" exit 1; elif [ -z "$namespace" ]; then echo "No Namespace provided" exit 1; elif [ -z "$name" ]; then echo "No Name provided" exit 1; fi kubectl describe pods -n $namespace $name | grep release | cut -f 2 -d'=' | xargs -J rel helm --tiller-namespace $TILLER_NS delete --purge rel
9adeb8da6962950d133c040fbf11d62e93c9d7c7
{ "blob_id": "9adeb8da6962950d133c040fbf11d62e93c9d7c7", "branch_name": "refs/heads/master", "committer_date": "2023-08-12T15:08:39", "content_id": "e3574dc187ec330fb50b1ae3f62e99b2d504e2e0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b1af22647be901b6de55454356db09011b839c19", "extension": "", "filename": "kubectl-purge", "fork_events_count": 1596, "gha_created_at": "2019-01-25T18:46:02", "gha_event_created_at": "2023-09-10T03:05:54", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 167596393, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 924, "license": "Apache-2.0", "license_type": "permissive", "path": "/plugins/kubectl/kubectl-purge", "provenance": "stack-edu-0068.json.gz:550128", "repo_name": "derailed/k9s", "revision_date": "2023-08-12T15:08:39", "revision_id": "b5961a5febb6ec3d25936ab8cc50d6f37d8ac642", "snapshot_id": "33d4a5b06422d9c154efdee855f7f7949f523627", "src_encoding": "UTF-8", "star_events_count": 22127, "url": "https://raw.githubusercontent.com/derailed/k9s/b5961a5febb6ec3d25936ab8cc50d6f37d8ac642/plugins/kubectl/kubectl-purge", "visit_date": "2023-08-31T13:41:45.004026", "added": "2024-11-19T00:58:01.392077+00:00", "created": "2023-08-12T15:08:39", "int_score": 4, "score": 4, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz" }
namespace FakeItEasy.Tests; using FakeItEasy.Tests.TestHelpers.FSharp; using FluentAssertions; using Xunit; public class MethodInfoExtensionsTests { [Fact] public void GetDescription_AnonymousParameters_OmitsParameterNames() { // F# (at least) allows users to declare methods with anonymous parameters, which requires // special handling to render in a pleasing way. // Attempts to trigger the method-rendering from specs have failed so far, as it requires // generating a method with anonymous types that can't be intercepted, on a type that can // be. But just in case we're not clever enough to find a way, and some client does, check // the rendering with a unit test. // Arrange var expected = "FakeItEasy.Tests.TestHelpers.FSharp.IHaveAMethodWithAnAnonymousParameter.Save(System.Int32)"; // Act var actual = typeof(IHaveAMethodWithAnAnonymousParameter).GetMethod("Save")!.GetDescription(); // Assert actual.Should().Be(expected); } }
9ef1ce7661bf2a95f5c058dbfc258d332e258a40
{ "blob_id": "9ef1ce7661bf2a95f5c058dbfc258d332e258a40", "branch_name": "refs/heads/master", "committer_date": "2023-08-14T16:57:13", "content_id": "9b9484d1794975bd1b03dd719c48f5ae8fae5238", "detected_licenses": [ "MIT" ], "directory_id": "b983a18ab3a4f7ebcb481ab479da2cfcda178548", "extension": "cs", "filename": "MethodInfoExtensionsTests.cs", "fork_events_count": 202, "gha_created_at": "2011-06-19T17:56:01", "gha_event_created_at": "2023-08-14T16:57:15", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 1920133, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1085, "license": "MIT", "license_type": "permissive", "path": "/tests/FakeItEasy.Tests/MethodInfoExtensionsTests.cs", "provenance": "stack-edu-0014.json.gz:728657", "repo_name": "FakeItEasy/FakeItEasy", "revision_date": "2023-08-14T16:57:13", "revision_id": "a5e84c10fd87061359be4496ac95c14f655e15d5", "snapshot_id": "460ae9d25bcc1dc5338e6783eae45d1bdd615753", "src_encoding": "UTF-8", "star_events_count": 1295, "url": "https://raw.githubusercontent.com/FakeItEasy/FakeItEasy/a5e84c10fd87061359be4496ac95c14f655e15d5/tests/FakeItEasy.Tests/MethodInfoExtensionsTests.cs", "visit_date": "2023-08-25T06:26:31.446145", "added": "2024-11-18T21:26:57.448488+00:00", "created": "2023-08-14T16:57:13", "int_score": 3, "score": 2.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
const fs = require('fs'); const path = require('path'); const rr = fs.createReadStream(path.join(__dirname, './exp6.js')); const zlib = require('zlib'); const z = zlib.createGzip(); const w = fs.createWriteStream(path.join(__dirname,'file.txt.gz')); rr.on('readable', ()=>{ console.log(`read data: ${rr.read()}`); }); rr.on('end', ()=>{ console.log('finish') }); rr.pipe(z).pipe(w, {end: false});
b85ce1ad23010672266d35b006df8b936a636bec
{ "blob_id": "b85ce1ad23010672266d35b006df8b936a636bec", "branch_name": "refs/heads/master", "committer_date": "2020-12-11T04:28:41", "content_id": "5a93d1790f9b6721e5da3c9885b9323682926ee3", "detected_licenses": [ "MIT" ], "directory_id": "f6748aed8be76d99dd041d450da1c6ee740d31d4", "extension": "js", "filename": "exp7.js", "fork_events_count": 4, "gha_created_at": "2016-10-07T13:01:06", "gha_event_created_at": "2019-12-26T02:07:49", "gha_language": null, "gha_license_id": "MIT", "github_id": 70246900, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 403, "license": "MIT", "license_type": "permissive", "path": "/examples/demo-stream/custom/exp7.js", "provenance": "stack-edu-0039.json.gz:148211", "repo_name": "Talbot3/FlyLab", "revision_date": "2020-12-11T04:28:41", "revision_id": "c3d6b1f66298147568668c3d6d49ee5d72e53ed6", "snapshot_id": "d52ec3cc32ca38c6ea51944f9649d7266bf2042c", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/Talbot3/FlyLab/c3d6b1f66298147568668c3d6d49ee5d72e53ed6/examples/demo-stream/custom/exp7.js", "visit_date": "2023-05-10T11:52:29.803492", "added": "2024-11-18T23:51:35.825559+00:00", "created": "2020-12-11T04:28:41", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
package eu.ginere.jdbc.mysql.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import eu.ginere.base.util.dao.DaoManagerException; import eu.ginere.base.util.dao.KeyDTO; /** * @author ventura * * Este dao sirve para obtener datos de una jerareuia de objetos almacenada en tablas. * Si tenemos una tabla madre con tablas hijas, en funcion del tipo del objeto de la tabla madre * realiza las queries pertinentes en las tablas hijas, al final las implementacion de los objetos * devuletos es polimorfica, esto es en una lista de objetos los objetos devuletos pueden * tener distintas implementacions. * * Ejemplo, hace queries en las tablas denuncias, denunciasFijos, denunciasMoviles y los * objetos devueltos pueden ser fijos, moviles, tramo, etc ... * * * @param <I> * @param <T> */ public abstract class ParentQueryDAO<P extends KeyDTO> extends AbstractDAO { static final Logger log = Logger.getLogger(ParentQueryDAO.class); protected final String typeColumnName; protected final String keyColumnName; protected final String GET_BY_ID_QUERY; protected final String GET_ALL_QUERY; protected final String GET_ALL_BY_CONDITIONS_QUERY; protected final String GET_ALL_BY_CONDITIONS_QUERY_ROW_NUM; protected final String GET_ALL_IDS; protected final String GET_IDS_BY_CONDITIONS; protected final String GET_IDS_BY_CONDITIONS_ROW_NUM; protected final String COUNT_QUERY; protected final String COUNT_BY_CONDITIONS_QUERY; protected final String DELETE_PARENT_QUERY; private final Map<String,ChildDAOInterface<? extends P> > cache=new Hashtable<String, ChildDAOInterface<? extends P>>(); private final Map<String,String > childDeleteQuery=new Hashtable<String, String>(); public static interface ChildDAOInterface<P> { public String getTableName(); public String getKeyColumnName(); public P get(Connection connection,String id) throws DaoManagerException; // public String insert(P element) throws DaoManagerException ; // public void update(P element) throws DaoManagerException ; } public void addChildQueryExtendsDAO(String type,ChildDAOInterface<? extends P> childDao){ cache.put(type, childDao); childDeleteQuery.put(type,"DELETE from " + childDao.getTableName() + " where "+childDao.getKeyColumnName() +"=?"); } protected ParentQueryDAO(String tableName, String keyColumnName, String typeColumnName, String createQueryArray[][]){ super(tableName,createQueryArray); this.keyColumnName=keyColumnName; this.typeColumnName=typeColumnName; StringBuilder builder=new StringBuilder(); builder.append(" SELECT "); builder.append(typeColumnName); builder.append(" FROM "); builder.append(tableName); builder.append(" WHERE "); builder.append(keyColumnName); builder.append("=? LIMIT 1"); this.GET_BY_ID_QUERY=builder.toString();; builder.setLength(0); builder.append(" SELECT "); builder.append(keyColumnName); builder.append(","); builder.append(typeColumnName); builder.append(" FROM "); builder.append(tableName); this.GET_ALL_QUERY=builder.toString(); // builder.append(" WHERE "); this.GET_ALL_BY_CONDITIONS_QUERY=builder.toString(); builder.setLength(0); builder.append(" SELECT "); builder.append(keyColumnName); builder.append(","); builder.append(typeColumnName); builder.append(" FROM ( SELECT "); builder.append(keyColumnName); builder.append(","); builder.append(typeColumnName); builder.append(" FROM "); builder.append(tableName); // builder.append(" WHERE "); this.GET_ALL_BY_CONDITIONS_QUERY_ROW_NUM=builder.toString(); builder.setLength(0); builder.append(" SELECT "); builder.append(keyColumnName); builder.append(" FROM "); builder.append(tableName); this.GET_ALL_IDS=builder.toString(); builder.setLength(0); builder.append(" SELECT "); builder.append(keyColumnName); builder.append(" from ( SELECT "); builder.append(keyColumnName); builder.append(" FROM "); builder.append(tableName); this.GET_IDS_BY_CONDITIONS_ROW_NUM=builder.toString(); builder.setLength(0); builder.append(" SELECT "); builder.append(keyColumnName); builder.append(" FROM "); builder.append(tableName); this.GET_IDS_BY_CONDITIONS=builder.toString(); builder.setLength(0); builder.append(" SELECT count(*) FROM "); builder.append(tableName); this.COUNT_QUERY=builder.toString(); // builder.append(" WHERE "); this.COUNT_BY_CONDITIONS_QUERY=builder.toString(); this.DELETE_PARENT_QUERY="DELETE from " + tableName + " where "+keyColumnName+"=?"; } public List<String> getAllIds () throws DaoManagerException{ Connection connection=getConnection(); String query=GET_ALL_IDS; try{ PreparedStatement pstm = getPrepareStatement(connection,query); return getStringList(pstm, query); }catch (DaoManagerException e) { String error="Query" + query; log.error(error, e); throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public List<String> getIdsByContitions (String conditions, Integer rowNum) throws DaoManagerException{ Connection connection=getConnection(); String query; if (rowNum!=null){ query=GET_IDS_BY_CONDITIONS_ROW_NUM+conditions+" ) LIMIT ? " ; } else { query=GET_IDS_BY_CONDITIONS+conditions; } try{ PreparedStatement pstm = getPrepareStatement(connection,query); if (rowNum!=null){ setInt(pstm,1,rowNum,query); } return getStringList(pstm, query); }catch (DaoManagerException e) { String error="Query" + query; log.error(error, e); throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public P get(String id) throws DaoManagerException { Connection connection = getConnection(); try { return get(connection,id); } finally { closeConnection(connection); } } public P get(String id,P defaultValue) throws DaoManagerException { Connection connection = getConnection(); try { return get(connection,id,defaultValue); } finally { closeConnection(connection); } } public P get(Connection connection,String id) throws DaoManagerException { String query=GET_BY_ID_QUERY; try { PreparedStatement pstm = getPrepareStatement(connection, query); try { setString(pstm, 1, id, query); ResultSet rset = executeQuery(pstm, query); try { if (rset.next()) { String type=rset.getString(typeColumnName); return getById(connection,id,type); } else { throw new DaoManagerException("id:'"+id+"'"); } }finally{ rset.close(); } }finally{ close(pstm); } } catch (SQLException e) { String error = "id:'" + id + "'"; throw new DaoManagerException(error, e); } } public P get(Connection connection,String id,P defaultValue) throws DaoManagerException { String query=GET_BY_ID_QUERY; try { PreparedStatement pstm = getPrepareStatement(connection, query); try { setString(pstm, 1, id, query); ResultSet rset = executeQuery(pstm, query); try { if (rset.next()) { String type=rset.getString(typeColumnName); return getById(connection,id,type); } else { return defaultValue; } }finally{ rset.close(); } }finally{ close(pstm); } } catch (SQLException e) { String error = "id:'" + id + "'"; throw new DaoManagerException(error, e); } } public boolean exists(String id) throws DaoManagerException { Connection connection = getConnection(); String query=GET_BY_ID_QUERY; try { PreparedStatement pstm = getPrepareStatement(connection, query); setString(pstm, 1, id, query); ResultSet rset = executeQuery(pstm, query); if (rset.next()) { return true; } else { return false; } } catch (SQLException e) { String error = "id:'" + id + "'"; throw new DaoManagerException(error, e); } finally { closeConnection(connection); } } public List<P> getAll () throws DaoManagerException{ Connection connection=getConnection(); String query=GET_ALL_QUERY; try{ PreparedStatement pstm = getPrepareStatement(connection,query); ResultSet rset = executeQuery(pstm,query); List<P> list= new ArrayList<P>(rset.getFetchSize()); while (rset.next()){ String id=rset.getString(keyColumnName); String type=rset.getString(typeColumnName); P p=getById(connection,id,type); list.add(p); } return list; }catch (SQLException e){ String error="Query" + query; throw new DaoManagerException(error,e); }catch (DaoManagerException e) { String error="Query" + query; throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public List<P> getList (GetListQueryInterface listQuery) throws DaoManagerException{ Connection connection=getConnection(); String query=listQuery.getQuery(); try{ PreparedStatement pstm = getPrepareStatement(connection,query); listQuery.setAttributes(pstm,query); ResultSet rset = executeQuery(pstm,query); List<P> list= new ArrayList<P>(rset.getFetchSize()); while (rset.next()){ String id=rset.getString(keyColumnName); String type=rset.getString(typeColumnName); P p=getById(connection,id,type); list.add(p); } return list; }catch (SQLException e){ String error="Query" + query; throw new DaoManagerException(error,e); }catch (DaoManagerException e) { String error="Query" + query; throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public List<P> getByConditions (String conditions,Integer rowNum) throws DaoManagerException{ Connection connection=getConnection(); String query; if (rowNum==null){ query=GET_ALL_BY_CONDITIONS_QUERY+conditions; } else { query=GET_ALL_BY_CONDITIONS_QUERY_ROW_NUM+conditions+" ) LIMIT ?"; } try{ PreparedStatement pstm = getPrepareStatement(connection,query); if (rowNum!=null){ setInt(pstm,1,rowNum,query); } ResultSet rset = executeQuery(pstm,query); List<P> list= new ArrayList<P>(rset.getFetchSize()); while (rset.next()){ String id=rset.getString(keyColumnName); String type=rset.getString(typeColumnName); P p=getById(connection,id,type); list.add(p); } return list; }catch (SQLException e){ String error="Query" + query; throw new DaoManagerException(error,e); }catch (DaoManagerException e) { String error="Query" + query; throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public void delete(String id)throws DaoManagerException{ Connection connection = getConnection(); try { delete(connection,id); } finally { closeConnection(connection); } } public void delete(Connection connection,String id)throws DaoManagerException{ try { try { connection.setAutoCommit(false); PreparedStatement pstm = getPrepareStatement(connection, GET_BY_ID_QUERY); setString(pstm, 1, id, GET_BY_ID_QUERY); ResultSet rset = executeQuery(pstm, GET_BY_ID_QUERY); if (!rset.next()) { return ; } String type=rset.getString(typeColumnName); // DELETE PARENT pstm = getPrepareStatement(connection,DELETE_PARENT_QUERY); setString(pstm, 1, id, DELETE_PARENT_QUERY); executeUpdate(pstm, DELETE_PARENT_QUERY); // DELETE CHILD delete(connection,id,type); // COMIT connection.commit(); }finally { connection.setAutoCommit(true); } } catch (Exception e) { String error = "id:'" + id ; throw new DaoManagerException(error, e); } } public long count() throws DaoManagerException{ Connection connection=getConnection(); String query=COUNT_QUERY; try{ PreparedStatement pstm = getPrepareStatement(connection,query); return getLongFromQuery(pstm, query, 0); }catch (DaoManagerException e) { String error="Query" + query; log.error(error, e); throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public long countByConditions(String conditions) throws DaoManagerException{ Connection connection=getConnection(); String query=COUNT_BY_CONDITIONS_QUERY+conditions; try{ PreparedStatement pstm = getPrepareStatement(connection,query); return getLongFromQuery(pstm, query, 0); }catch (DaoManagerException e) { String error="Query" + query; log.error(error, e); throw new DaoManagerException(error, e); }finally{ closeConnection(connection); } } public String toString() { return ToStringBuilder.reflectionToString(this); } private P getById(Connection connection,String id, String type) throws DaoManagerException { if (cache.containsKey(type)){ ChildDAOInterface<? extends P>dao=cache.get(type); return dao.get(connection,id); } else { throw new DaoManagerException("There no dao for type:"+type); } } private void delete(Connection connection, String id, String type) throws DaoManagerException { if (cache.containsKey(type)){ String deleteQuery=childDeleteQuery.get(type); PreparedStatement pstm = getPrepareStatement(connection, deleteQuery); try { setString(pstm, 1, id, deleteQuery); executeUpdate(pstm, deleteQuery); }finally{ close(pstm); } } else { throw new DaoManagerException("There no dao for type:"+type); } } }
41333530fd2c974a8ab16fb78749a0742a025d3f
{ "blob_id": "41333530fd2c974a8ab16fb78749a0742a025d3f", "branch_name": "refs/heads/master", "committer_date": "2016-08-17T17:59:39", "content_id": "833c14214e3ed90abcf72b5801934813a7a50c27", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "05d217894c550f47c9304e9dd81662a4c8b1ca18", "extension": "java", "filename": "ParentQueryDAO.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 20596386, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13730, "license": "Artistic-2.0", "license_type": "permissive", "path": "/src/main/java/eu/ginere/jdbc/mysql/dao/ParentQueryDAO.java", "provenance": "stack-edu-0027.json.gz:402315", "repo_name": "ginere/ginere-jdbc-mysql", "revision_date": "2016-08-17T17:59:39", "revision_id": "1ea64403a5ace75dcebbdfbad3ba268ac58542d5", "snapshot_id": "ce88d548b1c023c8762f4b733be1333c1f3cad43", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ginere/ginere-jdbc-mysql/1ea64403a5ace75dcebbdfbad3ba268ac58542d5/src/main/java/eu/ginere/jdbc/mysql/dao/ParentQueryDAO.java", "visit_date": "2020-03-26T16:03:59.762774", "added": "2024-11-19T00:37:30.252472+00:00", "created": "2016-08-17T17:59:39", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
// Copyright 2015 Satoshi Konno. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package upnp import ( "fmt" "net/http" "testing" ) func TestNullDevice(t *testing.T) { dev := NewDevice() err := dev.Start() if err != nil { t.Error(err) } if (dev.Port < DeviceDefaultPortBase) || (DeviceDefaultPortMax < dev.Port) { t.Errorf(errorTestDeviceInvalidPortRange, dev.Port, DeviceDefaultPortBase, DeviceDefaultPortMax) } url := fmt.Sprintf("http://localhost:%d/", dev.Port) res, err := http.Get(url) if err != nil { t.Error(err) } if res.StatusCode != http.StatusBadRequest { t.Errorf(errorTestDeviceInvalidStatusCode, url, res.StatusCode, http.StatusInternalServerError) } err = dev.Stop() if err != nil { t.Error(err) } } func TestSampleDevice(t *testing.T) { dev, err := NewTestDevice() if err != nil { t.Error(err) } // start device err = dev.Start() if err != nil { t.Error(err) } // check device if (dev.Port < DeviceDefaultPortBase) || (DeviceDefaultPortMax < dev.Port) { t.Errorf(errorTestDeviceInvalidPortRange, dev.Port, DeviceDefaultPortBase, DeviceDefaultPortMax) } devDescURL := fmt.Sprintf("http://localhost:%d%s", dev.Port, dev.DescriptionURL) res, err := http.Get(devDescURL) if err != nil { t.Error(err) } if res.StatusCode != http.StatusOK { t.Errorf(errorTestDeviceInvalidStatusCode, devDescURL, res.StatusCode, http.StatusOK) } // stop device err = dev.Stop() if err != nil { t.Error(err) } }
42aad5a0d50635984ddc04acf2c49cdd1a54644c
{ "blob_id": "42aad5a0d50635984ddc04acf2c49cdd1a54644c", "branch_name": "refs/heads/master", "committer_date": "2023-07-27T10:21:50", "content_id": "2c01d49fa741a618a7ed1a3fe90d3a89b334dd5f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b96074bb91eae97b1aa297af95507107cbdd8016", "extension": "go", "filename": "device_test.go", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30568493, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1558, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/net/upnp/device_test.go", "provenance": "stack-edu-0018.json.gz:308484", "repo_name": "cybergarage/go-net-upnp", "revision_date": "2023-07-27T10:21:50", "revision_id": "aaab7d8a905aa85babed1af8c376a020656f4af5", "snapshot_id": "66ca0e9f64f2d8a6df87ea15101939ba9ba51d33", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/cybergarage/go-net-upnp/aaab7d8a905aa85babed1af8c376a020656f4af5/net/upnp/device_test.go", "visit_date": "2023-08-28T11:54:21.371160", "added": "2024-11-18T21:24:10.857288+00:00", "created": "2023-07-27T10:21:50", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (process){ 'use strict'; var child_process = require('child_process'); var path = require('path'); var say = exports; var childD; // use the correct library per platform if (process.platform === 'darwin') { say.speaker = 'say'; say.base_speed = 175; } else if (process.platform === 'linux') { say.speaker = 'festival'; say.base_speed = 100; } else if (process.platform === 'win32') { say.speaker = 'powershell'; } /** * Uses system libraries to speak text via the speakers. * * @param {string} text Text to be spoken * @param {string|null} voice Name of voice to be spoken with * @param {number|null} speed Speed of text (e.g. 1.0 for normal, 0.5 half, 2.0 double) * @param {Function|null} callback A callback of type function(err) to return. */ say.speak = function(text, voice, speed, callback) { var commands, pipedData; if (typeof callback !== 'function') { callback = function() {}; } if (!text) { // throw TypeError because API was used incorrectly throw new TypeError('Must provide text parameter'); } // tailor command arguments to specific platforms if (process.platform === 'darwin') { if (!voice) { commands = [ text ]; } else { commands = [ '-v', voice, text]; } if (speed) { commands.push('-r', convertSpeed(speed)); } } else if (process.platform === 'linux') { commands = ['--pipe']; if (speed) { pipedData = '(Parameter.set \'Audio_Command "aplay -q -c 1 -t raw -f s16 -r $(($SR*' + convertSpeed(speed) + '/100)) $FILE") '; } if (voice) { pipedData += '(' + voice + ') '; } pipedData += '(SayText \"' + text + '\")'; } else if (process.platform === 'win32') { pipedData = text; commands = [ 'Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Speak([Console]::In.ReadToEnd())' ]; } else { // if we don't support the platform, callback with an error (next tick) - don't continue return process.nextTick(function() { callback(new Error('say.js speak does not support platform ' + process.platform)); }); } var options = (process.platform === 'win32') ? { shell: true } : undefined; childD = child_process.spawn(say.speaker, commands, options); childD.stdin.setEncoding('ascii'); childD.stderr.setEncoding('ascii'); if (pipedData) { childD.stdin.end(pipedData); } childD.stderr.once('data', function(data) { // we can't stop execution from this function callback(new Error(data)); }); childD.addListener('exit', function (code, signal) { if (code === null || signal !== null) { return callback(new Error('say.js: could not talk, had an error [code: ' + code + '] [signal: ' + signal + ']')); } childD = null; callback(null); }); }; say.export = function(text, voice, speed, filename, callback) { var commands, pipedData; if (!text) { // throw TypeError because API was used incorrectly throw new TypeError('Must provide text parameter'); } if (!filename) { // throw TypeError because API was used incorrectly throw new TypeError('Must provide a filename'); } if (typeof callback !== 'function') { callback = function() {}; } // tailor command arguments to specific platforms if (process.platform === 'darwin') { if (!voice) { commands = [ text ]; } else { commands = [ '-v', voice, text]; } if (speed) { commands.push('-r', convertSpeed(speed)); } if (filename){ commands.push('-o', filename, '--data-format=LEF32@32000'); } } else { // if we don't support the platform, callback with an error (next tick) - don't continue return process.nextTick(function() { callback(new Error('say.js export does not support platform ' + process.platform)); }); } childD = child_process.spawn(say.speaker, commands); childD.stdin.setEncoding('ascii'); childD.stderr.setEncoding('ascii'); if (pipedData) { childD.stdin.end(pipedData); } childD.stderr.once('data', function(data) { // we can't stop execution from this function callback(new Error(data)); }); childD.addListener('exit', function (code, signal) { if (code === null || signal !== null) { return callback(new Error('say.js: could not talk, had an error [code: ' + code + '] [signal: ' + signal + ']')); } childD = null; callback(null); }); }; /** * Stops currently playing audio. There will be unexpected results if multiple audios are being played at once * * TODO: If two messages are being spoken simultaneously, childD points to new instance, no way to kill previous */ exports.stop = function(callback) { if (typeof callback !== 'function') { callback = function() {}; } if (!childD) { return callback(new Error('No speech to kill')); } if (process.platform === 'linux') { // TODO: Need to ensure the following is true for all users, not just me. Danger Zone! // On my machine, original childD.pid process is completely gone. Instead there is now a // childD.pid + 1 sh process. Kill it and nothing happens. There's also a childD.pid + 2 // aplay process. Kill that and the audio actually stops. process.kill(childD.pid + 2); } else if (process.platform === 'win32') { childD.stdin.pause(); child_process.exec('taskkill /pid ' + childD.pid + ' /T /F') } else { childD.stdin.pause(); childD.kill(); } childD = null; callback(null); }; function convertSpeed(speed) { return Math.ceil(say.base_speed * speed); } }).call(this,require('_process')) },{"_process":8,"child_process":6,"path":7}],2:[function(require,module,exports){ // const reader = require('./read.js'); // function onLoad() { // document.addEventListener('ready', onReady, false); // }; // function onReady() { // document.addEventListener("setupReader", onSetupReader, false); // } // function onSetupReader(event) { // console.log('Received event also : ', event); // event.preventDefault(); // event.stopPropagation(); // // const reader = require('.read.js'); // const submitButton = document.querySelector("#submit"); // const stopButton = document.querySelector("#stop"); // submitButton.addEventListener("click", (ev) => { // ev.preventDefault(); // ev.stopPropagation(); // const toRead = document.getElementById("toRead").value; // const voice = document.getElementById("voices").value; // if (toRead.length > 100000) { // reader.readText('Woah buddy, thats too much text.'); // } else { // reader.readText(toRead, voice); // } // }); // stopButton.addEventListener("click", (ev) => { // ev.preventDefault(); // ev.stopPropagation(); // reader.stop(); // }); // }; },{}],3:[function(require,module,exports){ (function (window) { const reader = require('./read.js'); $('#submit').click(function(ev) { ev.preventDefault(); ev.stopPropagation(); const toRead = $("#toRead").val(); const voice = $("#voices").val(); console.log('reader : ', reader) if (toRead.length > 100000) { reader.readText('Woah buddy, thats too much text.'); } else { console.log('Calling read : ') reader.readText(toRead, voice); } }); $('#stop').click(function (ev) { ev.preventDefault(); ev.stopPropagation(); reader.stop(); }); })(window); },{"./read.js":5}],4:[function(require,module,exports){ const reader = require('./read.js'); /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function () { document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); }, // deviceready Event Handler // // Bind any cordova events here. Common events are: // 'pause', 'resume', etc. onDeviceReady: function (e) { this.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function (id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } }; app.initialize(); },{"./read.js":5}],5:[function(require,module,exports){ 'use strict'; const say = require('say'); function readText(text, voice) { let toUse = voice; if(!voice){ toUse = 'Alex'; } console.log('Calling speak', say) return say.speak(text, toUse); }; function stop() { return say.stop(); } module.exports = { readText, stop, } },{"say":1}],6:[function(require,module,exports){ },{}],7:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,require('_process')) },{"_process":8}],8:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}]},{},[2,3,4,5]);
5f5325682dfe9638eb74f320ca67520bc91c598f
{ "blob_id": "5f5325682dfe9638eb74f320ca67520bc91c598f", "branch_name": "refs/heads/master", "committer_date": "2017-02-18T22:33:56", "content_id": "b3c71f0eab3ee5123d139904982bea1ee31f0900", "detected_licenses": [ "MIT" ], "directory_id": "3bbc961c44cfe4d173f02d1df1ee73114524a364", "extension": "js", "filename": "bundle.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82356305, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 21706, "license": "MIT", "license_type": "permissive", "path": "/reader/www/js/bundle.js", "provenance": "stack-edu-0040.json.gz:81117", "repo_name": "vaelinn123/cordova-reader", "revision_date": "2017-02-18T22:33:56", "revision_id": "e47adad83233e711c1cbafe011679055bc82c019", "snapshot_id": "69d7f12fa42ca047014341f1487ab8b6c5a04522", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vaelinn123/cordova-reader/e47adad83233e711c1cbafe011679055bc82c019/reader/www/js/bundle.js", "visit_date": "2021-01-19T12:59:51.277527", "added": "2024-11-19T01:42:28.151002+00:00", "created": "2017-02-18T22:33:56", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
package org.firstinspires.ftc.teamcode.Main.HelperClasses; import com.qualcomm.robotcore.hardware.DcMotor; import net.frogbots.ftcopmodetunercommon.opmode.TunableOpMode; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; /** * The base OpMode class for all other OpModes * This extends the TunableOpMode from the frogbots, so we can 'tune' our values * Add all of the init code here * Define all hardware in this class */ public abstract class BaseOpMode extends TunableOpMode { private DcMotor rightFront, rightBack, leftFront, leftBack; // protected ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); // // Runnable test = new Runnable() { // @Override // public void run() { // initMotors(); // } // }; // Callable<Double> runLongCalculation = new Callable<Double>() { // @Override // public Double call() throws Exception { // return Math.cos(1); // } // }; public abstract void init(); // Future<Double> abacus = executor.submit(runLongCalculation); // executor.execute(test); // public void initMotors(){ // //Init Motors // rightFront = hardwareMap.dcMotor.get("rightFront"); // leftFront = hardwareMap.dcMotor.get("leftFront"); // rightBack = hardwareMap.dcMotor.get("rightBack"); // leftBack = hardwareMap.dcMotor.get("leftBack"); // } public void start(){} public void loop(){} }
0d308bdbf664ff5ec08f11640584eeb9c5d2b9f1
{ "blob_id": "0d308bdbf664ff5ec08f11640584eeb9c5d2b9f1", "branch_name": "refs/heads/master", "committer_date": "2020-11-06T23:19:22", "content_id": "98f108a61b119b0e24cef8d80a6889d8ce96e39d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e3dcddf00e38ecb66dc46964ef088ce8dcda4dfe", "extension": "java", "filename": "BaseOpMode.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": 1609, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Desktop/SkystoneV2/SkyStone/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Main/HelperClasses/BaseOpMode.java", "provenance": "stack-edu-0030.json.gz:633398", "repo_name": "pgusto34/UGIntroductoryCode", "revision_date": "2020-11-06T23:19:22", "revision_id": "77688aea1cc294c1b29c6651fe229f76f088a7fd", "snapshot_id": "555a1cb879d4ef7537c1feaa8ab24ce891611a64", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pgusto34/UGIntroductoryCode/77688aea1cc294c1b29c6651fe229f76f088a7fd/Desktop/SkystoneV2/SkyStone/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Main/HelperClasses/BaseOpMode.java", "visit_date": "2023-01-06T21:52:23.314634", "added": "2024-11-18T22:58:31.998531+00:00", "created": "2020-11-06T23:19:22", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz" }
#!/bin/bash set -e yarn global add grunt-cli@1.2.0 mkdir -p $LOGS_DIR if [ $JOB != "ci-checks" ]; then echo "start_browser_provider" ./scripts/travis/start_browser_provider.sh fi if [ $JOB != "ci-checks" ]; then grunt package echo "wait_for_browser_provider" ./scripts/travis/wait_for_browser_provider.sh fi
69f33e0aed7fadf8fb48f1219a6d6cc544a3fa34
{ "blob_id": "69f33e0aed7fadf8fb48f1219a6d6cc544a3fa34", "branch_name": "refs/heads/master", "committer_date": "2017-06-01T16:05:26", "content_id": "0b3356ea358cc43a9d86e213d062def76ffd1b0e", "detected_licenses": [ "MIT" ], "directory_id": "22997016d80dedd136249148bf6208271a02df1a", "extension": "sh", "filename": "before_build.sh", "fork_events_count": 0, "gha_created_at": "2017-06-01T15:20:03", "gha_event_created_at": "2022-12-06T22:41:12", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 93071253, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 323, "license": "MIT", "license_type": "permissive", "path": "/scripts/travis/before_build.sh", "provenance": "stack-edu-0069.json.gz:1057351", "repo_name": "alejandroSuch/angular.js", "revision_date": "2017-06-01T15:31:33", "revision_id": "e7d37afaab7f02344ae9c2c518d124d68ab0af46", "snapshot_id": "3512b7dc7036284588a44a138f3229add4245ae4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alejandroSuch/angular.js/e7d37afaab7f02344ae9c2c518d124d68ab0af46/scripts/travis/before_build.sh", "visit_date": "2022-12-18T05:21:13.892990", "added": "2024-11-19T01:07:27.324020+00:00", "created": "2017-06-01T15:31:33", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
package task import ( "context" "log" cmn "github.com/bredr/dapr-demo/services/common" dapr "github.com/dapr/go-sdk/client" "github.com/dapr/go-sdk/service/common" ) type Handler struct { Client dapr.Client OutputTopicName string } func (h *Handler) Process(ctx context.Context, e *common.TopicEvent) (retry bool, err error) { log.Printf("event - PubsubName: %s, Topic: %s, ID: %s, Data: %s", e.PubsubName, e.Topic, e.ID, e.Data) msg, err := cmn.FromEvent(e) if err != nil { return false, nil } msg.Value += 5 if err := h.Client.PublishEvent(ctx, e.PubsubName, h.OutputTopicName, msg.ToData()); err != nil { return true, err } return false, nil }
81841e5ef9d4ba0ce6fb201dcfe7ef73924657e5
{ "blob_id": "81841e5ef9d4ba0ce6fb201dcfe7ef73924657e5", "branch_name": "refs/heads/main", "committer_date": "2021-03-09T19:31:37", "content_id": "153f6281139c40abea3224b7620e57851dbc3a3c", "detected_licenses": [ "MIT" ], "directory_id": "0c12a0e42e69605f4e6837208cb34beb1962cc5e", "extension": "go", "filename": "task.go", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 341314967, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 679, "license": "MIT", "license_type": "permissive", "path": "/services/task1/task/task.go", "provenance": "stack-edu-0018.json.gz:466990", "repo_name": "bredr/dapr-demo", "revision_date": "2021-03-09T19:31:37", "revision_id": "8ae5c4ffeb453fe156c1a323bfa4e0f6eef52321", "snapshot_id": "22aa6fdda9916bfb6949e4ee8f6dc25a8adc0242", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bredr/dapr-demo/8ae5c4ffeb453fe156c1a323bfa4e0f6eef52321/services/task1/task/task.go", "visit_date": "2023-03-19T20:43:44.027929", "added": "2024-11-19T01:51:42.834431+00:00", "created": "2021-03-09T19:31:37", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
# Clear Session Behaviour ## What this does Resets the HOF session model `req.sessionModel.reset()` and clears anything stored by Redis when a user has submitted their information. This behaviour can be used on the final/penultimate step in a flow to ensure proper session clearing. Clear session happens automatically for the step that uses it if it has no next step. However, if it does, then set the following on the step: ``` '/confirm': { behaviour: require('hof').components.clearSession, clearSession: true, next: '/confirmation' } ``` However if you want to prevent clear session where there is no next step then set 'clearSession' to false: ``` '/confirm': { behaviour: require('hof').components.clearSession, clearSession: false } ``` ## Additional information In your fields file the clear session behaviour can be brought in like this. ``` '/confirm': { behaviour: require('hof').components.clearSession } ``` On your server.js file if you set res.locals to have a confirm step set: ``` app.use((req, res, next) => { res.locals.confirmStep = '/confirm'; next(); }); ``` Then the confirm behaviour will also ensure to reset options on your confirm step for 'uploadPdfShared' and 'submitted' back to false if using these options to keep track of the generation and submission of pdf files. The default configuration for your confirm step might looks like this: ``` '/confirm': { behaviour: [SubmitPDFBehaviour, require('hof').components.clearSession], uploadPdfShared: false, submitted: false } ``` where a SubmitPDFBehaviour is run first which updates the 'uploadPdfShared' and 'submitted' options on the confirm step to true. This clear session behaviour will ensure those are reset along with clearing the session model.
0cfdab83201077a0db1a75ffae55568a09150fcb
{ "blob_id": "0cfdab83201077a0db1a75ffae55568a09150fcb", "branch_name": "refs/heads/master", "committer_date": "2022-12-09T14:44:12", "content_id": "50f650c26e900ea54ebc1f2e606f287d824c2699", "detected_licenses": [ "MIT" ], "directory_id": "65afc18ae7577ac17281254a433075b7fbed3f2c", "extension": "md", "filename": "Readme.md", "fork_events_count": 0, "gha_created_at": "2018-09-28T10:02:40", "gha_event_created_at": "2023-06-22T02:26:40", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 150721462, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1761, "license": "MIT", "license_type": "permissive", "path": "/components/clear-session/Readme.md", "provenance": "stack-edu-markdown-0012.json.gz:152104", "repo_name": "johndallen/hof", "revision_date": "2022-12-09T14:44:12", "revision_id": "942a146008879f5b03b1fa952c570a6e85647d1b", "snapshot_id": "895cc164f4c8c27416eb70bd791a9c418bd4f5fb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/johndallen/hof/942a146008879f5b03b1fa952c570a6e85647d1b/components/clear-session/Readme.md", "visit_date": "2023-07-16T05:26:47.866844", "added": "2024-11-18T22:58:31.579261+00:00", "created": "2022-12-09T14:44:12", "int_score": 4, "score": 3.625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz" }
export interface SendMessageData { text: string sender: 'user' | 'request' showRate: boolean } export type UIManagmentEvents = | 'setUpSender' | 'setUpHeader' | 'setUpBadge' | 'setUpMessage' | 'setUpDialog' | 'blockSender' | 'dialogLoading' | 'showRate' | 'showNotification' export type NotificationsEvents = 'addMessages' | 'addSettings' | 'shown' | 'clicked' | 'enabled' export interface UIManagmentData { uiManagmentEvent: UIManagmentEvents data: any } export interface NotificationsData { notificationEvent: NotificationsEvents data: any } export type ModulesEvents = 'initModule' | 'switchModule' | 'updateModule' | 'getModuleConfig' export interface ModulesData { modulesEvent: ModulesEvents data: any } export type UIEventsNames = 'sendMessage' | 'uiManagment' | 'notifications' | 'modules' export type UIEventsData = SendMessageData | UIManagmentData | NotificationsData | ModulesData
b066b750bfe03aac319516d7e00748e0d284157d
{ "blob_id": "b066b750bfe03aac319516d7e00748e0d284157d", "branch_name": "refs/heads/master", "committer_date": "2020-08-20T11:26:34", "content_id": "c40141d41a783bcbf834b6c0a3df8890eba092d9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ec47d9dcc3bfb67f70f0ee46468fdb29fd2d730b", "extension": "ts", "filename": "uiEvents.d.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 282241135, "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 991, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/@types/uiEvents.d.ts", "provenance": "stack-edu-0075.json.gz:904554", "repo_name": "sovaai/chatKit-rasa-module", "revision_date": "2020-08-20T11:26:34", "revision_id": "5f2239baf6d9dd96b6b7536143d56a6d2b75e330", "snapshot_id": "c007b01dcc26b4268f704528ec5e458811ffe953", "src_encoding": "UTF-8", "star_events_count": 46, "url": "https://raw.githubusercontent.com/sovaai/chatKit-rasa-module/5f2239baf6d9dd96b6b7536143d56a6d2b75e330/src/@types/uiEvents.d.ts", "visit_date": "2022-12-04T04:30:16.590802", "added": "2024-11-18T22:47:24.262565+00:00", "created": "2020-08-20T11:26:34", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
/** * when the page is ready */ $(document).ready(function(){ //reset profile pic container height resetProfileHeight(); //showFiefdom $('.showFiefdom').on('click', function(){ //only if has center if($(this).data('center') && $(this).data('center') != ''){ drawMap($(this).data('center'), null, null, $(this).data('zoom')); } }); //showFief $('.showFief').on('click', function(){ $('#mapContainer').attr('data-zoom', 3); drawMap($(this).data('center'), null, null, 3); }); //mapkeeper toggle $('.makeMapkeeper').on('click', function(){ var tempId = 'tempID' . Math.round(new Date().getTime() + (Math.random() * 100)); $(this).attr('id', tempId); //don't click e.preventDefault(); //spinner up var target = document.getElementById(tempId); var spinner = new Spinner(spinnerOpts).spin(target); //all the ajax calls $.when( //get the requisite data $.ajax({ type: "GET", url: "/api/v1/users/makeMapkeeper/" + userId, dataType: "json", error: function(error){ //wind out the response windDown(spinner, error.error ? error.error : {'message':error.message}, true); } }) ).then( function(presponse){ //setup var response = presponse['message']; } ) //no clicky! return false; }); //invitePersona $('body').on('click', '.invitePersona', function(e){ //no submit e.preventDefault(); var clickedElement = $(this); clickedElement.prop("disabled", true); //spinner up var spinner = new Spinner(spinnerOpts).spin(spinnerTarget); //save this for later var templateId = "templatePersonaInvite"; var dialogId = 'personaAdminInviteUserForm'; var email = clickedElement.closest('form').find('#validClaim').val(); var personaId = clickedElement.data('persona_id'); //load our templates loadTemplates( ['personae/_invite.tmpl.htm'], function(templateGuts){ //setup clickedElement.prop("disabled", false); var disabled = ' disabled'; //template var template = templateGuts[templateId].format({ dialogId: dialogId, personaId: personaId, value: email }); //load the template to the page $('body').append(template); //wind out the response windDown(spinner); //listeners //if it's up, kill it if($("#" + dialogId).hasClass('ui-dialog-content')){ $("#" + dialogId).dialog('destroy').detach().remove(); } //display the dialog $("#" + dialogId).dialog(mediumDialogVars, { title: "Invite Persona User", buttons: { Submit: function(){ //post the request postWidgetForm($(this)); }, Cancel: function() { $(this).dialog('destroy').detach().remove(); } }, close: function(){ $(this).dialog('destroy').detach().remove() } }); } ); //no clicky! return false; }); }); function resetProfileHeight(){ if($('.rebelContainer').length > 0){ $('.rebelContainer').each(function(){ $(this).css("min-height", $(this).find('.underlayRebel').height()); }); } if($('.personaImageContainer').length > 0){ $('.personaImageContainer').each(function(){ var oThis = $(this); var img = new Image(); img.onload = function(){ var newHeight = this.height * (oThis.width() / this.width); oThis.css("min-height", newHeight); }; img.src = $(this).find('.personaImage').first().attr('src'); }); } } /** * when the page is done resizing, reset profile height */ $(window).resize(function () { resetProfileHeight(); });
a3d72bda456adc51f367d28a7186daff67d6d9fe
{ "blob_id": "a3d72bda456adc51f367d28a7186daff67d6d9fe", "branch_name": "refs/heads/master", "committer_date": "2019-08-15T23:53:47", "content_id": "18d541709f8e6c85c2d7cf6fc0e2da229b811ba0", "detected_licenses": [ "MIT" ], "directory_id": "1b070dfa5bede2322ece935f31196c6f1afd57aa", "extension": "js", "filename": "custom_persona.js", "fork_events_count": 1, "gha_created_at": "2015-03-14T00:43:04", "gha_event_created_at": "2023-04-19T19:20:41", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 32188881, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3613, "license": "MIT", "license_type": "permissive", "path": "/public/js/custom_persona.js", "provenance": "stack-edu-0037.json.gz:197469", "repo_name": "WoodyNaDobhar/interquest", "revision_date": "2019-08-15T23:53:47", "revision_id": "3601305ecd380a931904a8b826c237210d402392", "snapshot_id": "2dc5c2de4d668dac9406048856d45fcdd21ebc26", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/WoodyNaDobhar/interquest/3601305ecd380a931904a8b826c237210d402392/public/js/custom_persona.js", "visit_date": "2023-05-01T13:58:21.878593", "added": "2024-11-19T00:16:35.165647+00:00", "created": "2019-08-15T23:53:47", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
<?php /** * Copyright (c) 2009-2019. Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Breeze\Types; use Breeze\BreezeException; use Breeze\BreezeReader; use Breeze\BreezeWriter; use Breeze\Buffer; use Breeze\Message; /** * type message. contains a breeze message for get default instance. * @author: zhanglei * Created at: 2019-04-30 */ class TypeMessage implements Type { private $message; public function __construct(Message $message) { $this->message = $message; } public function read(Buffer $buf, $withType = true) { if ($withType) { $tp = $buf->readByte(); if ($tp == self::T_NULL) { return null; } if ($tp < self::T_MESSAGE) { throw new BreezeException('wrong breeze message type. type:' . $tp); } BreezeReader::readMessageNameByType($buf, $tp); } $msg = $this->message->defaultInstance(); $msg->readFrom($buf); return $msg; } public function write(Buffer $buf, $value, $withType = true) { if ($withType) { BreezeWriter::writeMessageType($buf, $this->message->messageName()); } $value->writeTo($buf); } public function checkType($value) { return ($value instanceof Message) && $value->messageName() === $this->message->messageName(); } public function writeType(Buffer $buf) { BreezeWriter::writeMessageType($buf, $this->message->messageName()); } }
82ef26ab72fe09de2117ed4fd86eddcdf5be9cd7
{ "blob_id": "82ef26ab72fe09de2117ed4fd86eddcdf5be9cd7", "branch_name": "refs/heads/master", "committer_date": "2019-12-12T07:59:58", "content_id": "43cd1ed6fd836a6b5fa3c1b8b60af2bf3263478a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d298f5457102c1e5f66c8f52a3a3a485a1f45422", "extension": "php", "filename": "TypeMessage.php", "fork_events_count": 1, "gha_created_at": "2019-04-19T10:03:47", "gha_event_created_at": "2019-09-11T12:52:30", "gha_language": "PHP", "gha_license_id": null, "github_id": 182244732, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2107, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/Breeze/Types/TypeMessage.php", "provenance": "stack-edu-0054.json.gz:228100", "repo_name": "weibreeze/breeze-php", "revision_date": "2019-12-12T07:59:58", "revision_id": "30f2ac87b1d58055d2292307f262bec17ff95554", "snapshot_id": "752158b1ba1aaa10225c17c1b3f33b6b46e65962", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/weibreeze/breeze-php/30f2ac87b1d58055d2292307f262bec17ff95554/src/Breeze/Types/TypeMessage.php", "visit_date": "2020-05-15T11:46:33.006472", "added": "2024-11-18T23:28:25.785804+00:00", "created": "2019-12-12T07:59:58", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
#!/usr/bin/env bash # THIS SCRIPT CREATE THREE JOB FILES WHICH YOU CAN SUBMIT IN PARALLEL ON CLUSTER # full pathway to GM images DATA_PATH= # full pathway to template image TEMPLATE= # full pathway to FSL config file (you need to change ref_mask parameter!) FSL_CONFIG= # full pathway where you want to save results VBM_EXPERIMENT_DIR= # size of kernel SMOOTH_KERNEL= mkdir -p ${VBM_EXPERIMENT_DIR}/smoothed mkdir -p ${VBM_EXPERIMENT_DIR}/transformed ############################################ # # # REGISTRATION IMAGE_LIST=$( ls ${DATA_PATH} ) /bin/rm -f ${VBM_EXPERIMENT_DIR}/fsl_reg.sh for filename in ${IMAGE_LIST[@]}; do f=${filename%.nii.gz*} echo "${FSLDIR}/bin/fsl_reg ${DATA_PATH}/${filename} ${TEMPLATE} \ ${VBM_EXPERIMENT_DIR}/transformed/${f}_GM_to_template_GM \ -fnirt \"--config=${FSL_CONFIG} --jout=${VBM_EXPERIMENT_DIR}/transformed/${f}_JAC_nl\" " >> ${VBM_EXPERIMENT_DIR}/fsl_reg.sh done chmod a+x ${VBM_EXPERIMENT_DIR}/fsl_reg.sh ############################################ # # # MODULATION /bin/rm -f ${VBM_EXPERIMENT_DIR}/fsl_mod.sh for filename in ${IMAGE_LIST[@]}; do f=${filename%.nii.gz*} echo "${FSLDIR}/bin/fslmaths ${VBM_EXPERIMENT_DIR}/transformed/${f}_GM_to_template_GM -mul \ ${VBM_EXPERIMENT_DIR}/transformed/${f}_JAC_nl ${VBM_EXPERIMENT_DIR}/transformed/${f}_GM_to_template_GM_mod -odt float" >> ${VBM_EXPERIMENT_DIR}/fsl_mod.sh done chmod a+x ${VBM_EXPERIMENT_DIR}/fsl_mod.sh ############################################ # # # SMOOTHING /bin/rm -f ${VBM_EXPERIMENT_DIR}/fsl_smooth.sh for filename in ${IMAGE_LIST[@]}; do f=${filename%.nii.gz*} echo "${FSLDIR}/bin/fslmaths ${VBM_EXPERIMENT_DIR}/transformed/${f}_GM_to_template_GM_mod -s ${SMOOTH_KERNEL} \ ${VBM_EXPERIMENT_DIR}/smoothed/${f}_GM_to_template_GM_mod_s${SMOOTH_KERNEL}" >> ${VBM_EXPERIMENT_DIR}/fsl_smooth.sh done chmod a+x ${VBM_EXPERIMENT_DIR}/fsl_smooth.sh
e03e304d3670add77f15392d0d0e16d97b2132e0
{ "blob_id": "e03e304d3670add77f15392d0d0e16d97b2132e0", "branch_name": "refs/heads/master", "committer_date": "2021-03-08T13:17:27", "content_id": "947e3dfadd6964b59e03d97718d265a445aa20e4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5d6b72bbfd6de4d22d60f2607dbe22e1942988b6", "extension": "sh", "filename": "fast_vbm.sh", "fork_events_count": 4, "gha_created_at": "2017-05-16T01:08:06", "gha_event_created_at": "2021-03-08T13:17:27", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 91399018, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1925, "license": "Apache-2.0", "license_type": "permissive", "path": "/scripts/shell/fast_vbm.sh", "provenance": "stack-edu-0069.json.gz:32309", "repo_name": "roshchupkin/VBM", "revision_date": "2021-03-08T13:17:27", "revision_id": "26c4e2a4495441de2c09c40a41d39bf885cd13d5", "snapshot_id": "581d147886ee436b855c1d427e211277693ddf2c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/roshchupkin/VBM/26c4e2a4495441de2c09c40a41d39bf885cd13d5/scripts/shell/fast_vbm.sh", "visit_date": "2021-07-12T04:40:30.734389", "added": "2024-11-19T00:04:50.368256+00:00", "created": "2021-03-08T13:17:27", "int_score": 3, "score": 3.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
package javax0.jamal.templated; public class Templated1 { //<editor-fold template="attributes" id="Templated1"> // // -- <editor-fold desc="generated fields"> // {%field :boolean:primary%} // {%field :Boolean:main%} // {%field :String:firstName%} // {%field :String:lastName%} // {%field :int:age%} // {%field :String:address%} // {%field :String:city%} // {%field :String:state%} // {%field :String:zipCode%} // {%field :String:phoneNumber%} // {%field :String:email%} // {%field :String:github%} // {%field :String:linkedin%} // {%field :String:website%} // {%field :String:objective%} // {%field :String:education%} // {%field :String:experience%} // {%field :String:skills%} // {%field :String:projects%} // {%field :String:interests%} // {%field :String:references%} // // -- </editor-fold> // -- <editor-fold desc="generated fields"> private boolean primary; public boolean isPrimary(){ return primary; } public void setPrimary(boolean primary){ this.primary=primary; } private Boolean main; public Boolean isMain(){ return main; } public void setMain(Boolean main){ this.main=main; } private String firstName; public String getFirstName(){ return firstName; } public void setFirstName(String firstName){ this.firstName=firstName; } private String lastName; public String getLastName(){ return lastName; } public void setLastName(String lastName){ this.lastName=lastName; } private int age; public int getAge(){ return age; } public void setAge(int age){ this.age=age; } private String address; public String getAddress(){ return address; } public void setAddress(String address){ this.address=address; } private String city; public String getCity(){ return city; } public void setCity(String city){ this.city=city; } private String state; public String getState(){ return state; } public void setState(String state){ this.state=state; } private String zipCode; public String getZipCode(){ return zipCode; } public void setZipCode(String zipCode){ this.zipCode=zipCode; } private String phoneNumber; public String getPhoneNumber(){ return phoneNumber; } public void setPhoneNumber(String phoneNumber){ this.phoneNumber=phoneNumber; } private String email; public String getEmail(){ return email; } public void setEmail(String email){ this.email=email; } private String github; public String getGithub(){ return github; } public void setGithub(String github){ this.github=github; } private String linkedin; public String getLinkedin(){ return linkedin; } public void setLinkedin(String linkedin){ this.linkedin=linkedin; } private String website; public String getWebsite(){ return website; } public void setWebsite(String website){ this.website=website; } private String objective; public String getObjective(){ return objective; } public void setObjective(String objective){ this.objective=objective; } private String education; public String getEducation(){ return education; } public void setEducation(String education){ this.education=education; } private String experience; public String getExperience(){ return experience; } public void setExperience(String experience){ this.experience=experience; } private String skills; public String getSkills(){ return skills; } public void setSkills(String skills){ this.skills=skills; } private String projects; public String getProjects(){ return projects; } public void setProjects(String projects){ this.projects=projects; } private String interests; public String getInterests(){ return interests; } public void setInterests(String interests){ this.interests=interests; } private String references; public String getReferences(){ return references; } public void setReferences(String references){ this.references=references; } // -- </editor-fold> //</editor-fold> }
a7a715ff2f721fbb42a61ddadce78690fd011c0f
{ "blob_id": "a7a715ff2f721fbb42a61ddadce78690fd011c0f", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T14:28:16", "content_id": "26a1d760a3a7ae702a3ec9a6bcd61abdab8eb0ab", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7a4da4c6ee5f03c2071244f532a9135bb0b48af6", "extension": "java", "filename": "Templated1.java", "fork_events_count": 4, "gha_created_at": "2018-08-09T07:34:42", "gha_event_created_at": "2023-09-14T09:36:04", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 144117144, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4273, "license": "Apache-2.0", "license_type": "permissive", "path": "/jamal-test/src/test/java/javax0/jamal/templated/Templated1.java", "provenance": "stack-edu-0022.json.gz:869978", "repo_name": "verhas/jamal", "revision_date": "2023-08-30T14:28:16", "revision_id": "54372562c3440dfce38a9cf4a5b58722f2eb9247", "snapshot_id": "b81fd42da8826459b0252c8c44a071d00c9ddbbc", "src_encoding": "UTF-8", "star_events_count": 43, "url": "https://raw.githubusercontent.com/verhas/jamal/54372562c3440dfce38a9cf4a5b58722f2eb9247/jamal-test/src/test/java/javax0/jamal/templated/Templated1.java", "visit_date": "2023-09-01T20:52:06.513523", "added": "2024-11-19T02:50:01.466547+00:00", "created": "2023-08-30T14:28:16", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
package com.chuwa.cordova.trtc; import android.app.Dialog; import android.content.Context; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import java.util.ArrayList; /** * 通过单选对话框 */ public class RadioGroupDialog extends Dialog implements RadioGroup.OnCheckedChangeListener { private int mSelected = 0; private RadioGroup rgMain; private ArrayList<RadioButton> rbList; private onItemClickListener itemListener; public interface onItemClickListener{ void onItemClick(int position); } public RadioGroupDialog(Context context, String[] menus) { super(context, FakeR.getId(context, "style", "common_dlg")); rgMain = new RadioGroup(context); setContentView(rgMain); rgMain.setOrientation(LinearLayout.VERTICAL); rgMain.setOnCheckedChangeListener(this); initMenus(menus); //setSelected(mSelected); } @Override public void onCheckedChanged(RadioGroup radioGroup, int btnId) { if (null != itemListener){ for (int i=0; i<rbList.size(); i++){ if (rbList.get(i).getId() == btnId){ itemListener.onItemClick(i); break; } } } dismiss(); } public void setSelected(int selected){ rgMain.clearCheck(); if (selected < rbList.size()) rbList.get(selected).setChecked(true); } public void clearCheck(){ rgMain.clearCheck(); } public void setOnItemClickListener(onItemClickListener listener){ itemListener = listener; } private void initMenus(String[] menus){ RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(5, 10, 5, 10); rbList = new ArrayList<>(); for (String menu : menus){ RadioButton rbMenu = new RadioButton(getContext()); rbMenu.setText(menu); rbList.add(rbMenu); rgMain.addView(rbMenu, layoutParams); } } }
2a50c0e522bc3593ccda7817b5b269eb8840fa3e
{ "blob_id": "2a50c0e522bc3593ccda7817b5b269eb8840fa3e", "branch_name": "refs/heads/master", "committer_date": "2019-04-18T03:08:54", "content_id": "f914cc8e11927448fd0b44540c05855a1301de89", "detected_licenses": [ "MIT" ], "directory_id": "fec3f27e093cb087ce0fb3fa104fa2f113cf11f4", "extension": "java", "filename": "RadioGroupDialog.java", "fork_events_count": 0, "gha_created_at": "2019-04-18T03:08:23", "gha_event_created_at": "2019-04-18T03:08:24", "gha_language": null, "gha_license_id": null, "github_id": 182007210, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2236, "license": "MIT", "license_type": "permissive", "path": "/src/android/videocall/ui/utils/RadioGroupDialog.java", "provenance": "stack-edu-0031.json.gz:440454", "repo_name": "UTSOURCE/cordova-plugin-trtc", "revision_date": "2019-04-18T03:08:54", "revision_id": "4c9040c805729e4235ff1d6c47cd5a8ab91f0677", "snapshot_id": "089b4a235db85a6a8aee7a00827ec7675638ac2d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/UTSOURCE/cordova-plugin-trtc/4c9040c805729e4235ff1d6c47cd5a8ab91f0677/src/android/videocall/ui/utils/RadioGroupDialog.java", "visit_date": "2020-05-15T00:07:52.211812", "added": "2024-11-18T21:09:42.852213+00:00", "created": "2019-04-18T03:08:54", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }