text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
import * as async from 'async'; import * as chokidar from 'chokidar'; import * as fs from 'fs-extra'; import Mock from './mock'; import Configuration from './configuration'; import Processor from './processor'; (module).exports = function () { 'use strict'; const processor = new Processor(); const defaults = { destination: '.tmp/mocks/' }; const utils = require('../lib/utils'); return { run: run, watch: watch }; /** * Run ngapimock. * @param configuration The configuration. */ function run(configuration: Configuration) { if (configuration === undefined) { console.error('No configuration has been specified.'); throw new Error('No configuration has been specified.'); } if (configuration.src === undefined) { console.error('No mock source directory have been specified.'); throw new Error('No mock source directory have been specified.'); } const config = { baseUrl: configuration.baseUrl, source: configuration.src, done: configuration.done !== undefined ? configuration.done : () => { }, destination: configuration.outputDir !== undefined ? configuration.outputDir : defaults.destination }; let mocks: Mock[]; async.series({ processMocks: (callback: Function) => { console.info('Process all the mocks'); mocks = processor.processMocks(config.source); callback(null, 'processed mocks'); }, registerMocks: function (callback) { console.info('Register mocks'); utils.registerMocks(mocks); callback(null, 'registered mocks'); }, generateMockingInterface: function (callback) { console.info('Generate the mocking web interface'); processor.generateMockingInterface(config.destination); callback(null, 'generated mocking interface'); }, generateProtractorMock: function (callback) { console.info('Generate protractor.mock.js'); processor.generateProtractorMock(config.destination, config.baseUrl); callback(null, 200); } }, function (err) { if (err !== undefined && err !== null) { console.error(err); } config.done(); }); } /** * Watch to file changes. * @param directory The directory to watch */ function watch(directory: String) { console.info('Watching', directory, 'for changes'); const watcher = chokidar.watch(directory + '/**/*.json', { ignored: /[\/\\]\./, persistent: true }); watcher .on('add', path => _processMock(path)) .on('change', path => _processMock(path)) .on('unlink', path => _processMock(path)); } /** * Processes all the mocks that are present in the given directory. * @param {string} directory The directory containing the mocks. * @returns {Mock[]} mocks The mocks. */ function _processMock(file: string): void { try { const mock: Mock = fs.readJsonSync(file); utils.updateMock(mock); } catch (ex) { console.info(file, 'contains invalid json'); } } };
a4cb093cd7aa1a89f86e1c9e68fcc9b55d475d47
{ "blob_id": "a4cb093cd7aa1a89f86e1c9e68fcc9b55d475d47", "branch_name": "refs/heads/master", "committer_date": "2019-08-12T10:36:33", "content_id": "a5461c1e7ea729095a77d7cb848c83aeaf6acff2", "detected_licenses": [ "MIT" ], "directory_id": "ba85afc3412f669a4cdd9f167b6972bec16e14fc", "extension": "ts", "filename": "index.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": 3626, "license": "MIT", "license_type": "permissive", "path": "/tasks/index.ts", "provenance": "stack-edu-0075.json.gz:32873", "repo_name": "heniu75/ng-apimock", "revision_date": "2019-08-12T10:36:33", "revision_id": "bd07ab57c91e8c842286deefa2e223d2349d82b4", "snapshot_id": "90fe5492d2f7274a14d5f2cb4689602625aa6837", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/heniu75/ng-apimock/bd07ab57c91e8c842286deefa2e223d2349d82b4/tasks/index.ts", "visit_date": "2020-07-11T23:18:47.402739", "added": "2024-11-19T02:45:27.929973+00:00", "created": "2019-08-12T10:36:33", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
$(function(){ $(".sshweb_side_tree li a").bind("click",function(){ var title = $(this).text(); var iconCls = $(this).attr("data-icon"); var url = $(this).attr("data-link"); var iframe = $(this).attr("iframe")==1?true:false; addTab(title,url,iconCls,iframe); }); }); function addTab(title,url,iconCls,iframe){ var tabPanel = $("#sshweb_tabs"); if(!tabPanel.tabs("exists",title)){ var content = "<iframe scrolling='auto' frameborder='0' src='"+url+"' style='width:100%;height:100%;'></iframe>"; if(iframe){ tabPanel.tabs("add",{ title:title, content:content, //<iframe>放到tabs,灵活,里边的页面做任何操作,不会受,影响外面的页面,缺点:里边的用js,css,重复加载js文件,css iconCls:iconCls, fit:true, cls:"pd3", closable:true }); }else{ tabPanel.tabs("add",{ title:title, href:url, //本质是url指向的页面<body></body>,好处,不用重复的加载js文件,里边的这张页面,js,css,必须写在<body></body>,注意没url地址的datagrid的id不能重名 iconCls:iconCls, fit:true, cls:"pd3", closable:true }); } }else{ tabPanel.tabs("select",title) } }
72af7d62a66768be3db55d32d595e04a0be0886a
{ "blob_id": "72af7d62a66768be3db55d32d595e04a0be0886a", "branch_name": "refs/heads/master", "committer_date": "2018-12-05T18:02:21", "content_id": "92ef8393e6e8bfed14a2bfa70b7cb5e15cb64bd4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "70f9db28a8d469709405ac15f8263d428536b410", "extension": "js", "filename": "main.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 159191373, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1247, "license": "Apache-2.0", "license_type": "permissive", "path": "/sshwebeasyui/src/main/webapp/resources/js/main.js", "provenance": "stack-edu-0043.json.gz:451589", "repo_name": "YufeizhangRay/role-based-privilege-control-model", "revision_date": "2018-12-05T18:02:21", "revision_id": "f9aaec52dfcf09eda15ac4329508d6208ddc1f79", "snapshot_id": "3d2b7df7c08269d58293386a5ba7322837d6d36b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/YufeizhangRay/role-based-privilege-control-model/f9aaec52dfcf09eda15ac4329508d6208ddc1f79/sshwebeasyui/src/main/webapp/resources/js/main.js", "visit_date": "2020-04-08T08:43:51.830770", "added": "2024-11-18T22:42:04.909866+00:00", "created": "2018-12-05T18:02:21", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
<?php /** * @link https://miranj.in/ * @copyright Copyright (c) Miranj Design LLP */ namespace miranj\cryptographer\models; use craft\base\Model; class Settings extends Model { // Public Properties // ========================================================================= /** * @var string|null */ public $hashidsAlphabet = null; /** * @var int|null */ public $hashidsMinLength = 15; /** * @var string|null */ public $secret = null; /** * @inheritdoc */ public function rules(): array { return [ [['hashidsAlphabet', 'secret'], 'string'], [['hashidsMinLength'], 'numerical'], ]; } }
53504a1aa58e1f83fd31e79aa2f3037a7c525b26
{ "blob_id": "53504a1aa58e1f83fd31e79aa2f3037a7c525b26", "branch_name": "refs/heads/v1", "committer_date": "2022-07-19T10:05:27", "content_id": "d8bed8d3edb445a81dc60f4e36bfa4657d0723dc", "detected_licenses": [ "MIT" ], "directory_id": "5b45065441396f473a90d7471f2508bd10932d32", "extension": "php", "filename": "Settings.php", "fork_events_count": 2, "gha_created_at": "2015-03-24T20:02:12", "gha_event_created_at": "2019-11-25T13:03:50", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 32821984, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 755, "license": "MIT", "license_type": "permissive", "path": "/src/models/Settings.php", "provenance": "stack-edu-0051.json.gz:818355", "repo_name": "miranj/craft-cryptographer", "revision_date": "2022-07-19T10:05:27", "revision_id": "63ac9cb60fc404fddbcbc923873c83a8c0cf092f", "snapshot_id": "27b943ff1c315c272acae71504d2d48b83acce85", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/miranj/craft-cryptographer/63ac9cb60fc404fddbcbc923873c83a8c0cf092f/src/models/Settings.php", "visit_date": "2022-08-12T04:10:30.370118", "added": "2024-11-19T03:21:54.857589+00:00", "created": "2022-07-19T10:05:27", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
import requests import json # import related models here from .models import CarDealer, DealerReview from requests.auth import HTTPBasicAuth # Create a `get_request` to make HTTP GET requests # e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'}, # auth=HTTPBasicAuth('apikey', api_key)) def get_request(url, **kwargs): print(kwargs) print("GET from {} ".format(url)) try: # Call get method of requests library with URL and parameters response = requests.get(url, headers={'Content-Type': 'application/json'}, params=kwargs) except: # If any error occurs print("Network exception occurred") status_code = response.status_code print("With status {} ".format(status_code)) json_data = json.loads(response.text) return json_data # Create a `post_request` to make HTTP POST requests # e.g., response = requests.post(url, params=kwargs, json=payload) # def post_request(url, **kwargs): def post_request(url, **kwargs): print(kwargs) print("POST to {} ".format(url)) try: # Call post method of requests library with URL and parameters payload = kwargs.pop("payload") response = requests.post(url, headers={'Content-Type': 'application/json'}, params=kwargs, json=payload) except: # If any error occurs print("Network exception occurred") status_code = response.status_code print("With status {} ".format(status_code)) json_data = json.loads(response.text) return json_data # Create a get_dealers_from_cf method to get dealers from a cloud function # def get_dealers_from_cf(url, **kwargs): # - Call get_request() with specified arguments # - Parse JSON results into a CarDealer object list def get_dealers_from_cf(url, **kwargs): results = [] # Call get_request with a URL parameter json_result = get_request(url) if json_result: # Get the row list in JSON as dealers dealers = json_result["entries"] # For each dealer object for dealer_doc in dealers: # Get its content in `doc` object # dealer_doc = dealer["doc"] # Create a CarDealer object with values in `doc` object dealer_obj = CarDealer( address=dealer_doc["address"], city=dealer_doc["city"], full_name=dealer_doc["full_name"], id=dealer_doc["id"], lat=dealer_doc["lat"], long=dealer_doc["long"], short_name=dealer_doc["short_name"], st=dealer_doc["st"], zip=dealer_doc["zip"] ) results.append(dealer_obj) return results # Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function # def get_dealer_by_id_from_cf(url, dealerId): # - Call get_request() with specified arguments # - Parse JSON results into a DealerView object list def get_dealer_reviews_from_cf(url, **kwargs): results = [] json_result = get_request(url) if json_result: reviews = json_result["entries"] for review_doc in reviews: review_obj = DealerReview( dealership=review_doc.get("dealership"), name=review_doc.get("name"), purchase=review_doc.get("purchase"), review=review_doc.get("review"), purchase_date=review_doc.get("purchase_date"), car_make=review_doc.get("car_make"), car_model=review_doc.get("car_model"), car_year=review_doc.get("car_year"), sentiment=analyze_review_sentiments(review_doc.get("review")), id=review_doc.get("id") ) results.append(review_obj) return results def store_review(url, payload): post_request(url, payload=payload) # Create an `analyze_review_sentiments` method to call Watson NLU and analyze text # def analyze_review_sentiments(text): # - Call get_request() with specified arguments # - Get the returned sentiment label such as Positive or Negative def analyze_review_sentiments(text): url = "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/1d6d2a23-a3c3-4ecb-bb1d-1d3eebb6a8c6/v1/analyze?version=2021-03-25" api_key = "ul4LUhas5N_IUWIGV1wfauUZ-8W1f9JfxbOgM_2ve79j" params = { "text": text, "features": { "sentiment": { } }, "language": "en" } # params["return_analyzed_text"] = kwargs["return_analyzed_text"] response = requests.post(url, json=params, headers={'Content-Type': 'application/json'}, auth=('apikey', api_key)) return response.json()["sentiment"]["document"]["label"]
c78fbd40d765460b618e144d21989122d0d385c3
{ "blob_id": "c78fbd40d765460b618e144d21989122d0d385c3", "branch_name": "refs/heads/master", "committer_date": "2021-06-26T16:14:30", "content_id": "3a896b326b611ddbf74fe3c2975263ccbdfe28c5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b045fd588bc59c40cccee0edf3669504bcc19083", "extension": "py", "filename": "restapis.py", "fork_events_count": 0, "gha_created_at": "2023-01-06T15:37:27", "gha_event_created_at": "2023-01-06T15:37:28", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 585971774, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4950, "license": "Apache-2.0", "license_type": "permissive", "path": "/server/djangoapp/restapis.py", "provenance": "stack-edu-0056.json.gz:408227", "repo_name": "swapnilAndhale/agfzb-CloudAppDevelopment_Capstone", "revision_date": "2021-06-26T16:14:30", "revision_id": "ec21379345c11f51ef78d07167adf41f82b40575", "snapshot_id": "6281821a092503d56da868a7e16d8c5737d2ef89", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/swapnilAndhale/agfzb-CloudAppDevelopment_Capstone/ec21379345c11f51ef78d07167adf41f82b40575/server/djangoapp/restapis.py", "visit_date": "2023-06-06T01:07:20.431916", "added": "2024-11-19T02:29:55.352915+00:00", "created": "2021-06-26T16:14:30", "int_score": 3, "score": 2.96875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
"""Async adapters to MQTT, using the hbmqtt library. We can make the send code slightly cleaner by using async/await. To preverse compatability with Python 3.4, we explicitly queue up the connect request instead. """ import hbmqtt.client import hbmqtt.session import json import asyncio from collections import deque from thingflow.base import InputThing, FatalError, OutputThing, \ filtermethod, EventLoopOutputThingMixin class QueueWriter(OutputThing, InputThing): def __init__(self, previous_in_chain, uri, topic, scheduler): super().__init__() self.uri = uri self.topic = topic self.scheduler = scheduler self.connected = False self.pending_task = None self.pending_message = None self.pending_error = None self.request_queue = deque() self.client = hbmqtt.client.MQTTClient(loop=scheduler.event_loop) self.dispose = previous_in_chain.connect(self) def has_pending_requests(self): """Return True if there are pending requests. Useful for tests without having to expose internal state. Note that, in the event of a diconnect(), we don't remove the pending task, as we will be calling on_error() or on_completed() directly intead of _process_queue(). """ return ((self.pending_task is not None) and (not self.pending_task.done())) or \ (self.pending_message is not None) or \ len(self.request_queue)>0 def dump_state(self): """Return a string representing the internal state (for debugging). """ return "QueueWriter(pending_task=%s,pending_message=%s,queue=%s)" %\ (repr(self.pending_task), repr(self.pending_message), repr(self.request_queue)) def _to_message(self, x): return bytes(json.dumps((x.sensor_id, x.ts, x.val),), encoding='utf-8') def _process_queue(self, future): assert future == self.pending_task exc = future.exception() if exc: raise FatalError("mqtt request failed with exception: %s" % exc) if self.pending_message: self._dispatch_next(self.pending_message) self.pending_message = None if len(self.request_queue)==0: self.pending_task = None #print("Completed last task") else: x = self.request_queue.popleft() if x is not None: self.pending_message = x self.pending_task = \ self.scheduler._schedule_coroutine(self.client.publish(self.topic, self._to_message(x)), self._process_queue) #print("enqueuing message %s on %s (from request_q)" % # (repr(x), self.topic)) else: e = self.pending_error self.pending_task = \ self.scheduler._schedule_coroutine(self.client.disconnect(), lambda f: self._dispatch_error(e) if e is not None else lambda f: self._dispatch_completed) #print("initiated disconnect (pending_error=%s)" % e) def on_next(self, x): if self.connected == False: self.request_queue.append(x) self.pending_task = \ self.scheduler._schedule_coroutine(self.client.connect(self.uri), self._process_queue) self.connected = True #print("connection in progress, put message %s on request_queue" # % repr(x)) elif self.pending_task is not None: self.request_queue.append(x) #print("put message %s on request_queue" % repr(x)) else: self.pending_message = x self.pending_task = \ self.scheduler._schedule_coroutine(self.client.publish(self.topic, self._to_message(x)), self._process_queue) #print("enqueuing message %s on %s" % (repr(x), self.topic)) def on_error(self, e): if len(self.request_queue)>0: # empty the pending request queue, we won't try to # send these. self.request_queue = deque() #print("on_error: dropped pending requests") if self.pending_task is None: self.pending_task = \ self.scheduler._schedule_coroutine(self.client.disconnect(), lambda f: self._dispatch_error(e)) #print("on_error: initiated disconnect") else: self.pending_error = e self.request_queue.append(None) #print("on_error: queued disconnect") def on_completed(self): if self.pending_task is None: self.pending_task = \ self.scheduler._schedule_coroutine(self.client.disconnect(), self._process_queue) #print("on_completed: initiated disconnect") else: self.request_queue.append(None) #print("on_completed: queued disconnect") @filtermethod(OutputThing) def mqtt_async_send(this, uri, topic, scheduler): """ Filter method to send a message on the specified uri and topic. It is added to the output_thing. """ return QueueWriter(this, uri, topic, scheduler) DELIVER_TIMEOUT=2 # seconds class QueueReader(OutputThing, EventLoopOutputThingMixin): """Subscribe to a topic, wait for incoming messages, and push them downstream. """ # state constants INITIAL_STATE = "INITIAL" CONNECTING_STATE = "CONNECTING" SUBSCRIBING_STATE = "SUBSCRIBING" ACTIVE_STATE = "ACTIVE" UNSUBSCRIBING_STATE = "UNSUBSCRIBING" DISCONNECTING_STATE = "DISCONNECTING" FINAL_STATE = "FINAL" def __init__(self, uri, topic, scheduler, qos=hbmqtt.client.QOS_1, timeout=DELIVER_TIMEOUT): super().__init__() self.uri = uri self.topic = topic self.qos = qos self.scheduler = scheduler self.state = QueueReader.INITIAL_STATE self.pending_task = None self.stop_requested = False self.client = hbmqtt.client.MQTTClient(loop=scheduler.event_loop) self.timeout = timeout # no need to change, overridable just for testing def _start_task(self, call, next_state): #print("_start_task: %s, next_state=%s" % (repr(call), next_state)) self.state = next_state self.pending_task = self.scheduler._schedule_coroutine(call, self._process_event) def _process_stop_request(self): if self.stop_requested: #print("stop requested") self._start_task(self.client.unsubscribe([self.topic,]), QueueReader.UNSUBSCRIBING_STATE) return True else: return False def _process_event(self, future): assert future == self.pending_task #print("_process_event state=%s" % self.state) exc = future.exception() if exc and isinstance(exc, asyncio.TimeoutError) and\ self.state==QueueReader.ACTIVE_STATE: # we timeout every few seconds to check for stop requests if not self._process_stop_request(): self._start_task(self.client.deliver_message(self.timeout), QueueReader.ACTIVE_STATE) elif exc: raise FatalError("mqtt request failed with exception: %s" % exc) elif self.state==QueueReader.CONNECTING_STATE: if not self._process_stop_request(): self._start_task(self.client.subscribe([(self.topic, self.qos),]), QueueReader.SUBSCRIBING_STATE) elif self.state==QueueReader.SUBSCRIBING_STATE: if not self._process_stop_request(): self._start_task(self.client.deliver_message(self.timeout), QueueReader.ACTIVE_STATE) elif self.state==QueueReader.ACTIVE_STATE: result = future.result() assert isinstance(result, hbmqtt.session.ApplicationMessage) message = str(result.data, encoding='utf-8') self._dispatch_next(json.loads(message)) if not self._process_stop_request(): self._start_task(self.client.deliver_message(self.timeout), QueueReader.ACTIVE_STATE) elif self.state==QueueReader.UNSUBSCRIBING_STATE: self._start_task(self.client.disconnect(), QueueReader.DISCONNECTING_STATE) elif self.state==QueueReader.DISCONNECTING_STATE: self._dispatch_completed() self.state = QueueReader.FINAL_STATE self.pending_task = None self.scheduler._remove_from_active_schedules(self) print("QueueReader in FINAL state") elif self.state==QueueReader.FINAL_STATE: raise Exception("_process_event should not be called in final state") else: raise Exception("_process_event: invalidate state %s" % self.state) def _observe_event_loop(self): """This gets things kicked off. Most of the real action will occur in _process_event(). """ assert self.state == QueueReader.INITIAL_STATE,\ "_observe_event_loop called when in state %s" % self.state self._start_task(self.client.connect(self.uri), QueueReader.CONNECTING_STATE) def _stop_loop(self): """Stop listening for new messages, processing any pending messages, and move to the final state. """ self.stop_requested = True
1687bdb00a27e467823ed32c2073aaf98df81a92
{ "blob_id": "1687bdb00a27e467823ed32c2073aaf98df81a92", "branch_name": "refs/heads/master", "committer_date": "2019-02-28T09:59:13", "content_id": "b3ee675607554d3caaf52db083506457878de8a7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "094a82883b0f4490dbca6c042e129faf0593d7bc", "extension": "py", "filename": "mqtt_async.py", "fork_events_count": 0, "gha_created_at": "2019-02-07T14:44:44", "gha_event_created_at": "2019-02-07T14:44:45", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 169587091, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10147, "license": "Apache-2.0", "license_type": "permissive", "path": "/thingflow/adapters/mqtt_async.py", "provenance": "stack-edu-0064.json.gz:514768", "repo_name": "kesking82/thingflow-python", "revision_date": "2019-02-28T09:59:13", "revision_id": "4c00deafd1bf425ec90ef2159fc5f3ea2553ade8", "snapshot_id": "904495aa370fb0fdef5e1eb162f0553a37bd7271", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kesking82/thingflow-python/4c00deafd1bf425ec90ef2159fc5f3ea2553ade8/thingflow/adapters/mqtt_async.py", "visit_date": "2020-04-21T13:05:57.615247", "added": "2024-11-19T02:37:44.020684+00:00", "created": "2019-02-28T09:59:13", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
<?php include 'header.php'; if ($_SESSION['user_id'] == '') { ?> <script> setTimeout(function () { $('.Login').click(); }, 500); </script> <?php } else { $op_date_time = date('Y-m-d H:i:s'); $userInfo = $authobj->userProfile($_SESSION['user_id']); ### card detail $card_detatil = $authobj->card_detail($_SESSION['user_id']); if (isset($_POST['submitData'])) { //print_r($_POST); $start_date = date('Y-m-d'); $end_date = date('Y-m-d', strtotime('+1 year')); $coupon_code = $_REQUEST['coupon_code']; $card_id = $_REQUEST['card_id']; $user_id = $_SESSION['user_id']; $amount = $_REQUEST['amount']; $_POST['user_id'] = $user_id; $urlrequest = urlencode(serialize($_POST)); $urldata = array(); foreach ($_POST as $key => $value) { $url = $key . "=" . $value; array_push($urldata, $url); } $urlpost = implode("&", $urldata); echo $card_id; if ($card_id == 'paypal') { header('location: paypal_process.php?payment_type=gift_order&' . $urlpost); } else { $payment_method = 'Credit Card'; print_r($_REQUEST); $query = "SELECT card_holder_name,card_number,expiry_month,expiry_year,address,bank_name,cvv FROM `nfw_user_card` where id = $card_id"; $carddata = resultAssociate($query); $payment_data = json_encode(end($carddata)); mysql_query(" insert into nfw_coupon (coupon_code,value,value_type,start_date,end_date) values('$coupon_code','$amount','Fixed','$start_date','$end_date')"); $last_id = mysql_insert_id(); mysql_query("insert into nfw_coupon_purchase (user_id,coupon_id,payment_method, payment_data,amount,op_date_time) value('$user_id','$last_id','$payment_method','$payment_data','$amount','$op_date_time')"); $coupon_last_id = mysql_insert_id(); $purchase_email = $userInfo[0]['email']; header('location:sendMail.php?mail_type=7&email=' . $purchase_email . '&couponpurchaseid=' . $coupon_last_id); } } $ids = $_SESSION['user_id']; $data = resultAssociate("SELECT np.id,nc.coupon_code,nc.end_date,np.amount, np.payment_method, np.payment_data FROM `nfw_coupon_purchase` as np join nfw_coupon as nc on np.coupon_id = nc.id where np.id not in(select nfw_purchase_id from nfw_coupon_sendgift) and np.user_id = $ids"); // print_r($data); #For delete address if (isset($_POST['deleteCart'])) { $deleteids = $_POST['deleteCart']; mysql_query("delete from nfw_coupon_purchase where id = $deleteids "); header("location:couponPurchase.php"); } if (isset($_POST['submitPop'])) { $nfw_purchase_id = $_POST['addID']; $email = $_POST['email']; $name = $_POST['name']; $checkuser = resultAssociate("select id from auth_user where email = '$email'"); if ($checkuser) { $checkuser11 = $checkuser[0]['id']; $coupon_id = resultAssociate("SELECT coupon_id FROM `nfw_coupon_purchase` where id = $nfw_purchase_id "); $coupon_id1 = $coupon_id[0]['coupon_id']; mysql_query("insert into nfw_coupon_sendgift (nfw_purchase_id,user_name,user_email,op_date_time,user_status) values('$nfw_purchase_id','$name','$email','$op_date_time','r') "); mysql_query("insert into nfw_coupon_sending_info (user_id,coupon_id,mail,subject,content,op_date_time) values('$checkuser11','$coupon_id1','$email','Coupon Information','','$op_date_time')"); ///// notification $message = "Congratulations!!! You have received gift<br/>Start Shoping now"; $baselink = 'http://' . $_SERVER['SERVER_NAME']; $baselinkmain = strpos($baselink, '192.168') ? $baselink . '/nf3/gitfrontend' : $baselink . '/frontend'; $page_link = $baselinkmain . '/views/storCredit.php'; $query = "insert into nfw_notification_user (title,message,user_id,status,page_link) values('Gift Received','$message','$checkuser11','0','$page_link')"; mysql_query($query); } else { mysql_query("insert into nfw_coupon_sendgift (nfw_purchase_id,user_name,user_email,op_date_time,user_status) values('$nfw_purchase_id','$name','$email','$op_date_time','ur') "); } header('location:sendMail.php?mail_type=5&email=' . $email . '&couponpurchaseid=' . $nfw_purchase_id . '&receiver_name=' . $name . '&sender_email=' . $userInfo[0]['email']); // header("location:couponPurchase.php"); } // insert card detail if (isset($_REQUEST['card_submit'])) { // print_r($_POST); $authobj->cardInfoInsertion($_SESSION['user_id'], $_POST); header("location: couponPurchase.php"); } ?> <style> .profile td{ border:none; } </style> <style> .datatable th{ border: none; border-bottom: 1px solid gainsboro; } .datatable td{ border: none; border-bottom: 1px solid gainsboro;; } .updateAddress td{ border: none; } .gift_detail td{ padding: 0px!important; border: none !important; font-size: 10px; } .gift_detail{ margin-bottom: 10px; } .payment_span{ box-sizing: border-box; width: 100%; background: #CECECE; /* height: 20px; */ float: left; color: #000000; padding: 6px; margin-bottom: 11px; } </style> <section class="page_title_2 bg_light_2 t_align_c relative wrapper" style=" padding-top: 15px; padding-bottom: 0px; box-shadow: 0px 3px 7px -1px #DBDADA;"> <div class="container"> <h3 style="color: #000 !important; font-weight: 300;text-transform: capitalize;">Welcome <?php echo $userInfo[0]['first_name']; ?></h3> <p style="color:black;margin-top: 10px;">Buy Gift Coupon</p> <div style="margin-top: 10px;"> </div> </div> </section> <div class="section_offset counter"> <div class="container"> <div class="row"> <aside class="col-lg-3 col-md-2 col-sm-2 m_bottom_50 m_xs_bottom_30" style=" margin-left: -40px;width:18%" > <?php include 'leftMenu.php'; ?> </aside> <div class="col-lg-9 col-md-9 col-sm-9 m_bottom_70 m_xs_bottom_30" style="width: 85%;"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="icon-user"></i> Client Code : <?php echo $userInfo[0]['registration_id'] ?></h3> </div> <div class="panel-body"> <div align=""> <form method="post" action="#"> <div class='col-md-12' style="" align="center"> <table class="profile" align="center" style="color:black"> <tr> <td> <span for="name" class="control-label" style="">Enter Amount &nbsp;&nbsp; US$</span> </td> <td> <input type="text" name="amount" class="form-control is_number" value="" style="height: 30px;width:50%;float:left;" required autocomplete="off"> </td> </tr> <tr> <td> <span for="name" class="control-label" style=""> Valid Till</span> </td> <td> <?php $temp = array_merge(range('A', 'Z'), range(0, 9)); $temp1 = ""; for ($i = 0; $i < 8; $i++) { $temp1 .= $temp[rand(0, (count($temp) - 1))]; } ?> 1 Year from date of purchase. <input type="hidden" name="coupon_code" class="form-control" value="<?php echo $temp1; ?>" style="height: 30px;width: 50%; margin-left: 8px;" readonly > </td> </tr> <tr> <td> <span for="name" class="control-label" style="">Payment Method</span> </td> <td> <span class="payment_span"> <i class="icon-credit-card"></i> Credit Card </span> <?php if ($card_detatil) { for ($k = 0; $k < count($card_detatil); $k++) { $info1 = $card_detatil[$k]; ?> <div class=""> <input type="radio" checked id="radio_6_<?php echo $k; ?>" name="card_id" class="d_none" value="<?php echo $info1['id'] ?>"> <label for="radio_6_<?php echo $k; ?>" class="d_inline_m m_right_15 m_bottom_3 fw_light"> <?php $dd = substr($info1['card_number'], -4); echo '************' . $dd . ' <b> Exp. month</b>' . ' ' . $info1['expiry_month'] . ' <b> Exp. year</b> ' . ' ' . $info1['expiry_year'] ?> </label> </div> <?php } } else { ?> <span style="color:red;margin-top: 17px;">CREDIT CARD DETAILS NOT FOUND! KINDLY ADD CREDIT CARD DETAILS <i class="icon-right-1"></i></span> <button type="button" class="btn btn-default " data-toggle="modal" data-target="#myCardModal" id=""><i class="icon-plus"></i> Add Card Detail</button> <?php } ?> </td> </tr> <!--paypal option--> <!-- <tr> <td></td> <td> <span class="payment_span"> <i class="icon-paypal"></i> PayPal</span> <input type="radio" checked id="radio_6_paypal" name="card_id" class="d_none" value="paypal"> <label for="radio_6_paypal" class="d_inline_m m_right_15 m_bottom_3 fw_light"> Pay using PayPal Account</label> </td> </tr>--> <tr> <td> </td> <td> <button type="submit" name="submitData" class="btn btn-default submit" > Pay Now </button> </td> </tr> </table> </div> </form> </div> </div> </div> <!-- ############################# --> <?php for ($i = 0; $i < count($data); $i++) { ?> <div class="col-md-3" style=""> <div class="thumbnail" style="height: 346px; border: 4px solid #DDD;"> <img src="../assets/images/gift.jpg" alt="" style=" border-bottom: 0px;"> <div class="caption" style="border-top: 0px;"> <h3 style=" color: #fff; background-color: #000; /* font-family: lato; */ font-weight: 300; font-size: 34px; padding: 9px 0px; text-align: center;"> <small style="line-height: 43px; color: #fff; font-size: 16px;">US$</small> <?php echo number_format($data[$i]['amount'], 2, '.', '') ?> </h3> <h3 style=" font-size: 27px; text-align: center; border-bottom: 1px solid #000; margin-bottom: 10px; font-weight: 300;" ><?php echo $data[$i]['coupon_code'] ?></h3> <center> <p style="font-size: 11px; margin-bottom: 10px;"> <table class="gift_detail"> <tr><td>Valid Till</td> <td>: <?php echo $data[$i]['end_date'] ?></td></tr> <tr><td>Purchased By</td> <td> : <?php $dd = $data[$i]['payment_method']; echo $dd; ?></td></tr> </table> </p> <div style=""> <a href="#" class="btn btn-default gift_id_get" role="button" data-toggle="modal" data-target="#givegift" gift_id ="<?php echo $data[$i]['id']; ?>" <i class="icon-gift"></i> Send Gift </a> <!-- <form method="post" class="pull-right"> <button class="btn btn-default" type="submit" name="deleteCart" value="<?php echo $data[$i]['id']; ?> " id="deleteid"> <i class="icon-trash"></i> </button> </form>--> </div> </center> </div> </div> </div> <?php } ?> </div> </div> </div> </div> <?php } include 'footer.php'; ?> <!-- Pop up for address upation --> <style> .close{ opacity: 1; color: white; } .modal-header{ padding: 3px 19px; background: black; } </style> <div class="modal fade" id="myCardModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content" style=""> <div class="modal-header" style="color: white"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <p class="modal-title" id="myModalLabel"> <i class="icon-edit"></i> Fill Card Detail </p> </div> <form class="form-horizontal" role="form" method="post" action="#"> <div class="modal-body" style="margin-right: -36%;"> <fieldset> <div class="form-group"> <label class="col-sm-3 control-label" for="card-holder-name">Name on Card</label> <div class="col-sm-4"> <input type="text" class="form-control" name="card-holder-name" id="card-holder-name" placeholder="Name on Card" > </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="card-number">Card Number</label> <div class="col-sm-4"> <input type="text" class="form-control is_number" name="card-number" id="card-number" placeholder="Credit Card Number"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="expiry-month">Expiration Date</label> <div class="col-sm-9"> <div class="row"> <div class="col-xs-3" style="width:135px"> <select class="form-control col-sm-3" name="expiry-month" id="expiry-month"> <option>Month</option> <option value="01">Jan (01)</option> <option value="02">Feb (02)</option> <option value="03">Mar (03)</option> <option value="04">Apr (04)</option> <option value="05">May (05)</option> <option value="06">June (06)</option> <option value="07">July (07)</option> <option value="08">Aug (08)</option> <option value="09">Sep (09)</option> <option value="10">Oct (10)</option> <option value="11">Nov (11)</option> <option value="12">Dec (12)</option> </select> </div> <div class="col-xs-3" style="width:135px"> <select class="form-control isNumber" name="expiry-year"> <?php for ($i = 2015; $i < 2040; $i++) { ?> <option value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php } ?> </select> </div> </div> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="cvv">Bank Name</label> <div class="col-xs-4"> <input type="text" class="form-control" name="bank_name" id="address" placeholder="Bank Name" style="" > </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="cvv">Address</label> <div class="col-xs-4"> <input type="text" class="form-control" name="address" id="address" placeholder="Address" style="" > </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="cvv">CVV</label> <div class="col-sm-3"> <input type="text" class="form-control is_number" name="cvv" id="cvv" placeholder="Code" min="3" max="3" style="width:45%" > </div> </div> </fieldset> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default btn-xs" name="card_submit" value="cc" style=""> <i class="icon-check"></i> Submit </button> </div> </form> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <style> table td, table th { border: none !important; } </style> <div class="modal fade" id="givegift"> <div class="modal-dialog"> <div class="modal-content" style="width:60%;margin-left: 16%;"> <div class="modal-header" style="color: white"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <p class="modal-title" id="myModalLabel"> <i class="icon-pencil"></i> Enter detail of gift receiver </p> </div> <form method="post" action="#"> <div class="modal-body"> <table class="" style=" width: 100%;"> <tr> <td style="line-height: 25px;"> <span><b>Recipient’s Name</b></span> <input type="text" name="name" class="form-control" placeholder="Name" style="" autocomplete="off" required> </td> </tr> <tr> <td style="line-height: 25px;"> <span><b>Recipient’s Email</b></span> <input type="email" name="email" class="form-control" placeholder="Email" style="" autocomplete="off" required> </td> </tr> </table> <input type="hidden" name="addID" value=""> </div> <div class="modal-footer" style=" padding: 15px 35px;"> <button type="submit" class="btn btn-default btn-xs pull-left" name="submitPop" value="cfgc" style=""> <i class="icon-check"></i> Submit </button> </div> </form> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <script> $(function () { $(".gift_id_get").click(function () { var ids = $(this).attr('gift_id'); $("input[name='addID']").val(ids); }); }); </script> <script> function myFunction() { var txt; var r = confirm("Are you sure!"); if (r == true) { } else { $('#deleteid').attr('name', 'test'); } } </script>
fee12889f0add0b1b9382576e5d11370f88682dd
{ "blob_id": "fee12889f0add0b1b9382576e5d11370f88682dd", "branch_name": "refs/heads/master", "committer_date": "2022-05-18T13:14:07", "content_id": "6916845e0517a63337e31f8bb5e69c31fe78e1e2", "detected_licenses": [ "MIT" ], "directory_id": "6e55971906dd6eb4541082e462245c0b5329d8cf", "extension": "php", "filename": "couponPurchase.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 243523873, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 25846, "license": "MIT", "license_type": "permissive", "path": "/views/couponPurchase.php", "provenance": "stack-edu-0050.json.gz:41693", "repo_name": "octopuscart/nfemail", "revision_date": "2022-05-18T13:14:07", "revision_id": "0d4d2182770bed684bf5f59e4488caf2a8ec0e93", "snapshot_id": "782bf94fae716477c7193a165f86b4ed54e69406", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/octopuscart/nfemail/0d4d2182770bed684bf5f59e4488caf2a8ec0e93/views/couponPurchase.php", "visit_date": "2022-05-29T07:37:52.348713", "added": "2024-11-19T00:19:45.008435+00:00", "created": "2022-05-18T13:14:07", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
// Code generated by counterfeiter. DO NOT EDIT. package fakes import ( "net" "sync" ) type DeviceNameGenerator struct { GenerateForHostStub func(containerIP net.IP) (string, error) generateForHostMutex sync.RWMutex generateForHostArgsForCall []struct { containerIP net.IP } generateForHostReturns struct { result1 string result2 error } generateForHostReturnsOnCall map[int]struct { result1 string result2 error } GenerateTemporaryForContainerStub func(containerIP net.IP) (string, error) generateTemporaryForContainerMutex sync.RWMutex generateTemporaryForContainerArgsForCall []struct { containerIP net.IP } generateTemporaryForContainerReturns struct { result1 string result2 error } generateTemporaryForContainerReturnsOnCall map[int]struct { result1 string result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *DeviceNameGenerator) GenerateForHost(containerIP net.IP) (string, error) { fake.generateForHostMutex.Lock() ret, specificReturn := fake.generateForHostReturnsOnCall[len(fake.generateForHostArgsForCall)] fake.generateForHostArgsForCall = append(fake.generateForHostArgsForCall, struct { containerIP net.IP }{containerIP}) fake.recordInvocation("GenerateForHost", []interface{}{containerIP}) fake.generateForHostMutex.Unlock() if fake.GenerateForHostStub != nil { return fake.GenerateForHostStub(containerIP) } if specificReturn { return ret.result1, ret.result2 } return fake.generateForHostReturns.result1, fake.generateForHostReturns.result2 } func (fake *DeviceNameGenerator) GenerateForHostCallCount() int { fake.generateForHostMutex.RLock() defer fake.generateForHostMutex.RUnlock() return len(fake.generateForHostArgsForCall) } func (fake *DeviceNameGenerator) GenerateForHostArgsForCall(i int) net.IP { fake.generateForHostMutex.RLock() defer fake.generateForHostMutex.RUnlock() return fake.generateForHostArgsForCall[i].containerIP } func (fake *DeviceNameGenerator) GenerateForHostReturns(result1 string, result2 error) { fake.GenerateForHostStub = nil fake.generateForHostReturns = struct { result1 string result2 error }{result1, result2} } func (fake *DeviceNameGenerator) GenerateForHostReturnsOnCall(i int, result1 string, result2 error) { fake.GenerateForHostStub = nil if fake.generateForHostReturnsOnCall == nil { fake.generateForHostReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.generateForHostReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *DeviceNameGenerator) GenerateTemporaryForContainer(containerIP net.IP) (string, error) { fake.generateTemporaryForContainerMutex.Lock() ret, specificReturn := fake.generateTemporaryForContainerReturnsOnCall[len(fake.generateTemporaryForContainerArgsForCall)] fake.generateTemporaryForContainerArgsForCall = append(fake.generateTemporaryForContainerArgsForCall, struct { containerIP net.IP }{containerIP}) fake.recordInvocation("GenerateTemporaryForContainer", []interface{}{containerIP}) fake.generateTemporaryForContainerMutex.Unlock() if fake.GenerateTemporaryForContainerStub != nil { return fake.GenerateTemporaryForContainerStub(containerIP) } if specificReturn { return ret.result1, ret.result2 } return fake.generateTemporaryForContainerReturns.result1, fake.generateTemporaryForContainerReturns.result2 } func (fake *DeviceNameGenerator) GenerateTemporaryForContainerCallCount() int { fake.generateTemporaryForContainerMutex.RLock() defer fake.generateTemporaryForContainerMutex.RUnlock() return len(fake.generateTemporaryForContainerArgsForCall) } func (fake *DeviceNameGenerator) GenerateTemporaryForContainerArgsForCall(i int) net.IP { fake.generateTemporaryForContainerMutex.RLock() defer fake.generateTemporaryForContainerMutex.RUnlock() return fake.generateTemporaryForContainerArgsForCall[i].containerIP } func (fake *DeviceNameGenerator) GenerateTemporaryForContainerReturns(result1 string, result2 error) { fake.GenerateTemporaryForContainerStub = nil fake.generateTemporaryForContainerReturns = struct { result1 string result2 error }{result1, result2} } func (fake *DeviceNameGenerator) GenerateTemporaryForContainerReturnsOnCall(i int, result1 string, result2 error) { fake.GenerateTemporaryForContainerStub = nil if fake.generateTemporaryForContainerReturnsOnCall == nil { fake.generateTemporaryForContainerReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.generateTemporaryForContainerReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *DeviceNameGenerator) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.generateForHostMutex.RLock() defer fake.generateForHostMutex.RUnlock() fake.generateTemporaryForContainerMutex.RLock() defer fake.generateTemporaryForContainerMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *DeviceNameGenerator) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) }
db5145c9c2dca9bf811d06a6bf0273ba99a179a1
{ "blob_id": "db5145c9c2dca9bf811d06a6bf0273ba99a179a1", "branch_name": "refs/heads/main", "committer_date": "2023-08-03T13:08:42", "content_id": "2c57012294ef231cad2287bfea2a64609c8228ca", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ed077bafa0d69f4d750187ec34f6900cab17efa7", "extension": "go", "filename": "deviceNameGenerator.go", "fork_events_count": 10, "gha_created_at": "2017-03-07T19:27:16", "gha_event_created_at": "2023-08-03T13:08:44", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 84237647, "is_generated": true, "is_vendor": false, "language": "Go", "length_bytes": 5560, "license": "Apache-2.0", "license_type": "permissive", "path": "/cni/config/fakes/deviceNameGenerator.go", "provenance": "stack-edu-0016.json.gz:364212", "repo_name": "cloudfoundry/silk", "revision_date": "2023-08-03T13:08:42", "revision_id": "dd9aec0ef0927c12b0281b877e4ca66b93416a4b", "snapshot_id": "6eddbb3390e255f7c31ed3e3ee1c39301e4e9630", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/cloudfoundry/silk/dd9aec0ef0927c12b0281b877e4ca66b93416a4b/cni/config/fakes/deviceNameGenerator.go", "visit_date": "2023-08-22T01:49:04.920691", "added": "2024-11-18T19:33:43.401692+00:00", "created": "2023-08-03T13:08:42", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
function getWeight(name){ // return 97 - 65// name[0].charCodeAt() let lettersOnly = name.replace(/[^a-zA-Z]/gi,"") return lettersOnly.split("").reduce((acc,curr,idx) => { if (curr.toUpperCase() === curr ) acc += curr.charCodeAt() + 32; else acc += curr.charCodeAt() - 32; return acc; },0); // return lettersOnly; } console.log( getWeight("Joe"),//254); getWeight("CJ"),//205); getWeight("cj"),//141); )
d3ec23ec3d0f35f582c0e6660167629b4b76d948
{ "blob_id": "d3ec23ec3d0f35f582c0e6660167629b4b76d948", "branch_name": "refs/heads/main", "committer_date": "2021-09-18T16:21:48", "content_id": "d968a78302222c9ae62a24fa6c7dfc5bbf504d56", "detected_licenses": [ "MIT" ], "directory_id": "29c8c9d908da84ab90cfaec70ebcffaab94e182d", "extension": "js", "filename": "disagreeableASCII.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 345016881, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 468, "license": "MIT", "license_type": "permissive", "path": "/Mar2021/disagreeableASCII.js", "provenance": "stack-edu-0032.json.gz:529119", "repo_name": "rafiq/codeWars", "revision_date": "2021-09-18T16:21:48", "revision_id": "b2c040005c0c29c86f6329bbcc663c2337c79668", "snapshot_id": "ff662d894b1d3ca747536139facee286936ab613", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rafiq/codeWars/b2c040005c0c29c86f6329bbcc663c2337c79668/Mar2021/disagreeableASCII.js", "visit_date": "2023-08-10T17:03:36.977696", "added": "2024-11-18T20:43:16.334020+00:00", "created": "2021-09-18T16:21:48", "int_score": 3, "score": 3.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
# Portable NIC Architecture The contents of this repository are a work in progress, intended to lead towards a published Portable NIC Architecture specification published by P4.org. ## Setup instructions See the [README](https://github.com/p4lang/p4-spec/blob/master/p4-16/spec/README.md) for the P4_16 language specification for instructions on installing software that enables you to produce HTML and PDF versions of the PNA specification from its Madoko source file. ## Spec release process Note: The following instructions were copied from the corresponding README of the Portable Switch Architecture specification, and may need some modifications when we reach the point of releasing a PNA specification. - increment version number in the document and commit - merge to master and tag the commit with pna-version (e.g. pna-v0.9) - generate the PDF and HTML - checkout the gh-pages branch and copy to <root>/docs as PNA-<version>.[html,pdf] - update links in <root>/index.html - add files, commit and push the gh-pages branch - checkout master, change the Title note to (working draft), commit and push Someday we may write a script to do this.
03a6bd65c6d88e49782a79b70b45db3b743ff4da
{ "blob_id": "03a6bd65c6d88e49782a79b70b45db3b743ff4da", "branch_name": "refs/heads/main", "committer_date": "2021-09-27T16:43:18", "content_id": "d54a716e0f3f8338b28fb849d39fdf6b737a36e1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "96e56e7120f31d1365b82a4e55cc66c6e7f8e751", "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": 1158, "license": "Apache-2.0", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0011.json.gz:147175", "repo_name": "pastorsong/pna", "revision_date": "2021-09-27T16:43:18", "revision_id": "b0ee29cfd2bdbc051e2c1172e9ccacd1481ac892", "snapshot_id": "a919deeffef579079be7254433a0f83a6f77b128", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pastorsong/pna/b0ee29cfd2bdbc051e2c1172e9ccacd1481ac892/README.md", "visit_date": "2023-08-26T18:58:31.168611", "added": "2024-11-19T02:06:44.342017+00:00", "created": "2021-09-27T16:43:18", "int_score": 3, "score": 3.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0011.json.gz" }
using System; using System.Collections.Generic; using UnityEngine; namespace PropHunt.Environment.Sound { /// <summary> /// Library file that contains sets of sound effects /// </summary> [CreateAssetMenu(fileName = "SFXLibrary", menuName = "ScriptableObjects/SpawnSFXLibraryScriptableObject", order = 1)] public class SoundEffectLibrary : ScriptableObject { /// <summary> /// Sets of labeled sounds that can be played from this library /// </summary> [SerializeField] public LabeledSFX[] sounds; /// <summary> /// Has the library been initialized /// </summary> private bool initialized = false; /// <summary> /// Lookup table for sounds effects by sound material /// </summary> private Dictionary<SoundMaterial, List<LabeledSFX>> soundMaterialLookup = new Dictionary<SoundMaterial, List<LabeledSFX>>(); /// <summary> /// Lookup table for sound effects by sound type /// </summary> private Dictionary<SoundType, List<LabeledSFX>> soundTypeLookup = new Dictionary<SoundType, List<LabeledSFX>>(); /// <summary> /// Lookup table for sounds by material and type /// </summary> /// <returns></returns> private Dictionary<Tuple<SoundMaterial, SoundType>, List<LabeledSFX>> soundMaterialTypeLookup = new Dictionary<Tuple<SoundMaterial, SoundType>, List<LabeledSFX>>(); /// <summary> /// Lookup table for sound effect by ID /// </summary> private Dictionary<string, LabeledSFX> soundIdLookup = new Dictionary<string, LabeledSFX>(); /// <summary> /// Resets the lookup tables for this sound effect library /// </summary> public void ClearLookups() { initialized = false; soundMaterialLookup.Clear(); soundTypeLookup.Clear(); soundMaterialTypeLookup.Clear(); soundIdLookup.Clear(); } /// <summary> /// Verifies that lookup tables exist. If they do not, they will be created /// </summary> public void VerifyLookups() { if (!initialized) { ClearLookups(); SetupLookups(); } } /// <summary> /// Creates lookup tables based on set of saved sound effects /// </summary> public void SetupLookups() { foreach (LabeledSFX labeled in sounds) { labeled.audioClip.LoadAudioData(); Tuple<SoundMaterial, SoundType> tupleKey = new Tuple<SoundMaterial, SoundType>(labeled.soundMaterial, labeled.soundType); if (!soundMaterialLookup.ContainsKey(labeled.soundMaterial)) { soundMaterialLookup[labeled.soundMaterial] = new List<LabeledSFX>(); } if (!soundTypeLookup.ContainsKey(labeled.soundType)) { soundTypeLookup[labeled.soundType] = new List<LabeledSFX>(); } if (!soundMaterialTypeLookup.ContainsKey(tupleKey)) { soundMaterialTypeLookup[tupleKey] = new List<LabeledSFX>(); } soundMaterialLookup[labeled.soundMaterial].Add(labeled); soundTypeLookup[labeled.soundType].Add(labeled); soundMaterialTypeLookup[tupleKey].Add(labeled); soundIdLookup[labeled.soundId] = labeled; } initialized = true; } /// <summary> /// Get a random sound effect by material /// </summary> /// <param name="soundMaterial">Sound material to filter by</param> /// <returns>A labeled sound effect that has the given sound material</returns> public LabeledSFX GetSFXClipBySoundMaterial(SoundMaterial soundMaterial) { List<LabeledSFX> sounds = soundMaterialLookup[soundMaterial]; return sounds[(int)UnityEngine.Random.Range(0, sounds.Count)]; } /// <summary> /// Gets a random sound effect clip by type of sound /// </summary> /// <param name="soundType">Lookup based on this sound type</param> /// <returns>A labeled sound effect that has the given sound type</returns> public LabeledSFX GetSFXClipBySoundType(SoundType soundType) { List<LabeledSFX> sounds = soundTypeLookup[soundType]; return sounds[(int)UnityEngine.Random.Range(0, sounds.Count)]; } /// <summary> /// Gets a sound effect clip by material and type /// </summary> /// <param name="soundMaterial">Sound material to filter search</param> /// <param name="soundType">Sound type to filter search</param> /// <returns>A labeled sound effect that has the given sound and material types</returns> public LabeledSFX GetSFXClipBySoundMaterialAndType(SoundMaterial soundMaterial, SoundType soundType) { List<LabeledSFX> sounds = soundMaterialTypeLookup[new Tuple<SoundMaterial, SoundType>(soundMaterial, soundType)]; return sounds[(int)UnityEngine.Random.Range(0, sounds.Count)]; } /// <summary> /// Gests a sound effect clip by a given id /// </summary> /// <param name="soundId">identifier name to lookup the sound by</param> /// <returns>The labeled sound effect with a given id</returns> public LabeledSFX GetSFXClipById(string soundId) { return soundIdLookup[soundId]; } /// <summary> /// Does this library contain any sound effects for a given material? /// </summary> /// <param name="soundMaterial">Sound material to lookup</param> /// <returns>True if any sound effects have this material, false otherwise</returns> public bool HasSoundEffect(SoundMaterial soundMaterial) { return soundMaterialLookup.ContainsKey(soundMaterial) && soundMaterialLookup[soundMaterial].Count > 0; } /// <summary> /// Does this library contain any sound effects for a given sound type /// </summary> /// <param name="soundType">Sound type to lookup</param> /// <returns>True if any sound effects have this type, false otherwise</returns> public bool HasSoundEffect(SoundType soundType) { return soundTypeLookup.ContainsKey(soundType) && soundTypeLookup[soundType].Count > 0; } /// <summary> /// Does this library contain any sound effects for a given sound material and type /// </summary> /// <param name="soundType">Sound type to lookup</param> /// <param name="soundMaterial">Sound material to lookup</param> /// <returns>True if any sound effects have this material and type, false otherwise</returns> public bool HasSoundEffect(SoundMaterial soundMaterial, SoundType soundType) { return soundMaterialTypeLookup.ContainsKey(new Tuple<SoundMaterial, SoundType>(soundMaterial, soundType)) && soundMaterialTypeLookup[new Tuple<SoundMaterial, SoundType>(soundMaterial, soundType)].Count > 0; } /// <summary> /// Does this library contain a sound effect with a given id /// </summary> /// <param name="soundId">Sound id to lookup</param> /// <returns>True if there is a sound effect with this id, false otherwise</returns> public bool HasSoundEffect(string soundId) { return soundIdLookup.ContainsKey(soundId); } } /// <summary> /// Various kinds of sound materials for labeling sound effects /// </summary> public enum SoundMaterial { Glass, Wood, Metal, Concrete, Water, Misc } /// <summary> /// Various types of sound for labeling sound effects /// </summary> public enum SoundType { Hit, Break, Scrape, Roll, Footstep, Misc, PropTransformation, Attack, Death, Checkpoint, } /// <summary> /// Labeled sound effect for categorizing and seraching sounds /// </summary> [System.Serializable] public class LabeledSFX { /// <summary> /// Type of material this sound is made by /// </summary> public SoundMaterial soundMaterial; /// <summary> /// The type of sound effect made in this clip /// </summary> public SoundType soundType; /// <summary> /// Sound effect audio clip related to this sound effect /// </summary> public AudioClip audioClip; /// <summary> /// unique identifier for this labeled sound effect /// </summary> public string soundId; } }
831267dc1fb302c15cd89e9c30a68e7de7705be1
{ "blob_id": "831267dc1fb302c15cd89e9c30a68e7de7705be1", "branch_name": "refs/heads/main", "committer_date": "2021-10-02T07:05:43", "content_id": "073401bbf657d5e44fbfc0fbbbc9995984fed24e", "detected_licenses": [ "MIT" ], "directory_id": "6561c54f95e23d19fb9b0f1438ae13dca39982eb", "extension": "cs", "filename": "SoundEffectLibrary.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9078, "license": "MIT", "license_type": "permissive", "path": "/Assets/Scripts/Environment/Sound/SoundEffectLibrary.cs", "provenance": "stack-edu-0010.json.gz:92458", "repo_name": "MackeyK24/FallingParkour", "revision_date": "2021-10-02T07:05:43", "revision_id": "fec464d3aa74aff78806dd9eb95f3cee254378c4", "snapshot_id": "8ac6ec7cb996af7b3eec4e7c4cc486a229d37b22", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MackeyK24/FallingParkour/fec464d3aa74aff78806dd9eb95f3cee254378c4/Assets/Scripts/Environment/Sound/SoundEffectLibrary.cs", "visit_date": "2023-08-16T14:05:37.004476", "added": "2024-11-18T21:04:13.902227+00:00", "created": "2021-10-02T07:05:43", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Adapter.Sample { public class ClassManager { public List<Student> students; public ClassManager() { students = new List<Student>(); this.students.Add(new Student(1, "Spyua")); this.students.Add(new Student(2, "Tom")); this.students.Add(new Student(3, "Mary")); } // Output with XmlformatSystem.InvalidOperationException: 'Adapter.Sample.Student cannot be serialized because it does not have a parameterless public virtual string GetAllStudents() { var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); var serializer = new XmlSerializer(students.GetType()); var settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; using (var stream = new StringWriter()) using (var writer = XmlWriter.Create(stream, settings)) { serializer.Serialize(writer, students, emptyNamepsaces); return stream.ToString(); } } } }
ee931539cca2bd99559c23f2eafa0fce19830fb2
{ "blob_id": "ee931539cca2bd99559c23f2eafa0fce19830fb2", "branch_name": "refs/heads/main", "committer_date": "2021-03-12T05:14:41", "content_id": "03ccce6cfa7e6646f231af0834812e77016f9aa3", "detected_licenses": [ "MIT" ], "directory_id": "6215f6dd5a5c87620ea7ab5c4dc26ac614666a52", "extension": "cs", "filename": "ClassManager.cs", "fork_events_count": 3, "gha_created_at": "2021-02-18T03:24:20", "gha_event_created_at": "2021-03-12T05:14:42", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 339924193, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1248, "license": "MIT", "license_type": "permissive", "path": "/Adapter/SimpleSample/ClassManager.cs", "provenance": "stack-edu-0013.json.gz:859750", "repo_name": "codesensegroup/DesignPatternWithCSharp", "revision_date": "2021-03-12T05:14:41", "revision_id": "fa5863d2c1243c46c47e8e263b496958135b5f98", "snapshot_id": "79dc32d2286523ae433d3d2bfbdbade943bf0ce8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/codesensegroup/DesignPatternWithCSharp/fa5863d2c1243c46c47e8e263b496958135b5f98/Adapter/SimpleSample/ClassManager.cs", "visit_date": "2023-03-16T19:03:46.514073", "added": "2024-11-18T21:53:47.923434+00:00", "created": "2021-03-12T05:14:41", "int_score": 3, "score": 3.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
import java.io.FileInputStream; import java.util.Date; import net.reliableresponse.notification.broker.BrokerFactory; import net.reliableresponse.notification.usermgmt.OnCallGroup; import net.reliableresponse.notification.usermgmt.OnCallSchedule; /* * Created on Apr 10, 2006 * *Copyright Reliable Response, 2006 */ public class AddOnCallGroup { /** * @param args */ public static void main(String[] args) throws Exception{ BrokerFactory.getConfigurationBroker().setConfiguration( new FileInputStream("conf/reliable.properties")); OnCallGroup group = new OnCallGroup(); group.setAutocommit(false); group.setGroupName("Test OnCallGroup"); group.addMember(BrokerFactory.getUserMgmtBroker().getUserByUuid("0000001"), -1); BrokerFactory.getGroupMgmtBroker().addGroup(group); OnCallSchedule schedule = new OnCallSchedule(); schedule.setRepetition(OnCallSchedule.REPEAT_DAILY); schedule.setAllDay(false); schedule.setFromDate(new Date()); schedule.setToDate(new Date()); group.setOnCallSchedule(schedule, 0); } }
38e8512ecd7db5b802701e2460e318d59f48f9b3
{ "blob_id": "38e8512ecd7db5b802701e2460e318d59f48f9b3", "branch_name": "refs/heads/master", "committer_date": "2014-12-08T14:05:12", "content_id": "3da550bbd7e91104c5cfbcaec28d56bc51c4db7e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "387673ac83c652d837e723b48204bdd22e6e3128", "extension": "java", "filename": "AddOnCallGroup.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": 1058, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/AddOnCallGroup.java", "provenance": "stack-edu-0029.json.gz:817508", "repo_name": "shijir38/OpenNotification", "revision_date": "2014-12-08T14:05:12", "revision_id": "26460a566886277b3ae14189e172473720f58cb1", "snapshot_id": "22e5910fb5f20619e313d8130ee8394c4a2765a6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shijir38/OpenNotification/26460a566886277b3ae14189e172473720f58cb1/src/AddOnCallGroup.java", "visit_date": "2021-01-19T17:10:31.909524", "added": "2024-11-18T21:37:40.698542+00:00", "created": "2014-12-08T14:05:12", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz" }
///<reference path="testReference.ts" /> var assert = chai.assert; describe("Axes", () => { it("Renders ticks", () => { var svg = generateSVG(500, 100); var xScale = new Plottable.LinearScale(); xScale.domain([0, 10]); xScale.range([0, 500]); var axis = new Plottable.XAxis(xScale, "bottom"); axis.renderTo(svg); var ticks = svg.selectAll(".tick"); assert.operator(ticks[0].length, ">=", 2, "There are at least two ticks."); svg.remove(); }); it("XAxis positions tick labels correctly", () => { var svg = generateSVG(500, 100); var xScale = new Plottable.LinearScale(); xScale.domain([0, 10]); xScale.range([0, 500]); var xAxis = new Plottable.XAxis(xScale, "bottom"); xAxis.renderTo(svg); var tickMarks = xAxis.axisElement.selectAll(".tick").select("line")[0]; var tickLabels = xAxis.axisElement.selectAll(".tick").select("text")[0]; for (var i=0; i< tickMarks.length; i++) { var markRect = tickMarks[i].getBoundingClientRect(); var labelRect = tickLabels[i].getBoundingClientRect(); assert.isTrue( (labelRect.left <= markRect.left && markRect.right <= labelRect.right), "tick label position defaults to centered"); } xAxis.tickLabelPosition("left"); xAxis._render(); tickMarks = xAxis.axisElement.selectAll(".tick").select("line")[0]; tickLabels = xAxis.axisElement.selectAll(".tick").select("text")[0]; for (i=0; i< tickMarks.length; i++) { markRect = tickMarks[i].getBoundingClientRect(); labelRect = tickLabels[i].getBoundingClientRect(); assert.operator(labelRect.right, "<=", markRect.left, "tick label is to the left of the mark"); } xAxis.tickLabelPosition("right"); xAxis._render(); tickMarks = xAxis.axisElement.selectAll(".tick").select("line")[0]; tickLabels = xAxis.axisElement.selectAll(".tick").select("text")[0]; for (i=0; i< tickMarks.length; i++) { markRect = tickMarks[i].getBoundingClientRect(); labelRect = tickLabels[i].getBoundingClientRect(); assert.operator(markRect.right, "<=", labelRect.left, "tick label is to the right of the mark"); } svg.remove(); }); it("YAxis positions tick labels correctly", () => { var svg = generateSVG(100, 500); var yScale = new Plottable.LinearScale(); yScale.domain([0, 10]); yScale.range([500, 0]); var yAxis = new Plottable.YAxis(yScale, "left"); yAxis.renderTo(svg); var tickMarks = yAxis.axisElement.selectAll(".tick").select("line")[0]; var tickLabels = yAxis.axisElement.selectAll(".tick").select("text")[0]; for (var i=0; i< tickMarks.length; i++) { var markRect = tickMarks[i].getBoundingClientRect(); var labelRect = tickLabels[i].getBoundingClientRect(); assert.isTrue( (labelRect.top <= markRect.top && markRect.bottom <= labelRect.bottom), "tick label position defaults to middle"); } yAxis.tickLabelPosition("top"); yAxis._render(); tickMarks = yAxis.axisElement.selectAll(".tick").select("line")[0]; tickLabels = yAxis.axisElement.selectAll(".tick").select("text")[0]; for (i=0; i< tickMarks.length; i++) { markRect = tickMarks[i].getBoundingClientRect(); labelRect = tickLabels[i].getBoundingClientRect(); assert.operator(labelRect.bottom, "<=", markRect.top + 1, "tick label above the mark"); // +1 for off-by-one on some browsers } yAxis.tickLabelPosition("bottom"); yAxis._render(); tickMarks = yAxis.axisElement.selectAll(".tick").select("line")[0]; tickLabels = yAxis.axisElement.selectAll(".tick").select("text")[0]; for (i=0; i< tickMarks.length; i++) { markRect = tickMarks[i].getBoundingClientRect(); labelRect = tickLabels[i].getBoundingClientRect(); assert.operator(markRect.bottom, "<=", labelRect.top, "tick label is below the mark"); } svg.remove(); }); });
812d8e30d716bc17edd4acc1055924d67f451a2e
{ "blob_id": "812d8e30d716bc17edd4acc1055924d67f451a2e", "branch_name": "refs/heads/master", "committer_date": "2014-04-08T03:05:15", "content_id": "b763ff31c6971e1c141c63924638eeab2312a1f2", "detected_licenses": [ "MIT" ], "directory_id": "45929eb6d664682b9827de231d3623ec085bc985", "extension": "ts", "filename": "axisTests.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": 3919, "license": "MIT", "license_type": "permissive", "path": "/test/axisTests.ts", "provenance": "stack-edu-0076.json.gz:132640", "repo_name": "thelastnode/plottable", "revision_date": "2014-04-08T03:05:15", "revision_id": "1618b6695c153cf8d94aae6d10ecbc59bb66e1bb", "snapshot_id": "21c7529d03aceabeed1ddf45badefec8a94de4bf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thelastnode/plottable/1618b6695c153cf8d94aae6d10ecbc59bb66e1bb/test/axisTests.ts", "visit_date": "2021-01-19T06:32:07.266531", "added": "2024-11-18T18:09:00.623963+00:00", "created": "2014-04-08T03:05:15", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz" }
/* * oSPARC - The SIMCORE frontend - https://osparc.io * Copyright: 2020 IT'IS Foundation - https://itis.swiss * License: MIT - https://opensource.org/licenses/MIT * Authors: Odei Maiz (odeimaiz) */ /** * Switch button for controlling the theme */ qx.Class.define("osparc.ui.switch.ThemeSwitcher", { extend: osparc.ui.basic.Switch, construct: function() { this.base(arguments); const validThemes = this.__validThemes = Object.values(qx.Theme.getAll()).filter(theme => theme.type === "meta"); if (validThemes.length !== 2) { this.setVisibility("excluded"); return; } this.set({ checked: qx.theme.manager.Meta.getInstance().getTheme().name === validThemes[1].name, toolTipText: this.tr("Switch theme") }); this.addListener("changeChecked", () => { this.__switchTheme(); }); }, members: { __validThemes: null, __switchTheme: function() { if (this.__validThemes.length !== 2) { return; } const currentTheme = qx.theme.manager.Meta.getInstance().getTheme(); const idx = this.__validThemes.findIndex(validTheme => validTheme.name === currentTheme.name); if (idx !== -1) { const theme = this.__validThemes[1-idx]; qx.theme.manager.Meta.getInstance().setTheme(theme); window.localStorage.setItem("themeName", theme.name); } } } });
cea7bea46630e9bae999d5054a9a25f8c0901d12
{ "blob_id": "cea7bea46630e9bae999d5054a9a25f8c0901d12", "branch_name": "refs/heads/master", "committer_date": "2021-10-04T17:18:39", "content_id": "f754d5d62d7493388d22880e2c0483de14d2fc99", "detected_licenses": [ "MIT" ], "directory_id": "4e42d7cc5f49e07deda57fbd171ea38dac49af07", "extension": "js", "filename": "ThemeSwitcher.js", "fork_events_count": 0, "gha_created_at": "2019-11-06T16:31:07", "gha_event_created_at": "2023-01-09T15:04:13", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 220041993, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1392, "license": "MIT", "license_type": "permissive", "path": "/services/web/client/source/class/osparc/ui/switch/ThemeSwitcher.js", "provenance": "stack-edu-0042.json.gz:508162", "repo_name": "Surfict/osparc-simcore", "revision_date": "2021-10-04T17:18:39", "revision_id": "1e0b89574ec17ecb089674f9e5daa83d624430c8", "snapshot_id": "5a8635a0c7380ffbfd28bc7b32a97ec9ab7f1613", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Surfict/osparc-simcore/1e0b89574ec17ecb089674f9e5daa83d624430c8/services/web/client/source/class/osparc/ui/switch/ThemeSwitcher.js", "visit_date": "2023-01-20T19:15:45.062059", "added": "2024-11-19T02:08:15.821482+00:00", "created": "2021-10-04T17:18:39", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz" }
#include "Sail.h" #include "Input.h" #include <iostream> #define PI 3.14159265358979323846 Sail::Sail() { SailDown = new aie::Texture("./textures/Sail_Folded.png"); SailUp = new aie::Texture("./textures/Sail_Open.png"); CurrentTexture = new aie::Texture("./textures/Sail_Folded.png"); cannon = new Cannon(); setChild(cannon); cannon->setParent(this); rotSpeed = 1.2f; CanChange = false; } Sail::~Sail() { delete cannon; delete SailDown; delete SailUp; delete CurrentTexture; } void Sail::draw(aie::Renderer2D* m_2dRenderer) { cannon->draw(m_2dRenderer); m_2dRenderer->drawSpriteTransformed3x3(CurrentTexture, global_Transform, 0, 0, -0.95); } void Sail::update(float deltaTime) { aie::Input* input = aie::Input::getInstance(); float rot = 0; Matrix3 tempRot; if (input->isKeyDown(aie::INPUT_KEY_Q)) rot = rotSpeed * deltaTime; if (input->isKeyDown(aie::INPUT_KEY_E)) rot -= rotSpeed * deltaTime; tempRot.setRotateZ(rot); local_Transform = local_Transform * tempRot; cannon->update(deltaTime); updateGlobalTransform(); }
84c4d7d32587b22920d551afd092181aa332e2f7
{ "blob_id": "84c4d7d32587b22920d551afd092181aa332e2f7", "branch_name": "refs/heads/master", "committer_date": "2017-05-15T22:57:29", "content_id": "704044b7d7fe59ef86a5f1ba7b2c5626ca4a4229", "detected_licenses": [ "MIT" ], "directory_id": "1ac50a3c9ed746076623c47637def95011aa043a", "extension": "cpp", "filename": "Sail.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 91280457, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1112, "license": "MIT", "license_type": "permissive", "path": "/Game/project2D/Sail.cpp", "provenance": "stack-edu-0005.json.gz:393300", "repo_name": "Hypro123/EDMathDemonstration", "revision_date": "2017-05-15T22:57:29", "revision_id": "77065d6034fd45ea6b0119b6d059c3f76313b316", "snapshot_id": "d9dd27d4829cc0311e283bffbc5cb6323835ffab", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Hypro123/EDMathDemonstration/77065d6034fd45ea6b0119b6d059c3f76313b316/Game/project2D/Sail.cpp", "visit_date": "2020-12-30T14:01:16.696983", "added": "2024-11-18T19:49:40.970029+00:00", "created": "2017-05-15T22:57:29", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
<?php /** * Created by PhpStorm. * User: Jan * Date: 7/7/2016 * Time: 11:16 AM */ class JobInvite extends Eloquent { public $timestamps = true; protected $table = 'job_invites'; }
b80168cc78262bc68905de2ddc1134bfb145f3c0
{ "blob_id": "b80168cc78262bc68905de2ddc1134bfb145f3c0", "branch_name": "refs/heads/master", "committer_date": "2016-11-15T12:22:40", "content_id": "dce3290a3a02c661c5e3cd4fd5558b698e2ee227", "detected_licenses": [ "MIT" ], "directory_id": "cef4a0238f835079306f54bd172ef376ef7e0217", "extension": "php", "filename": "JobInvite.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 107615334, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 193, "license": "MIT", "license_type": "permissive", "path": "/app/models/JobInvite.php", "provenance": "stack-edu-0052.json.gz:730811", "repo_name": "jjsarmiento/pvk", "revision_date": "2016-11-15T12:22:40", "revision_id": "9fb0d16bb6008e7adcc8fba2d77b3bd433e62e34", "snapshot_id": "b89f965371263fb3c2fd9d8e1fd2ecb047d69e7c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jjsarmiento/pvk/9fb0d16bb6008e7adcc8fba2d77b3bd433e62e34/app/models/JobInvite.php", "visit_date": "2021-07-14T21:56:24.994824", "added": "2024-11-18T21:51:32.513384+00:00", "created": "2016-11-15T12:22:40", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
package co.iyubinest.shapes; final class Diamond implements Shape { private static final int CHARS = 5; private static final int LINES = 5; public static Shape create() { return new Diamond(); } private static boolean upperTriangle(int line, int on) { return line <= CHARS / 2 && on >= (CHARS / 2) - line && on <= CHARS - 1 - (CHARS / 2) + line; } private static boolean bottomTriangle(int line, int on) { return line > CHARS / 2 && on >= line / 2 && on <= CHARS - 1 - (line / 2); } private static boolean positionFor(int line, int on) { return line <= CHARS / 2 ? upperTriangle(line, on) : bottomTriangle(line, on); } @Override public String value() { return new Builder() .lines(LINES) .chars(CHARS) .printer(Diamond::positionFor) .value(); } }
9ae27482ca8d5b473a99eb6ece45bef6b7007a92
{ "blob_id": "9ae27482ca8d5b473a99eb6ece45bef6b7007a92", "branch_name": "refs/heads/master", "committer_date": "2018-02-20T17:07:07", "content_id": "9f942d046bf73a9868d5d0b25aeac4426d3a0343", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c1801f35af4f7ac2912012a8b377825e84d6d247", "extension": "java", "filename": "Diamond.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 122125357, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 829, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/co/iyubinest/shapes/Diamond.java", "provenance": "stack-edu-0024.json.gz:804849", "repo_name": "go-cristian/Figures", "revision_date": "2018-02-20T17:07:07", "revision_id": "f796b4d49edc7ab20130c43e252ce0b481eaf781", "snapshot_id": "ec8c3234f3100c87414d2d92cc61635bae9a6d6d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/go-cristian/Figures/f796b4d49edc7ab20130c43e252ce0b481eaf781/src/co/iyubinest/shapes/Diamond.java", "visit_date": "2021-09-07T08:54:08.613113", "added": "2024-11-18T22:16:38.480604+00:00", "created": "2018-02-20T17:07:07", "int_score": 3, "score": 3.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
/*-----------------------------------------------------------------\ |Ces fonctions servent à réduire les nombres en prenant le produits| |de leurs chiffre. | \-----------------------------------------------------------------*/ #ifndef MULTIMULTI #define MULTIMULTI #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <math.h> void reduce(char* nombre); //Prend un argument une chaine sur laquelle on a écrit un nombre, fait le produit de ses chiffres et met le résultat dans nombre int howManyTimes(char* nombre); //Regarde combien de fois on peut réduire le nombre écrit dans la chaine nombre avant d'avoir un nombre d'un seul chiffre int writeLine(char* line,char* file);//Écrit la ligne line dans le fichier file en rajoutant un retour chariot. Renvoie 0 si tout va bien et 1 si on arrive pas à ouvrir le fichier. int sampleAnalyse(char* file,uint64_t start,uint64_t stop,int threadmax,int threadNumber); //Analyse le nombre de reduction pour les nombres de start à stop en reniseignant les découvertes dans file. Si il y a du multithreading on reiseigne le nombre e thread dans threadmax et on indique le numéro de la thread dans threadNumber à partir de 0. Revoie 0 si tout va bien. void test(); //on verifie que tout va bien typedef struct combiARG { int nombreChiffre; //nombre de chiffre dans les nombres étudiés uint64_t nombreCombinaisons; //nombre de combinaisons trouvées char** combinaisons; //liste des nombres } combiARG; void combiaisonLoop(combiARG* args); //boucles appelées par getCombinaisons void addCharX(char* string,char elem,int combien,combiARG* args); //ajoute combien fois elem à la fil de string et évalue ses reductions void rmChar(char* string,int combien); //enlève les combien derniers éléments de string combiARG* getCombinaisons(int digits); //renvoie une structure servant à retrouver les combinaisons de digits chiffres void combiAnalyze(char* file,char** listCombi,uint64_t nombreCombinaisons); //regarde le nombre de reductions du vecteur de nombre listCommbi (les nombreCombinaisos élements) et écrit le résultat dans file uint64_t factorial(unsigned int); #endif
ad0d17ed3d764ac71b53956086d444dd32f4be4c
{ "blob_id": "ad0d17ed3d764ac71b53956086d444dd32f4be4c", "branch_name": "refs/heads/master", "committer_date": "2019-08-28T16:46:52", "content_id": "7ba975391d9710d930f3db69d425db2a982eb0dc", "detected_licenses": [ "MIT" ], "directory_id": "927e5e3b6a34d4288eeaecbb9c40cba440e03304", "extension": "h", "filename": "multimulti.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 203431538, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2233, "license": "MIT", "license_type": "permissive", "path": "/multimulti.h", "provenance": "stack-edu-0001.json.gz:370842", "repo_name": "Arkaeriit/multinum", "revision_date": "2019-08-28T16:46:52", "revision_id": "6e0c6b44f1cb2d790f473c59d04d936d445a35ac", "snapshot_id": "af58e33ab3053c209de3c27b55199356bbb3eb78", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Arkaeriit/multinum/6e0c6b44f1cb2d790f473c59d04d936d445a35ac/multimulti.h", "visit_date": "2020-07-07T18:02:04.063779", "added": "2024-11-18T22:24:21.679886+00:00", "created": "2019-08-28T16:46:52", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
package io import ( "io/ioutil" "mime" "net/http" "os" "path/filepath" "strings" ) const timeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // ServeFile from a http.FileSystem func ServeFile(w http.ResponseWriter, r *http.Request, fileSystem http.FileSystem, fileName string, prefix string) ([]byte, error) { index, err := fileSystem.Open(fileName) if err != nil { return nil, err } if index == nil { return nil, os.ErrNotExist } stats, err := index.Stat() if err != nil { return nil, err } if stats.IsDir() { return nil, os.ErrNotExist } out, err := ioutil.ReadAll(index) if err != nil { return nil, err } w.Header().Set("Last-Modified", stats.ModTime().UTC().Format(timeFormat)) setContentType(w, fileName) setCacheControl(w) return out, nil } func setCacheControl(w http.ResponseWriter) { contentType := w.Header().Get("Content-Type") // Don't cache HTML files if strings.Contains(contentType, "text/html") { w.Header().Set("Content-Security-Policy", "script-src 'self'") return } w.Header().Set("Cache-Control", "public, max-age=31536000") } func setContentType(w http.ResponseWriter, fileName string) { extension := filepath.Ext(fileName) w.Header().Set("Content-Type", mime.TypeByExtension(extension)) }
88493287877d4704fe253c4a421470f676675ad3
{ "blob_id": "88493287877d4704fe253c4a421470f676675ad3", "branch_name": "refs/heads/master", "committer_date": "2019-10-06T18:30:48", "content_id": "bd4df5b53f4caf9c36608d60fc14bc67bda46242", "detected_licenses": [ "MIT" ], "directory_id": "329de1449be5dc971a1a1ec7d464c586555fd5ee", "extension": "go", "filename": "file.go", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1262, "license": "MIT", "license_type": "permissive", "path": "/file.go", "provenance": "stack-edu-0016.json.gz:733059", "repo_name": "coma-toast/io", "revision_date": "2019-10-06T18:30:48", "revision_id": "3aa4d5a5969d750d1e4fba0ab5fbd5724ec4f69a", "snapshot_id": "113b3dcae09f357e649d78e40c654a5b9fab3380", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/coma-toast/io/3aa4d5a5969d750d1e4fba0ab5fbd5724ec4f69a/file.go", "visit_date": "2020-08-07T12:25:06.526242", "added": "2024-11-18T20:52:30.027067+00:00", "created": "2019-10-06T18:30:48", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
module Riiif # Decodes the URL parameters into a Transformation object class OptionDecoder OUTPUT_FORMATS = %w(jpg png).freeze # a helper method for instantiating the OptionDecoder # @param [ActiveSupport::HashWithIndifferentAccess] options # @param [ImageInformation] image_info def self.decode(options, image_info) new(options, image_info).decode end # @param [ActiveSupport::HashWithIndifferentAccess] options # @param [ImageInformation] image_info def initialize(options, image_info) @options = options @image_info = image_info end attr_reader :image_info ## # @return [Transformation] def decode raise ArgumentError, "You must provide a format. You provided #{@options}" unless @options[:format] validate_format!(@options[:format]) Riiif::Transformation.new(decode_region(@options.delete(:region)), decode_size(@options.delete(:size)), decode_quality(@options[:quality]), decode_rotation(@options[:rotation]), @options[:format]) end def decode_quality(quality) return if quality.nil? || %w(default color).include?(quality) return quality if %w(bitonal grey).include?(quality) raise InvalidAttributeError, "Unsupported quality: #{quality}" end def decode_rotation(rotation) return if rotation.nil? || rotation == '0' begin Float(rotation) rescue ArgumentError raise InvalidAttributeError, "Unsupported rotation: #{rotation}" end end def validate_format!(format) raise InvalidAttributeError, "Unsupported format: #{format}" unless OUTPUT_FORMATS.include?(format) end def decode_region(region) if region.nil? || region == 'full' Riiif::Region::Imagemagick::FullDecoder.new.decode elsif md = /^pct:(\d+),(\d+),(\d+),(\d+)$/.match(region) Riiif::Region::Imagemagick::PercentageDecoder .new(image_info, md[1], md[2], md[3], md[4]).decode elsif md = /^(\d+),(\d+),(\d+),(\d+)$/.match(region) Riiif::Region::Imagemagick::AbsoluteDecoder.new(md[1], md[2], md[3], md[4]).decode elsif region == 'square' Riiif::Region::Imagemagick::SquareDecoder.new(image_info).decode else raise InvalidAttributeError, "Invalid region: #{region}" end end # rubocop:disable Metrics/PerceivedComplexity def decode_size(size) if size.nil? || size == 'full' Riiif::Size::Imagemagick::FullDecoder.new.decode elsif md = /^,(\d+)$/.match(size) Riiif::Size::Imagemagick::HeightDecoder.new(md[1]).decode elsif md = /^(\d+),$/.match(size) Riiif::Size::Imagemagick::WidthDecoder.new(md[1]).decode elsif md = /^pct:(\d+(.\d+)?)$/.match(size) Riiif::Size::Imagemagick::PercentDecoder.new(md[1]).decode elsif md = /^(\d+),(\d+)$/.match(size) Riiif::Size::Imagemagick::AbsoluteDecoder.new(md[1], md[2]).decode elsif md = /^!(\d+),(\d+)$/.match(size) Riiif::Size::Imagemagick::BestFitDecoder.new(md[1], md[2]).decode else raise InvalidAttributeError, "Invalid size: #{size}" end end # rubocop:enable Metrics/PerceivedComplexity end end
0b9865d958e8b7e71a17f1fed8e76f9a6bcb6794
{ "blob_id": "0b9865d958e8b7e71a17f1fed8e76f9a6bcb6794", "branch_name": "refs/heads/master", "committer_date": "2020-01-03T16:02:52", "content_id": "63f475a221b25469b967c6ad1f28edd62fe6710e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4f10195445444974ef70043f7487801cd67d0589", "extension": "rb", "filename": "option_decoder.rb", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131189819, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3339, "license": "Apache-2.0", "license_type": "permissive", "path": "/vendor/bundle/ruby/2.4.0/gems/riiif-1.7.1/app/services/riiif/option_decoder.rb", "provenance": "stack-edu-0066.json.gz:812673", "repo_name": "scottkushner/spc_repo", "revision_date": "2020-01-03T16:02:52", "revision_id": "1d744393c1d41a84d1d333e1fc3d5354ab187f20", "snapshot_id": "cea74b69cf8c1e25646e477dbf8d1652a1925797", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/scottkushner/spc_repo/1d744393c1d41a84d1d333e1fc3d5354ab187f20/vendor/bundle/ruby/2.4.0/gems/riiif-1.7.1/app/services/riiif/option_decoder.rb", "visit_date": "2023-01-24T04:11:26.478114", "added": "2024-11-19T03:35:12.005358+00:00", "created": "2020-01-03T16:02:52", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
package de.hszemi.sensorid; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.Socket; import java.net.UnknownHostException; /** * DataReporter sends a SensorDataMessage to the target host */ public class DataReporter extends AsyncTask<Void, Void, Boolean> { private SensorData.SensorDataMessage serializedData; private String targetHost; private Context context; public DataReporter(SensorData.SensorDataMessage serializedData, String targetHost, Context context) { this.serializedData = serializedData; this.targetHost = targetHost; this.context = context; } @Override protected Boolean doInBackground(Void... params) { Socket socket = null; try { socket = new Socket(this.targetHost, 54321); OutputStream os = socket.getOutputStream(); // send the serialized SensorDataMessage serializedData.writeTo(os); os.close(); return true; } catch (UnknownHostException e) { Log.e("SOCKETERROR", "UnknownHostException"); e.printStackTrace(); }catch (ConnectException e){ Log.e("SOCKETERROR", "ConnectException"); e.printStackTrace(); } catch (IOException e) { Log.e("SOCKETERROR", "IOException"); e.printStackTrace(); } finally{ if(socket != null){ try{ socket.close(); } catch(IOException e){ Log.e("SOCKETERROR", "IOException"); e.printStackTrace(); } } } // If we reach this part of the code, an exception occurred. // Probably the host did not respond. return false; } @Override protected void onPostExecute(Boolean result) { if(!result){ // SOMETHING WENT WRONG! ABORT MISSION! Toast.makeText(context, "Can't report data. Is the server at "+targetHost+" running?", Toast.LENGTH_SHORT).show(); } } public SensorData.SensorDataMessage getSerializedData() { return serializedData; } public void setSerializedData(SensorData.SensorDataMessage serializedData) { this.serializedData = serializedData; } public String getTargetHost() { return targetHost; } public void setTargetHost(String targetHost) { this.targetHost = targetHost; } }
30738d3436513a7d4f7fee590755294548616916
{ "blob_id": "30738d3436513a7d4f7fee590755294548616916", "branch_name": "refs/heads/master", "committer_date": "2016-10-09T16:49:07", "content_id": "852654cf20d42d923d4348b2ee301bce71c9e422", "detected_licenses": [ "MIT" ], "directory_id": "2eceb6fed27c2dce2043c12035458d1403dfa3ec", "extension": "java", "filename": "DataReporter.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 60213480, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2647, "license": "MIT", "license_type": "permissive", "path": "/app/src/main/java/de/hszemi/sensorid/DataReporter.java", "provenance": "stack-edu-0021.json.gz:171590", "repo_name": "HSZemi/sensorid", "revision_date": "2016-10-09T16:49:07", "revision_id": "c87b2ab02e7120654cd8c16d6b6d8653ee0a12dc", "snapshot_id": "dd3340392e2a0c068523517f968787cff3fe0738", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HSZemi/sensorid/c87b2ab02e7120654cd8c16d6b6d8653ee0a12dc/app/src/main/java/de/hszemi/sensorid/DataReporter.java", "visit_date": "2021-01-19T03:35:12.901672", "added": "2024-11-19T02:42:14.941669+00:00", "created": "2016-10-09T16:49:07", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
# salario ministro stf R$ 33.763 limite = 33763*0.9 import csv contador=0 listasalarios = open("C:\\Users\\Martim\\Documents\\salariosSC.csv",'r',encoding="UTF-8") lista = csv.reader(listasalarios,delimiter=";") #lista = listasalarios.readlines() # readlinesssssss #listasalarios.close() for servidor in lista: #print(servidor) if(servidor[0]=="Nome"): continue if (float(servidor[2])>=limite): print(servidor[0], "recebe salário de R$", servidor[2], "e trabalha como ", servidor[3] ) print("-----------------------------------------------------------------------------------------------") contador+=1 listasalarios.close() print("Total de salários acima do teto permitido: ", contador)
69019343b4180faab0d096c68f47fc168fbbf6f7
{ "blob_id": "69019343b4180faab0d096c68f47fc168fbbf6f7", "branch_name": "refs/heads/master", "committer_date": "2018-08-17T12:25:09", "content_id": "ec044bbeb03be97ead5d0c1ac0d803d8d92c583a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1095a359ed5b501ef4ed8dfef7662301f223e6de", "extension": "py", "filename": "salariosSC.py", "fork_events_count": 1, "gha_created_at": "2018-06-07T23:04:54", "gha_event_created_at": "2022-10-29T02:52:43", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 136540271, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license": "Apache-2.0", "license_type": "permissive", "path": "/SalariosAcimaLimite/salariosSC.py", "provenance": "stack-edu-0062.json.gz:310402", "repo_name": "mdietterle/aulas", "revision_date": "2018-08-17T12:25:09", "revision_id": "b289a7252c2c8f7dfb4ee5482326a94e7d87ee45", "snapshot_id": "9fbdcbcfb2a65ada90bb00c04a6114fd7c58e483", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mdietterle/aulas/b289a7252c2c8f7dfb4ee5482326a94e7d87ee45/SalariosAcimaLimite/salariosSC.py", "visit_date": "2022-11-11T10:03:49.968067", "added": "2024-11-18T22:36:02.632730+00:00", "created": "2018-08-17T12:25:09", "int_score": 3, "score": 3.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
# ntp Set the time and timezone appropriately. For information about PTA and how to use it with this Ansible role please visit https://github.com/Forcepoint/fp-pta-overview/blob/master/README.md ## Requirements None ## Role Variables ### REQUIRED * ntp_server: The IP or DNS name of the NTP server to sync with. ### OPTIONAL * ntp_timezone_name: The name of the timezone to use (EX: America/Denver). * ntp_timezone_desig: The file name designating the timezone to use (see /usr/share/zoneinfo/). ## Dependencies None ## Example Playbook Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: - name: setup ntp hosts: servers roles: - { role: ntp } ## License BSD-3-Clause ## Author Information Jeremy Cornett<EMAIL_ADDRESS>
dc9c354ab7d4ea676d9d8a9b837ebdad6c0e649c
{ "blob_id": "dc9c354ab7d4ea676d9d8a9b837ebdad6c0e649c", "branch_name": "refs/heads/master", "committer_date": "2020-06-09T05:04:25", "content_id": "6b8eb4b5fdf901c2d9fe56ba29fd39f13159a1e3", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e40c538cac840c21b5225df82c599f99f75ad910", "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": 246358670, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 859, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0012.json.gz:41276", "repo_name": "Forcepoint/fp-pta-ansible-ntp", "revision_date": "2020-06-09T05:04:25", "revision_id": "85eec8215aaa35f9c274b627d3d12eb244997454", "snapshot_id": "019d7a8c13e0f94915c6094aab21b4c133fa72f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Forcepoint/fp-pta-ansible-ntp/85eec8215aaa35f9c274b627d3d12eb244997454/README.md", "visit_date": "2022-10-07T13:03:48.474471", "added": "2024-11-19T00:53:31.856280+00:00", "created": "2020-06-09T05:04:25", "int_score": 3, "score": 3.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz" }
/** * FileQ * Copyright(C) Brad Huang * app.js: Node entry point */ ////// INIT ////// const express = require('express'); const app = express(); const http = require('http'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const configs = require('./configs'); const indexRoutes = require('./routes/index'); const exceptionsRoutes = require('./routes/exceptions'); ////// ESTABLISH DB CONNECTION ////// mongoose.connect(configs.DB_CONNECTION, { useNewUrlParser: true }); console.log("DB Connection Successful"); ////// SET ENVIRONMENT VARIABLES ////// app.set('port', configs.PORT || 3001); app.set('views', './views'); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser({ limit: '50mb' })); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); ////// ADD ROUTES ////// app.use(indexRoutes); app.use(exceptionsRoutes); ////// CREATE SERVER ////// app.listen(app.get('port'), () => { console.log('Server running on port ' + app.get('port')); });
66ceea6224ea499c5b52b9f60f4dd6a8f7f0daa6
{ "blob_id": "66ceea6224ea499c5b52b9f60f4dd6a8f7f0daa6", "branch_name": "refs/heads/master", "committer_date": "2019-04-09T19:59:09", "content_id": "7e186b38c0876d64cbd213e4f4c987092e0f0f7d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "bacf0e3cd43643a26493776c7de05d8cd2b07840", "extension": "js", "filename": "app.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142640219, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1044, "license": "Apache-2.0", "license_type": "permissive", "path": "/app.js", "provenance": "stack-edu-0032.json.gz:783783", "repo_name": "BradHuang1999/FileQ", "revision_date": "2019-04-09T19:59:09", "revision_id": "bc72516576160d1dca78269d8e48c1ecc320b52f", "snapshot_id": "731b20606b1da40b99352402a4da2846b6f86ff0", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/BradHuang1999/FileQ/bc72516576160d1dca78269d8e48c1ecc320b52f/app.js", "visit_date": "2020-03-24T09:52:16.244091", "added": "2024-11-19T03:42:13.165803+00:00", "created": "2019-04-09T19:59:09", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
/****************************************************************************** ******************************************************************************* ** ** Author: Lingurar Petru-Mugurel ** Written: luni 18 mai 2015, 15:24:15 +0300- ** Last updated: --- ** ** Compilation: g++ -std=c++11 -Wall -Werror -Wextra -pedantic -Wshadow ** (g++ 5.1) -Woverloaded-virtual -Winvalid-pch -Wcast-align ** -Wformat=2 -Wformat-nonliteral -Wmissing-declarations ** -Wmissing-format-attribute -Wmissing-include-dirs ** -Wredundant-decls -Wswitch-default -Wswitch-enum ** ** Execution: ./... ** ** Description: ** Show a basic implementation of assert and how NDEBUG can be defined at ** at compile time. ** ** Bugs: ** --- None --- ** ** TODO: ** --- None --- ** ** Notes: ** The behavior of assert depends on the status of a preprocessor variable ** named NDEBUG. If NDEBUG is defined, assert does nothing. By default, NDEBUG ** is not defined, so, by default, assert performs a run-time check. ** We can “turn off” debugging by providing a #define to define NDEBUG. ** Alternatively, most compilers provide a command-line option that lets us ** define preprocessor variables: ** $ CC -D NDEBUG main.C # use /D with the Microsoft compiler ** has the same effect as writing #define NDEBUG at the beginning of main.C. ** ******************************************************************************* ******************************************************************************/ #include <iostream> //#define NDEBUG // ifndef de mai jos verifica daca inainte de el !!! // a fost sau nu declarat NDEBUG #ifndef NDEBUG #include <cassert> #endif int main() { std::cout << "\nPlease enter 2 numbers: "; int n1, n2; std::cin >> n1 >> n2; assert(n1 == n2); return 0; }
bf0d91e2074005a8aa4d05d8bd22999a67eee07f
{ "blob_id": "bf0d91e2074005a8aa4d05d8bd22999a67eee07f", "branch_name": "refs/heads/master", "committer_date": "2015-09-30T18:12:49", "content_id": "35ec4235b9bf52c5efa65b5e8ef03928e2c5c422", "detected_licenses": [ "Unlicense" ], "directory_id": "1d201504615b58da4b39e660a9afdaa547e7c2dd", "extension": "cc", "filename": "assert.cc", "fork_events_count": 0, "gha_created_at": "2015-06-16T15:54:52", "gha_event_created_at": "2015-09-30T18:12:50", "gha_language": "C++", "gha_license_id": null, "github_id": 37540346, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1864, "license": "Unlicense", "license_type": "permissive", "path": "/C++/C++ Primer 5th ed/Ch 6 - Functions/assert.cc", "provenance": "stack-edu-0007.json.gz:240697", "repo_name": "Mugurell/Learning", "revision_date": "2015-09-30T18:12:49", "revision_id": "835a295c060807be9b98ad9bfc3d80f12e2542f5", "snapshot_id": "6e9a20233c6abe4d8b30fadb0275988d6bff70b7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Mugurell/Learning/835a295c060807be9b98ad9bfc3d80f12e2542f5/C++/C++ Primer 5th ed/Ch 6 - Functions/assert.cc", "visit_date": "2021-01-19T18:10:43.330159", "added": "2024-11-18T21:50:49.080486+00:00", "created": "2015-09-30T18:12:49", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz" }
/** * * Solution to homework task * Data Structures Course * Faculty of Mathematics and Informatics of Sofia University * Winter semester 2016/2017 * * @author Kristiyan Vachev * @idnumber 61905 * @task 5 * @compiler VS * */ #include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <filesystem> #include "Tree/BinaryTree.h"; bool IsFile(std::string fileName); int main() { int n = 2; std::cin >> n; BinaryTree* tree = new BinaryTree(); //Read first set of numbers and add them inside the tree std::string input = "123456.bin"; std::cin >> input; if (!IsFile(input)) { std::cout << "Invalid file path" << std::endl; delete tree; return 1; } std::ifstream reader(input); while (!reader.eof()) { long newNumber = 0; reader.read((char*)&newNumber, sizeof(newNumber)); //EOF reads until it meets a bad character, thus every time reading one more character than necessary if (!reader.eof()) { tree->Add(newNumber); } } reader.close(); --n; BinaryTree* intersectedTree = new BinaryTree(); //Read each next file and save every number that is within the original tree while (n > 0) { input = "4.bin"; std::cin >> input; if (!IsFile(input)) { std::cout << "Invalid file path" << std::endl; delete tree; delete intersectedTree; return 1; } std::ifstream intersectionReader(input); while (!intersectionReader.eof()) { long nextNumber; intersectionReader.read((char*)&nextNumber, sizeof(nextNumber)); //EOF reads until it meets a bad character, thus every time reading one more character than necessary if (!intersectionReader.eof()) { if (tree->Search(nextNumber) != nullptr) { intersectedTree->Add(nextNumber); } } } intersectionReader.close(); delete tree; tree = intersectedTree; intersectedTree = new BinaryTree(); --n; } //Write each number into the file std::ofstream writer("result.bin", std::ios::binary); while (!tree->Nodes()->IsEmpty()) { BNode* currentNode = tree->Nodes()->Pop(); long number = currentNode->Key(); writer.write((char*)&number, sizeof(long)); } writer.close(); delete tree; return 0; } bool IsFile(std::string fileName) { struct stat s; if (stat(fileName.c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) { return false; } else if (s.st_mode & S_IFREG) { return true; } else { return false; } } else { return false; } }
836954969d5eb4a712379709692f08b52777307a
{ "blob_id": "836954969d5eb4a712379709692f08b52777307a", "branch_name": "refs/heads/master", "committer_date": "2017-08-30T07:46:23", "content_id": "7ef0e8b407ce8e113062d1fe7522637db066470a", "detected_licenses": [ "MIT" ], "directory_id": "f1eeb5cd669520712c94495ebb69c76240134007", "extension": "cpp", "filename": "main.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 98017595, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2451, "license": "MIT", "license_type": "permissive", "path": "/Homeworks/05.Intersection/Intersection/Intersection/main.cpp", "provenance": "stack-edu-0006.json.gz:204637", "repo_name": "KristiyanVachev/CPP_DSA", "revision_date": "2017-08-30T07:46:23", "revision_id": "7b4bd1b0ad2f00a01a990e437a6e5594be259e22", "snapshot_id": "c65876d27f10481a82707f0705d5f1dfd925d9a8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KristiyanVachev/CPP_DSA/7b4bd1b0ad2f00a01a990e437a6e5594be259e22/Homeworks/05.Intersection/Intersection/Intersection/main.cpp", "visit_date": "2021-01-01T17:11:38.055409", "added": "2024-11-18T23:07:10.304911+00:00", "created": "2017-08-30T07:46:23", "int_score": 3, "score": 2.875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
# borrow-it This is a Chrome extension designed to help people borrow more easily from a library whilst on the web in a browser. Key initial feature is that it adds a borrow button to book retailer websites. The intial version has been modified to test with users at Manchester Metropolitan University. The ultimate goal of the extension is to offer Borrow It as a library tool for any library user in the UK and beyond. Features to build include: * location based library tools or a quick search query to find your library (if it's not close to where you currently are located) * More tools to search your library via the web (text select tool that offers you the option to search the term at your library (particularly for academic library users)
a661943414ffd18b29430cf5ba56f7f5f697604f
{ "blob_id": "a661943414ffd18b29430cf5ba56f7f5f697604f", "branch_name": "refs/heads/master", "committer_date": "2017-01-02T23:41:10", "content_id": "37bf9c56399d58f09f46d598e1a9bcfad1b627bc", "detected_licenses": [ "MIT" ], "directory_id": "5f9a347a1a4b2e7583e17d2c4c616111407446bb", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2017-01-02T22:36:00", "gha_event_created_at": "2017-01-02T23:41:10", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 77866189, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 754, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0007.json.gz:46201", "repo_name": "storyjack3r/borrow-it", "revision_date": "2017-01-02T23:41:10", "revision_id": "ca0ef7c52751b947782933238a42452a88370c6c", "snapshot_id": "27fd1643e83d422ba82161d5c3dc01c2a00b1dd8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/storyjack3r/borrow-it/ca0ef7c52751b947782933238a42452a88370c6c/README.md", "visit_date": "2021-01-11T10:03:16.477692", "added": "2024-11-19T01:34:10.391152+00:00", "created": "2017-01-02T23:41:10", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
<?php /** * Furnace Project * * This source file is subject to the BSD license bundled with * this package in the LICENSE.txt file. It is also available * on the world-wide-web at http://www.opensource.org/licenses/bsd-license.php. * If you are unable to receive a copy of the license or have * questions concerning the terms, please send an email to * [email protected]. * * @category akandels * @package furnace * @author Andrew Kandels ([email protected]) * @copyright Copyright (c) 2013 Andrew P. Kandels (http://andrewkandels.com) * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://contain-project.org/furnace */ namespace Furnace\View\Helper; use Zend\View\Helper\AbstractHelper; use Furnace\Entity\Job as JobEntity; /** * Furnace job status view helper * * @category akandels * @package furnace * @copyright Copyright (c) 2013 Andrew P. Kandels (http://andrewkandels.com) * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ class Status extends AbstractHelper { /** * Invokes the view helper * * @param Furnace\Entity\Job * @return string */ public function __invoke(JobEntity $job) { if ($job->isQueued()) { $status = 'queued'; } elseif ($job->isCompleted()) { $status = 'completed'; } elseif ($job->isStarted()) { $status = 'started'; } elseif ($job->getError()) { $status = 'error'; } else { $status = 'pending'; } return $this->view->render('furnace/partials/status', array( 'status' => $status, 'job' => $job, )); } }
530cd08cdd3acd5b137d6430f0fd98bee37b2341
{ "blob_id": "530cd08cdd3acd5b137d6430f0fd98bee37b2341", "branch_name": "refs/heads/master", "committer_date": "2014-08-14T15:46:54", "content_id": "bc445db428d95337561c4cf9166c0bd0aedca2dc", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "57064ae85f97871169a50dd1b2701daa5b89ae5c", "extension": "php", "filename": "Status.php", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 11280493, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1756, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/Furnace/View/Helper/Status.php", "provenance": "stack-edu-0051.json.gz:753307", "repo_name": "andrew-kandels/furnace", "revision_date": "2014-08-14T15:46:54", "revision_id": "05a56e93dfee75fd49faf6d24c455e9fb8a8d2e7", "snapshot_id": "f976865f08ab398a6be707a8838971a63b3581bc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andrew-kandels/furnace/05a56e93dfee75fd49faf6d24c455e9fb8a8d2e7/src/Furnace/View/Helper/Status.php", "visit_date": "2023-08-11T06:59:39.894335", "added": "2024-11-19T03:09:28.423846+00:00", "created": "2014-08-14T15:46:54", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
/** * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ package com.wegas.reviewing.persistence.evaluation; import ch.albasim.wegas.annotations.View; import ch.albasim.wegas.annotations.WegasEntityProperty; import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.Lob; /** * * Textual evaluation instance * * @author Maxence Laurent (maxence.laurent at gmail.com) */ @Entity public class TextEvaluationInstance extends EvaluationInstance { private static final long serialVersionUID = 1L; /** * the evaluation itself */ @Lob @Basic(fetch = FetchType.EAGER) // CARE, lazy fetch on Basics has some trouble. @Column(name = "evaluationvalue") @WegasEntityProperty(view = @View(label = "Value")) private String value; /** * get the evaluation * * @return the evaluation */ public String getValue() { return value; } /** * set the evaluation * * @param value the evaluation */ public void setValue(String value) { this.value = value; } }
1c56c9ade642618be29dde748ff8388fe8068932
{ "blob_id": "1c56c9ade642618be29dde748ff8388fe8068932", "branch_name": "refs/heads/master", "committer_date": "2023-08-25T11:26:08", "content_id": "f6d66ac3fae55ff9b55ab39e315dcdf5b48066c4", "detected_licenses": [ "MIT" ], "directory_id": "8c604e804cf5e1e85661a204960fbda5e9c76b66", "extension": "java", "filename": "TextEvaluationInstance.java", "fork_events_count": 13, "gha_created_at": "2012-01-04T13:31:04", "gha_event_created_at": "2023-09-06T09:40:06", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 3102131, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1280, "license": "MIT", "license_type": "permissive", "path": "/wegas-core/src/main/java/com/wegas/reviewing/persistence/evaluation/TextEvaluationInstance.java", "provenance": "stack-edu-0028.json.gz:744439", "repo_name": "Heigvd/Wegas", "revision_date": "2023-08-25T10:12:47", "revision_id": "2b7d9c369b1dcc0c751ddfb6e8ab19bdb4f87893", "snapshot_id": "70a3723e021e6ba24badf0e9f9a8b88e86254ae0", "src_encoding": "UTF-8", "star_events_count": 29, "url": "https://raw.githubusercontent.com/Heigvd/Wegas/2b7d9c369b1dcc0c751ddfb6e8ab19bdb4f87893/wegas-core/src/main/java/com/wegas/reviewing/persistence/evaluation/TextEvaluationInstance.java", "visit_date": "2023-09-01T05:19:32.371274", "added": "2024-11-19T00:30:18.395241+00:00", "created": "2023-08-25T10:12:47", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
package ua.danit.photogramm.web.model; import java.util.Collection; import java.util.Collections; import org.springframework.security.core.GrantedAuthority; import ua.danit.photogramm.users.data.model.User; /** * This is user interface for internal usage only, * implemented {@link org.springframework.security.core.userdetails.UserDetails} * and delegate all functionality to {@link ua.danit.photogramm.users.data.model.User} * * @author Andrey Minov */ public class InternalUser implements org.springframework.security.core.userdetails.UserDetails { private User entity; /** * Instantiates a new Internal user. * * @param entity the entity from data storage. */ public InternalUser(User entity) { this.entity = entity; } @Override public Collection<GrantedAuthority> getAuthorities() { return Collections.emptyList(); } @Override public String getPassword() { return entity.getPassword(); } @Override public String getUsername() { return entity.getNickname(); } @Override public boolean isEnabled() { return true; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } public User getEntity() { return entity; } }
2cf3b7f96d63903f217ba9322d73b0819c703d02
{ "blob_id": "2cf3b7f96d63903f217ba9322d73b0819c703d02", "branch_name": "refs/heads/master", "committer_date": "2018-02-08T09:07:43", "content_id": "69c7834bd53599aa17be527fdbb7b84cfb2a98dc", "detected_licenses": [ "MIT" ], "directory_id": "629c51b94a2e4a75256c32f0beb7740dda76d1c1", "extension": "java", "filename": "InternalUser.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120736425, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1378, "license": "MIT", "license_type": "permissive", "path": "/web_application/src/main/java/ua/danit/photogramm/web/model/InternalUser.java", "provenance": "stack-edu-0021.json.gz:125686", "repo_name": "djandrewd/photogramm", "revision_date": "2018-02-08T09:07:43", "revision_id": "af56f312d816d4581032b05416e69505e50c393f", "snapshot_id": "4d779580627d9661c5bf56e57c4abe065e1cec56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/djandrewd/photogramm/af56f312d816d4581032b05416e69505e50c393f/web_application/src/main/java/ua/danit/photogramm/web/model/InternalUser.java", "visit_date": "2021-05-02T12:08:20.875559", "added": "2024-11-18T22:53:43.368232+00:00", "created": "2018-02-08T09:07:43", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
// Copyright 2010 The Walk Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package walk import ( "github.com/lxn/win" ) // Rectangle defines upper left corner with width and height region in 1/96" units, or native // pixels, or grid rows and columns. type Rectangle struct { X, Y, Width, Height int } func rectangleFromRECT(r win.RECT) Rectangle { return Rectangle{ X: int(r.Left), Y: int(r.Top), Width: int(r.Right - r.Left), Height: int(r.Bottom - r.Top), } } func (r Rectangle) Left() int { return r.X } func (r Rectangle) Top() int { return r.Y } func (r Rectangle) Right() int { return r.X + r.Width - 1 } func (r Rectangle) Bottom() int { return r.Y + r.Height - 1 } func (r Rectangle) Location() Point { return Point{r.X, r.Y} } func (r *Rectangle) SetLocation(p Point) Rectangle { r.X = p.X r.Y = p.Y return *r } func (r Rectangle) Size() Size { return Size{r.Width, r.Height} } func (r *Rectangle) SetSize(s Size) Rectangle { r.Width = s.Width r.Height = s.Height return *r } func (r Rectangle) toRECT() win.RECT { return win.RECT{ int32(r.X), int32(r.Y), int32(r.X + r.Width), int32(r.Y + r.Height), } }
22f909f8d034ffb87ed6670584007a67a8e7713a
{ "blob_id": "22f909f8d034ffb87ed6670584007a67a8e7713a", "branch_name": "refs/heads/master", "committer_date": "2021-06-20T08:32:53", "content_id": "045600ec2b5929226e7d4532d68bf0b08d6ceb75", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f984428ff73901b4ea9932ab8fd6aaa89d01f6db", "extension": "go", "filename": "rectangle.go", "fork_events_count": 2, "gha_created_at": "2019-11-17T19:47:06", "gha_event_created_at": "2023-02-25T04:32:57", "gha_language": "Go", "gha_license_id": "NOASSERTION", "github_id": 222302664, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1279, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/vendor/github.com/lxn/walk/rectangle.go", "provenance": "stack-edu-0018.json.gz:118214", "repo_name": "lietu/better-dns", "revision_date": "2021-06-20T08:32:53", "revision_id": "fe4d82b4a89a4b87b4ffaf2783170107221c9665", "snapshot_id": "354511fee7a3ff981b026405c247b0c3bac2839f", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/lietu/better-dns/fe4d82b4a89a4b87b4ffaf2783170107221c9665/vendor/github.com/lxn/walk/rectangle.go", "visit_date": "2023-03-08T17:04:04.513298", "added": "2024-11-18T23:23:36.201282+00:00", "created": "2021-06-20T08:32:53", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const eventSchema = new Schema({ status: { type: mongoose.SchemaTypes.String, default: 'Waiting For Approval' }, name: {type: mongoose.SchemaTypes.String, required: true, unique: true }, creator: {type: mongoose.SchemaTypes.ObjectId, required: true, ref: 'User' }, creationDate: { type: mongoose.SchemaTypes.Date, default: Date.now }, eventDate: {type: mongoose.SchemaTypes.Date, required: true }, ticketPrice: {type: mongoose.SchemaTypes.Number, required: true }, availableSeats: {type: mongoose.SchemaTypes.Number, required: true, minLength: 10, maxLength: 100 }, reservedSeats: [{ type: mongoose.SchemaTypes.String }], description: { type: mongoose.SchemaTypes.String }, participants: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'User' }], imageUrl: { type: mongoose.SchemaTypes.String, required: true } }); const Event = mongoose.model('Event', eventSchema); module.exports = Event;
a788aca0aaf10a0ab3ade277187a696742fa8bdf
{ "blob_id": "a788aca0aaf10a0ab3ade277187a696742fa8bdf", "branch_name": "refs/heads/master", "committer_date": "2020-10-14T06:52:24", "content_id": "a34f1919ecfef902ce011c4180f763885ccb1ba3", "detected_licenses": [ "MIT" ], "directory_id": "53bcae919a9ed064ea090b7a11305e2a413c2f4c", "extension": "js", "filename": "EventSchema.js", "fork_events_count": 0, "gha_created_at": "2019-02-21T18:01:32", "gha_event_created_at": "2022-12-22T09:46:45", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 171919716, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1006, "license": "MIT", "license_type": "permissive", "path": "/server/models/EventSchema.js", "provenance": "stack-edu-0045.json.gz:547575", "repo_name": "nikiqta/Event-Room", "revision_date": "2020-10-14T06:52:24", "revision_id": "c6978fff523247a250001e693317373594ca29b4", "snapshot_id": "d3dce0cac3411de5671283d504d877dd25d3290c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nikiqta/Event-Room/c6978fff523247a250001e693317373594ca29b4/server/models/EventSchema.js", "visit_date": "2023-01-03T18:55:28.056091", "added": "2024-11-19T00:42:03.813946+00:00", "created": "2020-10-14T06:52:24", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
package ru.ps.vlcatv.utils.playlist.parse; import java.util.Locale; import ru.ps.vlcatv.utils.Text; import ru.ps.vlcatv.utils.json.JSONObject; public class ParseControllerTRAILER { private final static String TAG_FOUND = "found"; private final static String TAG_URI = "uri"; public String buildRequest(final String uri, final String baseHttp, final String pathLocal) { try { int pos = uri.lastIndexOf('/'); if (pos <= 0) return null; String name = uri.substring((pos + 1), uri.length()); pos = name.lastIndexOf('.'); if (pos <= 0) return null; name = name.substring(0, pos); return String.format( Locale.getDefault(), "%scheck?uri=file:///%s%s", baseHttp, pathLocal, name ); } catch (Exception ignore) {} return null; } public String buildResponse(final String txt, final String baseHttp) { try { if (Text.isempty(txt)) return null; JSONObject obj = new JSONObject(txt.trim()); if (!obj.optBoolean(TAG_FOUND, false)) return null; String s = obj.optString(TAG_URI, null); if (Text.isempty(s)) return null; return String.format( Locale.getDefault(), "%sget?uri=%s", baseHttp, s ); } catch (Exception ignore) {} return null; } }
cf218c7b451e015a0578bb7c40cc21338b171486
{ "blob_id": "cf218c7b451e015a0578bb7c40cc21338b171486", "branch_name": "refs/heads/master", "committer_date": "2021-03-07T10:16:33", "content_id": "7ff16fa86859cd4e8e364419b1453d944f2327f3", "detected_licenses": [ "MIT" ], "directory_id": "c0314f5ae0b5f9897f4d11c75d62880671e0ec8c", "extension": "java", "filename": "ParseControllerTRAILER.java", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 252246482, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1674, "license": "MIT", "license_type": "permissive", "path": "/source/utils.atv/src/main/java/ru/ps/vlcatv/utils/playlist/parse/ParseControllerTRAILER.java", "provenance": "stack-edu-0027.json.gz:617365", "repo_name": "CloneTV/VLC-TV-Remote", "revision_date": "2021-03-07T10:16:33", "revision_id": "50539a0fab02622cf175f6eca15ffcfc4e3a1ef2", "snapshot_id": "1e1ccf7bf940387cc7d63e183f418551142cd4b8", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/CloneTV/VLC-TV-Remote/50539a0fab02622cf175f6eca15ffcfc4e3a1ef2/source/utils.atv/src/main/java/ru/ps/vlcatv/utils/playlist/parse/ParseControllerTRAILER.java", "visit_date": "2021-05-20T10:23:35.721008", "added": "2024-11-18T21:22:04.920589+00:00", "created": "2021-03-07T10:16:33", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
#!/usr/bin/env ruby require_relative 'dice.tab.rb' d = DiceNotationParser.new #d.instance_eval{ @yydebug = true } while line = ARGF.gets do s = line.chop next if /^\s*$/ =~ s unless $stdin.isatty then puts s end begin insn_stack = d.parse(s) p insn_stack rescue ParseError puts $! end end
4dac5b108b0e5273a46182af81e57a6867a8b1e9
{ "blob_id": "4dac5b108b0e5273a46182af81e57a6867a8b1e9", "branch_name": "refs/heads/master", "committer_date": "2023-07-11T02:34:14", "content_id": "7f2415b9f934572e92db73f2bf4e8294ccda9f5a", "detected_licenses": [ "MIT" ], "directory_id": "f973f1e31a0c5c367912a6cb5a4019e3025a8d00", "extension": "rb", "filename": "parse_dice.rb", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 12478801, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 325, "license": "MIT", "license_type": "permissive", "path": "/ruby/parse_dice.rb", "provenance": "stack-edu-0067.json.gz:288625", "repo_name": "autch/dicevm", "revision_date": "2023-07-11T02:34:14", "revision_id": "edc9e07f107343f292a7f388d2bfcff01e1e201f", "snapshot_id": "f1fb9c8b10fddf600c0c94681e603f09aaacaf0a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/autch/dicevm/edc9e07f107343f292a7f388d2bfcff01e1e201f/ruby/parse_dice.rb", "visit_date": "2023-07-22T08:50:38.268728", "added": "2024-11-18T20:53:45.626651+00:00", "created": "2023-07-11T02:34:14", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
var Client = function(socket) { this.socket = socket; this.id = null; this.data = null; }; Client.prototype.setId = function (id) { this.id = id; } Client.prototype.setData = function (data) { this.data = data; } module.exports = Client;
2c3504edf40db54161245a7af8fa327e45d9aee4
{ "blob_id": "2c3504edf40db54161245a7af8fa327e45d9aee4", "branch_name": "refs/heads/master", "committer_date": "2015-02-23T01:32:47", "content_id": "437edee0faaa18e718f931368550c55d796e29dd", "detected_licenses": [ "MIT" ], "directory_id": "60f477703c33811f5bea352d5d5ceb5c55ec580d", "extension": "js", "filename": "client.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31142561, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 250, "license": "MIT", "license_type": "permissive", "path": "/models/client.js", "provenance": "stack-edu-0039.json.gz:263216", "repo_name": "tweir/node-edison-server", "revision_date": "2015-02-23T01:32:47", "revision_id": "8394e8d89695a788b8e1b384c5909de811febec6", "snapshot_id": "c467f6cb42e617390118558cdf6b35715f1286ab", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tweir/node-edison-server/8394e8d89695a788b8e1b384c5909de811febec6/models/client.js", "visit_date": "2021-01-10T20:19:14.965788", "added": "2024-11-18T19:07:45.406609+00:00", "created": "2015-02-23T01:32:47", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
/* * $Id: TcpDataLink.h 6668 2014-12-16 23:12:47Z oschwaldp $ * * * Distributed under the OpenDDS License. * See: http://www.opendds.org/license.html */ #ifndef OPENDDS_TCPDATALINK_H #define OPENDDS_TCPDATALINK_H #include "TcpConnection_rch.h" #include "TcpTransport_rch.h" #include "dds/DCPS/transport/framework/DataLink.h" #include "ace/INET_Addr.h" namespace OpenDDS { namespace DCPS { class TransportSendStrategy; class TransportStrategy; class TcpDataLink : public DataLink { public: TcpDataLink(const ACE_INET_Addr& remote_address, TcpTransport* transport_impl, Priority priority, bool is_loopback, bool is_active); virtual ~TcpDataLink(); /// Accessor for the remote address. const ACE_INET_Addr& remote_address() const; /// Called when an established connection object is available /// for this TcpDataLink. Called by the TcpTransport's /// connect_datalink() method. int connect(const TcpConnection_rch& connection, const TransportSendStrategy_rch& send_strategy, const TransportStrategy_rch& receive_strategy); int reuse_existing_connection(const TcpConnection_rch& connection); int reconnect(TcpConnection* connection); TcpConnection_rch get_connection(); TcpTransport_rch get_transport_impl(); virtual bool issues_on_deleted_callback() const; virtual void pre_stop_i(); /// Set release pending flag. void set_release_pending(bool flag); /// Get release pending flag. bool is_release_pending() const; protected: /// Called when the DataLink is self-releasing because all of its /// reservations have been released, or when the TransportImpl is /// handling a shutdown() call. virtual void stop_i(); private: void send_graceful_disconnect_message(); ACE_INET_Addr remote_address_; TcpConnection_rch connection_; TcpTransport_rch transport_; bool graceful_disconnect_sent_; ACE_Atomic_Op<ACE_Thread_Mutex, bool> release_is_pending_; }; } // namespace DCPS } // namespace OpenDDS #if defined (__ACE_INLINE__) #include "TcpDataLink.inl" #endif /* __ACE_INLINE__ */ #endif /* OPENDDS_TCPDATALINK_H */
643627b928a2e1d6fea4c91ed503d9e08f6e1b48
{ "blob_id": "643627b928a2e1d6fea4c91ed503d9e08f6e1b48", "branch_name": "refs/heads/master", "committer_date": "2015-09-06T03:25:05", "content_id": "c719022de87d5858bb64ada52045a44492abfe26", "detected_licenses": [ "MIT" ], "directory_id": "fd7d1350eefac8a9bbd952568f074284663f2794", "extension": "h", "filename": "TcpDataLink.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41980019, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2253, "license": "MIT", "license_type": "permissive", "path": "/dds/DCPS/transport/tcp/TcpDataLink.h", "provenance": "stack-edu-0005.json.gz:113611", "repo_name": "binary42/OCI", "revision_date": "2015-09-06T03:25:05", "revision_id": "08191bfe4899f535ff99637d019734ed044f479d", "snapshot_id": "4ceb7c4ed2150b4edd0496b2a06d80f623a71a53", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/binary42/OCI/08191bfe4899f535ff99637d019734ed044f479d/dds/DCPS/transport/tcp/TcpDataLink.h", "visit_date": "2020-06-02T08:58:51.021571", "added": "2024-11-18T21:41:44.073474+00:00", "created": "2015-09-06T03:25:05", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
import {customStorage} from "./js/customStorage.js"; // customStorage.set("user1", "markus"); customStorage.set("user2", { name: "markus2", photo: "photo002.jpg" }); // console.log(customStorage.get("user2").photo === "photo002.jpg"); // console.log(customStorage.get("user2")); // console.dir(customStorage.get("user2")); customStorage.showAll(); // customStorage.remove("user1"); // customStorage.clearAll(); // console.dir(customStorage.get("user1")); document.body.innerHTML = JSON.stringify(customStorage.get("user2")); // document.body.innerHTML = customStorage.showAll());
0c095a1778a7bdd40806bc5564692c8651cfe7d5
{ "blob_id": "0c095a1778a7bdd40806bc5564692c8651cfe7d5", "branch_name": "refs/heads/master", "committer_date": "2017-03-16T23:13:31", "content_id": "4c4915f693ab4030394be0d1babd1540f80169f9", "detected_licenses": [ "MIT" ], "directory_id": "4be1fa00a52c3f35406c1fa2f015df5b010b1d52", "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": 85164179, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 588, "license": "MIT", "license_type": "permissive", "path": "/src/index.js", "provenance": "stack-edu-0045.json.gz:615051", "repo_name": "liquidnuker/tf_storejs1", "revision_date": "2017-03-16T23:13:31", "revision_id": "99c4bb22eda8924da49ce13deeb1a52ca1d5792f", "snapshot_id": "f12e64648409cc5d87a215c8bfad5c481ec1de74", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liquidnuker/tf_storejs1/99c4bb22eda8924da49ce13deeb1a52ca1d5792f/src/index.js", "visit_date": "2021-01-22T19:08:28.440195", "added": "2024-11-18T19:14:11.691548+00:00", "created": "2017-03-16T23:13:31", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
var callbackArguments = []; var argument1 = function callback(a,b,c,d) { callbackArguments.push(JSON.stringify(arguments)) base_0[9] = {"100":1.3935417423360814e+308,"":1.615470619610044e+307,"4.964830601246131e+307":6.385343526227509e+307} argument2[9.331954948603684e+307] = 1.6648961154781206e+308 argument3 = null return a+b/c-d }; var argument2 = function callback(a,b,c,d) { callbackArguments.push(JSON.stringify(arguments)) argument3[82] = 714 argument2['Cb'] = [403,1.7976931348623157e+308,-100,82,100,-1,893,403] return a*b+c/d }; var argument3 = null; var argument4 = null; var argument5 = function callback(a,b,c,d) { callbackArguments.push(JSON.stringify(arguments)) argument6[213] = null argument5[4] = null return a+b/c*d }; var argument6 = ",':D*1c"; var argument7 = null; var argument8 = r_3; var argument9 = true; var argument10 = false; var argument11 = function callback(a,b,c,d) { callbackArguments.push(JSON.stringify(arguments)) argument8[4] = true argument10['*c'] = "" return a+b/c/d }; var base_0 = [25,823,843,82] var r_0= undefined try { r_0 = base_0.reduce(argument1) } catch(e) { r_0= "Error" } var base_1 = [25,823,843,82] var r_1= undefined try { r_1 = base_1.reduce(argument2,argument3,argument4) } catch(e) { r_1= "Error" } var base_2 = [25,823,843,82] var r_2= undefined try { r_2 = base_2.reduce(argument5,argument6,argument7) } catch(e) { r_2= "Error" } var base_3 = [25,823,843,82] var r_3= undefined try { r_3 = base_3.reduce(argument8,argument9,argument10,argument11) } catch(e) { r_3= "Error" } function serialize(array){ return array.map(function(a){ if (a === null || a == undefined) return a; var name = a.constructor.name; if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String') return JSON.stringify(a); return name; }); } setTimeout(function(){ require("fs").writeFileSync("./experiments/reduce/reduceGen/test408.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments})) },300)
1e2f861c5720baff15c3846c9d142154a3be887a
{ "blob_id": "1e2f861c5720baff15c3846c9d142154a3be887a", "branch_name": "refs/heads/master", "committer_date": "2018-09-27T09:53:20", "content_id": "893909f91e1712acc7483b189b2cd65c10396e46", "detected_licenses": [ "MIT" ], "directory_id": "7f2cb1bde9a7dc80034b56f1313ea29638eccb4f", "extension": "js", "filename": "test408.js", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 149324674, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2066, "license": "MIT", "license_type": "permissive", "path": "/experiments/reduce/reduceGen/test408.js", "provenance": "stack-edu-0032.json.gz:214", "repo_name": "sola-da/LambdaTester", "revision_date": "2018-09-27T09:53:20", "revision_id": "f993f9d67eab0120b14111be1a56d40b4c5ac9af", "snapshot_id": "be1144b9ea59c6827ff028d02b9edf62c0d19bd4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/sola-da/LambdaTester/f993f9d67eab0120b14111be1a56d40b4c5ac9af/experiments/reduce/reduceGen/test408.js", "visit_date": "2020-03-29T00:06:10.640768", "added": "2024-11-18T18:28:48.030055+00:00", "created": "2018-09-27T09:53:20", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
// [prettierx] test script notice: // This test script runs for test files in another directory, // **not** on any files in *this* directory. // [FUTURE TBD] use Nodejs path function (...) const dirPath = `${__dirname}/../../../js/empty-paren-comment`; run_spec(dirPath, ["babel", "babel-flow", "flow", "typescript"], { spaceInParens: true, });
0beef5182c25ae761185ed648d5c35022d161aa9
{ "blob_id": "0beef5182c25ae761185ed648d5c35022d161aa9", "branch_name": "refs/heads/dev", "committer_date": "2021-07-12T02:29:39", "content_id": "7ce67068ec50c6216f125119b210f0d3972855dd", "detected_licenses": [ "MIT" ], "directory_id": "39e05d33e6b088f3f525c70f8b4c910b9edd605e", "extension": "js", "filename": "jsfmt.spec.js", "fork_events_count": 25, "gha_created_at": "2019-02-24T15:48:26", "gha_event_created_at": "2023-03-18T14:04:06", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 172356775, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 349, "license": "MIT", "license_type": "permissive", "path": "/tests/format/x/js/empty-statement-with-inner-spacing/jsfmt.spec.js", "provenance": "stack-edu-0045.json.gz:147318", "repo_name": "brodybits/prettierx", "revision_date": "2021-07-12T02:29:39", "revision_id": "f0db4cd00bcf44df5cd378ad6469d1527eafee97", "snapshot_id": "fe7b3e95e779e89bda2174618c0f080cdecd6eaa", "src_encoding": "UTF-8", "star_events_count": 208, "url": "https://raw.githubusercontent.com/brodybits/prettierx/f0db4cd00bcf44df5cd378ad6469d1527eafee97/tests/format/x/js/empty-statement-with-inner-spacing/jsfmt.spec.js", "visit_date": "2023-08-31T13:23:02.967875", "added": "2024-11-19T01:48:10.157233+00:00", "created": "2021-07-12T02:29:39", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
<!-- --- First check out the Docs: https://immutable-js.github.io/immutable-js/docs/ And check out the Wiki: https://github.com/immutable-js/immutable-js/wiki/ Search existing issues: https://github.com/immutable-js/immutable-js/search?type=Issues&q=question Ask on Stack Overflow!: https://stackoverflow.com/questions/tagged/immutable.js?sort=votes * Stack Overflow gets more attention * Answered questions are searchable * A whole community can answer --- Feature request? --- This library attempts to be as stable as possible so features have to meet a high bar to be added. This library also prefers interoperability with other libraries over continuous additions. Here are some tips to get your feature added: * Search existing issues and pull requests first. * Send a Pull Request! Start with API design and post for review early. --- Found a bug? --- Search existing issues first: https://github.com/immutable-js/immutable-js/search?type=Issues&q=bug Please ensure you're using the latest version, and provide some information below. --> ### What happened <!-- Shortly summarize what went wrong. Be sure to include not just what happened, but what you expected to happen as well. --> ### How to reproduce <!-- Provide enough information that someone else could produce the same error. Share code or even better, send a Pull Request with a new failing test case! -->
17f2e6aa47671c478eb01fbcfa6d75ae055a6de1
{ "blob_id": "17f2e6aa47671c478eb01fbcfa6d75ae055a6de1", "branch_name": "refs/heads/main", "committer_date": "2023-08-16T08:10:59", "content_id": "3387aa797e93352b60788234b48e0f583c3222e5", "detected_licenses": [ "MIT" ], "directory_id": "6dc9c6b3f6066b4b7de8d126edd425fa328803c4", "extension": "md", "filename": "ISSUE_TEMPLATE.md", "fork_events_count": 565, "gha_created_at": "2014-07-02T06:02:29", "gha_event_created_at": "2023-08-31T14:59:27", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 21413198, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1679, "license": "MIT", "license_type": "permissive", "path": "/.github/ISSUE_TEMPLATE.md", "provenance": "stack-edu-markdown-0016.json.gz:332815", "repo_name": "immutable-js/immutable-js", "revision_date": "2023-08-16T08:10:59", "revision_id": "7b3aa41e8be06c5e4610bbe7b6761c6f12c2d6ce", "snapshot_id": "bd5eb7a49b337bec41c2932abef558ca600fa4a8", "src_encoding": "UTF-8", "star_events_count": 8218, "url": "https://raw.githubusercontent.com/immutable-js/immutable-js/7b3aa41e8be06c5e4610bbe7b6761c6f12c2d6ce/.github/ISSUE_TEMPLATE.md", "visit_date": "2023-08-17T02:46:52.552529", "added": "2024-11-18T23:24:33.558351+00:00", "created": "2023-08-16T08:10:59", "int_score": 3, "score": 2.765625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0016.json.gz" }
function getCookie(){ var cookie = {}; var all = document.cookie; if( all == "" ){ return null; } // console.log(all,'all'); var list = all.split(";"); for( var i = 0; i < list.length; i++ ){ var cok = list[i]; var p = cok.indexOf("="); var name = cok.substring( 0,p ).trim(); var value = cok.substring(p+1); value = decodeURIComponent( value ); cookie[ name ] = value; } return cookie; } function setCookie(name,value,dayToLive){ var cookie = name + "=" + encodeURIComponent( value ); if( typeof dayToLive === "number"){ cookie += "; max-age=" + ( dayToLive * 60 * 60 * 24 ); } cookie += ";path=/"; document.cookie = cookie; } function deleteCookie( name ){ var domain = location.host; var cookie = name + "=" + ";max-age=0;path=/"; document.cookie = cookie; var cookie = name + "=" + ";max-age=0;path=/;domain=."+domain; //去除qq登录后,token里的domain前的地址有一个点 document.cookie = cookie; } export default { getCookie: getCookie, setCookie: setCookie, deleteCookie: deleteCookie }
ad0b67b140bd3d1a7357fb4418d44b981b6fe7ca
{ "blob_id": "ad0b67b140bd3d1a7357fb4418d44b981b6fe7ca", "branch_name": "refs/heads/master", "committer_date": "2018-12-17T07:47:37", "content_id": "4e65ef9c1c701d3bbdd743579085970080badac3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "610a7210091fee9e88a66b3204ff3fdff43a58b4", "extension": "js", "filename": "cookIe.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 160764177, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1206, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/core/cookIe.js", "provenance": "stack-edu-0044.json.gz:89911", "repo_name": "lumingjia0904/new-test", "revision_date": "2018-12-17T07:47:37", "revision_id": "a06edbcd3c17daf19ba24ae04c32c15ae23dc533", "snapshot_id": "d91768598d5a23566861ae1eb3c2e457a17cdce4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/lumingjia0904/new-test/a06edbcd3c17daf19ba24ae04c32c15ae23dc533/src/core/cookIe.js", "visit_date": "2020-04-10T03:12:53.426148", "added": "2024-11-18T20:54:49.685924+00:00", "created": "2018-12-17T07:47:37", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz" }
import sys import os import argparse sys.path.append(os.path.dirname(os.path.dirname(__file__))) import bench import jax.numpy as jnp class ns2d(bench.bench2d): def __init__(self): super().__init__() self.parser.add_argument('--re', type=float, action='store', default=100.0, help='Reynolds') self.parser.add_argument('--ma', type=float, action='store', default=0.1, help='Mach') args = self.parser.parse_args() re = args.re ma = args.ma self.u0 = 1.0 ll = 1.0 nu = self.u0 * ll / re sound_speed = self.u0 / ma dx = ll / (self.side_size - 1.0) dy = ll / (self.side_size - 1.0) safe_factor_CFL = 0.2 safe_factor_diffusion = 0.1 dt_CFL = safe_factor_CFL * ma * dx dt_Re = safe_factor_diffusion * re * dx * dx dt = min(dt_CFL, dt_Re) self.dtdx = dt / dx self.dtdy = dt / dy dtdxx = dt / (dx * dx) dtdyy = dt / (dy * dy) self.nu_dtdxx = nu * dtdxx self.nu_dtdyy = nu * dtdyy self.c2_dtdx = sound_speed * sound_speed * self.dtdx self.c2_dtdy = sound_speed * sound_speed * self.dtdy print("\nSimulation info: 2D cavity flow") print(" Domain x from 0 to 1, y from 0 to 1") print(" Re: ", re) print(" Ma: ", ma) print(" dx = ", dx) print(" dt = ", dt) print(" lid velocity = ", self.u0) def initial_condition(self, dtype): u = jnp.zeros((self.side_size, self.side_size), dtype=dtype) v = jnp.zeros((self.side_size, self.side_size), dtype=dtype) p = jnp.zeros((self.side_size, self.side_size), dtype=dtype) u = u.at[1:self.side_size - 1, self.side_size - 1].set(self.u0) return u, v, p def test_result(self, u, t): pass # ua = self.analytical_mesh(u.dtype, t) # mid = int(self.side_size / 2) # # plt_step = max(math.floor(self.side_size / 500), 1) # # plt.plot(u[mid, ::plt_step]) # # plt.plot(ua[mid, ::plt_step]) # # plt.show() # error = ua - u # print(" \nCheck result") # print(" u at centre: ", u[mid, mid]) # print(" u analytical at centre: ", ua[mid, mid]) # print(" mean squared error: ", jnp.linalg.norm(error)) # print(" mean squared analytical: ", jnp.linalg.norm(ua))
d3c90119d83b84f721016bffea27ebdf17d0afc5
{ "blob_id": "d3c90119d83b84f721016bffea27ebdf17d0afc5", "branch_name": "refs/heads/main", "committer_date": "2023-03-02T23:23:39", "content_id": "ba4ac2a402f8db99ccc94da4b97e54fc1f5e4ddf", "detected_licenses": [ "MIT" ], "directory_id": "24fe144187aec62c56083c77f7625c9c259836ba", "extension": "py", "filename": "ns2d.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 587578004, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2633, "license": "MIT", "license_type": "permissive", "path": "/navier_stokes_2d/ns2d.py", "provenance": "stack-edu-0059.json.gz:613145", "repo_name": "xuzhen-he/XLA_numerical_models", "revision_date": "2023-03-02T23:23:39", "revision_id": "6781f88caf5b667ad18e18f0be2bee892ba7f70c", "snapshot_id": "6425d4ec64d7518c33797451a3ff0935fd8b6c8a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xuzhen-he/XLA_numerical_models/6781f88caf5b667ad18e18f0be2bee892ba7f70c/navier_stokes_2d/ns2d.py", "visit_date": "2023-04-09T10:59:29.974001", "added": "2024-11-18T22:43:27.828220+00:00", "created": "2023-03-02T23:23:39", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
package com.kh.klib.bkgroup.model.dao; import java.util.ArrayList; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.kh.klib.bkgroup.model.vo.BookGroup; import com.kh.klib.bkgroup.model.vo.BookGroupSearchValue; import com.kh.klib.bkgroup.model.vo.GroupSign; import com.kh.klib.common.model.vo.Files; import com.kh.klib.common.model.vo.PageInfo; import com.kh.klib.member.model.vo.Member; @Repository("gDAO") public class GroupDAO { public int getListCount(SqlSessionTemplate sqlSession) { return sqlSession.selectOne("groupMapper.getListCount"); } public ArrayList selectBList(SqlSessionTemplate sqlSession, PageInfo pi) { int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); System.out.println(pi.getCurrentPage()); System.out.println(offset); System.out.println("rowBounds : " + rowBounds); return (ArrayList)sqlSession.selectList("groupMapper.selectBList", null, rowBounds); } public ArrayList selectFList(SqlSessionTemplate sqlSession, PageInfo pi) { int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); return (ArrayList)sqlSession.selectList("groupMapper.selectFList", null, rowBounds); } public int insertGroup(SqlSessionTemplate sqlSession, BookGroup g) { return sqlSession.insert("groupMapper.insertGroup", g); } public int insertFile(SqlSessionTemplate sqlSession, Files f) { return sqlSession.insert("groupMapper.insertFile", f); } public BookGroup selectGroup(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.selectOne("groupMapper.selectGroup", gNo); } public Files selectFile(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.selectOne("groupMapper.selectFile", gNo); } public int deleteGroup(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.update("groupMapper.deleteGroup", gNo); } public int deleteFiles(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.update("groupMapper.deleteFiles", gNo); } public Member selectMember(SqlSessionTemplate sqlSession, int uNo) { return sqlSession.selectOne("groupMapper.selectMember", uNo); } public BookGroup selectBookGroup(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.selectOne("groupMapper.selectBookGroup", gNo); } public int updateGroup(SqlSessionTemplate sqlSession, BookGroup group) { return sqlSession.update("groupMapper.updateGroup", group); } public int updateFile(SqlSessionTemplate sqlSession, Files f) { return sqlSession.update("groupMapper.updateFile", f); } public int searchListCount(SqlSessionTemplate sqlSession, BookGroupSearchValue gsv) { return sqlSession.selectOne("groupMapper.searchListCount", gsv); } public ArrayList selectSearchGList(SqlSessionTemplate sqlSession, BookGroupSearchValue gsv, PageInfo pi) { int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); return (ArrayList)sqlSession.selectList("groupMapper.selectSearchGList", gsv, rowBounds); } public ArrayList selectSearchFList(SqlSessionTemplate sqlSession, BookGroupSearchValue gsv, PageInfo pi) { int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); return (ArrayList)sqlSession.selectList("groupMapper.selectSearchFList", gsv, rowBounds); } public int insertGroupSign(SqlSessionTemplate sqlSession, GroupSign gs) { return sqlSession.insert("groupMapper.inserGroupSign", gs); } public ArrayList<GroupSign> selectGroupSign(SqlSessionTemplate sqlSession, int uNo) { return (ArrayList)sqlSession.selectList("groupMapper.selectGroupSign", uNo); } public int selectGroupSignListCount(SqlSessionTemplate sqlSession, int uNo) { return sqlSession.selectOne("groupMapper.selectGroupSignListCount", uNo); } public ArrayList<BookGroup> selectBookGroupList(SqlSessionTemplate sqlSession) { return (ArrayList)sqlSession.selectList("groupMapper.selectBookGroupList"); } public int getSignMemberCount(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.selectOne("groupMapper.getSignMemberCount", gNo); } public ArrayList<BookGroup> selectMyBookGroupList(SqlSessionTemplate sqlSession, String nickname) { return (ArrayList)sqlSession.selectList("groupMapper.selectMyBookGroupList", nickname); } public GroupSign selectMyGroupSign(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.selectOne("groupMapper.selectMyGroupSign", gNo); } public ArrayList<GroupSign> selectgroupSignGno(SqlSessionTemplate sqlSession, int gNo) { return (ArrayList)sqlSession.selectList("groupMapper.selectgroupSignGno", gNo); } public int deleteGsCancle(SqlSessionTemplate sqlSession, GroupSign gs) { return sqlSession.delete("groupMapper.deleteGsCancle", gs); } public ArrayList<Member> selectSignMemberList(SqlSessionTemplate sqlSession, int signUno) { return (ArrayList)sqlSession.selectList("groupMapper.selectSignMemberList", signUno); } public int updateGsMemberApply(SqlSessionTemplate sqlSession, GroupSign gs) { return sqlSession.update("groupMapper.updateGsMemberApply", gs); } public int updateGsMemberNoApply(SqlSessionTemplate sqlSession, GroupSign gs) { return sqlSession.update("groupMapper.updateGsMemberNoApply", gs); } public int updateDeadLine(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.update("groupMapper.updateDeadLine", gNo); } public int updateNoDeadLine(SqlSessionTemplate sqlSession, int gNo) { return sqlSession.update("groupMapper.updateNoDeadLine", gNo); } }
640442cef77bdd5ae33a04047d45e8032864c1e2
{ "blob_id": "640442cef77bdd5ae33a04047d45e8032864c1e2", "branch_name": "refs/heads/develop", "committer_date": "2021-07-29T12:43:51", "content_id": "0e78aaec9554d2f41c97d42cae26524a1c60ebf9", "detected_licenses": [ "MIT" ], "directory_id": "5190f540ac29868ca11a795b30ba36a99091055e", "extension": "java", "filename": "GroupDAO.java", "fork_events_count": 0, "gha_created_at": "2021-06-14T12:38:37", "gha_event_created_at": "2021-07-29T12:43:52", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 376818075, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6000, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/com/kh/klib/bkgroup/model/dao/GroupDAO.java", "provenance": "stack-edu-0028.json.gz:720529", "repo_name": "dvdpid/KHLIB", "revision_date": "2021-07-29T12:43:51", "revision_id": "7a7c9c5e7c1c801901ffa7cc66c083b0a7255dab", "snapshot_id": "35e45aeed439095f31d68921ceb06df8c46acfe4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dvdpid/KHLIB/7a7c9c5e7c1c801901ffa7cc66c083b0a7255dab/src/main/java/com/kh/klib/bkgroup/model/dao/GroupDAO.java", "visit_date": "2023-06-27T12:56:54.574637", "added": "2024-11-18T22:58:43.503475+00:00", "created": "2021-07-29T12:43:51", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
// Copyright (c) OpenFaaS Author(s) 2018. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package function import ( "io/ioutil" "net/http" "strings" "github.com/openfaas-incubator/go-function-sdk" ) var ( usernameSecret string passwordSecret string ) func init() { // optional, add error handling, or read on each request / use sync.Once() usernameRaw, err := ioutil.ReadFile("/var/openfaas/secrets/fn-basic-auth-username") if err != nil { panic(err) } usernameSecret = strings.TrimSpace(string(usernameRaw)) passwordRaw, err := ioutil.ReadFile("/var/openfaas/secrets/fn-basic-auth-password") if err != nil { panic(err) } passwordSecret = strings.TrimSpace(string(passwordRaw)) } // Handle a function invocation func Handle(req handler.Request) (handler.Response, error) { var err error res := handler.Response{} if !isAuthorized(req) { message := "You must authorize." res.Body = []byte(message) res.StatusCode = http.StatusUnauthorized res.Header = http.Header{ "WWW-Authenticate": []string{`Basic realm="Restricted"`}, } return res, err } res.StatusCode = http.StatusOK res.Body = []byte("Authorization. OK.") return res, err } func isAuthorized(req handler.Request) bool { r := http.Request{} r.Header = http.Header{ "Authorization": []string{req.Header.Get("Authorization")}, } if username, password, ok := r.BasicAuth(); ok && username == usernameSecret && password == passwordSecret { return true } return false }
2e4cf134556015816d561aa67497d2a920636150
{ "blob_id": "2e4cf134556015816d561aa67497d2a920636150", "branch_name": "refs/heads/master", "committer_date": "2020-12-21T17:23:42", "content_id": "0f24ccfc8c1c6c787251d54db2cc85e9be5c052c", "detected_licenses": [ "MIT" ], "directory_id": "68edbf88e2a4996fb85c4d7018fabf91b02bfe4a", "extension": "go", "filename": "handler.go", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 143605994, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1566, "license": "MIT", "license_type": "permissive", "path": "/basic-auth/handler.go", "provenance": "stack-edu-0017.json.gz:182795", "repo_name": "openfaas-incubator/openfaas-function-auth", "revision_date": "2020-12-21T17:23:42", "revision_id": "7f1ded39591f6fca068795435362eb3f4e69f5df", "snapshot_id": "00a6b2ab1d97933963007d2fffc4ed3e2f61b192", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/openfaas-incubator/openfaas-function-auth/7f1ded39591f6fca068795435362eb3f4e69f5df/basic-auth/handler.go", "visit_date": "2021-06-19T10:14:49.732849", "added": "2024-11-18T23:49:14.954753+00:00", "created": "2020-12-21T17:23:42", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Meeting { public partial class NewPersonForm : Form { private MainForm Parent; public NewPersonForm(MainForm parent) { InitializeComponent(); this.Parent = parent; tbName.KeyDown += new KeyEventHandler(tb_KeyDown); } private void tb_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { savePerson(); } } private void bSave_Click(object sender, EventArgs e) { savePerson(); } private void savePerson() { Parent.NewPeopleNames.Add(tbName.Text); bool[] days = new bool[] { false, false, false, false, false }; if (checkBox1.Checked) { days[0] = true; } if (checkBox2.Checked) { days[1] = true; } if (checkBox3.Checked) { days[2] = true; } if (checkBox4.Checked) { days[3] = true; } if (checkBox5.Checked) { days[4] = true; } Parent.NewPeopleDays.Add(days); tbName.Clear(); checkBox1.Checked = false; checkBox2.Checked = false; checkBox3.Checked = false; checkBox4.Checked = false; checkBox5.Checked = false; this.ActiveControl = tbName; } private void bClose_Click(object sender, EventArgs e) { Close(); } } }
82e0fa1a9154d131ac00a912f04565079c659bc2
{ "blob_id": "82e0fa1a9154d131ac00a912f04565079c659bc2", "branch_name": "refs/heads/master", "committer_date": "2015-06-06T21:51:54", "content_id": "1dfe739bafdf127244d9c6928c1c45c91bf9d66a", "detected_licenses": [ "MIT" ], "directory_id": "0209b2888b845f6bfb0e0047e3322a1affcd82f2", "extension": "cs", "filename": "NewPersonForm.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 36972381, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1892, "license": "MIT", "license_type": "permissive", "path": "/Meeting/NewPersonForm.cs", "provenance": "stack-edu-0010.json.gz:596761", "repo_name": "martindisch/Meeting", "revision_date": "2015-06-06T21:51:54", "revision_id": "39a6e6729e6ab95ca6746d73f98230a36e9678fd", "snapshot_id": "b5c0b7e7f45145c042a2912c8121a09ae631ab0e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/martindisch/Meeting/39a6e6729e6ab95ca6746d73f98230a36e9678fd/Meeting/NewPersonForm.cs", "visit_date": "2021-01-20T11:45:35.110652", "added": "2024-11-18T23:09:47.620718+00:00", "created": "2015-06-06T21:51:54", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
const { omit } = require("lodash"); const should = require("should"); const CodeBuilder = require("./code-builder"); const { removeProperty } = require("./general"); const { constructAppendedParamsCode } = require("./params"); describe("Test helpers methods", () => { describe("Test RemoveProperty helper", () => { it("RemoveProperty called with invalid params", () => { (function () { removeProperty("str", "property"); }.should.throw(new Error("originalObject must be an object."))); }); it("returned object stayed the same if a non existing property name sent", () => { const obj = { a: 1, b: 2 }; const result = removeProperty(obj, "c"); result.should.equal(obj); }); it("insensitive case property removed from object successfully", () => { const obj = { a: 1, b: 2 }; const result = removeProperty(obj, "B"); result.should.deepEqual(omit(obj, "b")); }); }); describe("Test constructAppendedParamsCode helper", () => { const fakeParams = [ { name: "a", value: "1" }, { name: "b", value: "2" }, ]; it("called with invalid code argument", () => { (function () { constructAppendedParamsCode({}, []); }.should.throw( new Error("code argument must be an instance of CodeBuilder") )); }); it("called with invalid params argument", () => { (function () { constructAppendedParamsCode(new CodeBuilder(), {}); }.should.throw(new Error("params argument must be an array"))); }); describe("called with multiple options variations", () => { const fakeParamsWithFile = [ ...fakeParams, { name: "a", fileName: "fakeFileName" }, ]; const lastIndex = params.length - 1; it("called with file param and false isBrowser option", () => { const result = constructAppendedParamsCode( new CodeBuilder(), fakeParamsWithFile, { isBrowser: false, } ); result.should.be.an.instanceof(CodeBuilder); result .join() .should.containEql( `fs.createReadStream("/PATH/TO/${fakeParamsWithFile[lastIndex].fileName}")` ); }); it("called with file param and true isBrowser option", () => { const result = constructAppendedParamsCode( new CodeBuilder(), fakeParamsWithFile, { isBrowser: true, } ); result.should.be.an.instanceof(CodeBuilder); result .join() .should.containEql( `yourAppInput.files[0], ${JSON.stringify( params[lastIndex].fileName )}` ); }); it("called with dataVarName option", () => { const result = constructAppendedParamsCode(new CodeBuilder(), params, { dataVarName: "dataObject", }); result.should.be.an.instanceof(CodeBuilder); result.join().should.containEql("dataObject.append"); }); }); it("returned new code object with two params", () => { const result = constructAppendedParamsCode(new CodeBuilder(), fakeParams); result.should.be.an.instanceof(CodeBuilder); result.getLength().should.equal(2); result .join() .should.equal('data.append("a", "1");\ndata.append("b", "2");'); }); }); });
621051b8a66c396c9c1cffaee2b7afc692f8ef4f
{ "blob_id": "621051b8a66c396c9c1cffaee2b7afc692f8ef4f", "branch_name": "refs/heads/master", "committer_date": "2023-03-22T07:43:53", "content_id": "f92751f874a05c5efbec0977af83b83e4cb285cc", "detected_licenses": [ "MIT" ], "directory_id": "82c0f56c4c5c7978325aa8bd8d24bb05fefc6f59", "extension": "js", "filename": "helpers.spec.js", "fork_events_count": 4, "gha_created_at": "2019-07-10T11:48:02", "gha_event_created_at": "2023-03-22T07:43:22", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 196195438, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3422, "license": "MIT", "license_type": "permissive", "path": "/src/helpers/helpers.spec.js", "provenance": "stack-edu-0041.json.gz:274711", "repo_name": "RapidAPI/httpsnippet", "revision_date": "2023-03-22T07:43:53", "revision_id": "bb95ea86bdaa7e7523563730f4a34ae946038b29", "snapshot_id": "0359cbd5e7e8842e4770881c27682f85dc10e84d", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/RapidAPI/httpsnippet/bb95ea86bdaa7e7523563730f4a34ae946038b29/src/helpers/helpers.spec.js", "visit_date": "2023-05-10T16:38:55.024342", "added": "2024-11-18T22:41:32.552701+00:00", "created": "2023-03-22T07:43:53", "int_score": 3, "score": 2.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz" }
import React from "react"; import EventProxy from "./eventProxy"; import { fetchGet } from "./IO"; const debug = require("debug")("react-safe-component"); const REGEX = /\d+_\d+/g; const lifeCycleMethods = [ // "componentWillMount", "componentDidMount" // "componentWillReceiveProps", // "shouldComponentUpdate", // "componentWillUpdate", // "componentDidUpdate", // "componentWillUnmount", // "render" ]; /** * 组件接受到消息的回调 * targetKeys:查询字符串,需要从本地store里面获取 */ function messageReceiveCallback(msg, store) { const currentPath = "/" + window.location.pathname.split("/").slice(2); const page = window.__pages.filter(el => { return el.pagePath == currentPath; })[0]; const { eventType, interfaceAddress, modal, targetKeys, eventsSettings = {}, events = [], key } = msg; const pageData = store.getState()[page.pageName]; const queryParams = targetKeys.reduce((prev, cur) => { const { fieldDesc, fieldName, key } = cur; const fieldValue = pageData[key] || ""; prev[fieldName] = fieldValue; return prev; }, {}); const { attribute } = eventsSettings; // events的格式为:(页面key_组件key) let pageKey, elementKey; for (let t = 0, len = events.length; t < len; t++) { const el = REGEX.exec(events[t]); [pageKey, elementKey] = el && el[0].split("_"); } console.log( "messageReceiveCallback中的数据===", msg, store, queryParams, this.props.propsUtils ); console.log('queryParams===',queryParams); // 获取数据设置到某一个组件的某一个属性上 fetchGet(interfaceAddress, queryParams) .then(res => { this.props.propsUtils.settingPropsDirectly(key, attribute, [ { id: 12, name: "覃亮", sex: "男" }, { id: 11, name: "方康蕾", sex: "女" } ]); }) .catch(e => { }); } const wrap = ( Component, { events = [], type, addonMethods = {}, eventsSettings = {}, store = {}, vergineType = "", componentKey = "", elementKey = "", key = "", dispatch = () => {}, propsUtils = {} } ) => { const currentPath = "/" + window.location.pathname.split("/").slice(2); const page = window.__pages.filter(el => { return el.pagePath == currentPath; })[0]; /** * 添加实例方法 */ const keys = Object.keys(addonMethods); console.log("addonMethods=====", addonMethods); for (let t = 0, len = keys.length; t < len; t++) { const methodName = addonMethods[keys[t]]; Component.prototype[methodName] = (value, cmptKey) => { dispatch({ type: [page.pageName] + ".", payload: { [cmptKey]: value } }); }; } /** * 已经挂载了错误事件 */ if (!Component.prototype.renderSafeComponentError) { Component.prototype.renderSafeComponentError = function() { return "Oops... an error has occured"; }; } const wrapMethod = methodName => { const originalMethod = Component.prototype[methodName]; if (!originalMethod) { Component.prototype[methodName] = function() {}; } Component.prototype[methodName] = function() { try { if (methodName == "componentDidMount") { // 数据组件监听,行为组件直接绑定到click上 if (type == "data") { for (let t = 0, len = events.length; t < len; t++) { EventProxy.on(events[t], msg => { console.log("数据组件接受到事件:", eventsSettings, events, msg); messageReceiveCallback.bind(this)( { ...msg, eventsSettings, events }, store ); }); } return originalMethod.apply(this, arguments); } } return originalMethod.apply(this, arguments); } catch (e) { debug(e); if (methodName === "render") { return React.createElement( "div", { className: "react__safecomponent-error" }, Component.prototype.renderSafeComponentError.call(this) ); } if (methodName === "shouldComponentUpdate") { return false; } } }; }; lifeCycleMethods.forEach(wrapMethod); return Component; }; export default wrap;
42080ba7baea82b1dc53f98e109fcab4dda65970
{ "blob_id": "42080ba7baea82b1dc53f98e109fcab4dda65970", "branch_name": "refs/heads/master", "committer_date": "2018-06-29T05:09:08", "content_id": "d33cb21e6a94f084c21c39dbde82a96b2b010e6f", "detected_licenses": [ "MIT" ], "directory_id": "ee85a49f59d7c4c54d64f2457e614b63df99b74c", "extension": "js", "filename": "motifyLifecycle.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 133620017, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4481, "license": "MIT", "license_type": "permissive", "path": "/app/modules/utils/motifyLifecycle.js", "provenance": "stack-edu-0036.json.gz:503805", "repo_name": "liangklfangl/structor-usage", "revision_date": "2018-06-29T05:09:08", "revision_id": "331e0bdb43eb36d4c72c6a654b7b68138a831438", "snapshot_id": "08741781b274974702d0ff3ff1693d43e5f66eda", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liangklfangl/structor-usage/331e0bdb43eb36d4c72c6a654b7b68138a831438/app/modules/utils/motifyLifecycle.js", "visit_date": "2020-03-17T13:10:18.362966", "added": "2024-11-19T02:04:23.536471+00:00", "created": "2018-06-29T05:09:08", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
var map; var markerArray = []; function initMap() { var startplace = {lat: 14.5176, lng: 121.0509}; var map = new google.maps.Map(document.getElementById('map'), { center: startplace, zoom: 13 }); var submit = document.getElementById('submit'); submit.addEventListener('click',function(e){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }) e.preventDefault(); var formData = { start: $('#start').val(), end: $('#end').val(), device_id : $('#device_id').val() } console.log(formData); $.ajax({ type:"POST", url : "/history", data: formData, datatype: 'json', success: function(data){ console.log(data); clearMarkers(); $.each(data,function(index){ console.log(data[index].latitude); var myLocation = {lat: data[index].latitude , lng: data[index].longitude}; var marker = new google.maps.Marker({position: myLocation, map: map}); markerArray.push(marker); marker.setMap(map); }); },error: function(data){ console.log(data); } }) }); } function setMapOnAll(map) { for (var i = 0; i < markerArray.length; i++) { markerArray[i].setMap(map); } } // Removes the markers from the map, but keeps them in the array. function clearMarkers() { setMapOnAll(null); markerArray = []; }
c5888f8420848f79089878f99f679b346a32e46c
{ "blob_id": "c5888f8420848f79089878f99f679b346a32e46c", "branch_name": "refs/heads/master", "committer_date": "2018-09-12T18:07:23", "content_id": "f547889497354133a984ab2f0152df877818fa2f", "detected_licenses": [ "MIT" ], "directory_id": "f6df73f52d4913937a99a9ca9d3d1f18099f4284", "extension": "js", "filename": "history.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137714654, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1558, "license": "MIT", "license_type": "permissive", "path": "/public/js/history.js", "provenance": "stack-edu-0043.json.gz:286930", "repo_name": "michaelAbrigos/biketrackSocial", "revision_date": "2018-09-12T18:07:23", "revision_id": "cba917ebdb681950a4ea1c4187c6f9081b8d9dc4", "snapshot_id": "3191584d67edb5425e6abc6fc7033b6a63a79a8c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/michaelAbrigos/biketrackSocial/cba917ebdb681950a4ea1c4187c6f9081b8d9dc4/public/js/history.js", "visit_date": "2020-03-20T20:55:39.882986", "added": "2024-11-19T01:21:37.231325+00:00", "created": "2018-09-12T18:07:23", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
package com.android.teacher.fragments; import android.content.res.TypedArray; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.android.teacher.R; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class AlfavitFragment extends Fragment { private static String POS = "pos"; private int pos; private String[] names; TypedArray images; TypedArray sounds; MediaPlayer mp = new MediaPlayer(); public static AlfavitFragment newInstance(int position){ Bundle args = new Bundle(); args.putInt(POS, position); AlfavitFragment fragment = new AlfavitFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pos = getArguments().getInt(POS); names = getResources().getStringArray(R.array.names); images = getResources().obtainTypedArray(R.array.images); sounds = getResources().obtainTypedArray(R.array.sounds); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_alfavit, null); ImageView image = (ImageView)view.findViewById(R.id.imageAlfavit); TextView name = (TextView)view.findViewById(R.id.name); ImageButton btn = (ImageButton)view.findViewById(R.id.sound); image.setImageResource(images.getResourceId(pos, -1)); name.setText(names[pos]); setPlayLoad(); btn.setVisibility(View.VISIBLE); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mp.start(); } }); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) {setPlayLoad();} }); return view; } private void setPlayLoad(){ byte[] playload = new byte[0]; try { int soundID = sounds.getResourceId(pos, -1); playload = IOUtils.toByteArray(getContext().getResources().openRawResource(soundID)); } catch (IOException e) {e.printStackTrace();} playMp3(playload); } private void playMp3(byte[] mp3SoundByteArray) { try { // create temp file that will hold byte array File tempMp3 = File.createTempFile("tempSnd", "mp3", getActivity().getCacheDir()); tempMp3.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tempMp3); fos.write(mp3SoundByteArray); fos.close(); // Tried passing path directly, but kept getting // "Prepare failed.: status=0x1" // so using file descriptor instead FileInputStream fis = new FileInputStream(tempMp3); mp.reset(); mp.setDataSource(fis.getFD()); mp.prepareAsync(); } catch (IOException ex) { ex.printStackTrace(); } } }
69d16a1d3b110bcc64bb66523f3b4b87799d33b7
{ "blob_id": "69d16a1d3b110bcc64bb66523f3b4b87799d33b7", "branch_name": "refs/heads/master", "committer_date": "2016-06-19T18:32:10", "content_id": "ee97b4fee2df5d72afadc25a65716b924350ed95", "detected_licenses": [ "MIT" ], "directory_id": "46ec8186eb9e6fcf7f896639b819a1a52f2d4ce6", "extension": "java", "filename": "AlfavitFragment.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 59862350, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3492, "license": "MIT", "license_type": "permissive", "path": "/app/src/main/java/com/android/teacher/fragments/AlfavitFragment.java", "provenance": "stack-edu-0027.json.gz:588437", "repo_name": "YadgarBabaev/Nestan-Teacher", "revision_date": "2016-06-19T18:32:10", "revision_id": "edfaa90e0eaa49d14bd8d9042198176542d74f41", "snapshot_id": "9ca5f86e670fe40eb9135a5760920e360412e6f0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/YadgarBabaev/Nestan-Teacher/edfaa90e0eaa49d14bd8d9042198176542d74f41/app/src/main/java/com/android/teacher/fragments/AlfavitFragment.java", "visit_date": "2020-05-25T14:59:21.976245", "added": "2024-11-19T00:02:00.748381+00:00", "created": "2016-06-19T18:32:10", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
using AL.Core.Definitions; namespace AL.Core.Extensions { /// <summary> /// Provides a set of extensions for <see cref="System.Enum" />s /// </summary> public static class EnumExtensions { /// <summary> /// Converts a <see cref="Slot" /> to an <see cref="EquipmentSlot" />. /// </summary> /// <param name="slot">The <see cref="Slot" /> to convert.</param> /// <returns> /// <see cref="EquipmentSlot" /> /// </returns> public static EquipmentSlot ToEquipmentSlot(this Slot slot) => (EquipmentSlot)(int)slot; /// <summary> /// Converts an <see cref="EquipmentSlot" /> to a <see cref="Slot" />. /// </summary> /// <param name="equipmentSlot">The <see cref="EquipmentSlot" /> to convert.</param> /// <returns> /// <see cref="Slot" /> /// </returns> public static Slot ToSlot(this EquipmentSlot equipmentSlot) => (Slot)(int)equipmentSlot; /// <summary> /// Converts an <see cref="TradeSlot" /> to a <see cref="Slot" />. /// </summary> /// <param name="tradeSlot">The <see cref="TradeSlot" /> to convert.</param> /// <returns> /// <see cref="Slot" /> /// </returns> public static Slot ToSlot(this TradeSlot tradeSlot) => (Slot)(int)tradeSlot; /// <summary> /// Converts a <see cref="Slot" /> to an <see cref="TradeSlot" />. /// </summary> /// <param name="slot">The <see cref="Slot" /> to convert.</param> /// <returns> /// <see cref="TradeSlot" /> /// </returns> public static TradeSlot ToTradeSlot(this Slot slot) => (TradeSlot)(int)slot; } }
9b9d85f3bed816dd9d28064dd646994d35fc3f75
{ "blob_id": "9b9d85f3bed816dd9d28064dd646994d35fc3f75", "branch_name": "refs/heads/main", "committer_date": "2021-10-04T19:08:05", "content_id": "0d4768429653b4fab57a5abd20ba005320d58a4b", "detected_licenses": [ "MIT" ], "directory_id": "1141086bc9d4651d2ce099bd0aaa5ed389720571", "extension": "cs", "filename": "EnumExtensions.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 377389665, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1761, "license": "MIT", "license_type": "permissive", "path": "/AL.Core/Extensions/EnumExtensions.cs", "provenance": "stack-edu-0014.json.gz:245140", "repo_name": "Sichii/ALClientCS", "revision_date": "2021-10-04T19:08:05", "revision_id": "5fd7e12d537628684a1de9e4e88abccecef509c4", "snapshot_id": "0810530387f267b3a7abcb54a1ee466b1d8eac32", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Sichii/ALClientCS/5fd7e12d537628684a1de9e4e88abccecef509c4/AL.Core/Extensions/EnumExtensions.cs", "visit_date": "2023-08-29T12:36:46.341279", "added": "2024-11-18T23:18:14.492168+00:00", "created": "2021-10-04T19:08:05", "int_score": 3, "score": 3.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
# Garlic Bread > Based on [https://www.simplyrecipes.com/recipes/garlic_bread/](https://www.simplyrecipes.com/recipes/garlic_bread/) and [https://www.washingtonpost.com/recipes/triple-garlic-bread/17638](https://www.washingtonpost.com/recipes/triple-garlic-bread/17638) <!-- {cts} rating=4; (User can specify rating on scale of 1-5) --> Personal rating: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-regular-star: <!-- {cte} --> <!-- {cts} name_image=garlic_bread.jpeg; (User can specify image name) --> ![garlic_bread.jpeg](./garlic_bread.jpeg){: .image-recipe loading=lazy } <!-- {cte} --> ## Ingredients - [ ] ~2-4 Garlic Cloves, grated or very finely diced to a paste - [ ] ~2-4 tbsp butter - [ ] ~2 tbsp Extra-virgin Olive Oil - [ ] 1/2 tsp kosher salt - [ ] Bread Loaf - [ ] ~3 tbsp Cheese, grated ## Recipe - Position rack in middle to upper third of the oven. Preheat to 400F - Combine everything except for the cheese in a microwave safe bowl and microwave until liquid (1 min + ~15s intervals) - Spread evenly on each half and top with cheese - Bake for 10-15 min until golden and crispy - Then turn up to a broil for a few minutes to finish - Slice and serve ## Notes - [Extra Tips](https://www.budgetbytes.com/garlic-bread/) - Also consider chives or parsley
81448b63421d0fcd0fbd97424520cae71315824c
{ "blob_id": "81448b63421d0fcd0fbd97424520cae71315824c", "branch_name": "refs/heads/main", "committer_date": "2023-08-29T01:52:20", "content_id": "47c9a70347e5ba753162852fc0cfe3ae547ea2f2", "detected_licenses": [ "MIT" ], "directory_id": "0031e2199bff2bed2286202cdf04a99192109389", "extension": "md", "filename": "garlic_bread.md", "fork_events_count": 1, "gha_created_at": "2017-09-13T00:21:11", "gha_event_created_at": "2023-06-01T12:08:15", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 103333639, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1430, "license": "MIT", "license_type": "permissive", "path": "/docs/sides/garlic_bread.md", "provenance": "stack-edu-markdown-0002.json.gz:253265", "repo_name": "KyleKing/recipes", "revision_date": "2023-08-29T01:52:20", "revision_id": "6d625398950564f44d1f87b3b89562e40285d0a0", "snapshot_id": "186d8bb1037ebc74500d9bb1aa57a8bcf2bb0897", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/KyleKing/recipes/6d625398950564f44d1f87b3b89562e40285d0a0/docs/sides/garlic_bread.md", "visit_date": "2023-08-30T04:56:54.446532", "added": "2024-11-18T21:46:00.207570+00:00", "created": "2023-08-29T01:52:20", "int_score": 3, "score": 3.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
package com.geek.conding.business.base.async; import com.geek.conding.business.constants.TaskConstants; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; /** * @Author 张耀烽 * @Date Created in 2020/4/4 0:05 * @Version v1.0 * @Description 异步消息队列 */ @Component public class QueueAsync { @Autowired private RedisTemplate redisTemplate; /** * 异步发送日志消息队列 * <p> * Redis */ @Async(TaskConstants.TASK_EXECUTOR) public void sendQueueSysLog(String ip, String uri, String methodName, String logTypeName, String logDesc) { ImmutableMap<String, String> queueMap = ImmutableMap.<String, String>builder() //用户信息暂时为null .put("user", "") .put("ip", ip) .put("uri", uri) .put("methodName", methodName) .put("logTypeName", logTypeName) .put("logDesc", logDesc) .build(); redisTemplate.opsForList().rightPush("syslog:log", queueMap); } /** * 异步发送日志消息队列 * <p> * 数据库RDS */ @Async(TaskConstants.TASK_EXECUTOR) public void sendSysLog(String ip, String uri, String methodName, String logTypeName, String logDesc) { ImmutableMap<String, String> queueMap = ImmutableMap.<String, String>builder() .put("user", "") .put("ip", ip) .put("uri", uri) .put("methodName", methodName) .put("logTypeName", logTypeName) .put("logDesc", logDesc) .build(); //这里要保存到数据库 之后完善 } }
5f8724dfaf76e975df72ec0cb285f22ca77a1ae6
{ "blob_id": "5f8724dfaf76e975df72ec0cb285f22ca77a1ae6", "branch_name": "refs/heads/master", "committer_date": "2020-07-22T10:29:10", "content_id": "7e796336162fcc9007ad77f5f349b30c4b3e9b41", "detected_licenses": [ "Apache-2.0" ], "directory_id": "352f5a3e8d166f9f84bb659885b4d2a63b39ea48", "extension": "java", "filename": "QueueAsync.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": 1926, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/geek/conding/business/base/async/QueueAsync.java", "provenance": "stack-edu-0031.json.gz:114678", "repo_name": "JadeChong/easy_boot", "revision_date": "2020-07-22T10:29:10", "revision_id": "603e4bd6f83336b7de45a12fee2b2f1786e3557f", "snapshot_id": "729347962255938863299a56b1948fea7aee80ce", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JadeChong/easy_boot/603e4bd6f83336b7de45a12fee2b2f1786e3557f/src/main/java/com/geek/conding/business/base/async/QueueAsync.java", "visit_date": "2022-11-23T04:53:56.747413", "added": "2024-11-18T22:33:17.726301+00:00", "created": "2020-07-22T10:29:10", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
/* This file is generated from specs/discord/webhook.endpoints-params.json, Please don't edit it. */ /** * @file specs-code/discord/webhook.endpoints-params.h * @see https://discord.com/developers/docs/resources/webhook */ /* Create Webhook */ /* defined at specs/discord/webhook.endpoints-params.json:9:22 */ /** * @verbatim embed:rst:leading-asterisk * .. container:: toggle * .. container:: header * **Methods** * * Initializer: * * :code:`void discord_create_webhook_params_init(struct discord_create_webhook_params *)` * * Cleanup: * * :code:`void discord_create_webhook_params_cleanup(struct discord_create_webhook_params *)` * * :code:`void discord_create_webhook_params_list_free(struct discord_create_webhook_params **)` * * JSON Decoder: * * :code:`void discord_create_webhook_params_from_json(char *rbuf, size_t len, struct discord_create_webhook_params **)` * * :code:`void discord_create_webhook_params_list_from_json(char *rbuf, size_t len, struct discord_create_webhook_params ***)` * * JSON Encoder: * * :code:`void discord_create_webhook_params_to_json(char *wbuf, size_t len, struct discord_create_webhook_params *)` * * :code:`void discord_create_webhook_params_list_to_json(char *wbuf, size_t len, struct discord_create_webhook_params **)` * @endverbatim */ struct discord_create_webhook_params { /* specs/discord/webhook.endpoints-params.json:12:20 '{ "name": "name", "type":{ "base":"char", "dec":"*" }, "comment":"name of the webhook(1-80) chars" }' */ char *name; /**< name of the webhook(1-80) chars */ /* specs/discord/webhook.endpoints-params.json:13:20 '{ "name": "avatar", "type":{ "base":"char", "dec":"*" }, "inject_if_not":null, "comment":"base64 image for the default webhook avatar" }' */ char *avatar; /**< base64 image for the default webhook avatar */ }; extern void discord_create_webhook_params_cleanup_v(void *p); extern void discord_create_webhook_params_cleanup(struct discord_create_webhook_params *p); extern void discord_create_webhook_params_init_v(void *p); extern void discord_create_webhook_params_init(struct discord_create_webhook_params *p); extern void discord_create_webhook_params_from_json_v(char *json, size_t len, void *pp); extern void discord_create_webhook_params_from_json(char *json, size_t len, struct discord_create_webhook_params **pp); extern size_t discord_create_webhook_params_to_json_v(char *json, size_t len, void *p); extern size_t discord_create_webhook_params_to_json(char *json, size_t len, struct discord_create_webhook_params *p); extern void discord_create_webhook_params_list_free_v(void **p); extern void discord_create_webhook_params_list_free(struct discord_create_webhook_params **p); extern void discord_create_webhook_params_list_from_json_v(char *str, size_t len, void *p); extern void discord_create_webhook_params_list_from_json(char *str, size_t len, struct discord_create_webhook_params ***p); extern size_t discord_create_webhook_params_list_to_json_v(char *str, size_t len, void *p); extern size_t discord_create_webhook_params_list_to_json(char *str, size_t len, struct discord_create_webhook_params **p); /* Modify Webhook */ /* defined at specs/discord/webhook.endpoints-params.json:19:22 */ /** * @verbatim embed:rst:leading-asterisk * .. container:: toggle * .. container:: header * **Methods** * * Initializer: * * :code:`void discord_modify_webhook_params_init(struct discord_modify_webhook_params *)` * * Cleanup: * * :code:`void discord_modify_webhook_params_cleanup(struct discord_modify_webhook_params *)` * * :code:`void discord_modify_webhook_params_list_free(struct discord_modify_webhook_params **)` * * JSON Decoder: * * :code:`void discord_modify_webhook_params_from_json(char *rbuf, size_t len, struct discord_modify_webhook_params **)` * * :code:`void discord_modify_webhook_params_list_from_json(char *rbuf, size_t len, struct discord_modify_webhook_params ***)` * * JSON Encoder: * * :code:`void discord_modify_webhook_params_to_json(char *wbuf, size_t len, struct discord_modify_webhook_params *)` * * :code:`void discord_modify_webhook_params_list_to_json(char *wbuf, size_t len, struct discord_modify_webhook_params **)` * @endverbatim */ struct discord_modify_webhook_params { /* specs/discord/webhook.endpoints-params.json:22:20 '{ "name": "name", "type":{ "base":"char", "dec":"*" }, "inject_if_not":null, "comment":"name of the webhook(1-80) chars" }' */ char *name; /**< name of the webhook(1-80) chars */ /* specs/discord/webhook.endpoints-params.json:23:20 '{ "name": "avatar", "type":{ "base":"char", "dec":"*" }, "inject_if_not":null, "comment":"base64 image for the default webhook avatar" }' */ char *avatar; /**< base64 image for the default webhook avatar */ /* specs/discord/webhook.endpoints-params.json:24:20 '{ "name": "channel_id", "type":{ "base":"char", "dec":"*", "converter":"snowflake" }, "inject_if_not":0, "comment":"the new channel id this webhook should be moved to" }' */ u64_snowflake_t channel_id; /**< the new channel id this webhook should be moved to */ }; extern void discord_modify_webhook_params_cleanup_v(void *p); extern void discord_modify_webhook_params_cleanup(struct discord_modify_webhook_params *p); extern void discord_modify_webhook_params_init_v(void *p); extern void discord_modify_webhook_params_init(struct discord_modify_webhook_params *p); extern void discord_modify_webhook_params_from_json_v(char *json, size_t len, void *pp); extern void discord_modify_webhook_params_from_json(char *json, size_t len, struct discord_modify_webhook_params **pp); extern size_t discord_modify_webhook_params_to_json_v(char *json, size_t len, void *p); extern size_t discord_modify_webhook_params_to_json(char *json, size_t len, struct discord_modify_webhook_params *p); extern void discord_modify_webhook_params_list_free_v(void **p); extern void discord_modify_webhook_params_list_free(struct discord_modify_webhook_params **p); extern void discord_modify_webhook_params_list_from_json_v(char *str, size_t len, void *p); extern void discord_modify_webhook_params_list_from_json(char *str, size_t len, struct discord_modify_webhook_params ***p); extern size_t discord_modify_webhook_params_list_to_json_v(char *str, size_t len, void *p); extern size_t discord_modify_webhook_params_list_to_json(char *str, size_t len, struct discord_modify_webhook_params **p); /* Modify Webhook with Token */ /* defined at specs/discord/webhook.endpoints-params.json:30:22 */ /** * @verbatim embed:rst:leading-asterisk * .. container:: toggle * .. container:: header * **Methods** * * Initializer: * * :code:`void discord_modify_webhook_with_token_params_init(struct discord_modify_webhook_with_token_params *)` * * Cleanup: * * :code:`void discord_modify_webhook_with_token_params_cleanup(struct discord_modify_webhook_with_token_params *)` * * :code:`void discord_modify_webhook_with_token_params_list_free(struct discord_modify_webhook_with_token_params **)` * * JSON Decoder: * * :code:`void discord_modify_webhook_with_token_params_from_json(char *rbuf, size_t len, struct discord_modify_webhook_with_token_params **)` * * :code:`void discord_modify_webhook_with_token_params_list_from_json(char *rbuf, size_t len, struct discord_modify_webhook_with_token_params ***)` * * JSON Encoder: * * :code:`void discord_modify_webhook_with_token_params_to_json(char *wbuf, size_t len, struct discord_modify_webhook_with_token_params *)` * * :code:`void discord_modify_webhook_with_token_params_list_to_json(char *wbuf, size_t len, struct discord_modify_webhook_with_token_params **)` * @endverbatim */ struct discord_modify_webhook_with_token_params { /* specs/discord/webhook.endpoints-params.json:33:20 '{ "name": "name", "type":{ "base":"char", "dec":"*" }, "inject_if_not":null, "comment":"name of the webhook(1-80) chars" }' */ char *name; /**< name of the webhook(1-80) chars */ /* specs/discord/webhook.endpoints-params.json:34:20 '{ "name": "avatar", "type":{ "base":"char", "dec":"*" }, "inject_if_not":null, "comment":"base64 image for the default webhook avatar" }' */ char *avatar; /**< base64 image for the default webhook avatar */ }; extern void discord_modify_webhook_with_token_params_cleanup_v(void *p); extern void discord_modify_webhook_with_token_params_cleanup(struct discord_modify_webhook_with_token_params *p); extern void discord_modify_webhook_with_token_params_init_v(void *p); extern void discord_modify_webhook_with_token_params_init(struct discord_modify_webhook_with_token_params *p); extern void discord_modify_webhook_with_token_params_from_json_v(char *json, size_t len, void *pp); extern void discord_modify_webhook_with_token_params_from_json(char *json, size_t len, struct discord_modify_webhook_with_token_params **pp); extern size_t discord_modify_webhook_with_token_params_to_json_v(char *json, size_t len, void *p); extern size_t discord_modify_webhook_with_token_params_to_json(char *json, size_t len, struct discord_modify_webhook_with_token_params *p); extern void discord_modify_webhook_with_token_params_list_free_v(void **p); extern void discord_modify_webhook_with_token_params_list_free(struct discord_modify_webhook_with_token_params **p); extern void discord_modify_webhook_with_token_params_list_from_json_v(char *str, size_t len, void *p); extern void discord_modify_webhook_with_token_params_list_from_json(char *str, size_t len, struct discord_modify_webhook_with_token_params ***p); extern size_t discord_modify_webhook_with_token_params_list_to_json_v(char *str, size_t len, void *p); extern size_t discord_modify_webhook_with_token_params_list_to_json(char *str, size_t len, struct discord_modify_webhook_with_token_params **p); /* Execute Webhook */ /* defined at specs/discord/webhook.endpoints-params.json:40:22 */ /** * @verbatim embed:rst:leading-asterisk * .. container:: toggle * .. container:: header * **Methods** * * Initializer: * * :code:`void discord_execute_webhook_params_init(struct discord_execute_webhook_params *)` * * Cleanup: * * :code:`void discord_execute_webhook_params_cleanup(struct discord_execute_webhook_params *)` * * :code:`void discord_execute_webhook_params_list_free(struct discord_execute_webhook_params **)` * * JSON Decoder: * * :code:`void discord_execute_webhook_params_from_json(char *rbuf, size_t len, struct discord_execute_webhook_params **)` * * :code:`void discord_execute_webhook_params_list_from_json(char *rbuf, size_t len, struct discord_execute_webhook_params ***)` * * JSON Encoder: * * :code:`void discord_execute_webhook_params_to_json(char *wbuf, size_t len, struct discord_execute_webhook_params *)` * * :code:`void discord_execute_webhook_params_list_to_json(char *wbuf, size_t len, struct discord_execute_webhook_params **)` * @endverbatim */ struct discord_execute_webhook_params { /* specs/discord/webhook.endpoints-params.json:44:20 '{ "name": "wait", "type":{ "base":"bool"}, "loc":"query", "comment":" waits for server confirmation of message send before response, and returns the created message body (defaults to false; when false a message that is not saved does not return an error)" }' */ bool wait; /**< cannot unescape an ill-formed-string waits for server confirmation of message send before response, and returns the created message body (defaults to false; when false a message that i */ /* specs/discord/webhook.endpoints-params.json:45:20 '{ "name": "thread_id", "type":{ "base":"char", "dec":"*", "converter":"snowflake"}, "loc":"query", "comment":"Send a message to the specified thread withing a webhook's channel. The thread will automatically be unarchived", "inject_if_not":0 }' */ u64_snowflake_t thread_id; /**< Send a message to the specified thread withing a webhook's channel. The thread will automatically be unarchived */ /* specs/discord/webhook.endpoints-params.json:46:20 '{ "name": "content", "type":{ "base":"char", "dec":"*" }, "comment":"the message contents (up to 2000 characters)", "inject_if_not": null }' */ char *content; /**< the message contents (up to 2000 characters) */ /* specs/discord/webhook.endpoints-params.json:47:20 '{ "name": "username", "type":{ "base":"char", "dec":"*" }, "comment":"override the default username of the webhook", "inject_if_not": null }' */ char *username; /**< override the default username of the webhook */ /* specs/discord/webhook.endpoints-params.json:48:20 '{ "name": "avatar_url", "type":{ "base":"char", "dec":"*" }, "comment":"override the default avatar of the webhook", "inject_if_not": null }' */ char *avatar_url; /**< override the default avatar of the webhook */ /* specs/discord/webhook.endpoints-params.json:49:20 '{ "name": "tts", "type":{ "base":"bool" }, "comment":"true if this is a TTS message", "inject_if_not":false }' */ bool tts; /**< true if this is a TTS message */ /* specs/discord/webhook.endpoints-params.json:50:20 '{ "name": "file", "type":{ "base":"char", "dec":"*" }, "loc":"multipart", "comment":"the contents of the file being sent", "inject_if_not":null }' */ char *file; /**< the contents of the file being sent */ /* specs/discord/webhook.endpoints-params.json:51:20 '{ "name": "embeds", "type":{ "base":"struct discord_embed", "dec":"*" }, "comment":"embedded rich content", "inject_if_not":null }' */ struct discord_embed *embeds; /**< embedded rich content */ /* specs/discord/webhook.endpoints-params.json:52:20 '{ "name": "payload_json", "type":{ "base":"char", "dec":"*" }, "comment":"JSON encoded body of non-file params", "inject_if_not": null }' */ char *payload_json; /**< JSON encoded body of non-file params */ /* specs/discord/webhook.endpoints-params.json:53:20 '{ "name": "allowed_mentions", "type":{ "base":"struct discord_allowed_mentions", "dec":"*" }, "comment":"allowed mentions for the message", "inject_if_not": null }' */ struct discord_allowed_mentions *allowed_mentions; /**< allowed mentions for the message */ /* specs/discord/webhook.endpoints-params.json:54:20 '{ "name": "components", "type":{ "base":"struct discord_component", "dec":"ntl" }, "comment":"the components to include with the message", "inject_if_not": null }' */ struct discord_component **components; /**< the components to include with the message */ }; extern void discord_execute_webhook_params_cleanup_v(void *p); extern void discord_execute_webhook_params_cleanup(struct discord_execute_webhook_params *p); extern void discord_execute_webhook_params_init_v(void *p); extern void discord_execute_webhook_params_init(struct discord_execute_webhook_params *p); extern void discord_execute_webhook_params_from_json_v(char *json, size_t len, void *pp); extern void discord_execute_webhook_params_from_json(char *json, size_t len, struct discord_execute_webhook_params **pp); extern size_t discord_execute_webhook_params_to_json_v(char *json, size_t len, void *p); extern size_t discord_execute_webhook_params_to_json(char *json, size_t len, struct discord_execute_webhook_params *p); extern void discord_execute_webhook_params_list_free_v(void **p); extern void discord_execute_webhook_params_list_free(struct discord_execute_webhook_params **p); extern void discord_execute_webhook_params_list_from_json_v(char *str, size_t len, void *p); extern void discord_execute_webhook_params_list_from_json(char *str, size_t len, struct discord_execute_webhook_params ***p); extern size_t discord_execute_webhook_params_list_to_json_v(char *str, size_t len, void *p); extern size_t discord_execute_webhook_params_list_to_json(char *str, size_t len, struct discord_execute_webhook_params **p); /* Edit Webhook Message */ /* defined at specs/discord/webhook.endpoints-params.json:60:22 */ /** * @verbatim embed:rst:leading-asterisk * .. container:: toggle * .. container:: header * **Methods** * * Initializer: * * :code:`void discord_edit_webhook_message_params_init(struct discord_edit_webhook_message_params *)` * * Cleanup: * * :code:`void discord_edit_webhook_message_params_cleanup(struct discord_edit_webhook_message_params *)` * * :code:`void discord_edit_webhook_message_params_list_free(struct discord_edit_webhook_message_params **)` * * JSON Decoder: * * :code:`void discord_edit_webhook_message_params_from_json(char *rbuf, size_t len, struct discord_edit_webhook_message_params **)` * * :code:`void discord_edit_webhook_message_params_list_from_json(char *rbuf, size_t len, struct discord_edit_webhook_message_params ***)` * * JSON Encoder: * * :code:`void discord_edit_webhook_message_params_to_json(char *wbuf, size_t len, struct discord_edit_webhook_message_params *)` * * :code:`void discord_edit_webhook_message_params_list_to_json(char *wbuf, size_t len, struct discord_edit_webhook_message_params **)` * @endverbatim */ struct discord_edit_webhook_message_params { /* specs/discord/webhook.endpoints-params.json:63:20 '{ "name": "content", "type":{ "base":"char", "dec":"*" }, "comment":"name of the webhook(1-2000) chars", "inject_if_not":null }' */ char *content; /**< name of the webhook(1-2000) chars */ /* specs/discord/webhook.endpoints-params.json:64:20 '{ "name": "embeds", "type":{ "base":"struct discord_embed", "dec":"ntl" }, "comment":"array of up to 10 embeds objects", "inject_if_not":null }' */ struct discord_embed **embeds; /**< array of up to 10 embeds objects */ /* specs/discord/webhook.endpoints-params.json:65:20 '{ "name": "file", "type":{ "base":"char", "dec":"*" }, "loc":"multipart", "comment":"the contents of the file being sent/edited", "inject_if_not":null }' */ char *file; /**< the contents of the file being sent/edited */ /* specs/discord/webhook.endpoints-params.json:66:20 '{ "name": "payload_json", "type":{ "base":"char", "dec":"*" }, "comment":"JSON encoded body of non-file params (multipart/form-data only)", "inject_if_not":null }' */ char *payload_json; /**< JSON encoded body of non-file params (multipart/form-data only) */ /* specs/discord/webhook.endpoints-params.json:67:20 '{ "name": "allowed_mentions", "type":{ "base":"struct discord_allowed_mentions", "dec":"*" }, "comment":"allowed mentions for the message", "inject_if_not":null }' */ struct discord_allowed_mentions *allowed_mentions; /**< allowed mentions for the message */ /* specs/discord/webhook.endpoints-params.json:68:20 '{ "name": "attachments", "type":{ "base":"struct discord_attachment", "dec":"ntl" }, "comment":"attached files to keep", "inject_if_not":null }' */ struct discord_attachment **attachments; /**< attached files to keep */ /* specs/discord/webhook.endpoints-params.json:69:20 '{ "name": "components", "type":{ "base":"struct discord_component", "dec":"ntl" }, "comment":"the components to include with the message", "inject_if_not":null }' */ struct discord_component **components; /**< the components to include with the message */ }; extern void discord_edit_webhook_message_params_cleanup_v(void *p); extern void discord_edit_webhook_message_params_cleanup(struct discord_edit_webhook_message_params *p); extern void discord_edit_webhook_message_params_init_v(void *p); extern void discord_edit_webhook_message_params_init(struct discord_edit_webhook_message_params *p); extern void discord_edit_webhook_message_params_from_json_v(char *json, size_t len, void *pp); extern void discord_edit_webhook_message_params_from_json(char *json, size_t len, struct discord_edit_webhook_message_params **pp); extern size_t discord_edit_webhook_message_params_to_json_v(char *json, size_t len, void *p); extern size_t discord_edit_webhook_message_params_to_json(char *json, size_t len, struct discord_edit_webhook_message_params *p); extern void discord_edit_webhook_message_params_list_free_v(void **p); extern void discord_edit_webhook_message_params_list_free(struct discord_edit_webhook_message_params **p); extern void discord_edit_webhook_message_params_list_from_json_v(char *str, size_t len, void *p); extern void discord_edit_webhook_message_params_list_from_json(char *str, size_t len, struct discord_edit_webhook_message_params ***p); extern size_t discord_edit_webhook_message_params_list_to_json_v(char *str, size_t len, void *p); extern size_t discord_edit_webhook_message_params_list_to_json(char *str, size_t len, struct discord_edit_webhook_message_params **p);
6408804b4aeb9a661c47094154659bb49820c8f3
{ "blob_id": "6408804b4aeb9a661c47094154659bb49820c8f3", "branch_name": "refs/heads/master", "committer_date": "2021-10-21T16:06:43", "content_id": "3bd1225354c743c4e610d903b844dfc8bd4bcc0f", "detected_licenses": [ "MIT" ], "directory_id": "757ab2206fa9cb0cc417139af44fc08c7f4a4e11", "extension": "h", "filename": "webhook.endpoints-params.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20665, "license": "MIT", "license_type": "permissive", "path": "/specs-code/discord/webhook.endpoints-params.h", "provenance": "stack-edu-0001.json.gz:389172", "repo_name": "Furmissile/orca", "revision_date": "2021-10-21T16:06:43", "revision_id": "ebf6164a612fd27cd227270040e5e999f3122cf9", "snapshot_id": "0ed6a89a1f4f013838b3be1ec77d9c021fda3c02", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Furmissile/orca/ebf6164a612fd27cd227270040e5e999f3122cf9/specs-code/discord/webhook.endpoints-params.h", "visit_date": "2023-08-20T01:02:33.108053", "added": "2024-11-18T21:06:41.291444+00:00", "created": "2021-10-21T16:06:43", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
# olingo-jersey - Sample application to show integration of Apache Olingo with Apache Jersey - Apache Olingo is a popular Java Library that implements the Open Data Protocol (OData) - Apache Jersey is a lightweight popular framework for developing Restful Web Services in Java # Compile & execute with Maven ``` mvn clean package mvn jetty:run ``` # Sample URLs ``` <base URL>/Cars <base URL>/Cars?$filter=Model eq 'Maruti' ``` # Documentation - [Apache Olingo Documentation](https://olingo.apache.org/) - [Apache Jersey Documentation](https://jersey.java.net/)
25622e03282207d45d7e6796f917504536fc5410
{ "blob_id": "25622e03282207d45d7e6796f917504536fc5410", "branch_name": "refs/heads/master", "committer_date": "2018-08-09T09:31:00", "content_id": "2c666997c7f354a156ab8b1a68ab6bc7d0579934", "detected_licenses": [ "Apache-2.0" ], "directory_id": "757b7e12929956ce0da6178ab422f73ec0202966", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2018-08-09T08:02:38", "gha_event_created_at": "2018-08-09T08:02:38", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 144120300, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 570, "license": "Apache-2.0", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0000.json.gz:252472", "repo_name": "timurgen/olingo-jersey", "revision_date": "2018-08-09T09:31:00", "revision_id": "2db7517af9a5eaa7913faf5b2b3a7f816b03f813", "snapshot_id": "23605ae6a6566c94d59a888f3f8a68364484fdb8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/timurgen/olingo-jersey/2db7517af9a5eaa7913faf5b2b3a7f816b03f813/README.md", "visit_date": "2020-03-25T20:11:53.162827", "added": "2024-11-18T22:17:09.342137+00:00", "created": "2018-08-09T09:31:00", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz" }
#include "parg.hh" #include <iostream> #include <string> int program_options(OB::Parg& pg); int program_options(OB::Parg& pg) { // set info pg.name("app").version("0.1.0 (00.00.0000)"); pg.description("a command line app"); pg.usage("[flags] [options] [--] [arguments]"); pg.usage("[-v|--version]"); pg.usage("[-h|--help]"); pg.info("Exit Codes", {"0 -> normal", "1 -> error"}); pg.info("Examples", { pg.name() + " --help", pg.name() + " --version", }); pg.author("name <email>"); // set options pg.set("help,h", "print the help output"); pg.set("version,v", "print the program version"); pg.set("flag_a,a", "a boolean flag with default value of false"); pg.set("option,o", "20", "int", "an option with a default value of '20'"); pg.set("option_required,r", "", "string", "a required option"); // uncomment to collect positional arguments // pg.set_pos(); // uncomment to collect piped input // pg.set_stdin(); int status {pg.parse()}; // uncomment if at least one argument is expected // if (status > 0 && pg.get_stdin().empty()) // { // std::cout << pg.print_help() << "\n"; // std::cout << "Error: " << "expected arguments" << "\n"; // return -1; // } if (status < 0) { // handle parsing error std::cout << pg.help() << "\n"; std::cout << "Error: " << pg.error() << "\n"; return -1; } if (pg.get<bool>("help")) { // handle -h and --help std::cout << pg.help(); return 1; } if (pg.get<bool>("version")) { // handle -v and --version std::cout << pg.name() << " v" << pg.version() << "\n"; return 1; } return 0; } int main(int argc, char *argv[]) { OB::Parg pg {argc, argv}; int pstatus {program_options(pg)}; if (pstatus > 0) { // exit success return 0; } else if (pstatus < 0) { // exit error return 1; } // get flag bool flag_a {pg.get<bool>("flag_a")}; std::cout << "flag_a: " << std::boolalpha << flag_a << "\n"; // get int option int option {pg.get<int>("option")}; std::cout << "option: " << option << '\n'; // check for required string option if (pg.find("option_required")) { std::string option_required {pg.get("option_required")}; std::cout << "option_required: " << option_required << "\n"; } else { std::cout << pg.help() << "\n"; std::cout << "Error: " << "'option_required' is required" << "\n"; return -1; } return 0; }
d1fbf085cdced21f663dc1f0b7186d80661c4041
{ "blob_id": "d1fbf085cdced21f663dc1f0b7186d80661c4041", "branch_name": "refs/heads/master", "committer_date": "2018-05-20T06:39:13", "content_id": "fd4a1849c9fb1b414ce5433989cca1a6005c5980", "detected_licenses": [ "MIT" ], "directory_id": "43141b30f95cf48b7f934902fabd5eadad77ffec", "extension": "cc", "filename": "main.cc", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 119631197, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2458, "license": "MIT", "license_type": "permissive", "path": "/examples/advanced/src/main.cc", "provenance": "stack-edu-0007.json.gz:8537", "repo_name": "octobanana/parg", "revision_date": "2018-05-20T06:39:13", "revision_id": "60f1c64e48a00a55616f2c338d05e96d1af17734", "snapshot_id": "1615cb747b6faac9d88bae005ca034ec03c9c443", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/octobanana/parg/60f1c64e48a00a55616f2c338d05e96d1af17734/examples/advanced/src/main.cc", "visit_date": "2021-05-05T01:11:22.033291", "added": "2024-11-18T21:28:59.287938+00:00", "created": "2018-05-20T06:39:13", "int_score": 3, "score": 2.90625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz" }
title: Bamboo Documentation --- The documentation for Bamboo can be found [here](https://github.com/pirapira/bamboo) To use Bamboo with Embark you will need to first install the [embark-bamboo](https://github.com/embarklabs/embark-bamboo) plugin
d6dda7ef34b47d759f4cbce3f993ae16d8e9cbd0
{ "blob_id": "d6dda7ef34b47d759f4cbce3f993ae16d8e9cbd0", "branch_name": "refs/heads/master", "committer_date": "2020-10-31T06:44:25", "content_id": "f679f6f7cdc71dd680e0b2628d3d6b8e9359013f", "detected_licenses": [ "MIT" ], "directory_id": "a6bd485f7284add811acc601da2f15e9c59a10da", "extension": "md", "filename": "bamboo.md", "fork_events_count": 0, "gha_created_at": "2019-12-13T15:43:39", "gha_event_created_at": "2020-10-31T06:44:27", "gha_language": null, "gha_license_id": "MIT", "github_id": 227871005, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 249, "license": "MIT", "license_type": "permissive", "path": "/site/source/docs/bamboo.md", "provenance": "stack-edu-markdown-0000.json.gz:261582", "repo_name": "kjx98/embark", "revision_date": "2020-10-31T06:44:25", "revision_id": "fcf399b525a5caff9837a787d1c3bf1705c2a3c7", "snapshot_id": "c1d1c56a43e3d5743f2ba879b20095ff3e3198a7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kjx98/embark/fcf399b525a5caff9837a787d1c3bf1705c2a3c7/site/source/docs/bamboo.md", "visit_date": "2020-11-23T23:53:10.896094", "added": "2024-11-18T21:41:49.401162+00:00", "created": "2020-10-31T06:44:25", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz" }
class Strings { static pad = (xs, n) => { while (xs.length < n) { xs = '0' + xs; } return xs; } static chunk(string, chunkSize) { var rest = string; var chunks = []; while (rest.length > 0) { let chunk = rest.slice(0, chunkSize); rest = rest.slice(chunkSize); chunks.push(chunk); } return chunks; } static dechunk(chunks) { return chunks.join(''); } static b64EncodeUnicode(str) { // first we use encodeURIComponent to get percent-encoded UTF-8, // then we convert the percent encodings into raw bytes which // can be fed into btoa. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) { return String.fromCharCode('0x' + p1); })); } static b64DecodeUnicode(str) { // Going backwards: from bytestream, to percent-encoding, to original string. return decodeURIComponent(atob(str).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } } export default Strings;
b8d86a6ba9199891260e2e4c909e6bf057f495b2
{ "blob_id": "b8d86a6ba9199891260e2e4c909e6bf057f495b2", "branch_name": "refs/heads/master", "committer_date": "2020-11-10T04:02:18", "content_id": "ed8c97ffa72c3f73054d99d67709ec4f55b46fef", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a816619b3e64328f68c4c82893903ea22a8874b8", "extension": "js", "filename": "strings.js", "fork_events_count": 1, "gha_created_at": "2019-04-07T14:19:30", "gha_event_created_at": "2022-12-09T18:38:32", "gha_language": "JavaScript", "gha_license_id": "BSD-3-Clause", "github_id": 179976404, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1101, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/core/util/strings.js", "provenance": "stack-edu-0044.json.gz:403037", "repo_name": "hyperhyperspace/hyperhyperspace-web", "revision_date": "2020-11-10T04:02:18", "revision_id": "d96783ecafad15d7502efac0b07c9bae1d3f8872", "snapshot_id": "890d933c06299d539267ac1f2bbee5a2e30d0ca8", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/hyperhyperspace/hyperhyperspace-web/d96783ecafad15d7502efac0b07c9bae1d3f8872/src/core/util/strings.js", "visit_date": "2022-12-10T00:13:16.479485", "added": "2024-11-19T01:16:20.920184+00:00", "created": "2020-11-10T04:02:18", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz" }
#include "ListWidgetIOTriggerItem.h" #include "ui_ListWidgetIOTriggerItem.h" #include "TaskStepGlobal.h" #include <QMessageBox> #include <QDebug> ListWidgetIOTriggerItem::ListWidgetIOTriggerItem(QWidget *parent) : QWidget(parent), ui(new Ui::ListWidgetIOTriggerItem) { ui->setupUi(this); Ini_Flag = 1; ui->IOTriggerPortCbB->addItem(tr("IO1")); ui->IOTriggerPortCbB->addItem(tr("IO2")); ui->IOTriggerWayCbB->addItem(tr("上升沿")); ui->IOTriggerWayCbB->addItem(tr("下降沿")); ui->IOTriggerWayCbB->addItem(tr("高电平")); ui->IOTriggerWayCbB->addItem(tr("低电平")); } ListWidgetIOTriggerItem::~ListWidgetIOTriggerItem() { delete ui; } void ListWidgetIOTriggerItem::SetTaskName(QString str) { Ini_Flag = 1; ui->TaskNameCheckBox->setText(str); QString task_index_string = str.split(".").at(0); unsigned int task_index = task_index_string.toUInt(); if(task_index >= TS_MAX_NUM){ Ini_Flag = 0; return; } unsigned int Trigger_Type = 0; int ret = Task_Step_Trigger_Type_Get(task_index, &Trigger_Type); if(ret != 0){ Ini_Flag = 0; return; } else if(Trigger_Type == IO_TRIGGER_TYPE){ ui->TaskNameCheckBox->setChecked(true); ui->IOTriggerPortCbB->setEnabled(true); ui->IOTriggerWayCbB->setEnabled(true); unsigned short IO_Port = 0; unsigned short IO_Trigger_Type = 0; ret = Task_Step_Trigger_IO_Get(task_index, &IO_Port, &IO_Trigger_Type); if(ret == 0){ ui->IOTriggerPortCbB->setCurrentIndex(IO_Port - 1); ui->IOTriggerWayCbB->setCurrentIndex(IO_Trigger_Type - 1); } }else{ ui->IOTriggerPortCbB->setEnabled(false); ui->IOTriggerWayCbB->setEnabled(false); } Ini_Flag = 0; } void ListWidgetIOTriggerItem::on_TaskNameCheckBox_clicked() { if(Ini_Flag == 1) return; QString task_index_string = ui->TaskNameCheckBox->text().split(".").at(0); unsigned int task_index = task_index_string.toUInt(); if(task_index >= TS_MAX_NUM) return; if(ui->TaskNameCheckBox->isChecked()) { unsigned int Trigger_Type = 0; int ret = Task_Step_Trigger_Type_Get(task_index, &Trigger_Type); if(ret != 0){ return; }else if(Trigger_Type == CMD_TRIGGER_TYPE || Trigger_Type == CON_TRIGGER_TYPE){ QMessageBox::about(NULL, tr("提示"), tr("该任务已有其他触发,无法设置IO触发!")); Ini_Flag = 1; ui->TaskNameCheckBox->setChecked(false); Ini_Flag = 0; return; } ret = Task_Step_Trigger_Type_Set(task_index, IO_TRIGGER_TYPE); if(ret != 0) return; ui->IOTriggerPortCbB->setEnabled(true); ui->IOTriggerWayCbB->setEnabled(true); SetTaskIOTriggerParam(); } else { int ret = Task_Step_Trigger_Type_Set(task_index, NONE_TRIGGER_TYPE); if(ret != 0) return; ui->IOTriggerPortCbB->setEnabled(false); ui->IOTriggerWayCbB->setEnabled(false); } } void ListWidgetIOTriggerItem::SetTaskIOTriggerParam() { QString task_index_string = ui->TaskNameCheckBox->text().split(".").at(0); unsigned int task_index = task_index_string.toUInt(); if(task_index >= TS_MAX_NUM) return; Task_Step_Trigger_IO_Set(task_index, ui->IOTriggerPortCbB->currentIndex()+1, ui->IOTriggerWayCbB->currentIndex()+1); } void ListWidgetIOTriggerItem::on_IOTriggerWayCbB_currentIndexChanged(int index) { if(Ini_Flag == 1) return; SetTaskIOTriggerParam(); } void ListWidgetIOTriggerItem::on_IOTriggerPortCbB_currentIndexChanged(int index) { if(Ini_Flag == 1) return; SetTaskIOTriggerParam(); }
1d96cfd366e4da2378588e5bc97957e0c02b482d
{ "blob_id": "1d96cfd366e4da2378588e5bc97957e0c02b482d", "branch_name": "refs/heads/master", "committer_date": "2017-09-01T07:23:58", "content_id": "71bdb1d0782aa7fe9b41543ccccf874458f32a5d", "detected_licenses": [ "MIT" ], "directory_id": "ef7ad96103876b24bbb45be8dfba7e80771c76e7", "extension": "cpp", "filename": "ListWidgetIOTriggerItem.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3788, "license": "MIT", "license_type": "permissive", "path": "/ui-qt/DataOutput/IOTrigger/ListWidgetIOTriggerItem.cpp", "provenance": "stack-edu-0004.json.gz:490487", "repo_name": "TinySlik/FPGA-Industrial-Smart-Camera", "revision_date": "2017-09-01T07:23:58", "revision_id": "54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32", "snapshot_id": "ecb6274f4ef16cf9174cd73812486644f821152a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TinySlik/FPGA-Industrial-Smart-Camera/54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32/ui-qt/DataOutput/IOTrigger/ListWidgetIOTriggerItem.cpp", "visit_date": "2021-06-25T11:09:21.212466", "added": "2024-11-18T21:50:46.347803+00:00", "created": "2017-09-01T07:23:58", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
/* BSD 2-Clause License - see OPAL/LICENSE for details. */ package org.opalj.fpcf.fixtures.benchmark.b_fieldImmutability.general; import org.opalj.fpcf.properties.immutability.fields.DeepImmutableField; import org.opalj.fpcf.properties.immutability.fields.MutableField; import org.opalj.fpcf.properties.immutability.fields.ShallowImmutableField; import org.opalj.fpcf.properties.immutability.references.ImmutableFieldReference; import org.opalj.fpcf.properties.immutability.references.MutableFieldReference; public class ClassWithADeepImmutableField { @DeepImmutableField("Immutable Reference and Immutable Field Type") @ImmutableFieldReference("declared final field") private final FinalEmptyClass fec = new FinalEmptyClass(); public FinalEmptyClass getFec() { return fec; } @DeepImmutableField("Immutable Reference and Immutable Field Type") @ImmutableFieldReference("effective immutable field") private FinalEmptyClass name = new FinalEmptyClass(); @DeepImmutableField("immutable reference and deep immutable field type") @ImmutableFieldReference(value = "declared final field reference") private final FinalEmptyClass fec1; @ShallowImmutableField("immutable field reference and mutable type ClassWithPublicFields") @ImmutableFieldReference("declared final field") private final ClassWithPublicFields tmc; public ClassWithADeepImmutableField( ClassWithPublicFields tmc, FinalEmptyClass fec) { this.tmc = tmc; this.fec1 = fec; } @ShallowImmutableField("field has an immutable field reference and mutable type") @ImmutableFieldReference("declared final reference") private final ClassWithPublicFields cwpf = new ClassWithPublicFields(); public ClassWithPublicFields getTmc() { return cwpf; } } class ClassWithProtectedFields { @MutableField("the field has a mutable field reference") @MutableFieldReference("the field is protected") protected FinalEmptyClass fec1 = new FinalEmptyClass(); @MutableField("Because of Mutable Reference") @MutableFieldReference("Because it is declared as protected") protected ClassWithPublicFields cwpf1 = new ClassWithPublicFields(); @ShallowImmutableField("field has an immutable reference and mutable type") @ImmutableFieldReference("Declared final Field") private final ClassWithPublicFields cwpf2 = new ClassWithPublicFields(); @DeepImmutableField("immutable reference and deep immutable field type") @ImmutableFieldReference("Declared final Field") private final FinalEmptyClass fec2 = new FinalEmptyClass(); } class ClassWithPublicFields { @MutableField(value = "field is public") @MutableFieldReference(value = "field is public") public int n = 0; @MutableField(value = "field is public") @MutableFieldReference(value = "field is public") public String name = "name"; } class FinalEmptyClass{}
4b0daac03a61bfdfa026e4e0acb41b5ad1561e96
{ "blob_id": "4b0daac03a61bfdfa026e4e0acb41b5ad1561e96", "branch_name": "refs/heads/master", "committer_date": "2021-07-15T11:30:32", "content_id": "ddfa21fba23554418971c50d90150d8b5ed30153", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "4bbf1fef23ea95eeaee9727fd227d84e2a03ada8", "extension": "java", "filename": "ClassWithADeepImmutableField.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 386205887, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2940, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Docker/evaluation/old_glacier/checker-framework-2.0.0/checker/bin/b_fieldImmutability/general/ClassWithADeepImmutableField.java", "provenance": "stack-edu-0022.json.gz:75290", "repo_name": "roterEmil/CiFi-Artifact", "revision_date": "2021-07-15T11:17:52", "revision_id": "dfd589f1e4f48add3ad1b8b8930c94e5994889eb", "snapshot_id": "eeff1915c8fbf84060720cc9c9009d3d0660e131", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/roterEmil/CiFi-Artifact/dfd589f1e4f48add3ad1b8b8930c94e5994889eb/Docker/evaluation/old_glacier/checker-framework-2.0.0/checker/bin/b_fieldImmutability/general/ClassWithADeepImmutableField.java", "visit_date": "2023-04-19T05:32:52.877969", "added": "2024-11-19T02:17:13.522025+00:00", "created": "2021-07-15T11:17:52", "int_score": 3, "score": 2.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
/*============================================================================= Copyright (c) 2004 Angus Leeming Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #define YAC_SINGLE_COMPILATION_UNIT #include "yac_virtual_machine.hpp" #include <cmath> #include <iostream> #include <string> #include <vector> using std::cout; using std::string; using std::vector; using boost::shared_ptr; namespace { void evaluate1(); } // namespace anon int main() { evaluate1(); return 0; } namespace { double add(double a, double b) { return a + b; } double subt(double a, double b) { return a - b; } double mult(double a, double b) { return a * b; } double div(double a, double b) { return a / b; } double less(double a, double b) { return a < b; } typedef double(* func2_ptr_t)(double, double); typedef double(* func1_ptr_t)(double); shared_ptr<yac::function> make_function(char const * name, func2_ptr_t func_ptr) { using yac::function; using yac::function2; return shared_ptr<function>(new function2<double>(name, func_ptr)); } shared_ptr<yac::function> make_function(char const * name, func1_ptr_t func_ptr) { using yac::function; using yac::function1; return shared_ptr<function>(new function1<double>(name, func_ptr)); } shared_ptr<yac::function> make_function(char const * name, int arity) { using yac::function; using yac::user_function; return shared_ptr<function>(new user_function(name, arity)); } // A derivative parser using the (excellent!) YAC framework. void evaluate1() { using namespace yac; /* Generate a stack for the following statement list: deriv(sin(x)) = cos(x) deriv(cos(x)) = -sin(x) print deriv(sin(2)) print deriv(cos(5)) */ virtual_machine vm; vm.funcs.add ("add##2", make_function("add#", &add)) ("subt##2", make_function("subt#", &subt)) ("div##2", make_function("div#", &div)) ("mult##2", make_function("mult#", &mult)) ("sin#1", make_function("sin", &sin)) ("cos#1", make_function("cos", &cos)); // Add deriv to the symbol table. string const mangled_deriv_name = name_mangler("deriv", 1); char const * const deriv_cstr = mangled_deriv_name.c_str(); string const mangled_sin_name = name_mangler("sin", 1); char const * const sin_cstr = mangled_sin_name.c_str(); vm.funcs.add (deriv_cstr, make_function("deriv", 1)) ("sin#1", make_function("sin", &sin)) ("cos#1", make_function("cos", &cos)); // Args and stack vector<string> args; shared_ptr<spirit::symbols<double> > local_vars(new spirit::symbols<double>); stack stk; args.push_back("x"); local_vars->add("x"); // deriv(sin(x)) // stk.push_back(new variable_node(x_ptr)); stk.push_back(new variable_node(find(*local_vars, "x"))); stk.push_back(new sys_function_node(*find(vm.funcs, "sin#1"))); stk.push_back(new sys_function_node(*find(vm.funcs, "deriv#1"))); stk.push_back(new sys_function_node(*find(vm.funcs, "cos#1"))); // Put it all together vm.stk.push_back(new func_def_node( *find(vm.funcs, deriv_cstr), user_func_expression(args, local_vars, stk))); // print deriv(sin(2)) vm.stk.push_back(new const_value_node(2)); vm.stk.push_back(new sys_function_node(*find(vm.funcs, sin_cstr))); vm.stk.push_back(new sys_function_node(*find(vm.funcs, deriv_cstr))); vm.stk.push_back(new print_node); // output std::cout << "Result of\n" << "\t deriv(sin(2)) \n" << "\t print deriv(sin(2)) \n" << "is: \n"; evaluate(vm.stk); std::cout << std::endl; } } // namespace anon
c1f8bbe1ec9f60209309809700874e3957407131
{ "blob_id": "c1f8bbe1ec9f60209309809700874e3957407131", "branch_name": "refs/heads/master", "committer_date": "2022-11-05T19:46:49", "content_id": "75866a27d5e89ffa0d3dd02ab9d7939f37795f4e", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2b6144aeefe48a5a9244c3560ffc91ed202f2fb6", "extension": "cpp", "filename": "yac_deriv.cpp", "fork_events_count": 8, "gha_created_at": "2015-08-13T07:36:57", "gha_event_created_at": "2021-11-15T13:16:52", "gha_language": "C++", "gha_license_id": "BSD-2-Clause", "github_id": 40645334, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4002, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/volna_init/external/yac/yac_deriv.cpp", "provenance": "stack-edu-0006.json.gz:639026", "repo_name": "reguly/volna", "revision_date": "2022-11-05T19:46:49", "revision_id": "6656d994c75f93d0f29673a8fc0da10926fa8d4a", "snapshot_id": "b867a63c3bd09fa234264cb2d01b8d8dd353ae27", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/reguly/volna/6656d994c75f93d0f29673a8fc0da10926fa8d4a/volna_init/external/yac/yac_deriv.cpp", "visit_date": "2023-08-19T07:19:35.315350", "added": "2024-11-18T22:59:11.568327+00:00", "created": "2022-11-05T19:46:49", "int_score": 3, "score": 2.578125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
// // NetLogMessage.swift // Canary // // Created by Rake Yang on 2020/3/21. // Copyright © 2020年 BinaryParadise inc. All rights reserved. // import Foundation class NetLogMessage { var method: String? var requestURL: URL? var requestHeaderFields: [AnyHashable: Any]? var responseHeaderFields: [AnyHashable: Any]? var requestBody: Data? var responseBody: Data? var statusCode: Int? init(request: NSURLRequest, response: HTTPURLResponse, data: Data?) { method = request.httpMethod; requestURL = request.url; requestHeaderFields = request.allHTTPHeaderFields; requestBody = (request as URLRequest).httpBodyData; responseHeaderFields = response.allHeaderFields responseBody = data statusCode = response.statusCode } } extension URLRequest { var httpBodyData: Data? { if let stream = httpBodyStream { var data = Data() stream.open() let bufferSize = 1024 let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) defer { buffer.deallocate() } while stream.hasBytesAvailable { let len = stream.read(buffer, maxLength: bufferSize) if len > 0 && stream.streamError == nil { data.append(buffer, count: len) } } stream.close() return data.count > 0 ? data:nil } return httpBody } }
f6bd79eaee4009ac5dbb4a383aa47b4190811d10
{ "blob_id": "f6bd79eaee4009ac5dbb4a383aa47b4190811d10", "branch_name": "refs/heads/master", "committer_date": "2021-12-24T10:12:03", "content_id": "5b8e994cd7d5dbc2acffb4fb8d67f80c47a160ed", "detected_licenses": [ "MIT" ], "directory_id": "cb67f176f4b0efbc3b5b546e4bf8bb310c54865a", "extension": "swift", "filename": "NetLogMessage.swift", "fork_events_count": 0, "gha_created_at": "2020-03-18T14:19:00", "gha_event_created_at": "2020-12-21T10:29:45", "gha_language": "Swift", "gha_license_id": "MIT", "github_id": 248251690, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 1543, "license": "MIT", "license_type": "permissive", "path": "/Sources/CanaryCore/Logger/NetLogMessage.swift", "provenance": "stack-edu-0071.json.gz:150945", "repo_name": "BinaryParadise/Canary", "revision_date": "2021-12-24T10:12:03", "revision_id": "d1a9a131bac347f605fed51ff4a2c07bd3af4661", "snapshot_id": "0ff916a5c4085256a6d1315f6fb32747bb9c7fc1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BinaryParadise/Canary/d1a9a131bac347f605fed51ff4a2c07bd3af4661/Sources/CanaryCore/Logger/NetLogMessage.swift", "visit_date": "2022-03-05T15:16:20.189955", "added": "2024-11-18T19:03:54.716930+00:00", "created": "2021-12-24T10:12:03", "int_score": 3, "score": 2.8125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz" }
package kafka import ( "bytes" "encoding/binary" "fmt" "hash/crc32" "io" "net" "reflect" "testing" "time" ) type subject struct { i64 int64 i32 int32 i16 int16 s [5]byte } // Testing binary.Write size investigation func TestStructSize(testing *testing.T) { s := subject{int64(64), int32(32), int16(16), [5]byte{'h', 'e', 'l', 'l', 'o'}} v := reflect.Indirect(reflect.ValueOf(s)) var t reflect.Type = v.Type() fmt.Println(t) switch t.Kind() { case reflect.Struct: sum := 0 fmt.Printf("NumField ? %v\n", t.NumField()) for i, n := 0, t.NumField(); i < n; i++ { fmt.Printf("%d type %v, size %d\n", i, t.Field(i).Type, binary.Size(t.Field(i).Type)) //s := sizeof(t.Field(i).Type) //if s < 0 { // return -1 //} //sum += s } fmt.Println(sum) } } func TestSliceSize(t *testing.T) { //b := []byte{1,2,3,4} b := make([]byte, 4) fmt.Println(binary.Size(b)) } func TestEncodingStructAsByteSlice(t *testing.T) { s := subject{int64(64), int32(32), int16(16), [5]byte{'h', 'e', 'l', 'l', 'o'}} fmt.Printf("%v\n", binary.Size([]byte{1})) //// *bytes.Buffer type buff := new(bytes.Buffer) err := binary.Write(buff, binary.BigEndian, s) if err != nil { t.Errorf("Failed to encode struct : %v\n", err) t.FailNow() } fmt.Printf("% x\n", buff.Bytes()) expected := []byte{ 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 32, 0, 16, 'h', 'e', 'l', 'l', 'o', } if len(buff.Bytes()) != len(expected) { t.Errorf("not expected size, expected %d, actual %d\n", len(expected), len(buff.Bytes())) t.FailNow() } for i, v := range buff.Bytes() { if v != expected[i] { t.FailNow() } } } /** The protocol is built out of the following primitive types. Fixed Width Primitives int8, int16, int32, int64 - Signed integers with the given precision (in bits) stored in big endian order. Variable Length Primitives bytes, string - These types consist of a signed integer giving a length N followed by N bytes of content. A length of -1 indicates null. string uses an int16 for its size, and bytes uses an int32. Arrays This is a notation for handling repeated structures. These will always be encoded as an int32 size containing the length N followed by N repetitions of the structure which can itself be made up of other primitive types. In the BNF grammars below we will show an array of a structure foo as [foo]. */ func TestKafka(t *testing.T) { conn, err := net.Dial("tcp", "kafka:9092") if err != nil { fmt.Printf("Cannot establish connection to kafka broker : %v\n", err) t.FailNow() } defer conn.Close() conn.SetDeadline(time.Now().Add(5 * time.Second)) fmt.Println("Connected") // Send Versions request header := new(bytes.Buffer) // // Headers // apiKey int16 : 0 - 20 API key, the function of this request // apiVersion int16 : version of API // correlationId int32 : user supplied id, that will be passed back to the client // clientIdLen int16 : Length of client Id (-1 is null) // clientId []byte : clientId data, may be omitted writeBigEndian(header, int16(ApiVersions)) writeBigEndian(header, int16(0)) writeBigEndian(header, int32(13)) writeBigEndian(header, int16(-1)) // null client Id // // Message // Crc int32 : CRC32 of the remainder of the message bytes // MagicByte int8 : Always 1 // Attributes int8 : bits(xxxxyzzz), x always 0, y timestamp type (0 create, 1 append time), z compression codec // Timestamp int64 : ms since unix epoch UTC // keyLen int16 : length of key (-1 means null, with no 'key' value specified) // key []byte : key data // value []byte : opaque byte slice. Kafka supports recursive messages content := new(bytes.Buffer) writeBigEndian(content, int8(1)) writeBigEndian(content, int8(0)) writeBigEndian(content, time.Now().Unix()) writeBigEndian(content, int32(-1)) // no key // // Value // Note: this is changed per request type // example ApiVersions (key: 18) writeBigEndian(content, int32(-1)) // no payload for this API request // need to build message first, to calculate CRC32 crc := crc32.ChecksumIEEE(content.Bytes()) fmt.Printf("Calculated CRC32 : %v\n", crc) // FIXME: any issue with uint32 -> int32 ? msg := new(bytes.Buffer) writeBigEndian(msg, int32(crc)) // Then write message content.WriteTo(msg) fmt.Printf("Message ? %v\n", msg.Bytes()) // // MessageSet // Offset int64 : -1 can be used when uncompressed data is being sent // MessageSize int32 : the size of the subsequent message // Message messageSet := new(bytes.Buffer) writeBigEndian(messageSet, int64(1)) writeBigEndian(messageSet, int32(len(msg.Bytes()))) msg.WriteTo(messageSet) fmt.Printf("messageSet : %v\n", messageSet.Bytes()) request := new(bytes.Buffer) header.WriteTo(request) messageSet.WriteTo(request) writeBigEndian(conn, int32(len(request.Bytes()))) conn.Write(request.Bytes()) fmt.Println("Sent Request") length := new(int32) err = binary.Read(conn, binary.BigEndian, length) if err != nil { fmt.Printf("Error reading from Kafka :%v \n", err) t.FailNow() } fmt.Println("Response OK") fmt.Printf("Response length : %d\n", *length) response := make([]byte, *length) i, err := conn.Read(response) if err != nil || i != int(*length) { fmt.Printf("Couldn't read response") t.FailNow() } fmt.Printf("Response : %v\n", response) r := bytes.NewBuffer(response) // response header only contains correlationId correlationId := new(int32) readBigEndian(r, correlationId) fmt.Printf("CorrelationId : %d\n", *correlationId) errorCode := new(int16) readBigEndian(r, errorCode) fmt.Printf("Error code : %d\n", *errorCode) if ErrNone != int(*errorCode) { t.FailNow() } fmt.Printf("Message : %v\n", response[6:]) // now read [api_versions] // api_versions => api_key min_version max_version // api_key => INT16 // min_version => INT16 // max_version => INT16 // .. it's an array, so get size type Version struct { ApiKey int16 MinVersion int16 MaxVersion int16 } arrSize := new(int32) readBigEndian(r, arrSize) fmt.Printf("Next value is %d bytes\n", *arrSize) for i := 0; i < int(*arrSize); i += 1 { fmt.Printf("i : %d\n", i) v := new(Version) readBigEndian(r, v) fmt.Printf("Version : key %d, min %d, max %d\n", v.ApiKey, v.MinVersion, v.MaxVersion) } if _, err := r.ReadByte(); err != io.EOF { t.Errorf("Data still to be consumed") } else { fmt.Println(err) } } func writeBigEndian(w io.Writer, data interface{}) { if err := binary.Write(w, binary.BigEndian, data); err != nil { fmt.Printf("Couldn't write : %v\n", data) } } func readBigEndian(r io.Reader, data interface{}) { if err := binary.Read(r, binary.BigEndian, data); err != nil { fmt.Printf("Couldn't read : %v\n", data) } }
d0a66df25f7a92459f6c138c4e7ec42dee512d57
{ "blob_id": "d0a66df25f7a92459f6c138c4e7ec42dee512d57", "branch_name": "refs/heads/master", "committer_date": "2017-06-25T15:14:07", "content_id": "b6ea3fb4391cbb8fab240c4d5e63f8331e31bffb", "detected_licenses": [ "MIT" ], "directory_id": "45b98bee40d59c5f028b445f7400322f3ffeadae", "extension": "go", "filename": "kafka_protocol_test.go", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 85349766, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 6804, "license": "MIT", "license_type": "permissive", "path": "/kafka/kafka_protocol_test.go", "provenance": "stack-edu-0016.json.gz:625640", "repo_name": "sscaling/goplayground", "revision_date": "2017-06-25T15:14:07", "revision_id": "fbb17a4fa6f04276fbfbc371fef3f25cf3d9be9f", "snapshot_id": "ec54887bc83b6c0b9a8be4755b82b53e3b105686", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sscaling/goplayground/fbb17a4fa6f04276fbfbc371fef3f25cf3d9be9f/kafka/kafka_protocol_test.go", "visit_date": "2021-01-21T17:24:07.869800", "added": "2024-11-18T20:36:57.751992+00:00", "created": "2017-06-25T15:14:07", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
import path from 'path'; import fs from 'fs'; import rollupBabel from 'rollup-plugin-babel'; import {BuilderOptions, MessageError} from '@pika/types'; import {rollup} from 'rollup'; export async function beforeJob({out}: BuilderOptions) { const srcDirectory = path.join(out, 'dist-src/'); if (!fs.existsSync(srcDirectory)) { throw new MessageError('"dist-src/" does not exist, or was not yet created in the pipeline.'); } const srcEntrypoint = path.join(out, 'dist-src/index.js'); if (!fs.existsSync(srcEntrypoint)) { throw new MessageError('"dist-src/index.js" is the expected standard entrypoint, but it does not exist.'); } } export async function loadAllBabelPlugins() { const ES2019 = [ '@babel/plugin-proposal-json-strings', '@babel/plugin-syntax-optional-catch-binding', '@babel/plugin-proposal-optional-catch-binding', ]; const ES2018 = [ ...ES2019, import('@babel/plugin-syntax-async-generators'), import('@babel/plugin-proposal-async-generator-functions'), import('@babel/plugin-transform-dotall-regex'), import('@babel/plugin-transform-named-capturing-groups-regex'), import('@babel/plugin-syntax-object-rest-spread'), import('@babel/plugin-proposal-object-rest-spread'), import('@babel/plugin-proposal-unicode-property-regex'), ]; const ES2017 = [...ES2018, import('@babel/plugin-transform-async-to-generator')]; const ES2016 = [...ES2017, import('@babel/plugin-transform-exponentiation-operator')]; const ES2015 = [ ...ES2016, import('@babel/plugin-transform-arrow-functions'), import('@babel/plugin-transform-block-scoped-functions'), import('@babel/plugin-transform-block-scoping'), import('@babel/plugin-transform-classes'), import('@babel/plugin-transform-computed-properties'), import('@babel/plugin-transform-destructuring'), import('@babel/plugin-transform-duplicate-keys'), import('@babel/plugin-transform-for-of'), import('@babel/plugin-transform-function-name'), import('@babel/plugin-transform-literals'), import('@babel/plugin-transform-new-target'), import('@babel/plugin-transform-object-super'), import('@babel/plugin-transform-parameters'), import('@babel/plugin-transform-shorthand-properties'), import('@babel/plugin-transform-spread'), import('@babel/plugin-transform-sticky-regex'), import('@babel/plugin-transform-template-literals'), import('@babel/plugin-transform-typeof-symbol'), import('@babel/plugin-transform-unicode-regex'), ]; return [ await Promise.all(ES2019), await Promise.all(ES2018), await Promise.all(ES2017), await Promise.all(ES2016), await Promise.all(ES2015), ]; } async function buildSingleDist( distTag: string, distPlugins: any[] | null, {out, reporter}: BuilderOptions, ): Promise<void> { const writeToWeb = path.join(out, distTag, 'index.js'); const result = await rollup({ input: path.join(out, 'dist-src/index.js'), plugins: [ distPlugins && rollupBabel({ babelrc: false, compact: false, plugins: distPlugins, }), ], onwarn: ((warning, defaultOnWarnHandler) => { // // Unresolved external imports are expected // TODO: rewrite here? if ( warning.code === 'UNRESOLVED_IMPORT' && !(warning.source.startsWith('./') || warning.source.startsWith('../')) ) { return; } defaultOnWarnHandler(warning); }) as any, }); await result.write({ file: writeToWeb, format: 'esm', exports: 'named', }); reporter.created(writeToWeb, distTag); } export async function build(options: BuilderOptions): Promise<void> { const [neededForES2018, neededForES2017, neededForES2016, neededForES2015] = await loadAllBabelPlugins(); await buildSingleDist('dist-es2019', null, options); await buildSingleDist('dist-es2018', neededForES2018, options); await buildSingleDist('dist-es2017', neededForES2017, options); await buildSingleDist('dist-es2016', neededForES2016, options); await buildSingleDist('dist-es2015', neededForES2015, options); }
0221b3dc645810b9a4ceaf4b9f237d06969772fa
{ "blob_id": "0221b3dc645810b9a4ceaf4b9f237d06969772fa", "branch_name": "refs/heads/master", "committer_date": "2019-06-17T16:13:02", "content_id": "cfa62b32fad2e339bfc4a821cf9bf2ae4a4bdef2", "detected_licenses": [ "MIT" ], "directory_id": "9c5d2598bff55039925d1601372d80854f94da45", "extension": "ts", "filename": "index.ts", "fork_events_count": 0, "gha_created_at": "2019-07-15T13:10:23", "gha_event_created_at": "2019-07-15T13:10:23", "gha_language": null, "gha_license_id": "MIT", "github_id": 197001101, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4143, "license": "MIT", "license_type": "permissive", "path": "/packages/plugin-build-web-complete/src/index.ts", "provenance": "stack-edu-0074.json.gz:546086", "repo_name": "alexnm/builders", "revision_date": "2019-06-17T16:13:02", "revision_id": "b7d8e2d5c6c6430645257d8ef1d0ac0ae921f077", "snapshot_id": "bd75d121e51e57bc33ac50b41f4ad9f371022555", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alexnm/builders/b7d8e2d5c6c6430645257d8ef1d0ac0ae921f077/packages/plugin-build-web-complete/src/index.ts", "visit_date": "2020-06-20T04:54:20.362793", "added": "2024-11-18T23:41:19.970654+00:00", "created": "2019-06-17T16:13:02", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
import { join } from 'path' import { PLUGINS_FOLDER } from '../config' import { FileSystemHelper } from '../helpers/FileSystemHelper' export const getPlugin = async (pluginKey: unknown) => { if (!PLUGINS_FOLDER) { return ['ERROR', 'no plugins available'] } if (typeof pluginKey !== 'string') { return ['ERROR', 'plugin key invalid'] } const fileSystem = new FileSystemHelper(join(PLUGINS_FOLDER, pluginKey)) if (!fileSystem.fileExistsSync('frontend.js')) { return ['ERROR', 'plugin not found'] } const plugin = fileSystem.readTXTFileSync('frontend.js') if (!plugin) { return ['ERROR', 'plugin invalid'] } return ['SUCCESS', plugin] }
7570298cafba891802ef2faa61ab2efc3077d3c2
{ "blob_id": "7570298cafba891802ef2faa61ab2efc3077d3c2", "branch_name": "refs/heads/master", "committer_date": "2020-10-10T17:07:06", "content_id": "80eb516d3100b933347321f0e328d5a60e127bd7", "detected_licenses": [ "MIT" ], "directory_id": "126f6489144d691ccd247a374a100c31a4c3a035", "extension": "ts", "filename": "getPlugin.ts", "fork_events_count": 0, "gha_created_at": "2019-06-16T15:16:28", "gha_event_created_at": "2022-03-24T09:18:35", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 192205802, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 712, "license": "MIT", "license_type": "permissive", "path": "/src/routes/getPlugin.ts", "provenance": "stack-edu-0074.json.gz:644348", "repo_name": "andrehtissot/electron-game-collection-server", "revision_date": "2020-10-10T17:07:06", "revision_id": "80b905bebff3a464f3bcdf6ae8090c6472a9b76c", "snapshot_id": "c7a326f1dccbc679aef20399bd529dd9ab0da9b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andrehtissot/electron-game-collection-server/80b905bebff3a464f3bcdf6ae8090c6472a9b76c/src/routes/getPlugin.ts", "visit_date": "2022-05-07T00:59:35.751638", "added": "2024-11-18T22:23:57.355830+00:00", "created": "2020-10-10T17:07:06", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
from datetime import datetime from itertools import combinations import pendulum from airflow import DAG from airflow.sensors.sql import SqlSensor from airflow.operators.dummy import DummyOperator default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2022, 11, 28, tzinfo=pendulum.timezone('America/Los_Angeles')), 'concurrency': 8, 'email': ['[email protected]'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 5, } srcs = ['psfthr', 'mor2dm', 'midas', 'clarity', 'api', 'psfterp', 'optilink', 'genius', 'epsi2dm', ] def token_query(src): token_query_sql = f''' select case when cast(dateadd(hh, 3, max(DRP_TS)) as date) = cast(getdate() as date) and max(DRP_TS) < getdate() then 1 else 0 end from FI_EDW_TOKEN.dbo.EDW_TOKEN_DROPS with(nolock) where SRC_NM = '{src}' ''' return token_query_sql poke_int = 600 with DAG('test_token_drop', default_args=default_args, catchup=False, schedule_interval='15 0 * * *') as dag: # # define sensor tasks # clarity_fresh = SqlSensor( # task_id='clarity_fresness', # conn_id='ebi_datamart', # sql=token_query('CLARITY'), # pool='default_pool', # poke_interval=poke_int, # mode='reschedule', # dag=dag, # ) # # epsi_fresh = SqlSensor( # task_id='epsi_fresness', # conn_id='ebi_datamart', # sql=token_query('EPSI2DM'), # pool='default_pool', # poke_interval=poke_int, # mode='reschedule', # dag=dag, # ) # # morrisey_fresh = SqlSensor( # task_id='morrisey_fresness', # conn_id='ebi_datamart', # sql=token_query('MOR2DM'), # pool='default_pool', # poke_interval=poke_int, # mode='reschedule', # dag=dag, # ) # # # define dummy transform tasks # clarity_trans = DummyOperator( # task_id='clarity_only_transform', # pool='default_pool', # dag=dag, # ) # # clarity_epsi_trans = DummyOperator( # task_id='clarity_plus_epsi_transform', # pool='default_pool', # dag=dag, # ) # # clarity_morr_trans = DummyOperator( # task_id='clarity_plus_morrisey_transform', # pool='default_pool', # dag=dag, # ) # # # order of operations # clarity_fresh >> clarity_trans # clarity_fresh >> clarity_epsi_trans # clarity_fresh >> clarity_morr_trans # epsi_fresh >> clarity_epsi_trans # morrisey_fresh >> clarity_morr_trans # define sensor tasks and assign them to dict sensor_dict = {} for src in srcs: sensor = SqlSensor( task_id=f'{src}_freshness', conn_id='ebi_datamart', sql=token_query(src.upper()), # upper is how they're stored in DB pool='default_pool', poke_interval=poke_int, mode='reschedule', dag=dag, ) sensor_dict[src] = sensor # get combinations of each pair of sources combs = list(combinations(srcs, 2)) # create dummies for each pair and set them downstream of sensors for comb in combs: dummy = DummyOperator( task_id=f'{comb[0]}_{comb[1]}_transform', pool='default_pool', dag=dag, ) [sensor_dict[comb[0]], sensor_dict[comb[1]]] >> dummy
5417a97b1d75f7fa4b1ac1d8b5bd9dc6dcf09f06
{ "blob_id": "5417a97b1d75f7fa4b1ac1d8b5bd9dc6dcf09f06", "branch_name": "refs/heads/master", "committer_date": "2023-08-25T18:53:47", "content_id": "e6adfb3fccc650e4205111db9173fbceeb86f828", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0eaeac2b2b971a100bc0e70866a6e62f93a2d0dd", "extension": "py", "filename": "test_token_drop.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 231643438, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3838, "license": "Apache-2.0", "license_type": "permissive", "path": "/test_token_drop.py", "provenance": "stack-edu-0057.json.gz:235175", "repo_name": "sbliefnick1/coh_dags", "revision_date": "2023-08-25T18:53:47", "revision_id": "9b82af36f9999a0b9147a20ce374d0da5bb7e123", "snapshot_id": "047f3040e5e07504b38ef21d5caa61d00147c323", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/sbliefnick1/coh_dags/9b82af36f9999a0b9147a20ce374d0da5bb7e123/test_token_drop.py", "visit_date": "2023-09-01T18:12:26.096028", "added": "2024-11-18T18:39:41.678688+00:00", "created": "2023-08-25T18:53:47", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz" }
#pragma once #include "initiation/sipmessageprocessor.h" #include "initiation/siptypes.h" #include <QTimer> /* A class for handling all sent requests and processing responses. The purpose * of this class is to keep track of request transaction state on client side. * See RFC 3261 for more details. */ class SIPClient : public SIPMessageProcessor { Q_OBJECT public: SIPClient(); ~SIPClient(); void sendREGISTER(uint32_t timeout); void sendINVITE(uint32_t timeout); void sendBYE(); void sendCANCEL(); bool registrationActive() { return activeRegistration_; } bool shouldBeDestroyed() { return !shouldLive_; } public slots: // processes incoming response. Part of client transaction virtual void processIncomingResponse(SIPResponse& response, QVariant& content, bool retryRequest); void refreshRegistration(); private slots: void requestTimeOut(); private: bool correctRequestType(SIPRequestMethod method); bool sendRequest(SIPRequestMethod method); bool sendRequest(SIPRequestMethod method, uint32_t expires); // constructs the SIP message info struct as much as possible SIPRequest generateRequest(SIPRequestMethod method); bool checkTransactionType(SIPRequestMethod transactionRequest) { return transactionRequest == ongoingTransactionType_; } // timeout is in milliseconds. Used for request timeout. The default timeout // is 2 seconds which should be plenty of time for RTT void startTimeoutTimer(int timeout = 2000); void stopTimeoutTimer() { requestTimer_.stop(); } void processTimeout(); void byeTimeout(); bool goodResponse(); // use this to filter out untimely/duplicate responses // used to keep track of our current transaction. This means it is used to // determine what request the response is responding to. SIPRequestMethod ongoingTransactionType_; QTimer requestTimer_; uint32_t expires_; // This variable is used to avoid HEAP corruption by destroying the flow afterwards // instead of accidentally delete ourselves with signals etc. as part of the stack bool shouldLive_; bool activeRegistration_; std::chrono::time_point<std::chrono::system_clock> sendTime_; };
6342c220597386f0d2283377eb8ef1c1dbef07c2
{ "blob_id": "6342c220597386f0d2283377eb8ef1c1dbef07c2", "branch_name": "refs/heads/master", "committer_date": "2023-06-05T15:30:29", "content_id": "162abd59bb78719d78574f89e03d51c1576eb6d5", "detected_licenses": [ "ISC" ], "directory_id": "abede8addd0413f810f82e53a03114d02783eb9c", "extension": "h", "filename": "sipclient.h", "fork_events_count": 11, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 105107249, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2271, "license": "ISC", "license_type": "permissive", "path": "/src/initiation/transaction/sipclient.h", "provenance": "stack-edu-0005.json.gz:249523", "repo_name": "ultravideo/kvazzup", "revision_date": "2023-06-05T15:30:29", "revision_id": "156755983daa7d94ababa97bb946f203bed18bb6", "snapshot_id": "93bed5de33e987fd9dafc87a7299dd47ef53a0fd", "src_encoding": "UTF-8", "star_events_count": 44, "url": "https://raw.githubusercontent.com/ultravideo/kvazzup/156755983daa7d94ababa97bb946f203bed18bb6/src/initiation/transaction/sipclient.h", "visit_date": "2023-06-08T09:10:52.164300", "added": "2024-11-19T01:50:26.318990+00:00", "created": "2023-06-05T15:30:29", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
package org.aguinore.crackInterview; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.Scanner; import static org.junit.jupiter.api.Assertions.*; class CrackInterviewTest { @Test void rotLeftBruteforce() { int[] array = {1, 2, 3, 4, 5}; int[] result = {4, 5, 1, 2, 3}; assertArrayEquals(result, CrackInterview.rotLeftBruteforce(array, 3)); } @Test void makeAnagram() { String a = "abcde"; String b = "cdefg"; assertEquals(4, CrackInterview.makeAnagram(a, b)); } @Test void makeAnagramAnother() { String a = "cde"; String b = "abc"; assertEquals(4, CrackInterview.makeAnagram(a, b)); } @Test void makeAnagramRepetitions() { String a = "fcrxzwscanmligyxyvym"; String b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; assertEquals(30, CrackInterview.makeAnagram(a, b)); } @Test void checkMagazineFalse() { String[] magazine = {"two", "times", "three", "is", "not", "four"}; String[] note = {"two", "times", "two", "is", "four"}; assertFalse(CrackInterview.checkMagazine(magazine, note)); } @Test void checkMagazine() { String[] magazine = {"give", "me", "one", "grand", "today", "night"}; String[] note = {"give", "one", "grand", "today"}; assertTrue(CrackInterview.checkMagazine(magazine, note)); } @Test void hasListCyclesEmpty() { CrackInterview.Node node = new CrackInterview.Node(); node.next = null; assertFalse(CrackInterview.hasListCycles(node)); } @Test void hasListCyclesFalse() { CrackInterview.Node node = new CrackInterview.Node(); node.next = new CrackInterview.Node(); assertFalse(CrackInterview.hasListCycles(node)); } @Test void hasListCyclesTrue() { CrackInterview.Node node = new CrackInterview.Node(); node.next = node; assertTrue(CrackInterview.hasListCycles(node)); } @Test void ifBracketsBalanced() { String brackets = "{[()]}"; assertTrue(CrackInterview.ifBracketsBalanced(brackets)); } @Test void ifBracketsBalancedEmpty() { String brackets = ""; assertTrue(CrackInterview.ifBracketsBalanced(brackets)); } @Test void ifBracketsBalancedLong() { Scanner scanner = new Scanner(Thread.currentThread().getContextClassLoader() .getResourceAsStream("crackInterview/brackets")); Scanner anotherScanner = new Scanner(Thread.currentThread().getContextClassLoader() .getResourceAsStream("crackInterview/brackets_res")); while (scanner.hasNext()) { String brackets = scanner.nextLine(); String res = anotherScanner.nextLine(); if (res.equals("YES")) { assertTrue(CrackInterview.ifBracketsBalanced(brackets)); } else { assertFalse(CrackInterview.ifBracketsBalanced(brackets)); } } } @Test void ifBracketsBalancedFalse() { String brackets = "{[(])}"; assertFalse(CrackInterview.ifBracketsBalanced(brackets)); } @Test void ifBracketsBalancedMalformed() { String brackets = "{[(0]}"; assertFalse(CrackInterview.ifBracketsBalanced(brackets)); } @Test void findSubarrayWithSumEasy() { int[] arr = {3, 5, -1, 2, 4, -3, 7}; int[] expected = {1, 3}; assertArrayEquals(expected, CrackInterview.findSubarrayWithSum(arr, 6)); } @Test void findSubarrayWithSum() { int[] arr = {3, 5, -1, 2, 4, -3, 7}; int[] expected = {2, 3}; assertArrayEquals(expected, CrackInterview.findSubarrayWithSum(arr, 1)); } @Test void findSubarrayWithSum1() { int[] arr = {10, 70, -30, 10}; int[] expected = {1, 2}; assertArrayEquals(expected, CrackInterview.findSubarrayWithSum(arr, 40)); } @Test @Disabled void findSubarrayWithSum2() { int[] arr = {-100, 10, 30, -100}; int[] expected = {1, 2}; assertArrayEquals(expected, CrackInterview.findSubarrayWithSum(arr, 40)); } @Test void minimumBribes() { int[] arr = {2, 1, 5, 3, 4}; int result = 3; assertEquals(result, CrackInterview.minimumBribes(arr)); } @Test void minimumBribes2() { int[] arr = {1, 2, 5, 3, 7, 8, 6, 4}; int result = 7; assertEquals(result, CrackInterview.minimumBribes(arr)); } @Test void minimumBribesChaotic() { int[] arr = {2, 5, 1, 3, 4}; int result = -1; assertEquals(result, CrackInterview.minimumBribes(arr)); } @Test void numberOfPairs() { int[] arr = {10, 20, 20, 10, 10, 30, 50, 10, 20}; int result = 3; assertEquals(result, CrackInterview.numberOfPairs(arr)); } @Test void numberOfPairs2() { int[] arr = {1, 2, 1, 2, 1, 3, 2}; int result = 2; assertEquals(result, CrackInterview.numberOfPairs(arr)); } @Test void minimumDistanceBetweenPairs() { int[] arr = {7, 1, 3, 4, 1, 7}; int result = 3; assertEquals(result, CrackInterview.minimumDistanceBetweenPairs(arr)); } @Test void minimumDistanceBetweenPairs2() { int[] arr = {1, 2, 3, 4, 10}; int result = -1; assertEquals(result, CrackInterview.minimumDistanceBetweenPairs(arr)); } }
8f8183c4b78aecdf53fd8f5278ebbc5685be1daf
{ "blob_id": "8f8183c4b78aecdf53fd8f5278ebbc5685be1daf", "branch_name": "refs/heads/master", "committer_date": "2018-11-05T16:07:26", "content_id": "f283873f21270264afb8711d771f920e38a6bb44", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b0cd39bfe4441f7be977ae28b9d50f77cda12180", "extension": "java", "filename": "CrackInterviewTest.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 139033902, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5550, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/java/org/aguinore/crackInterview/CrackInterviewTest.java", "provenance": "stack-edu-0027.json.gz:645140", "repo_name": "Aguinore/hackerrank", "revision_date": "2018-11-05T16:07:26", "revision_id": "e69df84ae072c0c85cb738ee15c569d6355a1fc1", "snapshot_id": "599af593e8205c935cd3ac476a292615c80221cb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Aguinore/hackerrank/e69df84ae072c0c85cb738ee15c569d6355a1fc1/test/java/org/aguinore/crackInterview/CrackInterviewTest.java", "visit_date": "2020-03-21T20:52:36.742612", "added": "2024-11-18T21:49:59.545087+00:00", "created": "2018-11-05T16:07:26", "int_score": 3, "score": 3.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
package thecoronials.handler; //Author: Fabian Faerber import com.amazon.ask.dispatcher.request.handler.HandlerInput; import com.amazon.ask.dispatcher.request.handler.RequestHandler; import com.amazon.ask.model.Intent; import com.amazon.ask.model.Response; import com.amazon.ask.response.ResponseBuilder; import java.util.Optional; import static com.amazon.ask.request.Predicates.intentName; public class UseDefaultTransportHandler implements RequestHandler { @Override public boolean canHandle(final HandlerInput handlerInput) { return handlerInput.matches(intentName("UseDefaultTransport")); } @Override public Optional<Response> handle(HandlerInput handlerInput) { return handleMyInput(new MasterDataInput(handlerInput), handlerInput.getResponseBuilder()); } public Optional<Response> handleMyInput(final MasterDataInput transportInput, final ResponseBuilder responseBuilder) { final String jaNein = transportInput.getSlotValue("jaNein"); final Optional<Response> response; if ("nein".equals(jaNein)) { final Intent nextIntent = Intent.builder() .withName("AddTransport") .build(); response = responseBuilder .addDelegateDirective(nextIntent) .build(); } else { final Intent nextIntent = Intent.builder() .withName("SaveAppointment") .build(); response = responseBuilder .addDelegateDirective(nextIntent) .build(); } return response; } }
7b8fd063e123a30fbfafd282c647d5eec92faf6c
{ "blob_id": "7b8fd063e123a30fbfafd282c647d5eec92faf6c", "branch_name": "refs/heads/master", "committer_date": "2021-05-04T14:57:51", "content_id": "1e637572da44f1bb011cd5cfa9dd657815ca900b", "detected_licenses": [ "MIT" ], "directory_id": "7a4f4585bb2d62ec50e93dd44842d5917cf7ba54", "extension": "java", "filename": "UseDefaultTransportHandler.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 351077269, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1656, "license": "MIT", "license_type": "permissive", "path": "/skill/src/main/java/thecoronials/handler/UseDefaultTransportHandler.java", "provenance": "stack-edu-0027.json.gz:52378", "repo_name": "HM-DTLab-WiSe20-21-Alzheimer/WiSe20-21-Alzheimer-Terminhelfer", "revision_date": "2021-05-04T14:57:51", "revision_id": "6b53dca076db1039a5660053babaf928bcbd0974", "snapshot_id": "b40d7509023d64b8042b3763408f5c2f83f7fb96", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HM-DTLab-WiSe20-21-Alzheimer/WiSe20-21-Alzheimer-Terminhelfer/6b53dca076db1039a5660053babaf928bcbd0974/skill/src/main/java/thecoronials/handler/UseDefaultTransportHandler.java", "visit_date": "2023-04-22T11:11:00.721769", "added": "2024-11-19T00:30:24.934879+00:00", "created": "2021-05-04T14:57:51", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
package org.zaproxy.zap.extension.automacrobuilder.view; import javax.swing.*; import java.awt.*; @SuppressWarnings("serial") public abstract class GridBagJDialog extends JDialog { /** * create basic dialog<br> * * <pre> * |------------------------------------------------| * | | * | mainPanelContent | * | | * | -----------------------------------------------| * | | OK | | CANCEL || * |________________________________________________| * </pre> */ GridBagJDialog(Window owner, String title, ModalityType modalityType) { super(owner, title, modalityType); init(); } /** * create this dialog contents<br> * you must implement createMainPanelContent method */ private void init() { Component mainPanelContent = createMainPanelContent(); GridBagLayout layout = new GridBagLayout(); JPanel panel = new JPanel(); panel.setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.add(mainPanelContent, BorderLayout.CENTER); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 4; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0d; gbc.weighty = 0.8d; gbc.insets = new Insets(5, 5, 5, 5); layout.setConstraints(mainPanel, gbc); panel.add(mainPanel); JSeparator separator = new JSeparator(); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 4; gbc.gridheight = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0d; gbc.weighty = 0.1d; gbc.insets = new Insets(0, 5, 0, 5); layout.setConstraints(separator, gbc); panel.add(separator); JButton okBtn = new JButton("OK"); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.25d; gbc.weighty = 0.1d; gbc.insets = new Insets(5, 5, 5, 5); layout.setConstraints(okBtn, gbc); panel.add(okBtn); okBtn.addActionListener( e -> { okBtnActionPerformed(); }); JButton cancelBtn = new JButton("CANCEL"); gbc.gridx = 3; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.25d; gbc.weighty = 0.1d; gbc.insets = new Insets(5, 5, 5, 5); layout.setConstraints(cancelBtn, gbc); panel.add(cancelBtn); cancelBtn.addActionListener( e -> { cancelBtnActionPerformed(); }); getContentPane().add(panel, "Center"); setResizable(true); pack(); // set dialog position to centre of Owner window. setLocationRelativeTo(getOwner()); } /** * implement mainPanelContent component<br> * * @return Component */ protected abstract Component createMainPanelContent(); /** * OK button Action<br> * You must specify dispose() method at last line of this method. */ protected abstract void okBtnActionPerformed(); /** * CANCEL button Action<br> * You must specify dispose() method at last line of this method. */ protected abstract void cancelBtnActionPerformed(); }
2f4bdb3f829ebd267ea5e901a5b32647fd6abfaf
{ "blob_id": "2f4bdb3f829ebd267ea5e901a5b32647fd6abfaf", "branch_name": "refs/heads/master", "committer_date": "2022-09-15T12:01:03", "content_id": "74c5b8baf07600cae910850fb653e831b1d23e2a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "357a681920250f51e512f46937283f80a0a596f0", "extension": "java", "filename": "GridBagJDialog.java", "fork_events_count": 0, "gha_created_at": "2017-02-02T14:06:03", "gha_event_created_at": "2022-06-21T01:06:38", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 80730694, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3746, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/org/zaproxy/zap/extension/automacrobuilder/view/GridBagJDialog.java", "provenance": "stack-edu-0023.json.gz:223253", "repo_name": "gdgd009xcd/AutoMacroBuilder", "revision_date": "2022-09-15T12:01:03", "revision_id": "4c78ebaad5d127dc53eed17ff974e5ebacb56fdb", "snapshot_id": "1a7af7220d0ebd30aca38ddcc36ea99d32f8c133", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/gdgd009xcd/AutoMacroBuilder/4c78ebaad5d127dc53eed17ff974e5ebacb56fdb/src/main/java/org/zaproxy/zap/extension/automacrobuilder/view/GridBagJDialog.java", "visit_date": "2022-10-21T03:25:44.255236", "added": "2024-11-18T22:56:25.067807+00:00", "created": "2022-09-15T12:01:03", "int_score": 3, "score": 2.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _06.Interval_of_Numbers { class Program { static void Main(string[] args) { int startNunber = int.Parse(Console.ReadLine()); int endNumber = int.Parse(Console.ReadLine()); for (int i = Math.Min(startNunber,endNumber); i <= Math.Max(endNumber,startNunber); i++) { Console.WriteLine(i); } } } }
b43bff035be0e8c186034a316716c41e9221e6be
{ "blob_id": "b43bff035be0e8c186034a316716c41e9221e6be", "branch_name": "refs/heads/master", "committer_date": "2018-01-16T19:29:02", "content_id": "5b98f70b2a2f292c77fdf15af6669d8306078e80", "detected_licenses": [ "MIT" ], "directory_id": "e6cad808124c841021a477fa5d7142a630119f5e", "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": 117730191, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 549, "license": "MIT", "license_type": "permissive", "path": "/02. Conditional Statements and Loops - Exercises/06. Interval of Numbers/Program.cs", "provenance": "stack-edu-0011.json.gz:297366", "repo_name": "PavelIvanov96/Programming-Fundamentals-Extended-CSharp", "revision_date": "2018-01-16T19:29:02", "revision_id": "7a245dd48a38d819b0f8eef40617ad7ffc1cd53a", "snapshot_id": "018d3f824e5bf3014a8ee2d5d283fc9f4cfb3de4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PavelIvanov96/Programming-Fundamentals-Extended-CSharp/7a245dd48a38d819b0f8eef40617ad7ffc1cd53a/02. Conditional Statements and Loops - Exercises/06. Interval of Numbers/Program.cs", "visit_date": "2021-05-11T15:28:09.378579", "added": "2024-11-19T00:42:12.474442+00:00", "created": "2018-01-16T19:29:02", "int_score": 3, "score": 3.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
# import dependencies import argparse import os import numpy as np import PIL import PIL.Image as Image # create argument parser parser = argparse.ArgumentParser() parser.add_argument('--orig_data', default=None, type=str, required=True, help='absolute path to original data', metavar='PATH') parser.add_argument('--new_data', default=None, type=str, required=True, help='absolute path to rotated data', metavar='PATH') args = parser.parse_args() # define function def rotate(img, deg): '''rotate and save image''' # add RGB channels to monochrome image if len(np.array(img).shape) < 3: img = np.stack((img, ) * 3, axis=-1) # rotate image if deg == 0: img = Image.fromarray(np.array(img)) elif deg == 90: img = Image.fromarray(np.flipud(np.transpose(img, (1, 0, 2)))) elif deg == 180: img = Image.fromarray(np.fliplr(np.flipud(img))) elif deg == 270: img = Image.fromarray(np.transpose(np.flipud(img), (1, 0, 2))) else: raise ValueError('only 0, 90, 180, or 270 degrees rotations allowed') return img # create directory if not os.path.isdir(args.new_data): os.mkdir(args.new_data) for i in range(4): os.mkdir(os.path.join(args.new_data, str(i))) # process data for dir_ in os.listdir(args.orig_data): idx = 0 for img_name in os.listdir(os.path.join(args.orig_data, dir_)): if img_name.endswith('JPEG'): img = Image.open(os.path.join(args.orig_data, dir_, img_name)) if idx % 4 == 0: deg = 0 elif idx % 4 == 1: deg = 90 elif idx % 4 == 2: deg = 180 elif idx % 4 == 3: deg = 270 img = rotate(img, deg) img.save(os.path.join(args.new_data, str(idx % 4), img_name)) idx += 1 print('rotation dataset created')
6661c1eadf4b68d098c61ebf3ded7af004962bd5
{ "blob_id": "6661c1eadf4b68d098c61ebf3ded7af004962bd5", "branch_name": "refs/heads/master", "committer_date": "2019-05-24T06:15:26", "content_id": "ed7b45dd24d03f4573576f4af002d108484f4bcd", "detected_licenses": [ "MIT" ], "directory_id": "8a61ff289ec3e640fa7fb7fc769f4dd9acda0824", "extension": "py", "filename": "preprocess.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 182118606, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license": "MIT", "license_type": "permissive", "path": "/rotation-net/preprocess.py", "provenance": "stack-edu-0056.json.gz:870", "repo_name": "positivevaib/semi-supervised-imagenet-classification", "revision_date": "2019-05-24T06:15:26", "revision_id": "4fb6427f5a72951c1b866a1ddbc2599811bb5770", "snapshot_id": "f4dc824bdfaff084b2e3683585611d2c044e9613", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/positivevaib/semi-supervised-imagenet-classification/4fb6427f5a72951c1b866a1ddbc2599811bb5770/rotation-net/preprocess.py", "visit_date": "2022-01-23T20:01:30.123503", "added": "2024-11-18T19:24:04.835960+00:00", "created": "2019-05-24T06:15:26", "int_score": 3, "score": 3.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ package org.wso2.iot.integration.ui.pages.home; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.wso2.iot.integration.ui.pages.UIUtils; import org.wso2.iot.integration.ui.pages.UIElementMapper; import org.wso2.iot.integration.ui.pages.devices.EnrollDevicePage; import org.wso2.iot.integration.ui.pages.groups.DeviceAddGroupPage; import org.wso2.iot.integration.ui.pages.login.LoginPage; import java.io.IOException; /** * This class represents the IOT server home page. */ public class IOTHomePage { private WebDriver driver; private UIElementMapper uiElementMapper; public IOTHomePage(WebDriver driver) throws IOException { this.driver = driver; this.uiElementMapper = UIElementMapper.getInstance(); // Check that we're on the right page. WebDriverWait wait = new WebDriverWait(driver, UIUtils.webDriverTimeOut); if (!wait.until(ExpectedConditions.titleIs(uiElementMapper.getElement("cdmf.user.home.page")))) { throw new IllegalStateException("This is not the home page"); } } /** * Method to check the current User name * @return : True if the user name matches the logged in user. False otherwise. */ public boolean checkUserName() { String name = driver.findElement(By.xpath(uiElementMapper.getElement("iot.user.registered.name"))).getText(); return name.contains(uiElementMapper.getElement("iot.user.login.username")); } /** * Performs the logout function. * @return : IOT login page. */ public LoginPage logout() throws IOException { driver.findElement(By.xpath(uiElementMapper.getElement("iot.user.registered.name"))).click(); WebElement logout = driver.findElement(By.xpath(uiElementMapper.getElement("iot.user.logout.link.xpath"))); logout.click(); return new LoginPage(driver); } /** * Navigates to the New device enrollment page. * @return : Enroll Device page. */ public EnrollDevicePage enrollNewDevice() throws IOException { driver.findElement(By.xpath("iot.home.page.uuf-menu.xpath")).click(); driver.findElement(By.xpath("iot.home.page.uuf-menu.devicemgt.xpath")).click(); driver.findElement(By.xpath("iot.home.enrollDevice.xpath")).click(); return new EnrollDevicePage(driver); } /** * Performs the navigation to Add device group page. * @return : Add Device Group page. */ public DeviceAddGroupPage addNewGroup() throws IOException { driver.findElement(By.xpath("iot.home.page.uuf-menu.xpath")).click(); driver.findElement(By.xpath("iot.home.page.uuf-menu.groupmgt.xpath")).click(); driver.findElement(By.xpath("iot.device.viewGroup.empty.addGroup.xpath")).click(); return new DeviceAddGroupPage(driver); } //ToDo : To add policies }
d311709dd6db61bdac0477b56e30c1a7cfb2a590
{ "blob_id": "d311709dd6db61bdac0477b56e30c1a7cfb2a590", "branch_name": "refs/heads/master", "committer_date": "2017-09-26T08:56:21", "content_id": "58b929e9e3827d9800a0d37799de684ce597db25", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2c4c67c032cc0f4c03ca51056c74f2ae6646d7df", "extension": "java", "filename": "IOTHomePage.java", "fork_events_count": 0, "gha_created_at": "2017-04-17T11:45:23", "gha_event_created_at": "2017-04-17T11:45:23", "gha_language": null, "gha_license_id": null, "github_id": 88502958, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3716, "license": "Apache-2.0", "license_type": "permissive", "path": "/modules/integration/tests-common/web-ui-pages/src/main/java/org/wso2/iot/integration/ui/pages/home/IOTHomePage.java", "provenance": "stack-edu-0027.json.gz:514453", "repo_name": "pasindujw/product-iots", "revision_date": "2017-09-26T08:56:21", "revision_id": "6c0247df2b314b011321ba85366df1d97e591c13", "snapshot_id": "5f08f4eb5a7b9375ab9c905b13da630b6c3238d9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pasindujw/product-iots/6c0247df2b314b011321ba85366df1d97e591c13/modules/integration/tests-common/web-ui-pages/src/main/java/org/wso2/iot/integration/ui/pages/home/IOTHomePage.java", "visit_date": "2021-01-19T20:24:13.528705", "added": "2024-11-19T02:01:43.390792+00:00", "created": "2017-09-26T08:56:21", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
#include <cxxstd/iostream.h> #include <boost/numeric/mtl/mtl.hpp> using namespace mtl; using mtl::iall; // // we feed the beast with a const reference // void beast(const dense2D<double> &A) { dense2D<double> B = sub_matrix(A, 0, 5, 0, 5); B[1][1] = 666; } int main(int, char**) { using namespace mtl; using mtl::iall; const int m = 5, n = 5; dense2D<double> A(n, n); for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { A[i][j] = i+j; } } std::cout << "before: A is\n" << A << "\n"; // // calling the beast // beast(A); std::cout << "after: A is\n" << A << "\n"; return 0; }
ca087f0c674c69977cf98ff37a792b5d773b5129
{ "blob_id": "ca087f0c674c69977cf98ff37a792b5d773b5129", "branch_name": "refs/heads/public", "committer_date": "2022-01-26T13:27:47", "content_id": "8743021f765af18f2b91094f750b7ff4b23f25bb", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8b6b8639ba21cb271dacf60a2c999d852b1aa998", "extension": "cc", "filename": "design-flaws-mtl4.cc", "fork_events_count": 33, "gha_created_at": "2011-12-14T18:21:41", "gha_event_created_at": "2021-08-04T01:13:31", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 2981988, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 667, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/flens/examples/design-flaws-mtl4.cc", "provenance": "stack-edu-0003.json.gz:115467", "repo_name": "michael-lehn/FLENS", "revision_date": "2022-01-26T13:27:47", "revision_id": "80495fa97dda42a0acafc8f83fc9639ae36d2e10", "snapshot_id": "6673450461f2607a8b6c8242aa4f7927a70c4e23", "src_encoding": "UTF-8", "star_events_count": 111, "url": "https://raw.githubusercontent.com/michael-lehn/FLENS/80495fa97dda42a0acafc8f83fc9639ae36d2e10/flens/examples/design-flaws-mtl4.cc", "visit_date": "2022-02-14T13:05:37.624164", "added": "2024-11-18T21:04:34.902011+00:00", "created": "2022-01-26T13:27:47", "int_score": 3, "score": 2.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
package com.actelion.research.chem.descriptor.flexophore; import com.actelion.research.chem.Coordinates; import com.actelion.research.chem.Molecule3D; public class MolDistHistVizHelper { public static void centerNodes(MolDistHistViz mdhv){ Coordinates barycenter = getBarycenter(mdhv); for (int i = 0; i < mdhv.getNumPPNodes(); i++) { PPNodeViz node = mdhv.getNode(i); node.getCoordinates().x -= barycenter.x; node.getCoordinates().y -= barycenter.y; node.getCoordinates().z -= barycenter.z; } Molecule3D m = mdhv.getMolecule(); Coordinates [] arrCoordinates = m.getCoordinates(); for (int i = 0; i < arrCoordinates.length; i++) { Coordinates c = arrCoordinates[i]; c.x -= barycenter.x; c.y -= barycenter.y; c.z -= barycenter.z; m.setCoordinates(i, c); } } public static Coordinates getBarycenter(MolDistHistViz mdhv){ Coordinates [] arrCoordinates = new Coordinates[mdhv.getNumPPNodes()]; for (int i = 0; i < mdhv.getNumPPNodes(); i++) { PPNodeViz node = mdhv.getNode(i); arrCoordinates[i] = node.getCoordinates(); } return Coordinates.createBarycenter(arrCoordinates); } }
ec224adf61e25ce6ae592bcd9d47aef6125ec2c9
{ "blob_id": "ec224adf61e25ce6ae592bcd9d47aef6125ec2c9", "branch_name": "refs/heads/master", "committer_date": "2023-09-04T12:49:54", "content_id": "bfccf5423585c77fddfcbd982298378324475c48", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "34c28dff55ee2a21112d8721bb8ded2c92d1c7dc", "extension": "java", "filename": "MolDistHistVizHelper.java", "fork_events_count": 28, "gha_created_at": "2015-01-27T18:33:02", "gha_event_created_at": "2023-09-04T12:49:55", "gha_language": "Java", "gha_license_id": "NOASSERTION", "github_id": 29928471, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1318, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/main/java/com/actelion/research/chem/descriptor/flexophore/MolDistHistVizHelper.java", "provenance": "stack-edu-0024.json.gz:72326", "repo_name": "Actelion/openchemlib", "revision_date": "2023-09-04T12:49:54", "revision_id": "eb7d02d71b4ccb0e3292ef20d45cb4b47b456ba3", "snapshot_id": "eb5bf891149b77e64550c97f6ed05bf70c8f3883", "src_encoding": "UTF-8", "star_events_count": 72, "url": "https://raw.githubusercontent.com/Actelion/openchemlib/eb7d02d71b4ccb0e3292ef20d45cb4b47b456ba3/src/main/java/com/actelion/research/chem/descriptor/flexophore/MolDistHistVizHelper.java", "visit_date": "2023-09-05T00:38:09.121429", "added": "2024-11-19T00:18:39.937994+00:00", "created": "2023-09-04T12:49:54", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
"""added timeouts to Stage and Job Revision ID: 3c1af14e0370 Revises: ff4a425a6070 Create Date: 2020-01-14 07:26:17.893236 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '3c1af14e0370' down_revision = 'ff4a425a6070' branch_labels = None depends_on = None def upgrade(): op.add_column('jobs', sa.Column('timeout', sa.Integer(), nullable=True)) op.add_column('stages', sa.Column('timeouts', postgresql.JSONB(astext_type=sa.Text()), nullable=True)) def downgrade(): op.drop_column('stages', 'timeouts') op.drop_column('jobs', 'timeout')
d59e76d50839a07ce9805aa9c9296f82eb0569a4
{ "blob_id": "d59e76d50839a07ce9805aa9c9296f82eb0569a4", "branch_name": "refs/heads/master", "committer_date": "2021-05-09T08:04:08", "content_id": "c1e555ac12f75d584eabb93f068174c3938449d1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8e3c0584de50b605f9da593efe9018ac2b4d7d00", "extension": "py", "filename": "3c1af14e0370_added_timeouts_to_stage_and_job.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": 656, "license": "Apache-2.0", "license_type": "permissive", "path": "/server/kraken/migrations/versions/3c1af14e0370_added_timeouts_to_stage_and_job.py", "provenance": "stack-edu-0056.json.gz:230314", "repo_name": "GeneralCommission/kraken", "revision_date": "2021-05-09T08:04:08", "revision_id": "b79d60d6cff11f8e58f168d5e484cdea22a1dea1", "snapshot_id": "64bf4f55aa695e0b60c17ab69eb3b03819e1b277", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GeneralCommission/kraken/b79d60d6cff11f8e58f168d5e484cdea22a1dea1/server/kraken/migrations/versions/3c1af14e0370_added_timeouts_to_stage_and_job.py", "visit_date": "2023-04-24T18:53:43.105265", "added": "2024-11-19T02:08:16.665075+00:00", "created": "2021-05-09T08:04:08", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
package mage.cards.e; import java.util.UUID; import mage.MageInt; import mage.abilities.TriggeredAbility; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.MorbidCondition; import mage.abilities.decorator.ConditionalInterveningIfTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.hint.common.MorbidHint; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.game.permanent.token.SpiritWhiteToken; /** * * @author escplan9 (Derek Monturo - dmontur1 at gmail dot com) */ public final class EmissaryOfTheSleepless extends CardImpl { public EmissaryOfTheSleepless(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{W}"); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(2); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // When Emissary of the Sleepless enters the battlefield, if a creature died this turn, create a 1/1 white Spirit creature token with flying. TriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new CreateTokenEffect(new SpiritWhiteToken())); this.addAbility(new ConditionalInterveningIfTriggeredAbility(ability, MorbidCondition.instance, "When {this} enters the battlefield, if a creature died this turn, create a 1/1 white Spirit creature token with flying.").addHint(MorbidHint.instance)); } private EmissaryOfTheSleepless(final EmissaryOfTheSleepless card) { super(card); } @Override public EmissaryOfTheSleepless copy() { return new EmissaryOfTheSleepless(this); } }
ad5a42e1968edd75cca263755d4e129fd630f188
{ "blob_id": "ad5a42e1968edd75cca263755d4e129fd630f188", "branch_name": "refs/heads/master", "committer_date": "2023-09-03T03:53:12", "content_id": "48e73d741f01c4932dbbd30781d1619d96440458", "detected_licenses": [ "MIT" ], "directory_id": "ccf82688f082e26cba5fc397c76c77cc007ab2e8", "extension": "java", "filename": "EmissaryOfTheSleepless.java", "fork_events_count": 1133, "gha_created_at": "2012-04-27T13:18:34", "gha_event_created_at": "2023-09-14T20:18:55", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 4158448, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1858, "license": "MIT", "license_type": "permissive", "path": "/Mage.Sets/src/mage/cards/e/EmissaryOfTheSleepless.java", "provenance": "stack-edu-0024.json.gz:248834", "repo_name": "magefree/mage", "revision_date": "2023-09-03T03:53:12", "revision_id": "5dba61244c738f4a184af0d256046312ce21d911", "snapshot_id": "3261a89320f586d698dd03ca759a7562829f247f", "src_encoding": "UTF-8", "star_events_count": 1803, "url": "https://raw.githubusercontent.com/magefree/mage/5dba61244c738f4a184af0d256046312ce21d911/Mage.Sets/src/mage/cards/e/EmissaryOfTheSleepless.java", "visit_date": "2023-09-03T15:55:36.650410", "added": "2024-11-19T02:16:03.260562+00:00", "created": "2023-09-03T03:53:12", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
/* * Copyright 2015 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tools/android/memtrack_helper/memtrack_helper.h" #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> /* * This is a helper daemon for Android which makes memtrack graphics information * accessible via a UNIX socket. It is used by telemetry and memory-infra. * More description in the design-doc: https://goo.gl/4Y30p9 . */ static const char kShutdownRequest = 'Q'; // See $ANDROID/system/core/include/memtrack/memtrack.h. typedef void* memtrack_proc_handle; typedef int (*memtrack_init_t)(void); typedef memtrack_proc_handle (*memtrack_proc_new_t)(void); typedef void (*memtrack_proc_destroy_t)(memtrack_proc_handle); typedef int (*memtrack_proc_get_t)(memtrack_proc_handle, pid_t); typedef ssize_t (*memtrack_proc_graphics_total_t)(memtrack_proc_handle); typedef ssize_t (*memtrack_proc_graphics_pss_t)(memtrack_proc_handle); typedef ssize_t (*memtrack_proc_gl_total_t)(memtrack_proc_handle); typedef ssize_t (*memtrack_proc_gl_pss_t)(memtrack_proc_handle); typedef ssize_t (*memtrack_proc_other_total_t)(memtrack_proc_handle); typedef ssize_t (*memtrack_proc_other_pss_t)(memtrack_proc_handle); static memtrack_init_t memtrack_init; static memtrack_proc_new_t memtrack_proc_new; static memtrack_proc_destroy_t memtrack_proc_destroy; static memtrack_proc_get_t memtrack_proc_get; static memtrack_proc_graphics_total_t memtrack_proc_graphics_total; static memtrack_proc_graphics_pss_t memtrack_proc_graphics_pss; static memtrack_proc_gl_total_t memtrack_proc_gl_total; static memtrack_proc_gl_pss_t memtrack_proc_gl_pss; static memtrack_proc_other_total_t memtrack_proc_other_total; static memtrack_proc_other_pss_t memtrack_proc_other_pss; static void send_response(int client_sock, const char* resp) { send(client_sock, resp, strlen(resp) + 1, 0); } static void send_shutdown_request(struct sockaddr_un* addr) { int sock = socket(AF_UNIX, SOCK_SEQPACKET, 0); connect(sock, (struct sockaddr*)addr, sizeof(*addr)); send(sock, &kShutdownRequest, 1, 0); close(sock); } static void handle_one_request(int client_sock) { char buf[32]; char response[4096] = ""; ssize_t rsize = recv(client_sock, buf, sizeof(buf) - 1, 0); if (rsize < 1) return; buf[rsize] = '\0'; if (buf[0] == kShutdownRequest) exit(EXIT_SUCCESS); pid_t pid = -1; if (sscanf(buf, "%d", &pid) != 1 || pid < 0) return send_response(client_sock, "ERR invalid pid"); memtrack_proc_handle handle = memtrack_proc_new(); if (!handle) return send_response(client_sock, "ERR memtrack_proc_new()"); if (memtrack_proc_get(handle, pid)) { memtrack_proc_destroy(handle); return send_response(client_sock, "ERR memtrack_proc_get()"); } char* response_ptr = &response[0]; if (memtrack_proc_graphics_total) { response_ptr += sprintf(response_ptr, "graphics_total %zd\n", memtrack_proc_graphics_total(handle)); } if (memtrack_proc_graphics_pss) { response_ptr += sprintf(response_ptr, "graphics_pss %zd\n", memtrack_proc_graphics_pss(handle)); } if (memtrack_proc_gl_total) { response_ptr += sprintf(response_ptr, "gl_total %zd\n", memtrack_proc_gl_total(handle)); } if (memtrack_proc_gl_pss) { response_ptr += sprintf(response_ptr, "gl_pss %zd\n", memtrack_proc_gl_pss(handle)); } if (memtrack_proc_other_total) { response_ptr += sprintf(response_ptr, "other_total %zd\n", memtrack_proc_other_total(handle)); } if (memtrack_proc_other_pss) { response_ptr += sprintf(response_ptr, "other_pss %zd\n", memtrack_proc_other_pss(handle)); } memtrack_proc_destroy(handle); send_response(client_sock, response); } static void daemonize() { pid_t pid; pid = fork(); if (pid < 0) exit_with_failure("fork"); if (pid > 0) { // Main process keeps TTY while intermediate child do daemonization // because adb can immediately kill a process disconnected from adb's TTY. int ignore; wait(&ignore); exit(EXIT_SUCCESS); } if (setsid() == -1) exit_with_failure("setsid"); chdir("/"); umask(0); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); open("/dev/null", O_RDONLY); open("/dev/null", O_WRONLY); open("/dev/null", O_RDWR); pid = fork(); if (pid < 0) exit_with_failure("fork"); if (pid > 0) exit(EXIT_SUCCESS); } int main(int argc, char** argv) { int res; if (getuid() != 0) { fprintf(stderr, "FATAL: %s must be run as root!\n", argv[0]); return EXIT_FAILURE; } void* const libhandle = dlopen("libmemtrack.so", RTLD_GLOBAL | RTLD_NOW); if (!libhandle) exit_with_failure("dlopen() libmemtrack.so"); memtrack_init = (memtrack_init_t)dlsym(libhandle, "memtrack_init"); memtrack_proc_new = (memtrack_proc_new_t)dlsym(libhandle, "memtrack_proc_new"); memtrack_proc_destroy = (memtrack_proc_destroy_t)dlsym(libhandle, "memtrack_proc_destroy"); memtrack_proc_get = (memtrack_proc_get_t)dlsym(libhandle, "memtrack_proc_get"); memtrack_proc_graphics_total = (memtrack_proc_graphics_total_t)dlsym( libhandle, "memtrack_proc_graphics_total"); memtrack_proc_graphics_pss = (memtrack_proc_graphics_pss_t)dlsym( libhandle, "memtrack_proc_graphics_pss"); memtrack_proc_gl_total = (memtrack_proc_gl_total_t)dlsym(libhandle, "memtrack_proc_gl_total"); memtrack_proc_gl_pss = (memtrack_proc_gl_pss_t)dlsym(libhandle, "memtrack_proc_gl_pss"); memtrack_proc_other_total = (memtrack_proc_other_total_t)dlsym( libhandle, "memtrack_proc_other_total"); memtrack_proc_other_pss = (memtrack_proc_other_pss_t)dlsym(libhandle, "memtrack_proc_other_pss"); if (!memtrack_proc_new || !memtrack_proc_destroy || !memtrack_proc_get) { exit_with_failure("dlsym() libmemtrack.so"); } const int server_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (server_fd < 0) exit_with_failure("socket"); /* Initialize the socket */ struct sockaddr_un server_addr; init_memtrack_server_addr(&server_addr); /* Shutdown previously running instances if any. */ int i; for (i = 0; i < 3; ++i) { res = bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)); if (res && errno == EADDRINUSE) { send_shutdown_request(&server_addr); usleep(250000); continue; } break; } if (res) exit_with_failure("bind"); if (argc > 1 && strcmp(argv[1], "-d") == 0) daemonize(); long pid = getpid(); fprintf(stderr, "pid=%ld\n", pid); __android_log_print(ANDROID_LOG_INFO, kLogTag, "pid=%ld\n", pid); if (memtrack_init) { res = memtrack_init(); if (res == -ENOENT) { exit_with_failure("Unable to load memtrack module in libhardware. " "Probably implementation is missing in this ROM."); } else if (res != 0) { exit_with_failure("memtrack_init() returned non-zero status."); } } if (listen(server_fd, 128 /* max number of queued requests */)) exit_with_failure("listen"); for (;;) { struct sockaddr_un client_addr; socklen_t len = sizeof(client_addr); int client_sock = accept(server_fd, (struct sockaddr*)&client_addr, &len); handle_one_request(client_sock); close(client_sock); } return EXIT_SUCCESS; }
fa88a643c6bd51d2c3be19e4d3c970c869b1bf5a
{ "blob_id": "fa88a643c6bd51d2c3be19e4d3c970c869b1bf5a", "branch_name": "refs/heads/main", "committer_date": "2023-08-23T22:01:11", "content_id": "dfd409fb939a9e4da8da0d486808e6d412f4c4de", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a3d6556180e74af7b555f8d47d3fea55b94bcbda", "extension": "c", "filename": "memtrack_helper.c", "fork_events_count": 7102, "gha_created_at": "2018-02-05T20:55:32", "gha_event_created_at": "2023-09-10T23:44:27", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 120360765, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7699, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tools/android/memtrack_helper/memtrack_helper.c", "provenance": "stack-edu-0000.json.gz:114226", "repo_name": "chromium/chromium", "revision_date": "2023-08-23T22:01:11", "revision_id": "a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c", "snapshot_id": "aaa9eda10115b50b0616d2f1aed5ef35d1d779d6", "src_encoding": "UTF-8", "star_events_count": 17408, "url": "https://raw.githubusercontent.com/chromium/chromium/a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c/tools/android/memtrack_helper/memtrack_helper.c", "visit_date": "2023-08-24T00:35:12.585945", "added": "2024-11-18T21:46:58.711868+00:00", "created": "2023-08-23T22:01:11", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
// Copyright 2019 Johannes Köster, University of Duisburg-Essen. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Error definitions for the `pssm` module. use thiserror::Error; #[derive( Error, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize, )] pub enum Error { #[error( "query length {} is shorter than motif length {}", query_len, motif_len )] QueryTooShort { motif_len: usize, query_len: usize }, #[error("attempted to build a motif from sequences with mismatched lengths")] InconsistentLen, #[error("monomer '{}' is invalid", char::from(*mono))] InvalidMonomer { mono: u8 }, #[error("motif cannot be created from zero sequences")] EmptyMotif, #[error("information-free motif: a motif in which every monomer is equally likely at every position will result in a divide-by-zero exception")] NullMotif, #[error("expected pseudo-score array of length {}; got {}", expected, received)] InvalidPseudos { expected: u8, received: u8 }, } pub type Result<T, E = Error> = std::result::Result<T, E>;
67a90e75f1baeb5cf6df5dcbb2f3b3e57626548d
{ "blob_id": "67a90e75f1baeb5cf6df5dcbb2f3b3e57626548d", "branch_name": "refs/heads/master", "committer_date": "2023-07-11T15:06:15", "content_id": "f975d998bb38ae685dffbc8397fd307b4d141bc5", "detected_licenses": [ "MIT" ], "directory_id": "36dd5d6ca0e7acaeb0d2e7f6fc910b877e316df3", "extension": "rs", "filename": "errors.rs", "fork_events_count": 235, "gha_created_at": "2015-01-25T16:40:31", "gha_event_created_at": "2023-09-13T13:54:39", "gha_language": "Rust", "gha_license_id": "MIT", "github_id": 29821195, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1229, "license": "MIT", "license_type": "permissive", "path": "/src/pattern_matching/pssm/errors.rs", "provenance": "stack-edu-0068.json.gz:7393", "repo_name": "rust-bio/rust-bio", "revision_date": "2023-07-11T15:06:15", "revision_id": "bb882814395a172de48f670cd316429ea2e50864", "snapshot_id": "7371947178a3ca16b063940b463bff2cb83a8b59", "src_encoding": "UTF-8", "star_events_count": 1440, "url": "https://raw.githubusercontent.com/rust-bio/rust-bio/bb882814395a172de48f670cd316429ea2e50864/src/pattern_matching/pssm/errors.rs", "visit_date": "2023-08-05T07:08:29.484529", "added": "2024-11-18T22:09:56.854798+00:00", "created": "2023-07-11T15:06:15", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz" }
import { Axis } from './Axis'; import Body from './Body'; import ComputeIncidentEdge from './ComputeIncidentEdge'; import Contact from './Contact'; import ClipVertex from './ClipVertex'; import { EdgeNumbers } from './EdgeNumbers'; import Mat22 from './math/Mat22'; import Vec2 from './math/Vec2'; import ClipSegmentToLine from './ClipSegmentToLine'; /** * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies. * Erin Catto makes no representations about the suitability * of this software for any purpose. * It is provided "as is" without express or implied warranty. * * Ported to TypeScript by Richard Davey, 2020. */ // Box vertex and edge numbering: // // ^ y // | // e1 // v2 ------ v1 // | | // e2 | | e4 --> x // | | // v3 ------ v4 // e3 function computeFaceAX (posA: Vec2, posB: Vec2, RotA: Mat22, RotB: Mat22, hA: Vec2, hB: Vec2, frontNormalX: number, frontNormalY: number, clipPoints2: ClipVertex[]) { let front: number = Vec2.dotXYV(frontNormalX, frontNormalY, posA) + hA.x; let sideNormalX: number = RotA.b; let sideNormalY: number = RotA.d; let side: number = Vec2.dotXYV(sideNormalX, sideNormalY, posA); let negSide: number = -side + hA.y; let posSide: number = side + hA.y; // The results get stored in this incidentEdge array let incidentEdge: ClipVertex[] = []; ComputeIncidentEdge(incidentEdge, hB, posB, RotB, frontNormalX, frontNormalY); // Clip other face with 5 box planes (1 face plane, 4 edge planes) let clipPoints1: ClipVertex[] = []; // Clip to box side 1 let np: number = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormalX, -sideNormalY, negSide, EdgeNumbers.EDGE3); if (np < 2) { return null; } // Clip to negative box side 1 np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormalX, sideNormalY, posSide, EdgeNumbers.EDGE1); if (np < 2) { return null; } // The contact separation section needs: return front; } function computeFaceAY (posA: Vec2, posB: Vec2, RotA: Mat22, RotB: Mat22, hA: Vec2, hB: Vec2, frontNormalX: number, frontNormalY: number, clipPoints2: ClipVertex[]) { let front: number = Vec2.dotXYV(frontNormalX, frontNormalY, posA) + hA.y; let sideNormalX: number = RotA.a; let sideNormalY: number = RotA.c; let side: number = Vec2.dotXYV(sideNormalX, sideNormalY, posA); let negSide: number = -side + hA.x; let posSide: number = side + hA.x; // The results get stored in this incidentEdge array let incidentEdge: ClipVertex[] = []; ComputeIncidentEdge(incidentEdge, hB, posB, RotB, frontNormalX, frontNormalY); // Clip other face with 5 box planes (1 face plane, 4 edge planes) let clipPoints1: ClipVertex[] = []; // Clip to box side 1 let np: number = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormalX, -sideNormalY, negSide, EdgeNumbers.EDGE2); if (np < 2) { return null; } // Clip to negative box side 1 np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormalX, sideNormalY, posSide, EdgeNumbers.EDGE4); if (np < 2) { return null; } // The contact separation section needs: return front; } function computeFaceBX (posA: Vec2, posB: Vec2, RotA: Mat22, RotB: Mat22, hA: Vec2, hB: Vec2, frontNormalX: number, frontNormalY: number, clipPoints2: ClipVertex[]) { let front: number = Vec2.dotXYV(frontNormalX, frontNormalY, posB) + hB.x; let sideNormalX: number = RotB.b; let sideNormalY: number = RotB.d; let side: number = Vec2.dotXYV(sideNormalX, sideNormalY, posB); let negSide: number = -side + hB.y; let posSide: number = side + hB.y; // The results get stored in this incidentEdge array let incidentEdge: ClipVertex[] = []; ComputeIncidentEdge(incidentEdge, hA, posA, RotA, frontNormalX, frontNormalY); // Clip other face with 5 box planes (1 face plane, 4 edge planes) let clipPoints1: ClipVertex[] = []; // Clip to box side 1 let np: number = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormalX, -sideNormalY, negSide, EdgeNumbers.EDGE3); if (np < 2) { return null; } // Clip to negative box side 1 np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormalX, sideNormalY, posSide, EdgeNumbers.EDGE1); if (np < 2) { return null; } // The contact separation section needs: return front; } function computeFaceBY (posA: Vec2, posB: Vec2, RotA: Mat22, RotB: Mat22, hA: Vec2, hB: Vec2, frontNormalX: number, frontNormalY: number, clipPoints2: ClipVertex[]) { let front: number = Vec2.dotXYV(frontNormalX, frontNormalY, posB) + hB.y; let sideNormalX: number = RotB.a; let sideNormalY: number = RotB.c; let side: number = Vec2.dotXYV(sideNormalX, sideNormalY, posB); let negSide: number = -side + hB.x; let posSide: number = side + hB.x; // The results get stored in this incidentEdge array let incidentEdge: ClipVertex[] = []; ComputeIncidentEdge(incidentEdge, hA, posA, RotA, frontNormalX, frontNormalY); // Clip other face with 5 box planes (1 face plane, 4 edge planes) let clipPoints1: ClipVertex[] = []; // Clip to box side 1 let np: number = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormalX, -sideNormalY, negSide, EdgeNumbers.EDGE2); if (np < 2) { return null; } // Clip to negative box side 1 np = ClipSegmentToLine(clipPoints2, clipPoints1, sideNormalX, sideNormalY, posSide, EdgeNumbers.EDGE4); if (np < 2) { return null; } // The contact separation section needs: return front; } // Our cached collision vecs and mat22s let hA: Vec2 = new Vec2(); let hB: Vec2 = new Vec2(); let RotA: Mat22 = new Mat22(); let RotB: Mat22 = new Mat22(); let RotAT: Mat22 = new Mat22(); let RotBT: Mat22 = new Mat22(); let dp: Vec2 = new Vec2(); let dA: Vec2 = new Vec2(); let dB: Vec2 = new Vec2(); let C: Mat22 = new Mat22(); let absC: Mat22 = new Mat22(); let absCT: Mat22 = new Mat22(); let faceA: Vec2 = new Vec2(); let faceA1: Vec2 = new Vec2(); let faceA2: Vec2 = new Vec2(); let faceB: Vec2 = new Vec2(); let faceB1: Vec2 = new Vec2(); let faceB2: Vec2 = new Vec2(); export default function Collide (contacts: Contact[], bodyA: Body, bodyB: Body): number { // Setup // half the width of bodyA hA.set( 0.5 * bodyA.width, 0.5 * bodyA.height ); // half the width of bodyB hB.set( 0.5 * bodyB.width, 0.5 * bodyB.height ); let posA = bodyA.position; let posB = bodyB.position; RotA.set(bodyA.rotation); RotB.set(bodyB.rotation); RotAT.transpose(bodyA.rotation); RotBT.transpose(bodyB.rotation); dp.set( posB.x - posA.x, posB.y - posA.y ); dA.set( RotAT.a * dp.x + RotAT.b * dp.y, RotAT.c * dp.x + RotAT.d * dp.y ); dB.set( RotBT.a * dp.x + RotBT.b * dp.y, RotBT.c * dp.x + RotBT.d * dp.y ); C.mulMM(RotAT, RotB); Mat22.absM(C, absC); Mat22.transposeM(absC, absCT); // Box A faces faceA1.set( Math.abs(dA.x) - hA.x, Math.abs(dA.y) - hA.y ); // store result in faceA2 Mat22.mulMVV(absC, hB, faceA2); faceA.set( faceA1.x - faceA2.x, faceA1.y - faceA2.y ); if (faceA.x > 0 || faceA.y > 0) { return 0; } // Box B faces // store result in faceB2 Mat22.mulMVV(absCT, hA, faceB2); faceB1.set( Math.abs(dB.x) - faceB2.x, Math.abs(dB.y) - faceB2.y ); faceB.set( faceB1.x - hB.x, faceB1.y - hB.y ); if (faceB.x > 0 || faceB.y > 0) { return 0; } // Find best axis // Box A faces let axis: Axis = Axis.FACE_A_X; let separation: number = faceA.x; let normalX: number = 0; let normalY: number = 0; if (dA.x > 0) { normalX = RotA.a; normalY = RotA.c; } else { normalX = -RotA.a; normalY = -RotA.c; } const RELATIVE_TOL = 0.95; const ABSOLUTE_TOL = 0.01; if (faceA.y > RELATIVE_TOL * separation + ABSOLUTE_TOL * hA.y) { axis = Axis.FACE_A_Y; separation = faceA.y; if (dA.y > 0) { normalX = RotA.b; normalY = RotA.d; } else { normalX = -RotA.b; normalY = -RotA.d; } } // Box B faces if (faceB.x > RELATIVE_TOL * separation + ABSOLUTE_TOL * hB.x) { axis = Axis.FACE_B_X; separation = faceB.x; if (dB.x > 0) { normalX = RotB.a; normalY = RotB.c; } else { normalX = -RotB.a; normalY = -RotB.c; } } if (faceB.y > RELATIVE_TOL * separation + ABSOLUTE_TOL * hB.y) { axis = Axis.FACE_B_Y; separation = faceB.y; if (dB.y > 0) { normalX = RotB.b; normalY = RotB.d; } else { normalX = -RotB.b; normalY = -RotB.d; } } // Setup clipping plane data based on the separating axis // Compute the clipping lines and the line segment to be clipped. let frontNormalX: number = normalX; let frontNormalY: number = normalY; let clipPoints: ClipVertex[] = []; let front = null; if (axis === Axis.FACE_A_X) { front = computeFaceAX(posA, posB, RotA, RotB, hA, hB, frontNormalX, frontNormalY, clipPoints); } else if (axis === Axis.FACE_A_Y) { front = computeFaceAY(posA, posB, RotA, RotB, hA, hB, frontNormalX, frontNormalY, clipPoints); } else if (axis === Axis.FACE_B_X) { frontNormalX = -normalX; frontNormalY = -normalY; front = computeFaceBX(posA, posB, RotA, RotB, hA, hB, frontNormalX, frontNormalY, clipPoints); } else if (axis === Axis.FACE_B_Y) { frontNormalX = -normalX; frontNormalY = -normalY; front = computeFaceBY(posA, posB, RotA, RotB, hA, hB, frontNormalX, frontNormalY, clipPoints); } if (front === null) { return 0; } // Now clipPoints contains the clipping points. // Due to roundoff, it is possible that clipping removes all points. let numContacts: number = 0; for (let i = 0; i < 2; i++) { let separation = Vec2.dotXY(frontNormalX, frontNormalY, clipPoints[i].x, clipPoints[i].y) - front; if (separation <= 0) { contacts[numContacts] = new Contact( separation, normalX, normalY, clipPoints[i].x - (separation * frontNormalX), clipPoints[i].y - (separation * frontNormalY), clipPoints[i].fp ); if (axis === Axis.FACE_B_X || axis === Axis.FACE_B_Y) { contacts[numContacts].feature.flip(); } numContacts++; } } return numContacts; }
31f132d240914ebc1c5667a5a71c4da911f5fd88
{ "blob_id": "31f132d240914ebc1c5667a5a71c4da911f5fd88", "branch_name": "refs/heads/master", "committer_date": "2020-02-10T16:44:57", "content_id": "d666b04e245116b6e89367a002f5bf7ad4226bbc", "detected_licenses": [ "MIT" ], "directory_id": "22d42c29625cc8333811cdd4cacf80bad835f384", "extension": "ts", "filename": "Collide.ts", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 238470426, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11436, "license": "MIT", "license_type": "permissive", "path": "/src/Collide.ts", "provenance": "stack-edu-0073.json.gz:41107", "repo_name": "photonstorm/box2d-lite", "revision_date": "2020-02-10T16:44:57", "revision_id": "814bd3964b40e554abcc153717d3858d1e788b36", "snapshot_id": "5f3c0e3f44b27a9d752ffbcacee843db8c1631aa", "src_encoding": "UTF-8", "star_events_count": 23, "url": "https://raw.githubusercontent.com/photonstorm/box2d-lite/814bd3964b40e554abcc153717d3858d1e788b36/src/Collide.ts", "visit_date": "2020-12-29T05:27:27.457448", "added": "2024-11-18T21:54:26.379921+00:00", "created": "2020-02-10T16:44:57", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz" }
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <boost/tokenizer.hpp> extern "C" { #include "var.h" #include "sq_motion.h" } #include "pc_motion.h" static void set_motionbuf(tp_xp_mv_motion motionbuf[MODE2_MOTION_SIZE], std::ifstream &file){ char str[256]; char linebuf[1024]; for(int frame_no=0; frame_no<MODE2_MOTION_SIZE; frame_no++){ file.getline(linebuf, 1024); std::string line_str(linebuf); std::istringstream sstrm(line_str); sstrm.getline(str,10,','); motionbuf[frame_no].time = std::atoi(str); //キータイム for(int joint_no=0;joint_no<29;joint_no++){ sstrm.getline(str,10,','); motionbuf[frame_no].d[joint_no] = std::atoi(str); } for(int next=0;next<3;next++){ sstrm.getline(str,10,','); motionbuf[frame_no].cntr[next] = std::atoi(str); //次のページとオプション } } } void load_pc_motion(const char *dirpath) { std::vector<boost::filesystem::path> file_vec; boost::filesystem::path dir(dirpath); boost::filesystem::directory_iterator end; for(int i=0; i < MODE2_MOTION_NUM; i++){ for(int m=0; m < MODE2_MOTION_SIZE; m++){ xp_mv_motionbuf_var[i][m].time = 0; for(int joint_no=0; joint_no < 29; joint_no++){ xp_mv_motionbuf_var[i][m].d[joint_no] = 0; } for(int next=0; next < 3; next++){ xp_mv_motionbuf_var[i][m].cntr[next] = 0; } } } if ( boost::filesystem::exists(dir)) { std::copy(boost::filesystem::directory_iterator(dir), boost::filesystem::directory_iterator(), std::back_inserter(file_vec)); for(int i = 0; i < (int)file_vec.size(); i ++) { boost::filesystem::path &p = file_vec[i]; if (boost::filesystem::is_directory(p)) { //ディレクトリは無視 } else { std::string fleaf = p.filename().string(); std::string ext = p.extension().string(); int motion_no = 0; sscanf(fleaf.substr(0, 3).c_str(), "%d", &motion_no); std::cout << fleaf << ": No." << motion_no << std::endl; std::ifstream ifs(p.string().c_str()); if(ext == ".txt") set_motionbuf(xp_mv_motionbuf[motion_no], ifs); else if(ext == ".vm") set_motionbuf(xp_mv_motionbuf_var[motion_no], ifs); } } } else { std::cerr << "dir not found" << std::endl; } }
e3de6da758b85b1cd5fe26dd6e915522f927d5b9
{ "blob_id": "e3de6da758b85b1cd5fe26dd6e915522f927d5b9", "branch_name": "refs/heads/kinetic-devel", "committer_date": "2020-04-04T04:42:08", "content_id": "de406932f3db946737c1537597dc2ac00e560ed6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "09fb16e239df21be01542b2072bab28e3d51ec35", "extension": "cpp", "filename": "pc_motion.cpp", "fork_events_count": 2, "gha_created_at": "2019-09-11T04:01:55", "gha_event_created_at": "2020-09-02T14:18:15", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 207719899, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2279, "license": "Apache-2.0", "license_type": "permissive", "path": "/hajime_walk_ros/src/pc_motion.cpp", "provenance": "stack-edu-0004.json.gz:634035", "repo_name": "citbrains/opr_ros", "revision_date": "2020-04-04T04:42:08", "revision_id": "b25d14e710d07a9283f57c8da454d4a3a424bac2", "snapshot_id": "6b1ba0f40878bc5d2804fb2aba9634790013ad15", "src_encoding": "SHIFT_JIS", "star_events_count": 4, "url": "https://raw.githubusercontent.com/citbrains/opr_ros/b25d14e710d07a9283f57c8da454d4a3a424bac2/hajime_walk_ros/src/pc_motion.cpp", "visit_date": "2022-12-12T13:24:01.833608", "added": "2024-11-18T22:40:54.595335+00:00", "created": "2020-04-04T04:42:08", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
#!/usr/bin/env python from django.db import models from django.utils.translation import ugettext_lazy as _ from panda.models.dataset import Dataset from panda.models.user_proxy import UserProxy class SearchLog(models.Model): """ A log of a user search. """ user = models.ForeignKey(UserProxy, related_name='search_logs', help_text=_('The user who executed the search.'), verbose_name=_('user')) dataset = models.ForeignKey(Dataset, related_name='searches', null=True, default=None, help_text=_('The data set searched, or null if all were searched.'), verbose_name=_('dataset')) query = models.CharField(_('query'), max_length=4096, help_text=_('The search query that was executed')) when = models.DateTimeField(_('when'), auto_now=True, help_text=_('The date and time this search was logged.')) class Meta: app_label = 'panda' verbose_name = _('SearchLog') verbose_name_plural = _('SearchLogs') def __unicode__(self): if self.dataset: return _('%(user)s searched %(dataset)s for %(query)s') \ % {'user': self.user, 'dataset': self.dataset, 'query': self.query} else: return _('%(user)s searched for %(query)s') \ % {'user': self.user, 'query': self.query}
f14e87de7219d7c95f08a0e5bc1b1d2d78804a7d
{ "blob_id": "f14e87de7219d7c95f08a0e5bc1b1d2d78804a7d", "branch_name": "refs/heads/master", "committer_date": "2015-03-18T16:35:51", "content_id": "2d87891b907991ab5b67d1fc433c25c3e7f7920a", "detected_licenses": [ "MIT" ], "directory_id": "cb7dfc1f8933d266ab1bfc4ddd873815ca8f1ab9", "extension": "py", "filename": "search_log.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 28458507, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license": "MIT", "license_type": "permissive", "path": "/panda/models/search_log.py", "provenance": "stack-edu-0065.json.gz:171637", "repo_name": "zstumgoren/panda", "revision_date": "2015-03-18T16:35:51", "revision_id": "36f96fd7f02aad2cefb7928bdb5bee4c12d5009f", "snapshot_id": "fe4c3f01444ac7e0e2a240cec80db10f4784b78a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zstumgoren/panda/36f96fd7f02aad2cefb7928bdb5bee4c12d5009f/panda/models/search_log.py", "visit_date": "2020-12-28T22:12:32.751146", "added": "2024-11-19T01:44:06.322616+00:00", "created": "2015-03-18T16:35:51", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz" }
# History - v2.1.3 March 7, 2013 - Repackaged - Dependency upgrades - `html2coffeekup` from 1.4.x to ~1.4.0 - `coffee-script` from 1.3.x to ~1.4.0 - v2.1.2 August 10, 2012 - Re-added markdown files to npm distribution as they are required for the npm website - v2.1.1 July 17, 2012 - Split into its own plugin - v2.0.2 July 8, 2012 - Fixed HTML to CoffeeKup (bug introduced in v2.0.1) - Added better tests - v2.0.1 July 8, 2012 - Cleaned code a bit - Added support for null extensions for CoffeeScript files - v1.0.0 April 14, 2012 - Updated for DocPad v5.0 - Updated to CoffeeScript 1.3.x
34cea6e083525cc7a361254b91109540f1bd193b
{ "blob_id": "34cea6e083525cc7a361254b91109540f1bd193b", "branch_name": "refs/heads/master", "committer_date": "2015-03-05T05:26:30", "content_id": "ce2fd93bb6925e353c30711e8ae95441ec3a5438", "detected_licenses": [ "MIT" ], "directory_id": "6045c298240b2c885e42042b50a1c91b68dfc3fd", "extension": "md", "filename": "HISTORY.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": 612, "license": "MIT", "license_type": "permissive", "path": "/HISTORY.md", "provenance": "stack-edu-markdown-0002.json.gz:285845", "repo_name": "docpad-archive/docpad-plugin-html2coffee", "revision_date": "2015-03-05T05:26:30", "revision_id": "3d073f633d98807114cf6d64ef7a2474c7724349", "snapshot_id": "45aca6a51286774aec9715565828364a5f4a9526", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/docpad-archive/docpad-plugin-html2coffee/3d073f633d98807114cf6d64ef7a2474c7724349/HISTORY.md", "visit_date": "2021-05-28T20:04:28.437519", "added": "2024-11-19T01:02:54.510255+00:00", "created": "2015-03-05T05:26:30", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
/* * Copyright 2014 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.rendering.nui.layers.ingame.inventory; import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.logic.inventory.InventoryUtils; import org.terasology.math.Rect2i; import org.terasology.math.Vector2i; import org.terasology.rendering.nui.Canvas; import org.terasology.rendering.nui.CoreWidget; import org.terasology.rendering.nui.LayoutConfig; import org.terasology.rendering.nui.UIWidget; import org.terasology.rendering.nui.databinding.Binding; import org.terasology.rendering.nui.databinding.DefaultBinding; import org.terasology.rendering.nui.databinding.ReadOnlyBinding; import java.util.Iterator; import java.util.List; /** * @author Immortius */ public class InventoryGrid extends CoreWidget { @LayoutConfig private int maxHorizontalCells = 10; @LayoutConfig private Binding<Integer> cellOffset = new DefaultBinding<>(0); @LayoutConfig private Binding<Integer> maxCellCount = new DefaultBinding<>(Integer.MAX_VALUE); private List<InventoryCell> cells = Lists.newArrayList(); private Binding<EntityRef> targetEntity = new DefaultBinding<>(EntityRef.NULL); @Override public void update(float delta) { super.update(delta); int numSlots = getNumSlots(); // allow the UI to grow or shrink the cell count if the inventory changes size if (numSlots < cells.size()) { for (int i = cells.size(); i > numSlots && i > 0; --i) { cells.remove(i - 1); } } else if (numSlots > cells.size()) { for (int i = cells.size(); i < numSlots && i < getMaxCellCount(); ++i) { InventoryCell cell = new InventoryCell(); cell.bindTargetInventory(new ReadOnlyBinding<EntityRef>() { @Override public EntityRef get() { return getTargetEntity(); } }); cell.bindTargetSlot(new SlotBinding(i)); cells.add(cell); } } } @Override public void onDraw(Canvas canvas) { int numSlots = getNumSlots(); if (numSlots != 0 && !cells.isEmpty()) { Vector2i cellSize = canvas.calculatePreferredSize(cells.get(0)); int horizontalCells = Math.min(maxHorizontalCells, canvas.size().getX() / cellSize.getX()); for (int i = 0; i < numSlots && i < cells.size(); ++i) { int horizPos = i % horizontalCells; int vertPos = i / horizontalCells; canvas.drawWidget(cells.get(i), Rect2i.createFromMinAndSize(horizPos * cellSize.x, vertPos * cellSize.y, cellSize.x, cellSize.y)); } } } @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) { int numSlots = getNumSlots(); if (numSlots != 0 && !cells.isEmpty()) { Vector2i cellSize = canvas.calculatePreferredSize(cells.get(0)); int horizontalCells = Math.min(Math.min(maxHorizontalCells, numSlots), sizeHint.getX() / cellSize.getX()); int verticalCells = ((numSlots - 1) / horizontalCells) + 1; return new Vector2i(horizontalCells * cellSize.x, verticalCells * cellSize.y); } return Vector2i.zero(); } @Override public Iterator<UIWidget> iterator() { return Iterators.transform(cells.iterator(), new Function<UIWidget, UIWidget>() { @Override public UIWidget apply(UIWidget input) { return input; } }); } public int getMaxHorizontalCells() { return maxHorizontalCells; } public void setMaxHorizontalCells(int maxHorizontalCells) { this.maxHorizontalCells = maxHorizontalCells; } public void bindTargetEntity(Binding<EntityRef> binding) { targetEntity = binding; } public EntityRef getTargetEntity() { return targetEntity.get(); } /** * * @deprecated Use bindTargetEntity to assign a read only binding that is a getter */ @Deprecated public void setTargetEntity(EntityRef val) { targetEntity.set(val); } public void bindCellOffset(Binding<Integer> binding) { cellOffset = binding; } public int getCellOffset() { return cellOffset.get(); } public void setCellOffset(int val) { cellOffset.set(val); } public void bindMaxCellCount(Binding<Integer> binding) { maxCellCount = binding; } public int getMaxCellCount() { return maxCellCount.get(); } public void setMaxCellCount(int val) { maxCellCount.set(val); } public int getNumSlots() { return Math.min(InventoryUtils.getSlotCount(getTargetEntity()) - getCellOffset(), getMaxCellCount()); } private final class SlotBinding extends ReadOnlyBinding<Integer> { private int slot; private SlotBinding(int slot) { this.slot = slot; } @Override public Integer get() { return getCellOffset() + slot; } } }
45d04563ce2504a644d5527bad31a54cff7f0222
{ "blob_id": "45d04563ce2504a644d5527bad31a54cff7f0222", "branch_name": "refs/heads/develop", "committer_date": "2015-06-28T05:37:53", "content_id": "2756f969c8a5f17169d1ce8c1508a34825b25847", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8a05c5867217d74f8206cce053a547ff1e43f34c", "extension": "java", "filename": "InventoryGrid.java", "fork_events_count": 0, "gha_created_at": "2012-01-29T10:25:45", "gha_event_created_at": "2015-05-31T10:10:35", "gha_language": "Java", "gha_license_id": null, "github_id": 3296544, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5876, "license": "Apache-2.0", "license_type": "permissive", "path": "/engine/src/main/java/org/terasology/rendering/nui/layers/ingame/inventory/InventoryGrid.java", "provenance": "stack-edu-0030.json.gz:388724", "repo_name": "immortius/Terasology", "revision_date": "2015-06-28T05:33:05", "revision_id": "225c131473f003c7c625e231f8e8c38dcd75fd1c", "snapshot_id": "b87a8de43c8085bda3ba658071b5dbf4cf886518", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/immortius/Terasology/225c131473f003c7c625e231f8e8c38dcd75fd1c/engine/src/main/java/org/terasology/rendering/nui/layers/ingame/inventory/InventoryGrid.java", "visit_date": "2021-01-18T10:20:55.323799", "added": "2024-11-18T23:43:28.129569+00:00", "created": "2015-06-28T05:33:05", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz" }
<?php /** * @package jhframe * @license http://opensource.org/licenses/MIT The MIT License * @author Ryan Kelley * @copyright 2011-2015 Jakked Hardcore Gym */ namespace rakelley\jhframe\traits\model; /** * Model trait for inserting rows without auto key */ trait InsertAll { /** * Standard method for inserting a new row with values defined for all * columns. * The keys of $values are assumed to at least contain the full set of * columns. * Extraneous keys are safely ignored. * * @param array $values Key/value pairs for all columns * @return void */ protected function insertAll(array $values) { $this->db->newQuery('insert', $this->table, ['columns' => $this->columns]) ->makeStatement() ->Bind($this->columns, $values) ->Execute(); } }
58ad9453280b2ef04d401495424a09bd99a9c835
{ "blob_id": "58ad9453280b2ef04d401495424a09bd99a9c835", "branch_name": "refs/heads/master", "committer_date": "2015-06-09T16:57:54", "content_id": "0eddad116b9b9b3c7f00e369af9077461c8b5a76", "detected_licenses": [ "MIT" ], "directory_id": "98adb2f4bd7690e0b6201fd97cf4402f6e40ea8c", "extension": "php", "filename": "InsertAll.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 36441557, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 901, "license": "MIT", "license_type": "permissive", "path": "/src/traits/model/InsertAll.php", "provenance": "stack-edu-0050.json.gz:606361", "repo_name": "rakelley/jhframe", "revision_date": "2015-06-09T16:57:54", "revision_id": "a12f240ef6f487d1e2f685cfdb38f3f09efbbe80", "snapshot_id": "08b1a773bd7afb15681d50339038c8aebc87a1ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rakelley/jhframe/a12f240ef6f487d1e2f685cfdb38f3f09efbbe80/src/traits/model/InsertAll.php", "visit_date": "2021-01-10T04:53:58.126314", "added": "2024-11-18T23:55:34.376706+00:00", "created": "2015-06-09T16:57:54", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
package ini import ( "bufio" "io/ioutil" "os" "strings" "testing" ) var ( dict Dict err error ) func init() { dict, err = Load("example.ini") } func TestLoad(t *testing.T) { if err != nil { t.Error("Example: load error:", err) } } func TestLoadFileWithSpaces(t *testing.T) { if err := ioutil.WriteFile("testLoadFileWithSpaces.ini", []byte(" "), 0777); err != nil { t.Error("Unable to write test file") } defer os.Remove("testLoadFileWithSpaces.ini") if _, err := Load("testLoadFileWithSpaces.ini"); err != nil { t.Error("Load: Couldn't load ini file with line consisting only of spaces.") } } func TestWrite(t *testing.T) { d, err := Load("empty.ini") if err != nil { t.Error("Example: load error:", err) } d.SetString("", "key", "value") tempFile, err := ioutil.TempFile("", "") if err != nil { t.Error("Write: Couldn't create temp file.", err) } err = Write(tempFile.Name(), &d) if err != nil { t.Error("Write: Couldn't write to temp config file.", err) } contents, err := ioutil.ReadFile(tempFile.Name()) if err != nil { t.Error("Write: Couldn't read from the temp config file.", err) } if string(contents) != "key = value\n\n" { t.Error("Write: Contents of the config file doesn't match the expected.") } } func TestGetBool(t *testing.T) { b, found := dict.GetBool("pizza", "ham") if !found || !b { t.Error("Example: parse error for key ham of section pizza.") } b, found = dict.GetBool("pizza", "mushrooms") if !found || !b { t.Error("Example: parse error for key mushrooms of section pizza.") } b, found = dict.GetBool("pizza", "capres") if !found || b { t.Error("Example: parse error for key capres of section pizza.") } b, found = dict.GetBool("pizza", "cheese") if !found || b { t.Error("Example: parse error for key cheese of section pizza.") } } func TestGetStringIntAndDouble(t *testing.T) { str, found := dict.GetString("wine", "grape") if !found || str != "Cabernet Sauvignon" { t.Error("Example: parse error for key grape of section wine.") } i, found := dict.GetInt("wine", "year") if !found || i != 1989 { t.Error("Example: parse error for key year of section wine.") } str, found = dict.GetString("wine", "country") if !found || str != "Spain" { t.Error("Example: parse error for key grape of section wine.") } d, found := dict.GetDouble("wine", "alcohol") if !found || d != 12.5 { t.Error("Example: parse error for key grape of section wine.") } } func TestSetBoolAndStringAndIntAndDouble(t *testing.T) { dict.SetBool("pizza", "ham", false) b, found := dict.GetBool("pizza", "ham") if !found || b { t.Error("Example: bool set error for key ham of section pizza.") } dict.SetString("pizza", "ham", "no") n, found := dict.GetString("pizza", "ham") if !found || n != "no" { t.Error("Example: string set error for key ham of section pizza.") } dict.SetInt("wine", "year", 1978) i, found := dict.GetInt("wine", "year") if !found || i != 1978 { t.Error("Example: int set error for key year of section wine.") } dict.SetDouble("wine", "not-exists", 5.6) d, found := dict.GetDouble("wine", "not-exists") if !found || d != 5.6 { t.Error("Example: float set error for not existing key for wine.") } } func TestDelete(t *testing.T) { d, err := Load("empty.ini") if err != nil { t.Error("Example: load error:", err) } d.SetString("pizza", "ham", "yes") d.Delete("pizza", "ham") _, found := d.GetString("pizza", "ham") if found { t.Error("Example: delete error for key ham of section pizza.") } if len(d.GetSections()) > 1 { t.Error("Only a single section should exist after deletion.") } } func TestGetNotExist(t *testing.T) { _, found := dict.GetString("not", "exist") if found { t.Error("There is no key exist of section not.") } } func TestGetSections(t *testing.T) { sections := dict.GetSections() if len(sections) != 3 { t.Error("The number of sections is wrong:", len(sections)) } for _, section := range sections { if section != "" && section != "pizza" && section != "wine" { t.Errorf("Section '%s' should not be exist.", section) } } } func TestString(t *testing.T) { d, err := Load("empty.ini") if err != nil { t.Error("Example: load error:", err) } d.SetBool("", "key1", true) d.SetString("section1", "key1", "value2") d.SetInt("section1", "key2", 5) d.SetDouble("section1", "key3", 1.3) d.SetDouble("section2", "key1", 5.0) reader := strings.NewReader(d.String()) d2, err := LoadReader(bufio.NewReader(reader)) if err != nil { t.Error("Example: load error:", err) } b, found := d2.GetBool("", "key1") if !found || !b { t.Errorf("Stringify failed for key1") } s, found := d2.GetString("section1", "key1") if !found || s != "value2" { t.Error("Stringify failed for section1, key1") } i, found := d2.GetInt("section1", "key2") if !found || i != 5 { t.Error("Stringify failed for section1, key2") } db, found := d2.GetDouble("section1", "key3") if !found || db != 1.3 { t.Error("Stringify failed for section1, key3") } db, found = d2.GetDouble("section2", "key1") if !found || db != 5.0 { t.Error("Stringify failed for section2, key1") } }
29d90738f1b8268daa66ee856280ccb7b68b897d
{ "blob_id": "29d90738f1b8268daa66ee856280ccb7b68b897d", "branch_name": "refs/heads/master", "committer_date": "2019-04-26T14:36:38", "content_id": "4a64eb3fc9869623f581b6b7d221189c4b6e27c9", "detected_licenses": [ "MIT" ], "directory_id": "155a3c4b0233feffa39fef88c0682ebad12434ac", "extension": "go", "filename": "ini_test.go", "fork_events_count": 0, "gha_created_at": "2019-04-26T14:29:07", "gha_event_created_at": "2019-04-26T14:36:39", "gha_language": "Go", "gha_license_id": "MIT", "github_id": 183643159, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 5156, "license": "MIT", "license_type": "permissive", "path": "/ini_test.go", "provenance": "stack-edu-0018.json.gz:239928", "repo_name": "Nanitor/goini", "revision_date": "2019-04-26T14:36:38", "revision_id": "a89f3556031d611cf4b3ca65fad5c72cc5a3e1fc", "snapshot_id": "af2d68eb3277e2e680b928089fdb6b1cf8502357", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Nanitor/goini/a89f3556031d611cf4b3ca65fad5c72cc5a3e1fc/ini_test.go", "visit_date": "2020-05-17T09:48:52.975596", "added": "2024-11-18T20:43:25.298543+00:00", "created": "2019-04-26T14:36:38", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
package me.highgo.cart.domain; import com.jyall.exception.ErrorCode; import com.jyall.exception.JyBizException; import com.wordnik.swagger.annotations.ApiModel; import com.wordnik.swagger.annotations.ApiModelProperty; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * Cart.java * * @Description : 购物车 * @Author huangzhiwei * @DATE 2016/5/12 */ @ApiModel(value = "Cart",description = "购物车信息") public class Cart implements Serializable{ @ApiModelProperty(value = "购物项的最大容量") private static final Integer MAX_SIZE = 70 ; @Id @ApiModelProperty(value = "唯一ID",notes = "购物车的id,id属性是给MongoDB使用的,所以使用@Id注解") private String id; @ApiModelProperty(value = "用户唯一标识") private String uid; @ApiModelProperty(value = "购物车商品数量") private volatile int size; @ApiModelProperty(value = "购物车选中有效商品的数量") private volatile int selectedValidItemSize; @ApiModelProperty(value = "购物车中有效商品是否全部勾选") private boolean allSelected; @ApiModelProperty(value = "购物车中结算价格") @Transient private BigDecimal settlementPrice; @ApiModelProperty(value = "购物车中节省价") @Transient private BigDecimal savePrice; @ApiModelProperty(value = "购物项List") private List<Item> itemList = new ArrayList(); public static Integer getMaxSize() { return MAX_SIZE; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getSelectedValidItemSize() { return selectedValidItemSize; } public void setSelectedValidItemSize(int selectedValidItemSize) { this.selectedValidItemSize = selectedValidItemSize; } public boolean isAllSelected() { return allSelected; } public void setAllSelected(boolean allSelected) { this.allSelected = allSelected; } public BigDecimal getSettlementPrice() { return settlementPrice; } public void setSettlementPrice(BigDecimal settlementPrice) { this.settlementPrice = settlementPrice; } public BigDecimal getSavePrice() { return savePrice; } public void setSavePrice(BigDecimal savePrice) { this.savePrice = savePrice; } public List<Item> getItemList() { return itemList; } public void setItemList(List<Item> itemList) { this.itemList = itemList; } /** * 添加购物项 * @param item */ public void addItem(Item item) throws JyBizException { if (item == null) { return; } if (itemList.size() >= MAX_SIZE) { throw new JyBizException(ErrorCode.BIZ_ERROR_SHOP_CART_PURCHASELIMIT.value(),ErrorCode.BIZ_ERROR_SHOP_CART_PURCHASELIMIT.msg()); } final int index = indexOf(item); if (index >= 0) {//商品已经存在于购物车 final Item removeItem = itemList.remove(index); int totalCount = removeItem.getCount() + item.getCount(); if (totalCount > 199) totalCount = 199; item.setCount(totalCount); if (removeItem.isSelected() || item.isSelected()) {//有任何一个选中状态,那么就默认选中 item.setSelected(true); } } item.setActiveTime(System.currentTimeMillis()); itemList.add(item); updateCartSizeAndAllSelected();//更新购物车大小 } /** * 删除购物项 * @param item */ public void removeItem(Item item){ if (item == null) { return; } final int index = indexOf(item); if (index >= 0) //商品存在于购物车 itemList.remove(index); updateCartSizeAndAllSelected();//更新购物车大小 } /** * 修改购物项 勾选状态和数量 * @param item */ public void updateItem(Item item){ if (item == null) { return; } final int index = indexOf(item); if (index >= 0) {//商品存在于购物车 Item cartItem = itemList.get(index); cartItem.setSelected(item.isSelected()); cartItem.setCount(item.getCount()); itemList.set(index,cartItem); } updateCartSizeAndAllSelected();//更新购物车大小 } /** * 更新购物车的数量,结算商品数量,是否全选的状态 */ public void updateCartSizeAndAllSelected() { int count = 0; //购物车商品的总量 int selectedValidCount = 0; //结算有效商品的数量 int validCount = 0; //有效商品数量 boolean flag = true; //全选状态 if (itemList.size()>0){ for (Item item : itemList){ count += item.getCount(); if(item.isValid()){ //商品 validCount = validCount + item.getCount(); if (item.isSelected()){ selectedValidCount = selectedValidCount + item.getCount(); } } } if (selectedValidCount != validCount || validCount==0) //避免购物车全失效状态 flag = false; }else { //购物车无商品 flag = false; } size = count; selectedValidItemSize = selectedValidCount; allSelected = flag; } /** * 查询购物项的位序,不存在返回-1 * @param item * @return */ public int indexOf(Item item){ if (item == null) { for (int i = 0; i < itemList.size(); i++) if (itemList.get(i)==null) return i; } else { for (int i = 0; i < itemList.size(); i++) { if (item.equals(itemList.get(i))) { return i; } } } return -1; } }
d8a16a1d4442a831e044df6c021d0272643b9339
{ "blob_id": "d8a16a1d4442a831e044df6c021d0272643b9339", "branch_name": "refs/heads/master", "committer_date": "2016-05-12T09:38:59", "content_id": "942a329507a8e6473f76b2f7759d391221ed595a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8c5249a92327d80966bb523f8221821fc55347f2", "extension": "java", "filename": "Cart.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58617419, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6495, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/me/highgo/cart/domain/Cart.java", "provenance": "stack-edu-0031.json.gz:588241", "repo_name": "itgeeker/fd-highgo-cart", "revision_date": "2016-05-12T09:38:59", "revision_id": "20732b47092353fdef07a44c2b364c233fc4ab9b", "snapshot_id": "2ee0f7dc5c9b60d3e6f91bbb48fad314d5020b9e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/itgeeker/fd-highgo-cart/20732b47092353fdef07a44c2b364c233fc4ab9b/src/main/java/me/highgo/cart/domain/Cart.java", "visit_date": "2021-01-01T03:52:10.924209", "added": "2024-11-19T00:25:20.617183+00:00", "created": "2016-05-12T09:38:59", "int_score": 3, "score": 2.578125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
/** * Filename: "connect.cpp" * * Description: This is the main function which instantiates a connect node * * Author: Abhishek Shrivastava <[email protected]> **/ #include "../../includes/nodeClient.h" #include "../../includes/logger.h" using namespace std; string base_loc; int main(int argc, const char *argv[]) { base_loc = "~/connect"; // eg. ./connect my_ip my_port friend_ip friend_port if (argc < 3) { cout << "Usage: " << argv[0] << " my_ip my_port [friend_ip] [friend_port]" << endl; return 1; } string c_ip, f_ip; int c_port, f_port; c_ip = argv[1]; c_port = stoi(argv[2]); if (argc == 5) { f_ip = argv[3]; f_port = stoi(argv[4]); } else { f_ip = ""; f_port = 0; } nodeClient connect_node(c_ip, c_port, f_ip, f_port); // navigate to the base directory chdir(base_loc.c_str()); // start listening thread thread t(&nodeClient::startListen, connect_node); t.detach(); // start stablization thread // thread s_thread(&nodeClient::stabilize, connect_node); // s_thread.detach(); string line; while (getline(cin, line)) { if (line == "") continue; vector<string> tokens; // tokenize on '"' and then sanitize as required tokenize(line, tokens, "\""); // because switch cannot use string sanitize(tokens[0], ' '); int command = interpret_command(tokens[0]); switch(command) { case GET: { if (tokens.size() <= 1) { cout << "FAILURE: Invalid Parameters" << endl; break; } // if we are downloading after a search if (tokens[0][3] == '[') { connect_node.blackbox -> record("Get command for: " + tokens[0] + " outfile " + tokens[1]); for (auto k : tokens) cout << k << endl; if (connect_node.haveSearchResults) { string hit_n = tokens[0]; string outfile = tokens[1]; sanitize(hit_n, '['); sanitize(hit_n, ']'); sanitize(hit_n, 'p'); sanitize(hit_n, 'u'); sanitize(hit_n, 's'); sanitize(hit_n, 'h'); int hit_no = stoi(hit_n); connect_node.downloadFile(hit_no, outfile); } else cout << "No search results exist. Try again." << endl; } else { if (tokens.size() != 2) { cout << "FAILURE: Invalid Parameters" << endl; break; } string filepath = tokens[1]; sanitize(filepath, '"'); sanitize(filepath, '\\'); connect_node.blackbox -> record("Get command on path " + filepath); connect_node.downloadFile(filepath); } } break; case SHARE: { if (tokens.size() != 2) { cout << "Failure: Invalid Parameters" << endl; break; } string file_share_path = tokens[1]; sanitize(file_share_path, '\\'); sanitize(file_share_path, '"'); connect_node.blackbox -> record("Registering file: " + file_share_path + " on network"); connect_node.registerFile(file_share_path); } break; case DEL: { if (tokens.size() != 2) { cout << "Failure: Invalid Parameters" << endl; break; } string file_share_path = tokens[1]; sanitize(file_share_path, '\\'); sanitize(file_share_path, '"'); connect_node.blackbox -> record("Deregistering file: " + file_share_path + " on network"); connect_node.deregisterFile(file_share_path); } break; case SEARCH: { if (tokens.size() != 2) { cout << "FAILURE: Invalid Parameters" << endl; break; } string file_name = tokens[1]; sanitize(file_name, '\\'); sanitize(file_name, '"'); connect_node.blackbox -> record("Searching for file: " + file_name + " on server"); connect_node.searchFile(file_name); } break; case EXIT: { cout << "EXIT" << endl; } break; case SHOW: { cout << "SHOW" << endl; // TODO SHOT FT AND FILE MAP auto ft = connect_node.my_fingertable; for (auto i = ft.begin(); i != ft.end(); i++) { ft_struct* curr = i -> second; cout << "START: " << i -> first << " "; cout << "INTERVAL: " << curr->interval.first << "-" << curr->interval.second << " "; if (curr -> s_d != NULL) cout << "ID: " << curr -> s_d -> node_id << " " << curr -> s_d -> port; cout << endl; } } break; case STABLIZE: { cout << "STABLIZE" << endl; } break; default: cout << "Unknown Command" << endl; } } cout << "Bye Bye" << endl; return 0; }
73bbe4cc26869c93b624d07f1933c940392e9212
{ "blob_id": "73bbe4cc26869c93b624d07f1933c940392e9212", "branch_name": "refs/heads/master", "committer_date": "2017-11-01T17:34:03", "content_id": "e8675b3aaa2a82e20e6e885a540f126188bf4190", "detected_licenses": [ "MIT" ], "directory_id": "6665224054b3e1a3b8e1b0f036743cf7028ce337", "extension": "cpp", "filename": "connect.cpp", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 107798701, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5201, "license": "MIT", "license_type": "permissive", "path": "/src/nodeClient/connect.cpp", "provenance": "stack-edu-0007.json.gz:410439", "repo_name": "abstatic/connect", "revision_date": "2017-11-01T17:34:03", "revision_id": "a6f8415fefca2e1c4fc4eae6dfeb8e583cca211d", "snapshot_id": "3464623bc41fa7308fec96b6382fb0a2b69a2164", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/abstatic/connect/a6f8415fefca2e1c4fc4eae6dfeb8e583cca211d/src/nodeClient/connect.cpp", "visit_date": "2021-08-12T07:48:01.014692", "added": "2024-11-18T21:15:49.262849+00:00", "created": "2017-11-01T17:34:03", "int_score": 3, "score": 2.90625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz" }
using System; using System.Collections.Generic; using System.Text; namespace DataAccessHelper { /// <summary> /// 数据库可变映射 /// </summary> public interface IMappingMutable { /// <summary> /// 更换数据库 /// </summary> /// <param name="connectString">新的数据库连接字符串</param> void ChangeDataBase(string connString); /// <summary> /// 更换数据库, 数据表映射使用传入的映射规则 /// </summary> /// <param name="connStr">新的数据库连接字符串</param> /// <param name="rules">映射规则</param> /// <exception cref="ArgumentException">type类型不支持</exception> void ChangeDataBase(string connStr, List<TableMappingRule> rules); /// <summary> /// 根据条件改变多个传入类型的映射数据表(此操作会导致当前操作的context释放掉,调用前需确保context的内容已保存) /// </summary> /// <param name="rules">映射规则</param> /// <exception cref="ArgumentException">type类型不支持</exception> /// <returns>改变后的数据表映射</returns> List<TableAccessMapping> ChangeMappingTables(List<TableMappingRule> rules); /// <summary> /// 根据条件改变传入类型的映射数据表(此操作会导致当前操作的context释放掉,调用前需确保context的内容已保存) /// </summary> /// <typeparam name="T">条件类型</typeparam> /// <param name="type">要改变映射的实体类型</param> /// <param name="condition">改变条件</param> /// <exception cref="ArgumentException">type类型不支持</exception> /// <returns>改变后的数据表映射</returns> TableAccessMapping ChangeMappingTable(Type type, ITableMappable mapper, object condition); /// <summary> /// 获取所有实体类的数据表映射结构体 /// </summary> /// <returns>映射关系集合</returns> List<TableAccessMapping> GetTableNames(); /// <summary> /// 获取指定实体类的数据表映射结构体 /// </summary> /// <param name="mappingType">实体类性</param> /// <returns>传入实体类的映射关系</returns> TableAccessMapping GetTableName(Type mappingType); } }
a61fc7c4b150759214313f08bfa572bb7cee2b39
{ "blob_id": "a61fc7c4b150759214313f08bfa572bb7cee2b39", "branch_name": "refs/heads/master", "committer_date": "2022-06-17T09:35:32", "content_id": "ca00f8dc4806c66203b269af969d1f6752b71e8a", "detected_licenses": [ "Unlicense" ], "directory_id": "c419c929b935fbe2f77a653474f01e5f1a7af4a1", "extension": "cs", "filename": "IMappingMutable.cs", "fork_events_count": 6, "gha_created_at": "2019-10-08T04:25:13", "gha_event_created_at": "2022-06-17T09:35:32", "gha_language": "C#", "gha_license_id": null, "github_id": 213548439, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2480, "license": "Unlicense", "license_type": "permissive", "path": "/DataAccessHelper/IMappingMutable.cs", "provenance": "stack-edu-0010.json.gz:160329", "repo_name": "YinRunhao/DataAccessHelper", "revision_date": "2022-06-17T09:35:32", "revision_id": "20fce541908632058ec26fa818adaa2fb3b90587", "snapshot_id": "62ac8a2f5354d68b04ae5e1acaac94a45858f9bd", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/YinRunhao/DataAccessHelper/20fce541908632058ec26fa818adaa2fb3b90587/DataAccessHelper/IMappingMutable.cs", "visit_date": "2022-06-19T19:58:36.496566", "added": "2024-11-19T01:13:10.972481+00:00", "created": "2022-06-17T09:35:32", "int_score": 3, "score": 2.84375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; /** * */ class LogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { //Tabla de logs Schema::create('log', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('package')->unsigned(); $table->bigInteger('user')->unsigned(); $table->bigInteger('event')->unsigned(); $table->bigInteger('previous_event')->unsigned()->nullable(); $table->string('observation',255); $table->timestamps(); $table->softDeletes(); }); // Schema::table('log', function($table) { $table->foreign('package') ->references('id') ->on('package') ->onDelete('cascade') ->onUpdate('cascade'); /* $table->foreign('user') ->references('id') ->on('user') ->onDelete('cascade') ->onUpdate('cascade');*/ $table->foreign('event') ->references('id') ->on('event') ->onDelete('cascade') ->onUpdate('cascade'); $table->foreign('previous_event') ->references('id') ->on('event') ->onDelete('cascade') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('log'); } }
17abb155830569d0dadfdad89977483e6eff6f5d
{ "blob_id": "17abb155830569d0dadfdad89977483e6eff6f5d", "branch_name": "refs/heads/master", "committer_date": "2020-04-01T00:08:01", "content_id": "1396935c1de18a91d4966e8e7a38e0b0b699a481", "detected_licenses": [ "MIT" ], "directory_id": "a12d996126d5b4b8f9dc086d05f8d484f1114b34", "extension": "php", "filename": "2016_08_22_000020_log_table.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 252021380, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1519, "license": "MIT", "license_type": "permissive", "path": "/cacargo/database/migrations/2016_08_22_000020_log_table.php", "provenance": "stack-edu-0053.json.gz:927221", "repo_name": "aquiles099/respaldo", "revision_date": "2020-04-01T00:08:01", "revision_id": "a8460b02e3e72ddf0b7353bacfc473c3f8ac9aee", "snapshot_id": "f883ebb4778d052a203b762bba34dfa15adc742d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aquiles099/respaldo/a8460b02e3e72ddf0b7353bacfc473c3f8ac9aee/cacargo/database/migrations/2016_08_22_000020_log_table.php", "visit_date": "2021-05-19T16:20:16.995505", "added": "2024-11-19T00:19:38.403569+00:00", "created": "2020-04-01T00:08:01", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
/* eslint-env mocha */ require('../../../test-helper.js') const assert = require('assert') const Country = require('./bind-country.js') describe('server/bind-country', () => { describe('before', () => { it('should bind data to req', async () => { const req = {} req.ip = '8.8.8.8' await Country.before(req) assert.strictEqual(req.country.country.iso_code, 'US') }) }) })
0c6186e30e853605899f53ca82935db985d7505f
{ "blob_id": "0c6186e30e853605899f53ca82935db985d7505f", "branch_name": "refs/heads/master", "committer_date": "2020-12-17T21:37:48", "content_id": "e8dd7396e473533dba1dd1dee8561a5de70e7e07", "detected_licenses": [ "MIT" ], "directory_id": "7a052359d3fb2cca99a6447c247fca590a17d158", "extension": "js", "filename": "bind-country.test.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 162846995, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 408, "license": "MIT", "license_type": "permissive", "path": "/src/server/maxmind-geoip/bind-country.test.js", "provenance": "stack-edu-0036.json.gz:528952", "repo_name": "userdashboard/maxmind-geoip", "revision_date": "2020-12-17T21:37:48", "revision_id": "636a74445b9790bddbcca1b357b150e1051adc66", "snapshot_id": "5ccbeb33f030a5eb685dd474afddcdfa3ef1d990", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/userdashboard/maxmind-geoip/636a74445b9790bddbcca1b357b150e1051adc66/src/server/maxmind-geoip/bind-country.test.js", "visit_date": "2021-06-23T23:58:22.043736", "added": "2024-11-18T20:43:16.101122+00:00", "created": "2020-12-17T21:37:48", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use futures::{ channel::oneshot::{channel, Sender}, ready, task::{Context, Poll}, Stream, }; use pin_project::pin_project; use std::{marker::Unpin, pin::Pin}; use crate::future::ConservativeReceiver; /// A stream wrapper returned by StreamExt::return_remainder #[pin_project] pub struct ReturnRemainder<In> { #[pin] inner: Option<In>, send: Option<Sender<In>>, } impl<In> ReturnRemainder<In> { pub(crate) fn new(inner: In) -> (Self, ConservativeReceiver<In>) { let (send, recv) = channel(); ( Self { inner: Some(inner), send: Some(send), }, ConservativeReceiver::new(recv), ) } } impl<In: Stream + Unpin> Stream for ReturnRemainder<In> { type Item = In::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); let maybe_item = match this.inner.as_mut().as_pin_mut() { Some(inner) => ready!(inner.poll_next(cx)), None => return Poll::Ready(None), }; if maybe_item.is_none() { let inner = this .inner .get_mut() .take() .expect("inner was just polled, should be some"); let send = this.send.take().expect("send is None iff inner is None"); // The Receiver will handle errors let _ = send.send(inner); } Poll::Ready(maybe_item) } } #[cfg(test)] mod test { use super::*; use assert_matches::assert_matches; use futures::{ future, stream::{iter, StreamExt}, }; #[tokio::test] async fn success_get_remainder() { let s = iter(1..=10).take_while(|x| future::ready(*x <= 5)); let (s, rest) = ReturnRemainder::new(s); assert_eq!(vec![1, 2, 3, 4, 5], s.collect::<Vec<_>>().await); let rest = rest.await.expect("Failed to get what is left"); assert_eq!( vec![7, 8, 9, 10], rest.into_inner().collect::<Vec<_>>().await ); } #[tokio::test] async fn fail_get_remainder() { let s = iter(1..=10).take_while(|x| future::ready(*x <= 5)); let (s, rest) = ReturnRemainder::new(s); assert_matches!(rest.await, Err(_)); assert_eq!(vec![1, 2, 3, 4, 5], s.collect::<Vec<_>>().await); } }
8f424a801bf6456542e050dd4c6365d03385f3f3
{ "blob_id": "8f424a801bf6456542e050dd4c6365d03385f3f3", "branch_name": "refs/heads/master", "committer_date": "2021-10-12T18:23:32", "content_id": "6acb575a9f11c910ac56eb8fe449366c09f2f7a1", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "242bd48b89c47e7e0512a39cf83dba4d13145eac", "extension": "rs", "filename": "return_remainder.rs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 416464104, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2743, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/shed/futures_ext/src/stream/return_remainder.rs", "provenance": "stack-edu-0068.json.gz:398235", "repo_name": "shra1dhar/rust-shed", "revision_date": "2021-10-12T18:21:41", "revision_id": "a8a41f18807f31cddfb89d77d42b75d710025eed", "snapshot_id": "ab5f7c259a80935e9cb3754c34ef1130d6b14741", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shra1dhar/rust-shed/a8a41f18807f31cddfb89d77d42b75d710025eed/shed/futures_ext/src/stream/return_remainder.rs", "visit_date": "2023-08-15T00:39:25.563655", "added": "2024-11-18T20:55:01.763490+00:00", "created": "2021-10-12T18:21:41", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz" }
const sum = function(a, b) { return a + b; } const sumProxy = new Proxy(sum, { apply: function(target, thisArg, argumentsList) { const args = []; for( let item of argumentsList ){ args.push(item + 2); } console.log(`Calculate sum of: ${argumentsList}`); return target.apply(thisArg, args); } }); console.log(sumProxy(1, 2));
c07dead972c11f351be749159d8c71bfec922dd6
{ "blob_id": "c07dead972c11f351be749159d8c71bfec922dd6", "branch_name": "refs/heads/master", "committer_date": "2018-01-25T13:57:18", "content_id": "d5d52e2313c3915a72db947f65fb6e84c5dcd09b", "detected_licenses": [ "MIT" ], "directory_id": "2a1bb23319409746af2d6795700bfdb67c93a436", "extension": "js", "filename": "05.ProxyFunctionsDecorators.js", "fork_events_count": 2, "gha_created_at": "2017-10-23T09:56:59", "gha_event_created_at": "2017-11-07T17:39:06", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 107963566, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 409, "license": "MIT", "license_type": "permissive", "path": "/examples/00.ES6Features/05.ProxyFunctionsDecorators.js", "provenance": "stack-edu-0040.json.gz:488921", "repo_name": "NickolayLototskiyDevPro/node_advanced", "revision_date": "2018-01-25T13:57:18", "revision_id": "4dcbd7dbeb438584add78693764878db5f0c3ecb", "snapshot_id": "6446184150034728ea6937c21f9c2edb55c06ed4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/NickolayLototskiyDevPro/node_advanced/4dcbd7dbeb438584add78693764878db5f0c3ecb/examples/00.ES6Features/05.ProxyFunctionsDecorators.js", "visit_date": "2021-09-05T08:06:29.126769", "added": "2024-11-19T00:28:00.770754+00:00", "created": "2018-01-25T13:57:18", "int_score": 3, "score": 3.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
window.onload = function() { var counter = 1; var nextTimeout = null; var URL_POLLING_INTERVAL = 100; var URL_CACHE = null; var track = function() { var url = document.location.href; if (url.indexOf("/radio") === -1) return; window.postMessage({ type: "FROM_PAGE", text: counter + ' ' + url }, "*"); counter++; nextTimeout = setTimeout(track, 1000 * 60 * 5); }; var urlPolling = function() { if (URL_CACHE !== document.location.href) { URL_CACHE = document.location.href; counter = 1; if (nextTimeout) clearTimeout(nextTimeout); track(); } setTimeout(urlPolling, URL_POLLING_INTERVAL); } urlPolling(); };
0cc328bf0d98070ceb160ac713d2cdffee1dfa1d
{ "blob_id": "0cc328bf0d98070ceb160ac713d2cdffee1dfa1d", "branch_name": "refs/heads/master", "committer_date": "2016-12-12T18:20:48", "content_id": "c4df5a181a956c05fd1b46d9ebcfd35a21a5304c", "detected_licenses": [ "MIT" ], "directory_id": "e47df8bac983b67ecc877d6ef8a486167b3a382e", "extension": "js", "filename": "tunein.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 70006063, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 642, "license": "MIT", "license_type": "permissive", "path": "/tunein.js", "provenance": "stack-edu-0036.json.gz:500543", "repo_name": "musicreciqp/ChromeClient", "revision_date": "2016-12-12T18:20:48", "revision_id": "bd3ba6d4a8c230e485049f62a84c371518fcf1d0", "snapshot_id": "be339e7c7a2d29c2ee41e255b0fa04549f16e2e0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/musicreciqp/ChromeClient/bd3ba6d4a8c230e485049f62a84c371518fcf1d0/tunein.js", "visit_date": "2021-06-09T04:13:29.210751", "added": "2024-11-19T00:14:30.530395+00:00", "created": "2016-12-12T18:20:48", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
#include <qttasks.h> N::MonitorSize:: MonitorSize (QWidget * parent,Plan * p) : VcfView ( parent, p) { Configure ( ) ; } N::MonitorSize::~MonitorSize(void) { } void N::MonitorSize::Configure(void) { setWindowTitle ( tr("Monitor calibration") ) ; setScene ( Scene ) ; setTransform ( Transform ) ; setMouseTracking ( true ) ; ScreenSize = new VcfScreenSize ( this , NULL , plan ) ; ScreenSize -> Options = &Options ; ScreenSize -> monitor = QImage(":/images/calibration.png") ; ScreenSize -> screen = &screen ; ScreenSize -> font = font() ; scene ( ) -> addItem (ScreenSize) ; ScreenSize -> Attribute () ; if ( plan -> Booleans [ "Desktop" ] ) { } else if ( plan -> Booleans [ "Pad" ] ) { } else if ( plan -> Booleans [ "Phone" ] ) { } ; } bool N::MonitorSize::FocusIn(void) { nKickOut ( IsNull(plan) , false ) ; AssignAction ( Label , windowTitle ( ) ) ; LinkAction ( GoUp , Up ( ) ) ; LinkAction ( GoDown , Down ( ) ) ; LinkAction ( Previous , Left ( ) ) ; LinkAction ( Next , Right ( ) ) ; LinkAction ( GoEnd , Finalize ( ) ) ; return true ; } bool N::MonitorSize::FocusOut(void) { return true ; } bool N::MonitorSize::Relocation(void) { QWidget * vp = viewport() ; if (IsNull(vp)) return false ; QSize A = available(size()) ; QSizeF C = centimeter (A) ; QRectF V(0,0,C.width(),C.height()) ; PerfectView () ; ScreenSize->setPos(Origin) ; ScreenSize->setRect(V) ; ScreenSize->Park(A) ; return false ; } void N::MonitorSize::Left(void) { screen.WidthLength-- ; QSize A = available(size()) ; QSizeF C = centimeter (A) ; QRectF V(0,0,C.width(),C.height()) ; PerfectView ( ) ; ScreenSize -> setPos ( Origin ) ; ScreenSize -> setRect ( V ) ; ScreenSize -> Park ( A ) ; ScreenSize -> update ( ) ; UpdateScreen ( ) ; } void N::MonitorSize::Right(void) { screen.WidthLength++ ; QSize A = available(size()) ; QSizeF C = centimeter (A) ; QRectF V(0,0,C.width(),C.height()) ; PerfectView () ; ScreenSize -> setPos ( Origin ) ; ScreenSize -> setRect ( V ) ; ScreenSize -> Park ( A ) ; ScreenSize -> update ( ) ; UpdateScreen ( ) ; } void N::MonitorSize::Up(void) { screen.HeightLength++ ; QSize A = available(size()) ; QSizeF C = centimeter (A) ; QRectF V(0,0,C.width(),C.height()) ; PerfectView () ; ScreenSize -> setPos ( Origin ) ; ScreenSize -> setRect ( V ) ; ScreenSize -> Park ( A ) ; ScreenSize -> update ( ) ; UpdateScreen ( ) ; } void N::MonitorSize::Down(void) { screen.HeightLength-- ; QSize A = available(size()) ; QSizeF C = centimeter (A) ; QRectF V(0,0,C.width(),C.height()) ; PerfectView () ; ScreenSize->setPos(Origin) ; ScreenSize->setRect(V) ; ScreenSize->Park (A) ; ScreenSize->update ( ) ; UpdateScreen ( ) ; } void N::MonitorSize::UpdateScreen(void) { plan -> screen = screen ; } bool N::MonitorSize::Shutdown(void) { emit Apply ( ) ; DoProcessEvents ; return true ; } bool N::MonitorSize::Finalize(void) { emit Apply ( ) ; DoProcessEvents ; deleteLater ( ) ; return true ; }
8c350e2fd9d876b55599965b8e9c6fecbb2b2a75
{ "blob_id": "8c350e2fd9d876b55599965b8e9c6fecbb2b2a75", "branch_name": "refs/heads/main", "committer_date": "2021-06-16T15:16:14", "content_id": "4ba3e3d4faff15771977e509ce11328ff6776011", "detected_licenses": [ "MIT" ], "directory_id": "246468e49f17af5bc1995c50ffe9e53c56a22661", "extension": "cpp", "filename": "nMonitorSize.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 377539195, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4152, "license": "MIT", "license_type": "permissive", "path": "/src/QtTasks/GraphicsView/nMonitorSize.cpp", "provenance": "stack-edu-0002.json.gz:511571", "repo_name": "Vladimir-Lin/QtTasks", "revision_date": "2021-06-16T15:16:14", "revision_id": "2150f149509678f012afa05cd7fb7d4acbfdbc9d", "snapshot_id": "fcc2892364df42fc55b08978f529516629e6088d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Vladimir-Lin/QtTasks/2150f149509678f012afa05cd7fb7d4acbfdbc9d/src/QtTasks/GraphicsView/nMonitorSize.cpp", "visit_date": "2023-05-09T17:50:05.613087", "added": "2024-11-18T22:09:35.835213+00:00", "created": "2021-06-16T15:16:14", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
#include <cmath> #include <iostream> #include <random> #include <thread> #include "gflags/gflags.h" #include "glog/logging.h" #include "driver/engine.hpp" #include "lib/abstract_data_loader.hpp" #include "lib/labeled_sample.hpp" #include "lib/parser.hpp" #include "driver/engine_manager.hpp" using namespace csci5570; using Sample = lib::LabeledSample<std::vector<std::pair<int, int>>, int>; using DataStore = std::vector<Sample>; using Parse = std::function<Sample(boost::string_ref, int)>; DEFINE_string(config_file, "", "The config file path"); DEFINE_string(input, "", "The hdfs input url"); int main(int argc, char** argv) { for (int i = 0; i < argc; i++) gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); FLAGS_stderrthreshold = 0; FLAGS_colorlogtostderr = true; LOG(INFO) << FLAGS_config_file; Node node{0, "localhost", 12353}; bool recovery = false; if (std::strcmp(argv[argc - 2], "1") == 0) { recovery = true; } Engine engine(node, {node}); engine.StartEverything(); uint32_t kTableId = 0; int min_clock = 0; if (recovery) { // engine = Engine(node, {node}, true); min_clock = engine.RecoveryEngine(); // engine.Barrier(); } else { // 1.1 Create table kTableId = engine.CreateTable<double>(ModelType::SSP, StorageType::Map); // table 0 engine.Barrier(); } // 1.2 Load data // double lambda = 0.1; // double alpha = 0.01; // int n_features = 123; // std::string url = "hdfs:///datasets/classification/a9"; // DataStore data; // Parse parse(lib::Parser<Sample, DataStore>::parse_libsvm); // lib::AbstractDataLoader<Sample, DataStore>::load<Parse>(url, n_features, parse, &data); // 2. Start training task MLTask task; task.SetWorkerAlloc({{0, 3}}); // 3 workers on node 0 task.SetTables({kTableId}); // Use table 0 task.SetLambda([kTableId, min_clock](const Info& info) { LOG(INFO) << info.DebugString(); KVClientTable<double> table = info.CreateKVClientTable<double>(kTableId); std::vector<Key> parameter_keys; // parameters index std::vector<double> initial; // parameter values // initial parameters for (int m = 0; m < 10; m++) { parameter_keys.push_back(m); initial.push_back(0); } if (min_clock == 0) { table.Add(parameter_keys, initial); } // calculate and update parameters for (int i = min_clock; i < 20; i++) { std::vector<double> ret; // parameter values table.Get(parameter_keys, &ret); for (int j = 0; j < ret.size(); j++) { std::cout << "parameter is :" << ret[j] << std::endl; ret[j]++; } table.Add(parameter_keys, ret); table.Clock(); } }); engine.Run(task); // 3. Stop engine.StopEverything(); return 0; }
40985c95f812977d3ea552a832fe0e56340f4c45
{ "blob_id": "40985c95f812977d3ea552a832fe0e56340f4c45", "branch_name": "refs/heads/master", "committer_date": "2018-12-22T13:31:09", "content_id": "a48b400b0b678e3d5630849567950feb5bfa1499", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d6e206379502c033012eb1cad924a4ca0d71c12d", "extension": "cpp", "filename": "simple_example.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 149572796, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2829, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/simple_example.cpp", "provenance": "stack-edu-0003.json.gz:130206", "repo_name": "cherishher/ParameterServerPrototype", "revision_date": "2018-12-22T13:31:09", "revision_id": "04240a1fa15b7e75fd2dd87a98a6f0ac0779560a", "snapshot_id": "38704c3d526f7bef202982383b60c5d8f6c270bc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/cherishher/ParameterServerPrototype/04240a1fa15b7e75fd2dd87a98a6f0ac0779560a/app/simple_example.cpp", "visit_date": "2020-03-29T05:12:23.566102", "added": "2024-11-18T22:18:20.924233+00:00", "created": "2018-12-22T13:31:09", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
const _parseResolversFile = require('./_parseResolversFile') const _baseGraphQLTypes = require('../data/_baseGraphQLTypes') /** * Runs individual resolvers file validation on all files, merges resolvers, checks for * duplicates and returns the merged resolvers object. * * @param {String[]} resolverFiles * @private */ module.exports = (resolverFiles) => { let allResolvers = {} resolverFiles.forEach(file => { const fileResolvers = _parseResolversFile(file) _baseGraphQLTypes.forEach(type => { if (!fileResolvers.hasOwnProperty(type)) { return false } if (!allResolvers.hasOwnProperty(type)) { allResolvers[type] = {} } const allResolversTypeDataKeys = Object.keys(allResolvers[type]) const fileTypeDataKeys = Object.keys(fileResolvers[type]) const duplicates = fileTypeDataKeys.filter((key) => { return allResolversTypeDataKeys.indexOf(key) !== -1 }) if (duplicates.length) { throw new Error(`There are multiple entries of type ${type} called ${duplicates.join(', ')}.`) } Object.assign(allResolvers[type], fileResolvers[type]) }) }) return allResolvers }
e3d85fdf0d0cf684cd582fa30cce00b313694910
{ "blob_id": "e3d85fdf0d0cf684cd582fa30cce00b313694910", "branch_name": "refs/heads/master", "committer_date": "2018-05-20T23:14:56", "content_id": "f143a45b1b551e24a681f76037b12090f6727bef", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "47356c41d061ebc9617227e17da7a2b73ee25b47", "extension": "js", "filename": "_parseResolversFiles.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 132175411, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1190, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/_parseResolversFiles.js", "provenance": "stack-edu-0043.json.gz:634551", "repo_name": "sformisano/graphql-bundler", "revision_date": "2018-05-20T23:14:56", "revision_id": "36f405f2dd79d914d516c7894494f060ab60cd87", "snapshot_id": "cbf2caca3fee649cda840fadf770a3d2ef7cf989", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/sformisano/graphql-bundler/36f405f2dd79d914d516c7894494f060ab60cd87/src/_parseResolversFiles.js", "visit_date": "2020-03-15T13:47:56.936336", "added": "2024-11-18T23:53:56.120872+00:00", "created": "2018-05-20T23:14:56", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
# React.js - Portfolio [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) <br /> A portfolio built using React.js - includes 6 Full stack developnment projects from the last 6 months of Bootcamp <br /> Launch application [Github pages Deployment](https://fac-73.github.io/substance/) <br /> ## Table of Contents - [Installation](#installation) - [License](#license) - [Contributing](#contributing) - [Questions](#questions) ![React Portfolio](https://github.com/FAC-73/substance/blob/main/src/assets/homepage1.png?raw=true) <br /> ![React Portfolio](https://github.com/FAC-73/substance/blob/main/src/assets/projects1.png?raw=true) <br /> ![React Portfolio](https://github.com/FAC-73/substance/blob/main/src/assets/responsive1.png?raw=true) <br /> ## Requirements - [x] Updated portfolio featuring 6 total projects - [x] Use React - [x] A `Header` component that appears on multiple pages - [x] A single `Project` component that will be used multiple times on a single page - [x] Navigation with React Router, dynamic rendering, or another third part router - [x] A `Footer` component that appears on multiple pages - [x] Update GitHub profile with pinned repositories featuring those same projects - [x] Deploy this site to GitHub Pages using the [Create React App docs for deployment.](https://create-react-app.dev/docs/deployment/#github-pages) ## Installation Clone the repo to your local development environment. ```md git clone https://github.com/FAC-73/substance.git ``` Navigate to the substance folder directory using the command prompt. Run `npm install` to install all dependencies. in terminal or bash <br><br> Run `npm start` to run the application in terminal or bash <br><br> Use http://localhost:3000 [or whatever terminal port you have specified] in your browser ## Licence [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) <br /> ## Contributing [Kay Davis](https://github.com/FAC-73) <br /> ## Built with - [React](https://reactjs.org/) - [Javascript](https://www.w3schools.com/jsref/default.asp) - [Node.js](https://nodejs.org/en/) ## Questions? ### GitHub Username: [FAC-73](https://github.com/FAC-73) ### ✉️ Email me: [kaydavis21<EMAIL_ADDRESS> ### 📁 GitHub project repo: [https://github.com/FAC-73/substance](https://github.com/FAC-73/substance)
369447fbd1ef0ef7cf1ad331898fb612f1cb980b
{ "blob_id": "369447fbd1ef0ef7cf1ad331898fb612f1cb980b", "branch_name": "refs/heads/main", "committer_date": "2021-05-21T06:49:47", "content_id": "de78cbd85345d210d8cbcccca3f6c2fef5e92dbf", "detected_licenses": [ "MIT" ], "directory_id": "7f68f64dea4224d35784b4c9ad2c238b6a366103", "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": 369424647, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2453, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0007.json.gz:294224", "repo_name": "FAC-73/substance", "revision_date": "2021-05-21T06:49:47", "revision_id": "4f88d8572bd8af67d733cea849426c7a48ad66cb", "snapshot_id": "772dd03a704b270eca0af2df1ce0082802519469", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/FAC-73/substance/4f88d8572bd8af67d733cea849426c7a48ad66cb/README.md", "visit_date": "2023-04-26T23:33:16.382787", "added": "2024-11-19T01:44:14.414724+00:00", "created": "2021-05-21T06:49:47", "int_score": 4, "score": 3.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
package com.mmall.service.impl; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mmall.common.ServerResponse; import com.mmall.dao.CategoryMapper; import com.mmall.pojo.Category; import com.mmall.service.ICategoryService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Set; @Slf4j @Service("iCategoryService") public class CategoryServiceImpl implements ICategoryService { // private log logger = LoggerFactory.getLogger(CategoryServiceImpl.class); @Autowired private CategoryMapper categoryMapper; public ServerResponse addCategory(String categoryName){ if (StringUtils.isBlank(categoryName)){ return ServerResponse.createByErrorMessage("添加品类参数错误"); } Category category = new Category(); category.setName(categoryName); category.setParentId(0); category.setStatus(true); // 这个分类是可用的 int rowCount = categoryMapper.insert(category); if (rowCount > 0){ return ServerResponse.createBySuccess("添加品类成功"); } return ServerResponse.createByErrorMessage("添加品类失败"); } public ServerResponse updateCategory(Category category){ if (category.getId() == null ){ return ServerResponse.createByErrorMessage("更新品类参数错误"); } int rowCount = categoryMapper.updateByPrimaryKeySelective(category); if (rowCount > 0){ return ServerResponse.createBySuccess("更新品类成功"); } return ServerResponse.createByErrorMessage("更新品类失败"); } public ServerResponse<List<Category>> getChildenParallelCategory(Integer categoryId){ List<Category> categoryList = categoryMapper.selectCategoryChildenByParentId(categoryId); if (CollectionUtils.isEmpty(categoryList)){ log.info("未找到当前分类的子分类"); } return ServerResponse.createBySuccess(categoryList); } public ServerResponse<List<Category>> getCategory(Integer categoryId) { List<Category> categoryList = Lists.newArrayList(); if (categoryId == null){ categoryList = categoryMapper.selectCategory(); if (CollectionUtils.isEmpty(categoryList)){ log.info("分类为空"); } return ServerResponse.createBySuccess(categoryList); }else { Category category = categoryMapper.selectByPrimaryKey(categoryId); categoryList.add(category); return ServerResponse.createBySuccess(categoryList); } } public ServerResponse<List<Category>> getAllCategory(){ List<Category> categoryList = categoryMapper.selectCategory(); if (CollectionUtils.isEmpty(categoryList)){ log.info("分类为空"); } return ServerResponse.createBySuccess(categoryList); } // 递归查询本节点的id及孩子节点的id public ServerResponse<List<Integer>> selectCategoryAndChildenById(Integer categoryId){ Set<Category> categorySet = Sets.newHashSet(); findChildCategory(categorySet,categoryId); List<Integer> categoryIdList = Lists.newArrayList(); if (categoryId != null){ for (Category categoryItem : categorySet){ categoryIdList.add(categoryItem.getId()); } } return ServerResponse.createBySuccess(categoryIdList); } // 递归算法,算出子节点 private Set<Category> findChildCategory(Set<Category> categorySet,Integer categoryId){ Category category = categoryMapper.selectByPrimaryKey(categoryId); if (category != null){ categorySet.add(category); } List<Category> categoryList = categoryMapper.selectCategoryChildenByParentId(categoryId); for (Category categoryItem : categoryList){ findChildCategory(categorySet,categoryItem.getId()); } return categorySet; } }
24798bd78c9f1f56682c39dff0dd84789742276b
{ "blob_id": "24798bd78c9f1f56682c39dff0dd84789742276b", "branch_name": "refs/heads/master", "committer_date": "2018-09-06T02:02:34", "content_id": "30ca27ed56caa1ca625dcbfbcc22c61c2724d682", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8063dd9cf7ebe387e73726710b17f75f78944232", "extension": "java", "filename": "CategoryServiceImpl.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138393830, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4335, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/mmall/service/impl/CategoryServiceImpl.java", "provenance": "stack-edu-0020.json.gz:221137", "repo_name": "yanghong0203/mmall", "revision_date": "2018-09-06T02:02:34", "revision_id": "8fca04215e6501819126f68aaec2d8b2d62e50d9", "snapshot_id": "1189f78a48ecd59a989a9cce00925ed1decedb6e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yanghong0203/mmall/8fca04215e6501819126f68aaec2d8b2d62e50d9/src/main/java/com/mmall/service/impl/CategoryServiceImpl.java", "visit_date": "2020-03-21T09:19:08.955810", "added": "2024-11-18T23:27:41.638906+00:00", "created": "2018-09-06T02:02:34", "int_score": 2, "score": 2.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
<?php namespace Framework\Database\Connector; use Framework\Database\Connector; use Framework\Database\Query; class Mysql extends Connector{ protected function _isValidService($throwException = true){ $valid = false; if($this->isConnected && $this->service instanceof \PDO){ $valid = true; } if(!$valid && $throwException){ throw new \Exception("Not Connected to a valid service"); } return $valid; } public function connect(){ if (!$this->_isValidService(false)){ try{ $this->service = new \PDO("mysql:host={$this->host};dbname={$this->database}",$this->_username,$this->_password); $this->isConnected = true; }catch(\PDOException $ex){ throw new \Exception("Unable to connect to service"); } } return $this; } public function query():Query{ return new Query\Mysql(["connector"=>$this]); } public function execute(String $sql){ $this->_isValidService(); return $this->service->query($sql); } public function escape($value){ $this->_isValidService(); return $this->service->quote($value); } public function getLastInserted(){ $this->_isValidService(); return $this->service->lastInsertId(); } public function getLastError(){ $this->_isValidService(); return $this->service->errorInfo(); } }
a8d60553f7302cd12a4421f494e7b8d2733fe97f
{ "blob_id": "a8d60553f7302cd12a4421f494e7b8d2733fe97f", "branch_name": "refs/heads/master", "committer_date": "2019-01-23T19:32:47", "content_id": "f0fec83d1f9121914ac8a591a525d254c7140331", "detected_licenses": [ "MIT" ], "directory_id": "dfcc6c3bd4b5ec4fac863c89b495e0f178037350", "extension": "php", "filename": "Mysql.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 164676099, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1286, "license": "MIT", "license_type": "permissive", "path": "/Framework/Database/Connector/Mysql.php", "provenance": "stack-edu-0049.json.gz:251716", "repo_name": "DanielFarag/mvc", "revision_date": "2019-01-23T19:32:47", "revision_id": "a842b142a67edd63b0370787dcd45e7f8d5ae207", "snapshot_id": "522659f0c751b59e99defce2b9aba7e4c1242d93", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DanielFarag/mvc/a842b142a67edd63b0370787dcd45e7f8d5ae207/Framework/Database/Connector/Mysql.php", "visit_date": "2020-04-15T12:28:46.899147", "added": "2024-11-19T01:55:29.685505+00:00", "created": "2019-01-23T19:32:47", "int_score": 3, "score": 2.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz" }
package main import ( "errors" "github.com/savsgio/atreugo/v10" "github.com/valyala/fasthttp" ) // checkTokenMiddleware middleware to check jwt token authorization func authMiddleware(ctx *atreugo.RequestCtx) error { // Avoid middleware when you are going to login view if string(ctx.Path()) == "/login" { return ctx.Next() } jwtCookie := ctx.Request.Header.Cookie("atreugo_jwt") if len(jwtCookie) == 0 { return ctx.ErrorResponse(errors.New("login required"), fasthttp.StatusForbidden) } token, _, err := validateToken(string(jwtCookie)) if err != nil { return err } if !token.Valid { return ctx.ErrorResponse(errors.New("your session is expired, login again please"), fasthttp.StatusForbidden) } return ctx.Next() }
282cf92f25a83fba9f9c4d5bcac81e9403c7dd40
{ "blob_id": "282cf92f25a83fba9f9c4d5bcac81e9403c7dd40", "branch_name": "refs/heads/master", "committer_date": "2020-01-14T16:06:37", "content_id": "93fc5644522799cd453510c73ddcb38f754519cc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2099a861e707e318bed246d0cf4ea5ab8abdba61", "extension": "go", "filename": "middlewares.go", "fork_events_count": 0, "gha_created_at": "2020-01-14T19:06:10", "gha_event_created_at": "2020-01-14T19:06:10", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 233914969, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 748, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/jwt_auth/middlewares.go", "provenance": "stack-edu-0018.json.gz:218345", "repo_name": "rantav/atreugo", "revision_date": "2020-01-14T16:06:37", "revision_id": "625a10827f76c349b10645df8941d6b6c0030071", "snapshot_id": "6a07d7d57feb96bcd74ae391b5956aa397d750e5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rantav/atreugo/625a10827f76c349b10645df8941d6b6c0030071/examples/jwt_auth/middlewares.go", "visit_date": "2023-06-12T20:15:06.208410", "added": "2024-11-18T20:43:01.400723+00:00", "created": "2020-01-14T16:06:37", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }