text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
#include <fstream>
#include <algorithm>
#include "base.h"
#include "cartridge.h"
//--------------------------------------------
// --
//--------------------------------------------
Cartridge::Cartridge(const string &_filename)
{
ifstream cartridge(_filename, ios::binary);
cartridge.seekg(0, cartridge.end);
mRomSize = (int)cartridge.tellg();
cartridge.seekg(0, cartridge.beg);
mRom = new u8[mRomSize];
cartridge.read((char*)mRom, mRomSize);
cartridge.close();
// ...
mType = mRom[0x147];
switch(mType)
{
case MBC1:
case MBC3:
{
mRamSize = 32 * 1024;
mRam = new u8[32 * 1024] { 0 };
// sav filename
mSavFilename = _filename;
int dpos = mSavFilename.find_last_of('.');
if (dpos != -1)
mSavFilename = mSavFilename.substr(0, dpos);
mSavFilename += ".sav";
// ...
if (FileExists(mSavFilename))
{
ifstream fileram(mSavFilename, ios::binary);
fileram.read((char*)mRam, mRamSize);
fileram.close();
}
}
break;
}
// ...
char title[17] { 0 };
memcpy_s(title, 16, &mRom[0x134], 16);
mTitle = title;
}
//--------------------------------------------
// --
//--------------------------------------------
Cartridge::~Cartridge()
{
if (mRom != nullptr)
delete[] mRom;
if (mRam != nullptr)
{
ofstream output(mSavFilename, ofstream::binary);
output.write((char*)mRam, mRamSize);
output.close();
delete[] mRam;
}
}
//--------------------------------------------
// --
//--------------------------------------------
bool Cartridge::WriteU8(u16 _virtAddr, u8 _value)
{
switch(mType)
{
case MBC0:
break;
case MBC1:
case MBC3:
if (_virtAddr >= Memory::RomRamModeSelectStartAddr && _virtAddr <= Memory::RomRamModeSelectEndAddr)
{
mRomBankingMode = _value == 0;
return true;
}
if (_virtAddr >= Memory::RomBankNumberStartAddr && _virtAddr <= Memory::RomBankNumberEndAddr)
{
mRomBank = max(_value & 0x1F, 1);
return true;
}
if (_virtAddr >= Memory::RamBankNumberStartAddr && _virtAddr <= Memory::RamBankNumberEndAddr)
{
if (mRomBankingMode)
mRomBank |= _value & 0x60;
else
mRamBank = _value & 0x3;
return true;
}
break;
default:
cout << "unknown MBC: " << mType << endl;
break;
}
return false;
}
//--------------------------------------------
// --
//--------------------------------------------
u8 *Cartridge::GetBankRom(u16 _addr) const
{
switch(mType)
{
case MBC0:
return GetRom(_addr);
break;
case MBC1:
case MBC3:
return &mRom[Memory::RomStartAddr + (mRomBank * 0x4000) + (_addr - Memory::RomBankNStartAddr)];
break;
default:
cout << "opcode MBC: " << mType << endl;
break;
}
return nullptr;
}
//--------------------------------------------
// --
//--------------------------------------------
u8 *Cartridge::GetRam(u16 _addr)
{
return &mRam[(mRamBank * 0x1FFF) + (_addr - Memory::ExternalRamStartAddr)];
}
|
a6180df16e010f00852911640898d3faef923df1
|
{
"blob_id": "a6180df16e010f00852911640898d3faef923df1",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-12T10:28:33",
"content_id": "3c218baa52c579ef4244116208008cbefba4aa31",
"detected_licenses": [
"MIT"
],
"directory_id": "9b5aa28e873a07ee0b2633c812f9d31305f5dfdc",
"extension": "cpp",
"filename": "cartridge.cpp",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 51101342,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3546,
"license": "MIT",
"license_type": "permissive",
"path": "/gbe/cartridge.cpp",
"provenance": "stack-edu-0005.json.gz:366879",
"repo_name": "malandrin/gbe",
"revision_date": "2017-03-12T10:28:33",
"revision_id": "51822b0723cfdcf42b061862a83c814be553ba16",
"snapshot_id": "96a20828291b6a84837979ab937f40656c3d7134",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/malandrin/gbe/51822b0723cfdcf42b061862a83c814be553ba16/gbe/cartridge.cpp",
"visit_date": "2020-04-12T09:37:25.274836",
"added": "2024-11-18T22:11:35.432104+00:00",
"created": "2017-03-12T10:28:33",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
#include "TransformSystem.h"
#include "../../ECS/EntityManager/EntityManager.h"
#include "../../ECS/DispatcherReceiver/EventDispatcher/EventDispatcher.h"
#include "../../ECS/DispatcherReceiver/EventReceiver/EventReceiver.h"
#include "../../ECS/ECSEvent/ECSEvent.h"
#include "../../ECS/Component/Component.h"
#include "../Transform/Transform.h"
#include "../Components/HierarchyComponent/HierarchyComponent.h"
#include "../Components/TransformComponent/TransformComponent.h"
#include "../../ECS/MainResourceManager/MainResourceManager.h"
// Default TransformSystem Constructor
TransformSystem::TransformSystem(std::shared_ptr<EntityManager> newEntityManager, std::shared_ptr<EventQueue> newEventQueue)
:System(newEntityManager, newEventQueue, "TRANSFORM_SYSTEM")
{
}
// Default TransformSystem Destructor
TransformSystem::~TransformSystem()
{
}
// Initialize System.
void TransformSystem::initializeSystem()
{
}
// Update the Transform System.
void TransformSystem::update(const float & deltaTime, const float & currentFrameTime, const float & lastFrameTime)
{
processEvents(deltaTime, currentFrameTime, lastFrameTime);
// Get the EntityManager.
std::shared_ptr<EntityManager> entityManager = getEntityManager();
// Get the entities with a Transform Component.
std::shared_ptr<std::vector<long int>> entities = entityManager->getEntitiesWithComponentOfType(ComponentType::HIERARCHY_COMPONENT);
// If there are no entities, we do not really have to do anything.
if (entities != NULL)
{
// Iterate over the entities, and process them.
for (auto currentEntity : *entities)
{
// Get the Hierarchy Component.
std::shared_ptr<const HierarchyComponent> hierarchyComponent = std::dynamic_pointer_cast<const HierarchyComponent>(entityManager->viewComponentOfEntity(currentEntity, ComponentType::HIERARCHY_COMPONENT));
// Check if this entity does not have parent.
if (hierarchyComponent->getParent() == -1)
{
computeHierarchyTransformMatrix(currentEntity, glm::mat4(1.0));
}
}
}
}
// Compute the Hierarchy Transform Matrix.
void TransformSystem::computeHierarchyTransformMatrix(long int currentEntity, const glm::mat4 & hierarchyMatrix)
{
// Get the EntityManager.
std::shared_ptr<EntityManager> entityManager = getEntityManager();
// Check if this is the currentEntity.
if (currentEntity != -1)
{
// Get the Hierarchy Component.
std::shared_ptr<const HierarchyComponent> hierarchyComponent = std::dynamic_pointer_cast<const HierarchyComponent>(entityManager->viewComponentOfEntity(currentEntity, ComponentType::HIERARCHY_COMPONENT));
// Get the transform component.
std::shared_ptr<TransformComponent> transformComponent = std::dynamic_pointer_cast<TransformComponent>(entityManager->getComponentOfEntity(currentEntity, ComponentType::TRANSFORM_COMPONENT, "TRANSFORM_SYSTEM"));
// Compute the Hierarchy Component.
if (hierarchyComponent != NULL && transformComponent != NULL)
{
// Compute the transform.
transformComponent->getTransform()->computeTransformMatrix();
transformComponent->getTransform()->computeHierarchyTransformMatrix(hierarchyMatrix);
// Iterate over the entities lower on the hierarchy tree.
for (auto currentChildEntity = hierarchyComponent->getChildEntities().begin(); currentChildEntity != hierarchyComponent->getChildEntities().end(); currentChildEntity++)
{
computeHierarchyTransformMatrix(*currentChildEntity, *transformComponent->getTransform()->getHierarchyTransformMatrix());
}
}
}
}
// Process the Events.
void TransformSystem::processEvents(const float & deltaTime, const float & currentFrameTime, const float & lastFrameTime)
{
// Check if there are any Events.
while (getReceiver()->getNumberOfEvents() > 0)
{
// Get the events.
std::shared_ptr<const ECSEvent> nextEvent = getReceiver()->getNextEvent();
// Respond to the System shutdown.
if (nextEvent->getEventType() == EventType::ECS_SHUTDOWN_EVENT)
{
shutDownSystem();
}
}
}
// Shut Down the System.
void TransformSystem::shutDownSystem()
{
}
// Miscellaneous clean up the system.
void TransformSystem::destroySystem()
{
}
|
daab2aa368b7def0bbdee03f3d41c49189363f4b
|
{
"blob_id": "daab2aa368b7def0bbdee03f3d41c49189363f4b",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-23T19:41:07",
"content_id": "e8e051cffb2f95cfa407a3db5d894046617d1d16",
"detected_licenses": [
"MIT"
],
"directory_id": "3efba8973c0ddda350359cc9d1dd21bbf3666865",
"extension": "cpp",
"filename": "TransformSystem.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 77653583,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4138,
"license": "MIT",
"license_type": "permissive",
"path": "/ECS/Project/Project/Systems/TransformSystem/TransformSystem.cpp",
"provenance": "stack-edu-0008.json.gz:488921",
"repo_name": "AshwinKumarVijay/SceneECS",
"revision_date": "2017-02-23T19:41:07",
"revision_id": "2acc115d5e7738ef9bf087c025e5e5a10cac3443",
"snapshot_id": "0de78e5f0a1a9ae494a5687443907670d7d76ac3",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/AshwinKumarVijay/SceneECS/2acc115d5e7738ef9bf087c025e5e5a10cac3443/ECS/Project/Project/Systems/TransformSystem/TransformSystem.cpp",
"visit_date": "2021-04-29T08:11:07.161331",
"added": "2024-11-18T23:17:16.656809+00:00",
"created": "2017-02-23T19:41:07",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Text;
public class HttpResponse
{
private string ServerEngineName;
public HttpResponse(Version httpVersion, HttpStatusCode statusCode, string body, string contentType = "text/plain; charset=utf-8")
{
ServerEngineName = "ConsoleWebServer";
ProtocolVersion = Version.Parse(httpVersion.ToString().ToLower().Replace("HTTP/".ToLower(), string.Empty));
Headers = new SortedDictionary<string, ICollection<string>>();
Body = body;
StatusCode = statusCode;
AddHeader("Server", ServerEngineName);
AddHeader("Content-Length", body.Length.ToString());
AddHeader("Content-Type", contentType);
}
public Version ProtocolVersion { get; protected set; }
public IDictionary<string, ICollection<string>> Headers { get; protected set; }
public HttpStatusCode StatusCode { get; private set; }
public string Body { get; private set; }
public string StatusCodeAsString
{
get
{
return this.StatusCode.ToString();
}
}
public void AddHeader(string name, string value)
{
if (!Headers.ContainsKey(name))
{
Headers.Add(name, new HashSet<string>());
}
Headers[name].Add(value);
}
public override string ToString()
{
var headerStringBuilder = new StringBuilder();
foreach (var key in Headers.Keys)
{
headerStringBuilder.AppendLine(string.Format("{0}: {1}", key, string.Join("; ", Headers[key])));
}
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine(string.Format("{0}{1} {2} {3}", "HTTP/", ProtocolVersion, (int)StatusCode, StatusCodeAsString));
stringBuilder.AppendLine(headerStringBuilder.ToString());
if (!string.IsNullOrWhiteSpace(Body))
{
stringBuilder.AppendLine(Body);
}
return stringBuilder.ToString();
}
}
namespace ConsoleWebServer.Framework
{
using System.Diagnostics;
using System.Collections.Concurrent;
using System;
}
|
64a88631233b1821773d0b5d4169b074d21af8d0
|
{
"blob_id": "64a88631233b1821773d0b5d4169b074d21af8d0",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-07T01:33:46",
"content_id": "cef498ee0b30001938a7ab71f95dc2e01091e8e0",
"detected_licenses": [
"MIT"
],
"directory_id": "1ee0147c7f066fddc3997dd462ee16e06b2c080b",
"extension": "cs",
"filename": "HttpResponse.cs",
"fork_events_count": 0,
"gha_created_at": "2016-09-14T15:50:14",
"gha_event_created_at": "2016-09-14T15:50:14",
"gha_language": null,
"gha_license_id": null,
"github_id": 68220126,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2200,
"license": "MIT",
"license_type": "permissive",
"path": "/Exam 2015/ConsoleWebServer/ConsoleWebServer.Framework/HttpResponse.cs",
"provenance": "stack-edu-0012.json.gz:211027",
"repo_name": "DimitarDKirov/High-Quality-Code-Part-2",
"revision_date": "2016-10-07T01:33:46",
"revision_id": "2d880caee98cd84798f78f95e90f983234fa2578",
"snapshot_id": "b63d6f8f454b0f474d007df574561aabbac428f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DimitarDKirov/High-Quality-Code-Part-2/2d880caee98cd84798f78f95e90f983234fa2578/Exam 2015/ConsoleWebServer/ConsoleWebServer.Framework/HttpResponse.cs",
"visit_date": "2020-12-25T03:10:56.105079",
"added": "2024-11-19T01:23:04.836216+00:00",
"created": "2016-10-07T01:33:46",
"int_score": 3,
"score": 2.796875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
$(document).ready(function() {
var smoothie = new SmoothieChart();
smoothie.streamTo(document.getElementById("mycanvas"), 1000);
var ws = new WebSocket("ws://127.0.0.1:8080", "johnny-protocol");
// Data
var line1 = new TimeSeries();
ws.onmessage = function(message) {
line1.append(new Date().getTime(), message.data);
};
// setInterval(function() {
// ws.send("johnny:test-" + new Date().getTime());
// }, 1000);
// Add to SmoothieChart
smoothie.addTimeSeries(line1);
});
|
d733a883e6ff6fa9ddadb4a9ddcc1c0409f3cf1d
|
{
"blob_id": "d733a883e6ff6fa9ddadb4a9ddcc1c0409f3cf1d",
"branch_name": "refs/heads/master",
"committer_date": "2012-06-04T23:07:54",
"content_id": "450e400204e3af022dc169d0df21c03cfb5eb717",
"detected_licenses": [
"MIT"
],
"directory_id": "7b9ca9320f289f3994b1b31d12ae5e79637a7cdb",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 506,
"license": "MIT",
"license_type": "permissive",
"path": "/public/js/app.js",
"provenance": "stack-edu-0040.json.gz:332112",
"repo_name": "pathable/johnnyonthespot",
"revision_date": "2012-06-04T23:07:54",
"revision_id": "f08e1c4f09491b2aabac7eb1246cc87467fdcb8d",
"snapshot_id": "ef4e05b8b54a208a4843c8bab807489192182703",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pathable/johnnyonthespot/f08e1c4f09491b2aabac7eb1246cc87467fdcb8d/public/js/app.js",
"visit_date": "2021-01-19T17:13:42.768157",
"added": "2024-11-19T01:10:03.795676+00:00",
"created": "2012-06-04T23:07:54",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz"
}
|
import numpy as np
import pandas as pd
# create the output file
# read the addmission file
addmissions_file = pd.read_csv('ADMISSIONS_demo.csv')
addmissions_number = np.size(addmissions_file, 0)
HADM_ID = addmissions_file.get('HADM_ID')
# red the microbiologicalevents file
microbiologicalevents_file = pd.read_csv('MICROBIOLOGYEVENTS_demo.csv', usecols=['HADM_ID', 'INTERPRETATION'])
# microbiologicalevents_file = microbiologicalevents_file.sort_values(by=('HADM_ID'))
INTERPRETATION = microbiologicalevents_file.get('INTERPRETATION')
dignostics = []
for ind1 in addmissions_file.get('HADM_ID'):
all_microbiologicalevents_for_one_subject = microbiologicalevents_file.index[microbiologicalevents_file['HADM_ID']
== ind1].tolist()
temp_list = INTERPRETATION[all_microbiologicalevents_for_one_subject]
if any(temp_list == 'S') or any(temp_list == 'I'):
dignostics.append(1)
else:
dignostics.append(0)
output_dataframe = pd.DataFrame(data={'HADM_ID': np.array(HADM_ID), 'INTERPRETATION': np.array(dignostics)})
output_dataframe.to_csv('Output.csv')
|
c4d8a3c0f2cb0cb22a6f001cc6bd8545f68928de
|
{
"blob_id": "c4d8a3c0f2cb0cb22a6f001cc6bd8545f68928de",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-13T14:03:53",
"content_id": "8170dc552ff06e51550c86327806955ee7841949",
"detected_licenses": [
"MIT"
],
"directory_id": "bdc3bd0df350a50ec0f1f0aa0c56244735d736e3",
"extension": "py",
"filename": "output_file_script.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 190985896,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1192,
"license": "MIT",
"license_type": "permissive",
"path": "/output script/output_file_script.py",
"provenance": "stack-edu-0060.json.gz:401424",
"repo_name": "jlmhackaton/Patient2Vec",
"revision_date": "2019-06-13T14:03:53",
"revision_id": "9eeb5bd8f1b7497f88f85c4399ed445f47ed7655",
"snapshot_id": "791d6aaebf0241803e477646bd3215f4f41dccca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jlmhackaton/Patient2Vec/9eeb5bd8f1b7497f88f85c4399ed445f47ed7655/output script/output_file_script.py",
"visit_date": "2020-06-02T00:54:33.704226",
"added": "2024-11-19T01:55:12.978865+00:00",
"created": "2019-06-13T14:03:53",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
#ifndef __MONO_NATIVE_MSCORLIB_SYSTEM_COLLECTIONS_CONCURRENT_IPRODUCERCONSUMERCOLLECTION_1_H
#define __MONO_NATIVE_MSCORLIB_SYSTEM_COLLECTIONS_CONCURRENT_IPRODUCERCONSUMERCOLLECTION_1_H
#include <mscorlib/System/Collections/mscorlib_System_Collections_ICollection.h>
#include <mscorlib/System/Collections/mscorlib_System_Collections_IEnumerable.h>
#include <mscorlib/System/Collections/Generic/mscorlib_System_Collections_Generic_IEnumerable_1.h>
namespace mscorlib
{
namespace System
{
namespace Collections
{
namespace Concurrent
{
template<typename T>
class IProducerConsumerCollection
: public virtual mscorlib::System::Collections::ICollection
, public virtual mscorlib::System::Collections::IEnumerable
, public virtual mscorlib::System::Collections::Generic::IEnumerable<T>
{
public:
IProducerConsumerCollection(MonoObject *nativeObject)
: mscorlib::System::Collections::ICollection(nativeObject)
, mscorlib::System::Collections::IEnumerable(nativeObject)
, mscorlib::System::Collections::Generic::IEnumerable<T>(nativeObject)
{
};
~IProducerConsumerCollection()
{
};
__declspec(property(get=get___mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1, put=set___mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1)) MonoObject *__mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1;
MonoObject* get___mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1() const
{
return IProducerConsumerCollection::__mscorlib_System_Collections_Generic_IEnumerable_1;
}
void set___mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1(MonoObject *value)
{
IProducerConsumerCollection::__mscorlib_System_Collections_Generic_IEnumerable_1 = value;
}
IProducerConsumerCollection & operator=(IProducerConsumerCollection &value) { __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1 = value.__mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1; return value; };
operator MonoObject*() { return __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1; };
MonoObject* operator=(MonoObject* value) { __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1 = value; return value; };
virtual mscorlib::System::Boolean TryAdd(T item)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(item).name());
__parameters__[0] = (MonoObject*)item;
MonoType *__generic_types__[1];
__generic_types__[0] = Global::GetType(typeid(T).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Collections.Concurrent", "IProducerConsumerCollection`1", 1, __generic_types__, "TryAdd", __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
};
virtual mscorlib::System::Boolean TryTake(T item)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(item).name());
__parameters__[0] = (MonoObject*)item;
MonoType *__generic_types__[1];
__generic_types__[0] = Global::GetType(typeid(T).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Collections.Concurrent", "IProducerConsumerCollection`1", 1, __generic_types__, "TryTake", __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
};
virtual std::vector<T*> ToArray()
{
MonoType *__generic_types__[1];
__generic_types__[0] = Global::GetType(typeid(T).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Collections.Concurrent", "IProducerConsumerCollection`1", 1, __generic_types__, "ToArray", __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1, 0, NULL, NULL, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<T*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new T (__array_item__));
}
return __array_result__;
};
virtual void CopyTo(std::vector<T*> array, mscorlib::System::Int32 index)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System.Collections.Concurrent", "T")), 1));
__parameter_types__[1] = Global::GetType(typeid(index).name());
__parameters__[0] = Global::FromArray<T*>(array, typeid(T).name());
__parameters__[1] = &index;
MonoType *__generic_types__[1];
__generic_types__[0] = Global::GetType(typeid(T).name());
Global::InvokeMethod("mscorlib", "System.Collections.Concurrent", "IProducerConsumerCollection`1", 1, __generic_types__, "CopyTo", __mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1, 2, __parameter_types__, __parameters__, NULL);
};
protected:
private:
};
}
}
}
}
#endif
|
8ee6e1af023862a62fdeb845d7e31c73516f27e3
|
{
"blob_id": "8ee6e1af023862a62fdeb845d7e31c73516f27e3",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-01T17:55:27",
"content_id": "508860ef99d64ea19591626fcce6495d9555ee52",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "56f431ac8061ddb4c45b32457b0f948d1029d98f",
"extension": "h",
"filename": "mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 22582991,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5671,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/MonoNative/mscorlib/System/Collections/Concurrent/mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1.h",
"provenance": "stack-edu-0005.json.gz:43248",
"repo_name": "brunolauze/MonoNative",
"revision_date": "2016-03-01T17:55:27",
"revision_id": "959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66",
"snapshot_id": "886d2a346a959d86e7e0ff68661be1b6767c5ce6",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/brunolauze/MonoNative/959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66/MonoNative/mscorlib/System/Collections/Concurrent/mscorlib_System_Collections_Concurrent_IProducerConsumerCollection_1.h",
"visit_date": "2016-09-15T17:32:26.626998",
"added": "2024-11-18T20:25:52.886301+00:00",
"created": "2016-03-01T17:55:27",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
package com.github.tt4g.spring.webflux.mdc.trace.example.mdc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public Mono<String> hello() {
return Mono.just("Hello");
}
}
|
bbfe0aff4d15f1f204227cafaefa26ae0245ef25
|
{
"blob_id": "bbfe0aff4d15f1f204227cafaefa26ae0245ef25",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-23T23:21:28",
"content_id": "e08fe0997518143bf69383e3bb5ebe79f1a6e34a",
"detected_licenses": [
"MIT"
],
"directory_id": "7683a0ea85ed9cbab60aad695451eca3ba71988d",
"extension": "java",
"filename": "HelloController.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293079599,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 479,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/com/github/tt4g/spring/webflux/mdc/trace/example/mdc/HelloController.java",
"provenance": "stack-edu-0024.json.gz:589488",
"repo_name": "tt4g/spring-webflux-mdc-trace-example",
"revision_date": "2021-04-23T23:21:28",
"revision_id": "7e9ccd3a39300981b4a1bc841a24e1a416533753",
"snapshot_id": "d8a0fc0110e0e7e6adf6121d6c0325ee97786beb",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/tt4g/spring-webflux-mdc-trace-example/7e9ccd3a39300981b4a1bc841a24e1a416533753/src/main/java/com/github/tt4g/spring/webflux/mdc/trace/example/mdc/HelloController.java",
"visit_date": "2023-04-11T04:24:58.581598",
"added": "2024-11-19T00:51:47.394978+00:00",
"created": "2021-04-23T23:21:28",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package io.enoy.tg.example.actions;
import io.enoy.tg.action.TgController;
import io.enoy.tg.action.TgPostAction;
import io.enoy.tg.action.TgPreAction;
import io.enoy.tg.action.request.TgRequest;
import io.enoy.tg.bot.TgMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Scope;
import java.util.ArrayList;
import java.util.List;
@TgController(name = "Favorite Color", description = "Select your favorite color", regex = "\\/favorite_color")
@Scope("tg")
@RequiredArgsConstructor
public class FavoriteColor {
private final TgMessageService messageService;
private List<String> colors;
@TgPreAction
public void pre() {
colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
}
@TgRequest
public void favColor(String command) {
messageService.sendReplyKeyboard("Select your favorite color", colors, true, 2);
}
@TgRequest
public void favColor(String command, String color) {
messageService.sendMessage(String.format("%s is my favorite color too!", color));
}
@TgPostAction
public void post() {
messageService.removeKeyboard();
}
}
|
f4acca7b56b7d6616cde22f0465a8d48d14af036
|
{
"blob_id": "f4acca7b56b7d6616cde22f0465a8d48d14af036",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-24T17:14:01",
"content_id": "b9f12949215c545f855481819e38556e2b8920b6",
"detected_licenses": [
"MIT"
],
"directory_id": "2d3e8a5d5a8e0f4e8f3d013d2f320a31e29087d8",
"extension": "java",
"filename": "FavoriteColor.java",
"fork_events_count": 5,
"gha_created_at": "2017-11-22T22:38:40",
"gha_event_created_at": "2017-12-02T00:09:11",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 111739202,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1148,
"license": "MIT",
"license_type": "permissive",
"path": "/spring-tg-examples/src/main/java/io/enoy/tg/example/actions/FavoriteColor.java",
"provenance": "stack-edu-0029.json.gz:565659",
"repo_name": "enoy19/spring-tg",
"revision_date": "2018-05-24T17:14:01",
"revision_id": "0093a00ff6932100222641a810ae0ddc626addc6",
"snapshot_id": "a56de9c811efd4b019465deb4def7763ccf29d4b",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/enoy19/spring-tg/0093a00ff6932100222641a810ae0ddc626addc6/spring-tg-examples/src/main/java/io/enoy/tg/example/actions/FavoriteColor.java",
"visit_date": "2021-09-15T03:03:06.790679",
"added": "2024-11-19T00:05:20.075764+00:00",
"created": "2018-05-24T17:14:01",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
// Copyright 2012, Tencent Inc.
// Author: rabbitliu <rabbitliu@tencent.com>
package org.apache.zookeeper.server.counter;
import org.apache.log4j.Logger;
import java.util.HashMap;
// The counter for role-based operation and output like the following:
// ==========================================================================================
// Role Con R W Clo PCon PR PW PClo AcCon
// ==========================================================================================
// xcube 1 1 0 1 1 1 0 1 0
// xfs_server 2 2 0 2 1 1 0 1 0
// twse_rel_merge 4 0 0 0 1 0 0 0 1
public class RoleOpCounter {
private static final Logger LOG = Logger.getLogger(RoleOpCounter.class);
static private class CounterInfo {
public TimedStats createSessionStats = new TimedStats("CreateSession");
public TimedStats closeSessionStats = new TimedStats("CloseSession");
public TimedStats readStats = new TimedStats("Read");
public TimedStats writeStats = new TimedStats("Write");
} // end of class CounterInfo
private final int sampleTime = 5 * 60;
private static final int CREATESESSION = 11;
private static final int READ = 12;
private static final int WRITE = 13;
private static final int CLOSESESSION = 14;
private HashMap<String, CounterInfo> roleReportMap = new HashMap<String, CounterInfo>();
public RoleOpCounter() {
}
public void addCreateSession(long timestamp, String role) {
addCount(timestamp, role, CREATESESSION);
}
public void addRead(long timestamp, String role) {
addCount(timestamp, role, READ);
}
public void addWrite(long timestamp, String role) {
addCount(timestamp, role, WRITE);
}
public void addCloseSession(long timestamp, String role) {
addCount(timestamp, role, CLOSESESSION);
}
private void addCount(long timestamp, String role, int type) {
CounterInfo info = null;
synchronized(this.roleReportMap) {
info = roleReportMap.get(role);
if (info == null) {
info = new CounterInfo();
roleReportMap.put(role, info);
}
}
switch(type) {
case CREATESESSION: {
info.createSessionStats.addCount(timestamp);
break;
}
case READ: {
info.readStats.addCount(timestamp);
break;
}
case WRITE: {
info.writeStats.addCount(timestamp);
break;
}
case CLOSESESSION: {
info.closeSessionStats.addCount(timestamp);
break;
}
default: {
LOG.warn("Unknow operation type: " + type);
}
}
}
public String dump(HashMap<String, Integer> activeConnectionMap) {
StringBuilder sb = new StringBuilder();
sb.append("=========================================================================" +
"===================================\n");
sb.append(String.format("%-26.26s%-14s%-14s%-14s%-14s%-5s%-5s%-5s%-5s%-4s\n", "Role",
"Con", "R", "W", "Clo", "PCon", "PR", "PW", "PClo", "AcCon"));
sb.append("=========================================================================" +
"===================================\n");
long timestamp = System.currentTimeMillis() / 1000;
synchronized(roleReportMap) {
for (String role : roleReportMap.keySet()) {
CounterInfo info = roleReportMap.get(role);
Integer activeConnectionNum = activeConnectionMap.get(role);
if (activeConnectionNum == null) {
activeConnectionNum = 0;
}
sb.append(String.format("%-25.25s ", role));
sb.append(String.format("%-14s%-14s%-14s%-14s%-5s%-5s%-5s%-5s%-4s\n",
info.createSessionStats.getTotalCount(),
info.readStats.getTotalCount(),
info.writeStats.getTotalCount(),
info.closeSessionStats.getTotalCount(),
info.createSessionStats.getMaxCountOfPastSeconds(timestamp, sampleTime),
info.readStats.getMaxCountOfPastSeconds(timestamp, sampleTime),
info.writeStats.getMaxCountOfPastSeconds(timestamp, sampleTime),
info.closeSessionStats.getMaxCountOfPastSeconds(timestamp, sampleTime),
activeConnectionNum));
}
}
return sb.toString();
}
}
|
dc9685d21d288fbc7a0bfa7cc00793c75d0b5900
|
{
"blob_id": "dc9685d21d288fbc7a0bfa7cc00793c75d0b5900",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-05T14:46:20",
"content_id": "7d95e3b8ab7d5fb6b58caf8401598f15f58ad05e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fae0a973015ca7ca6f8c415f1257fdf6cff3c559",
"extension": "java",
"filename": "RoleOpCounter.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": 4852,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/zookeeper-3.3.3/src/java/main/org/apache/zookeeper/server/counter/RoleOpCounter.java",
"provenance": "stack-edu-0027.json.gz:571112",
"repo_name": "jiaqiang/thirdparty",
"revision_date": "2015-09-05T14:46:20",
"revision_id": "6ee8c1cfa659228770d1598139d47331a5e852a4",
"snapshot_id": "2c197db2f70f568829ff43ba0f96b9d5fbba96ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jiaqiang/thirdparty/6ee8c1cfa659228770d1598139d47331a5e852a4/zookeeper-3.3.3/src/java/main/org/apache/zookeeper/server/counter/RoleOpCounter.java",
"visit_date": "2021-01-15T12:37:59.453381",
"added": "2024-11-19T00:55:31.620514+00:00",
"created": "2015-09-05T14:46:20",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz"
}
|
#!/bin/bash
rm -rf ./plugin
docker build -t rootfsimage .
id=$(docker create rootfsimage true) # id was cd851ce43a403 when the image was created
mkdir -p plugin/rootfs
docker export "$id" | tar -x -C plugin/rootfs
docker rm -vf "$id"
docker rmi rootfsimage
cp config.json ./plugin/
docker plugin disable ekristen/multilogger
docker plugin rm ekristen/multilogger
docker plugin create ekristen/multilogger ./plugin
rm -rf ./plugin
|
8d99db4b5189413eae70ec467df7f6f21b9869ee
|
{
"blob_id": "8d99db4b5189413eae70ec467df7f6f21b9869ee",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-10T14:06:15",
"content_id": "d76fe4f03d3c19fbd3fa4c313e34e8d673ec8898",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0d95f7a01334fbaf07ed7aa71ed6a4a802c596b4",
"extension": "sh",
"filename": "build.sh",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98486174,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 434,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/build.sh",
"provenance": "stack-edu-0069.json.gz:836663",
"repo_name": "ekristen/docker-plugin-multilogger",
"revision_date": "2017-10-10T14:06:15",
"revision_id": "99938a5494c07a154e458f354d3a4d2fbda29053",
"snapshot_id": "97e5b62b346f7148a8d67291db37d38d1b4d5870",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ekristen/docker-plugin-multilogger/99938a5494c07a154e458f354d3a4d2fbda29053/build.sh",
"visit_date": "2021-01-01T19:00:17.751709",
"added": "2024-11-18T23:03:23.032957+00:00",
"created": "2017-10-10T14:06:15",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
import collections
import logging
import fdutils as utils
log = logging.getLogger(__name__)
def transform_password(values, crypto_engine_function):
""" transform a structure by encrypting/decrypting any value in a dictionary for any key that contains the word
'password'
"""
for _k, _v in values.items():
if isinstance(_v, collections.MutableMapping):
transform_password(_v, crypto_engine_function)
elif utils.lists.is_list_or_tuple(_v):
for _vv in (_vv for _vv in _v if isinstance(_vv, collections.MutableMapping)):
transform_password(_vv, crypto_engine_function)
elif 'password' in _k and _v:
values[_k] = crypto_engine_function(_v)
def get_ip_from_default_or_hostname(hostname, default_ip='', ip_type=''):
""" in case default ip is not given we try to get it from the hostname """
if ip_type.lower() in ('v4', '4', 4, 'ipv4', 'ip4'):
family = 'ipv4'
elif ip_type.lower() in ('v6', '6', 6, 'ipv6', 'ip6'):
family = 'ipv6'
else:
family = None
if not default_ip and hostname:
try:
ip_from_hostname = utils.net.nslookup_all(hostname, family)
if ip_from_hostname:
return ip_from_hostname[0]
except Exception:
log.debug('Problems doing an nslookup of ' + str(hostname))
return ''
else:
return default_ip
|
602db8c754692095290a0cd744ca03ed1a6dff63
|
{
"blob_id": "602db8c754692095290a0cd744ca03ed1a6dff63",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-21T20:01:39",
"content_id": "6dcdb4ec2222979a32a87a5f9c4fe8a733bff6a4",
"detected_licenses": [
"MIT"
],
"directory_id": "9d38d7cd271eba95578e36a6d5c8f0d3dda39fe5",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 1,
"gha_created_at": "2018-06-19T17:02:17",
"gha_event_created_at": "2022-10-21T20:01:40",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 137921045,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1439,
"license": "MIT",
"license_type": "permissive",
"path": "/remotelogin/devices/utils.py",
"provenance": "stack-edu-0061.json.gz:301349",
"repo_name": "filintod/pyremotelogin",
"revision_date": "2022-10-21T20:01:39",
"revision_id": "3661a686be58415f72db5800431f945ff48324a0",
"snapshot_id": "8e8be07b49e86b79e7fb0776c7462995a01c422e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/filintod/pyremotelogin/3661a686be58415f72db5800431f945ff48324a0/remotelogin/devices/utils.py",
"visit_date": "2022-11-10T09:38:54.522089",
"added": "2024-11-18T19:39:55.485500+00:00",
"created": "2022-10-21T20:01:39",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
/** License
*
* Copyright (c) 2015 Adam Śmigielski
*
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions: The above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the
* Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**/
/**
* @author Adam Śmigielski
* @file Manager.hpp
**/
#ifndef O8_WS_WINDOWS_MANAGER_HPP
#define O8_WS_WINDOWS_MANAGER_HPP
#include <Utilities\containers\IntrusiveList.hpp> /* IntrusiveList::List */
#include <O8\WS\Manager.hpp> /* Manager */
namespace O8
{
namespace Thread
{
class Factory;
}
namespace WS
{
class Window_windows;
class Manager_windows : public Manager, public Containers::IntrusiveList::List<Window_windows>
{
public:
Manager_windows(O8::Thread::Factory * thread_factory);
virtual ~Manager_windows();
/* Event processing */
virtual Platform::int32 Start_event_processing();
virtual Platform::int32 Stop_event_processing();
virtual Platform::int32 Process_events();
/* Window management */
virtual Window * Create_window();
private:
void destroy_windows();
void loop();
//loop
enum class loop_state
{
Unknown,
Halt,
Stoping,
Starting,
Run,
};
loop_state m_loop_state;
O8::Thread::Factory * m_thread_factory;
};
}
}
#endif /* O8_WS_WINDOWS_MANAGER_HPP */
|
721f8a24fbea2f2f485b4947b218197acb5816e6
|
{
"blob_id": "721f8a24fbea2f2f485b4947b218197acb5816e6",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-19T07:59:28",
"content_id": "48702e55fb605318d5eb2b0d89376633b9737417",
"detected_licenses": [
"MIT"
],
"directory_id": "58c873fbe83e7831a782f411cee03bfce1706147",
"extension": "hpp",
"filename": "Manager_windows.hpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32004908,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2372,
"license": "MIT",
"license_type": "permissive",
"path": "/src/O8/WS/WS_Windows/Manager_windows.hpp",
"provenance": "stack-edu-0006.json.gz:236258",
"repo_name": "adamsmigielski/O8",
"revision_date": "2018-10-19T07:59:28",
"revision_id": "4e2d542e3117b37674a3f5a4cf80573903b466d7",
"snapshot_id": "16044f43be5b7b1ca9d0d01bb363e7590c43141a",
"src_encoding": "WINDOWS-1250",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adamsmigielski/O8/4e2d542e3117b37674a3f5a4cf80573903b466d7/src/O8/WS/WS_Windows/Manager_windows.hpp",
"visit_date": "2021-01-17T13:33:48.951011",
"added": "2024-11-18T23:17:38.882505+00:00",
"created": "2018-10-19T07:59:28",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { Vector } from './Algebra';
import { Logger } from './Util/Log';
import { BoundingBox } from './Collision/Index';
/**
* Enum representing the different display modes available to Excalibur.
*/
export var DisplayMode;
(function (DisplayMode) {
/**
* Use the entire screen's css width/height for the game resolution dynamically. This is not the same as [[Screen.goFullScreen]]
*/
DisplayMode["FullScreen"] = "FullScreen";
/**
* Use the parent DOM container's css width/height for the game resolution dynamically
*/
DisplayMode["Container"] = "Container";
/**
* Default, use a specified resolution for the game
*/
DisplayMode["Fixed"] = "Fixed";
/**
* Allow the game to be positioned with the [[EngineOptions.position]] option
*/
DisplayMode["Position"] = "Position";
})(DisplayMode || (DisplayMode = {}));
/**
* Convenience class for quick resolutions
* Mostly sourced from https://emulation.gametechwiki.com/index.php/Resolution
*/
var Resolution = /** @class */ (function () {
function Resolution() {
}
Object.defineProperty(Resolution, "SVGA", {
get: function () {
return { width: 800, height: 600 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "Standard", {
get: function () {
return { width: 1920, height: 1080 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "Atari2600", {
get: function () {
return { width: 160, height: 192 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "GameBoy", {
get: function () {
return { width: 160, height: 144 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "GameBoyAdvance", {
get: function () {
return { width: 240, height: 160 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "NintendoDS", {
get: function () {
return { width: 256, height: 192 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "NES", {
get: function () {
return { width: 256, height: 224 };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resolution, "SNES", {
get: function () {
return { width: 256, height: 244 };
},
enumerable: false,
configurable: true
});
return Resolution;
}());
export { Resolution };
/**
* The Screen handles all aspects of interacting with the screen for Excalibur.
*
* [[include:Screen.md]]
*/
var Screen = /** @class */ (function () {
function Screen(options) {
var _this = this;
var _a, _b, _c;
this._antialiasing = true;
this._resolutionStack = [];
this._viewportStack = [];
this._pixelRatio = null;
this._isFullScreen = false;
this._isDisposed = false;
this._logger = Logger.getInstance();
this._pixelRatioChangeHandler = function () {
_this._logger.debug('Pixel Ratio Change', window.devicePixelRatio);
_this.applyResolutionAndViewport();
};
this._windowResizeHandler = function () {
var parent = (_this.displayMode === DisplayMode.Container ? (_this.canvas.parentElement || document.body) : window);
_this._logger.debug('View port resized');
_this._setHeightByDisplayMode(parent);
_this._logger.info('parent.clientHeight ' + parent.clientHeight);
_this.applyResolutionAndViewport();
};
this.viewport = options.viewport;
this.resolution = (_a = options.resolution) !== null && _a !== void 0 ? _a : __assign({}, this.viewport);
this._displayMode = (_b = options.displayMode) !== null && _b !== void 0 ? _b : DisplayMode.Fixed;
this._canvas = options.canvas;
this._ctx = options.context;
this._antialiasing = (_c = options.antialiasing) !== null && _c !== void 0 ? _c : this._antialiasing;
this._browser = options.browser;
this._position = options.position;
this._pixelRatio = options.pixelRatio;
this._applyDisplayMode();
this._mediaQueryList = this._browser.window.nativeComponent.matchMedia("(resolution: " + window.devicePixelRatio + "dppx)");
this._mediaQueryList.addEventListener('change', this._pixelRatioChangeHandler);
}
Screen.prototype.dispose = function () {
if (!this._isDisposed) {
// Clean up handlers
this._isDisposed = true;
this._browser.window.off('resize', this._windowResizeHandler);
this._mediaQueryList.removeEventListener('change', this._pixelRatioChangeHandler);
}
};
Object.defineProperty(Screen.prototype, "pixelRatio", {
get: function () {
if (this._pixelRatio) {
return this._pixelRatio;
}
if (window.devicePixelRatio < 1) {
return 1;
}
var devicePixelRatio = window.devicePixelRatio || 1;
return devicePixelRatio;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "isHiDpi", {
get: function () {
return this.pixelRatio !== 1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "displayMode", {
get: function () {
return this._displayMode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "canvas", {
get: function () {
return this._canvas;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "resolution", {
get: function () {
return this._resolution;
},
set: function (resolution) {
this._resolution = resolution;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "viewport", {
get: function () {
if (this._viewport) {
return this._viewport;
}
return this._resolution;
},
set: function (viewport) {
this._viewport = viewport;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "scaledWidth", {
get: function () {
return this._resolution.width * this.pixelRatio;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "scaledHeight", {
get: function () {
return this._resolution.height * this.pixelRatio;
},
enumerable: false,
configurable: true
});
Screen.prototype.setCurrentCamera = function (camera) {
this._camera = camera;
};
Screen.prototype.pushResolutionAndViewport = function () {
this._resolutionStack.push(this.resolution);
this._viewportStack.push(this.viewport);
this.resolution = __assign({}, this.resolution);
this.viewport = __assign({}, this.viewport);
};
Screen.prototype.popResolutionAndViewport = function () {
this.resolution = this._resolutionStack.pop();
this.viewport = this._viewportStack.pop();
};
Screen.prototype.applyResolutionAndViewport = function () {
this._canvas.width = this.scaledWidth;
this._canvas.height = this.scaledHeight;
this._canvas.style.imageRendering = this._antialiasing ? 'auto' : 'pixelated';
this._canvas.style.width = this.viewport.width + 'px';
this._canvas.style.height = this.viewport.height + 'px';
// After messing with the canvas width/height the graphics context is invalidated and needs to have some properties reset
this._ctx.resetTransform();
this._ctx.scale(this.pixelRatio, this.pixelRatio);
this._ctx.imageSmoothingEnabled = this._antialiasing;
};
Object.defineProperty(Screen.prototype, "antialiasing", {
get: function () {
return this._antialiasing;
},
set: function (isSmooth) {
this._antialiasing = isSmooth;
this._ctx.imageSmoothingEnabled = this._antialiasing;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "isFullScreen", {
/**
* Returns true if excalibur is fullscreened using the browser fullscreen api
*/
get: function () {
return this._isFullScreen;
},
enumerable: false,
configurable: true
});
/**
* Requests to go fullscreen using the browser fullscreen api
*/
Screen.prototype.goFullScreen = function () {
var _this = this;
return this._canvas.requestFullscreen().then(function () {
_this._isFullScreen = true;
});
};
/**
* Requests to exit fullscreen using the browser fullscreen api
*/
Screen.prototype.exitFullScreen = function () {
var _this = this;
return document.exitFullscreen().then(function () {
_this._isFullScreen = false;
});
};
/**
* Transforms the current x, y from screen coordinates to world coordinates
* @param point Screen coordinate to convert
*/
Screen.prototype.screenToWorldCoordinates = function (point) {
var _a, _b, _c, _d;
var newX = point.x;
var newY = point.y;
// transform back to world space
newX = (newX / this.viewport.width) * this.drawWidth;
newY = (newY / this.viewport.height) * this.drawHeight;
// transform based on zoom
newX = newX - this.halfDrawWidth;
newY = newY - this.halfDrawHeight;
// shift by focus
newX += (_b = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : 0;
newY += (_d = (_c = this._camera) === null || _c === void 0 ? void 0 : _c.y) !== null && _d !== void 0 ? _d : 0;
return new Vector(Math.floor(newX), Math.floor(newY));
};
/**
* Transforms a world coordinate, to a screen coordinate
* @param point World coordinate to convert
*/
Screen.prototype.worldToScreenCoordinates = function (point) {
var _a, _b, _c, _d;
var screenX = point.x;
var screenY = point.y;
// shift by focus
screenX -= (_b = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : 0;
screenY -= (_d = (_c = this._camera) === null || _c === void 0 ? void 0 : _c.y) !== null && _d !== void 0 ? _d : 0;
// transform back on zoom
screenX = screenX + this.halfDrawWidth;
screenY = screenY + this.halfDrawHeight;
// transform back to screen space
screenX = (screenX * this.viewport.width) / this.drawWidth;
screenY = (screenY * this.viewport.height) / this.drawHeight;
return new Vector(Math.floor(screenX), Math.floor(screenY));
};
/**
* Returns a BoundingBox of the top left corner of the screen
* and the bottom right corner of the screen.
*/
Screen.prototype.getWorldBounds = function () {
var left = this.screenToWorldCoordinates(Vector.Zero).x;
var top = this.screenToWorldCoordinates(Vector.Zero).y;
var right = left + this.drawWidth;
var bottom = top + this.drawHeight;
return new BoundingBox(left, top, right, bottom);
};
Object.defineProperty(Screen.prototype, "canvasWidth", {
/**
* The width of the game canvas in pixels (physical width component of the
* resolution of the canvas element)
*/
get: function () {
return this.canvas.width;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "halfCanvasWidth", {
/**
* Returns half width of the game canvas in pixels (half physical width component)
*/
get: function () {
return this.canvas.width / 2;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "canvasHeight", {
/**
* The height of the game canvas in pixels, (physical height component of
* the resolution of the canvas element)
*/
get: function () {
return this.canvas.height;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "halfCanvasHeight", {
/**
* Returns half height of the game canvas in pixels (half physical height component)
*/
get: function () {
return this.canvas.height / 2;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "drawWidth", {
/**
* Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
if (this._camera) {
return this.scaledWidth / this._camera.z / this.pixelRatio;
}
return this.scaledWidth / this.pixelRatio;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "halfDrawWidth", {
/**
* Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.drawWidth / 2;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "drawHeight", {
/**
* Returns the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
if (this._camera) {
return this.scaledHeight / this._camera.z / this.pixelRatio;
}
return this.scaledHeight / this.pixelRatio;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Screen.prototype, "halfDrawHeight", {
/**
* Returns half the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.drawHeight / 2;
},
enumerable: false,
configurable: true
});
Screen.prototype._applyDisplayMode = function () {
if (this.displayMode === DisplayMode.FullScreen || this.displayMode === DisplayMode.Container) {
var parent_1 = (this.displayMode === DisplayMode.Container ? (this.canvas.parentElement || document.body) : window);
this._setHeightByDisplayMode(parent_1);
this._browser.window.on('resize', this._windowResizeHandler);
}
else if (this.displayMode === DisplayMode.Position) {
this._initializeDisplayModePosition(this._position);
}
};
/**
* Sets the internal canvas height based on the selected display mode.
*/
Screen.prototype._setHeightByDisplayMode = function (parent) {
if (this.displayMode === DisplayMode.Container) {
this.resolution = {
width: parent.clientWidth,
height: parent.clientHeight
};
this.viewport = this.resolution;
}
if (this.displayMode === DisplayMode.FullScreen) {
document.body.style.margin = '0px';
document.body.style.overflow = 'hidden';
this.resolution = {
width: parent.innerWidth,
height: parent.innerHeight
};
this.viewport = this.resolution;
}
};
Screen.prototype._initializeDisplayModePosition = function (position) {
if (!position) {
throw new Error('DisplayMode of Position was selected but no position option was given');
}
else {
this.canvas.style.display = 'block';
this.canvas.style.position = 'absolute';
if (typeof position === 'string') {
var specifiedPosition = position.split(' ');
switch (specifiedPosition[0]) {
case 'top':
this.canvas.style.top = '0px';
break;
case 'bottom':
this.canvas.style.bottom = '0px';
break;
case 'middle':
this.canvas.style.top = '50%';
var offsetY = -this.halfDrawHeight;
this.canvas.style.marginTop = offsetY.toString();
break;
default:
throw new Error('Invalid Position Given');
}
if (specifiedPosition[1]) {
switch (specifiedPosition[1]) {
case 'left':
this.canvas.style.left = '0px';
break;
case 'right':
this.canvas.style.right = '0px';
break;
case 'center':
this.canvas.style.left = '50%';
var offsetX = -this.halfDrawWidth;
this.canvas.style.marginLeft = offsetX.toString();
break;
default:
throw new Error('Invalid Position Given');
}
}
}
else {
if (position.top) {
typeof position.top === 'number'
? (this.canvas.style.top = position.top.toString() + 'px')
: (this.canvas.style.top = position.top);
}
if (position.right) {
typeof position.right === 'number'
? (this.canvas.style.right = position.right.toString() + 'px')
: (this.canvas.style.right = position.right);
}
if (position.bottom) {
typeof position.bottom === 'number'
? (this.canvas.style.bottom = position.bottom.toString() + 'px')
: (this.canvas.style.bottom = position.bottom);
}
if (position.left) {
typeof position.left === 'number'
? (this.canvas.style.left = position.left.toString() + 'px')
: (this.canvas.style.left = position.left);
}
}
}
};
return Screen;
}());
export { Screen };
//# sourceMappingURL=Screen.js.map
|
f9cf1a45bd7d0e57698ec069efda9c284ab44bf6
|
{
"blob_id": "f9cf1a45bd7d0e57698ec069efda9c284ab44bf6",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-23T07:12:24",
"content_id": "aba6d0f5f08f338cef7158e3f1b46ee6ae27dcb9",
"detected_licenses": [
"MIT"
],
"directory_id": "b970e053302588f44ee1c6b7187c4769934c857f",
"extension": "js",
"filename": "Screen.js",
"fork_events_count": 5633,
"gha_created_at": "2011-02-25T05:53:47",
"gha_event_created_at": "2023-06-27T12:32:50",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 1409811,
"is_generated": true,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 19752,
"license": "MIT",
"license_type": "permissive",
"path": "/ajax/libs/excalibur/0.25.0-alpha.6981/Screen.js",
"provenance": "stack-edu-0040.json.gz:412569",
"repo_name": "cdnjs/cdnjs",
"revision_date": "2023-07-23T07:12:24",
"revision_id": "6843ffa5339e4595b3a6893ae3e9ede1117cc5f9",
"snapshot_id": "2fe0f21477c08618fe609da844f5d133224c3eda",
"src_encoding": "UTF-8",
"star_events_count": 8894,
"url": "https://raw.githubusercontent.com/cdnjs/cdnjs/6843ffa5339e4595b3a6893ae3e9ede1117cc5f9/ajax/libs/excalibur/0.25.0-alpha.6981/Screen.js",
"visit_date": "2023-07-23T14:52:44.587645",
"added": "2024-11-19T02:05:20.347546+00:00",
"created": "2023-07-23T07:12:24",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz"
}
|
package commands
import (
"fmt"
"os"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/logging"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/model"
"github.com/authelia/authelia/v4/internal/server"
"github.com/authelia/authelia/v4/internal/utils"
)
// NewRootCmd returns a new Root Cmd.
func NewRootCmd() (cmd *cobra.Command) {
version := utils.Version()
cmd = &cobra.Command{
Use: "authelia",
Example: cmdAutheliaExample,
Short: fmt.Sprintf("authelia %s", version),
Long: fmt.Sprintf(fmtAutheliaLong, version),
Version: version,
Args: cobra.NoArgs,
PreRun: newCmdWithConfigPreRun(true, true, true),
Run: cmdRootRun,
}
cmdWithConfigFlags(cmd, false, []string{})
cmd.AddCommand(
newBuildInfoCmd(),
NewCertificatesCmd(),
newCompletionCmd(),
NewHashPasswordCmd(),
NewRSACmd(),
NewStorageCmd(),
newValidateConfigCmd(),
newAccessControlCommand(),
)
return cmd
}
func cmdRootRun(_ *cobra.Command, _ []string) {
logger := logging.Logger()
logger.Infof("Authelia %s is starting", utils.Version())
if os.Getenv("ENVIRONMENT") == "dev" {
logger.Info("===> Authelia is running in development mode. <===")
}
if err := logging.InitializeLogger(config.Log, true); err != nil {
logger.Fatalf("Cannot initialize logger: %v", err)
}
providers, warnings, errors := getProviders()
if len(warnings) != 0 {
for _, err := range warnings {
logger.Warn(err)
}
}
if len(errors) != 0 {
for _, err := range errors {
logger.Error(err)
}
logger.Fatalf("Errors occurred provisioning providers.")
}
doStartupChecks(config, &providers)
s, listener := server.CreateServer(*config, providers)
logger.Fatal(s.Serve(listener))
}
func doStartupChecks(config *schema.Configuration, providers *middlewares.Providers) {
logger := logging.Logger()
var (
failures []string
err error
)
if err = doStartupCheck(logger, "storage", providers.StorageProvider, false); err != nil {
logger.Errorf("Failure running the storage provider startup check: %+v", err)
failures = append(failures, "storage")
}
if err = doStartupCheck(logger, "user", providers.UserProvider, false); err != nil {
logger.Errorf("Failure running the user provider startup check: %+v", err)
failures = append(failures, "user")
}
if err = doStartupCheck(logger, "notification", providers.Notifier, config.Notifier.DisableStartupCheck); err != nil {
logger.Errorf("Failure running the notification provider startup check: %+v", err)
failures = append(failures, "notification")
}
if !config.NTP.DisableStartupCheck && !providers.Authorizer.IsSecondFactorEnabled() {
logger.Debug("The NTP startup check was skipped due to there being no configured 2FA access control rules")
} else if err = doStartupCheck(logger, "ntp", providers.NTP, config.NTP.DisableStartupCheck); err != nil {
logger.Errorf("Failure running the user provider startup check: %+v", err)
if !config.NTP.DisableFailure {
failures = append(failures, "ntp")
}
}
if len(failures) != 0 {
logger.Fatalf("The following providers had fatal failures during startup: %s", strings.Join(failures, ", "))
}
}
func doStartupCheck(logger *logrus.Logger, name string, provider model.StartupCheck, disabled bool) error {
if disabled {
logger.Debugf("%s provider: startup check skipped as it is disabled", name)
return nil
}
if provider == nil {
return fmt.Errorf("unrecognized provider or it is not configured properly")
}
return provider.StartupCheck()
}
|
396727cdc30aa8d162dcab6c78272fc612c4bfb7
|
{
"blob_id": "396727cdc30aa8d162dcab6c78272fc612c4bfb7",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-22T03:27:02",
"content_id": "d64e99c2cbcec7b95cc7e1de6924d446b6f2bb8f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e05ce052a122ec3fe9b6b05ac66e6df0f47d1f6b",
"extension": "go",
"filename": "root.go",
"fork_events_count": 0,
"gha_created_at": "2020-04-15T23:22:22",
"gha_event_created_at": "2020-04-15T23:22:23",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 256059209,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3690,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/internal/commands/root.go",
"provenance": "stack-edu-0016.json.gz:201695",
"repo_name": "jystadj/authelia",
"revision_date": "2022-05-22T03:27:02",
"revision_id": "89bcf133aef868b6a7810ee4c466527ef9d5daf2",
"snapshot_id": "1bb2e83b1ba3d0607f5b72ae4039c68b35757e9d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jystadj/authelia/89bcf133aef868b6a7810ee4c466527ef9d5daf2/internal/commands/root.go",
"visit_date": "2022-07-30T21:12:55.909970",
"added": "2024-11-18T21:56:47.067684+00:00",
"created": "2022-05-22T03:27:02",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
<!---
~~ 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. See accompanying LICENSE file.
-->
# Building Hoya
Hoya is currently built with some unreleased Apache Artifacts, because it
uses Hadoop 2.1 and needs a version of HBase built against that.
Here's how to set this up.
## Before you begin
You will need a version of Maven 3.0, set up with enough memory
MAVEN_OPTS=-Xms256m -Xmx512m -Djava.awt.headless=true
*Important*: As of September 10, 2013, Maven 3.1 is not supported due to
[version issues](https://cwiki.apache.org/confluence/display/MAVEN/AetherClassNotFound).
## Building a compatible Hadoop version
During development, Hoya is built against a local version of Hadoop branch 2.1.x,
so that we can find and fix bugs in Hadoop as well in Hoya.
It will fall back to downloading the `-SNAPSHOT` artifacts from the ASF snapshot
repository
To build and install locally, check out apache svn/github, branch `2.1-beta`
Build and install it locally, skipping the tests:
mvn install -DskipTests
You have to do this every morning to avoid the ASF nightly artifacts being picked up/
To make a tarball for use in test runs:
#On osx
mvn clean package -Pdist -Dtar -DskipTests -Dmaven.javadoc.skip=true
# on linux
mvn package -Pdist -Pnative -Dtar -DskipTests -Dmaven.javadoc.skip=true
Then expand this
pushd hadoop-dist/target/
gunzip hadoop-2.1.2-SNAPSHOT.tar.gz
tar -xvf hadoop-2.1.2-SNAPSHOT.tar
popd
## building a compatible HBase version
Checkout the HBase `hbase-0.95` branch from apache svn/github.
git clone git://git.apache.org/hbase.git
git remote rename origin apache
The maven command for building hbase artifacts against this hadoop version is
mvn clean install assembly:single -DskipTests -Dmaven.javadoc.skip=true -Dhadoop.profile=2.0 -Dhadoop-two.version=2.1.2-SNAPSHOT
For building just the JAR files:
mvn clean install -DskipTests -Dhadoop.profile=2.0 -Dhadoop-two.version=2.1.2-beta
This will create `hbase-0.97.0-SNAPSHOT.tar.gz` in the directory `hbase-assembly/target/` in
the hbase source tree.
pushd hbase-assembly/target
gunzip hbase-0.97.0-SNAPSHOT-bin.tar.gz
tar -xvf hbase-0.97.0-SNAPSHOT-bin.tar
popd
This will create an untarred directory `hbase-0.97.0-SNAPSHOT-bin` containing
hbase. Both the `.tar.gz` and untarred file are needed for testing. Most
tests just work directly with the untarred file as it saves time uploading
and downloading then expanding the file.
For more information (including recommended Maven memory configuration options),
see [HBase building](http://hbase.apache.org/book/build.html)
*Tip:* you can force set a version in Maven by having it update all the POMs:
mvn versions:set -DnewVersion=0.97.1-SNAPSHOT
## Building Accumulo
In the accumulo project directory:
mvn clean install -DskipTests
mvn package -Passemble -DskipTests -Dhadoop.profile=2.0 -Dmaven.javadoc.skip=true
This creates an accumulo tar.gz file in `assemble/target/`. Unzip then untar
this, to create a .tar file and an expanded directory
accumulo/assemble/target/accumulo-1.6.0-SNAPSHOT-bin.tar
This can be done with the command sequence
pushd assemble/target/
gunzip -f accumulo-1.6.0-SNAPSHOT-bin.tar.gz
tar -xvf accumulo-1.6.0-SNAPSHOT-bin.tar
popd
## Testing
### Configuring Hoya to locate the relevant artifacts
You must have the file `src/test/resources/hoya-test.xml` (this
is ignored by git), declaring where HBase is:
<configuration>
<property>
<name>hoya.test.hbase.home</name>
<value>/Users/hoya/hbase/hbase-assembly/target/hbase-0.97.0-SNAPSHOT</value>
<description>HBASE Home</description>
</property>
<property>
<name>hoya.test.hbase.tar</name>
<value>/Users/hoya/hbase/hbase-assembly/target/hbase-0.97.0-SNAPSHOT-bin.tar.gz</value>
<description>HBASE archive URI</description>
</property>
<property>
<name>hoya.test.accumulo_home</name>
<value>/Users/hoya/hbase/hbase-assembly/target/accumulo-1.6.0-SNAPSHOT-bin.tar</value>
<description>HBASE Home</description>
</property>
<property>
<name>hoya.test.accumulo_tar</name>
<value>/Users/hoya/accumulo/assemble/target/accumulo-1.6.0-SNAPSHOT-bin.tar.gz</value>
<description>HBASE archive URI</description>
</property>
<property>
<name>zk.home</name>
<value>
/Users/hoya/Apps/zookeeper</value>
<description>Zookeeper home dir on target systems</description>
</property>
<property>
<name>hadoop.home</name>
<value>
/Users/hoya/hadoop-trunk/hadoop-dist/target/hadoop-2.1.2-SNAPSHOT</value>
<description>Hadoop home dir on target systems</description>
</property>
</configuration>
## Debugging a failing test
1. Locate the directory `target/$TESTNAME` where TESTNAME is the name of the
test case and or test method. This directory contains the Mini YARN Cluster
logs. For example, `TestLiveRegionService` stores its data under
`target/TestLiveRegionService`
1. Look under that directory for `-logdir` directories, then an application
and container containing logs. There may be more than node being simulated;
every node manager creates its own logdir.
1. Look for the `out.txt` and `err.txt` files for stdout and stderr log output.
1. Hoya uses SLF4J to log to `out.txt`; remotely executed processes may use
either stream for logging
Example:
target/TestLiveRegionService/TestLiveRegionService-logDir-nm-1_0/application_1376095770244_0001/container_1376095770244_0001_01_000001/out.txt
1. The actual test log from JUnit itself goes to the console and into
`target/surefire/`; this shows the events happening in the YARN services as well
as (if configured) HDFS and Zookeeper. It is noisy -everything after the *teardown*
message happens during cluster teardown, after the test itself has been completed.
Exceptions and messages here can generally be ignored.
This is all a bit complicated -debugging is simpler if a single test is run at a
time, which is straightforward
mvn clean test -Dtest=TestLiveRegionService
### Building the JAR file
You can create the JAR file and set up its directories with
mvn package -DskipTests
This copies all the dependencies to `target/lib`. The JAR has a manifest set
to pull this in, so you can just go `java -jar target/hoya-0.3-SNAPSHOT.jar org.apache.hadoop.hoya.Hoya`
## Attn OS/X developers
YARN on OS/X doesn't terminate subprocesses the way it does on Linux, so
HBase Region Servers created by the hbase shell script remain running
even after the tests terminate.
This causes some tests -especially those related to flexing down- to fail,
and test reruns may be very confused. If ever a test fails because there
are too many region servers running, this is the likely cause
After every test run: do a `jps -v` to look for any leftover HBase services
-and kill them.
Here is a handy bash command to do this
jps -l | grep HRegion | awk '{print $1}' | xargs kill -9
# Notes
Hoya uses Groovy 2.x as its language for writing tests -for better assertions
and easier handling of lists and closures. Although the first prototype
used Groovy on the production source, this has been dropped in favor of
a Java-only codebase. We do still push up `groovyall.jar` to the classpath
of the HoyaAM.
|
3d84c2a179a778914192251efdcbbcd9b13b26de
|
{
"blob_id": "3d84c2a179a778914192251efdcbbcd9b13b26de",
"branch_name": "refs/heads/master",
"committer_date": "2013-09-30T10:03:44",
"content_id": "d61d3a049ad700d36f8894cfce1da66fcfb08ecb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "81388f9ff9677db8d64bb1029bb414cf9e5e11f1",
"extension": "md",
"filename": "building.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": 8041,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/site/md/building.md",
"provenance": "stack-edu-markdown-0013.json.gz:194707",
"repo_name": "roshanp/hoya",
"revision_date": "2013-09-30T10:03:44",
"revision_id": "c25dd6c1d49a4a79d67e4d7a2cf2ca07d035f4ce",
"snapshot_id": "6cec64712700d979063d7880fab931cb036b0126",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/roshanp/hoya/c25dd6c1d49a4a79d67e4d7a2cf2ca07d035f4ce/src/site/md/building.md",
"visit_date": "2021-01-19T10:20:01.067803",
"added": "2024-11-19T01:34:09.757845+00:00",
"created": "2013-09-30T10:03:44",
"int_score": 4,
"score": 3.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz"
}
|
import {
createStore, combineReducers, applyMiddleware, compose,
} from 'redux';
import { connectRouter, routerMiddleware } from 'connected-react-router';
import { createLogger } from 'redux-logger';
import freeze from 'redux-freeze';
// import thunk from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import history from '../../utils/history';
import * as rootReducer from '../reducers/index';
import saga from '../sagas';
const sagaMiddleware = createSagaMiddleware();
// 1. 配置 middleware 中间件; 因 store已区分环境, 所以不需要在单独抽出 middleware 单独作为模块(避免二次判断环境)
const middleware = [
routerMiddleware(history), // router-redux配置 history
// thunk, // 异步
sagaMiddleware, // 异步
freeze, // 如果 state在其他地方改变, 会跳出错误
createLogger(), // 调试日志
];
// 2. 配置 enhancer 增强器; 使用多个 store enhancer, 要使用 compose() 方法
const enhancer = compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), // 必须在 middleware 之后
);
// 3. 配置 combine: 组合 redux 与 router
const combine = combineReducers({
...rootReducer,
router: connectRouter(history),
});
// 4. 配置 store; 判断 dev环境下浏览器是否配有 redux-devtools 工具
const configureStore = (initialState) => {
let store;
if (!(window.__REDUX_DEVTOOLS_EXTENSION__ || window.__REDUX_DEVTOOLS_EXTENSION__)) {
store = createStore(
combine,
initialState,
applyMiddleware(...middleware),
);
} else {
store = createStore(
combine,
initialState,
enhancer,
);
}
// 启动saga中间件
sagaMiddleware.run(saga);
return store;
};
export { configureStore, history };
|
64d3f0fc21a4ee7099d99b02b4abb45de7308365
|
{
"blob_id": "64d3f0fc21a4ee7099d99b02b4abb45de7308365",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-29T04:30:16",
"content_id": "ab1c5f6bc7af93d5f36606a2777841dbb7be237b",
"detected_licenses": [
"MIT"
],
"directory_id": "c6803fd3d6f645a3e48eafdc84f29eb5745d8ce2",
"extension": "js",
"filename": "store.test.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1814,
"license": "MIT",
"license_type": "permissive",
"path": "/src/redux/store/store.test.js",
"provenance": "stack-edu-0042.json.gz:430161",
"repo_name": "delta94/react-antd-admin",
"revision_date": "2019-07-29T04:30:16",
"revision_id": "1414ebe14ed877ff92a1bb620d0d79b2688455b1",
"snapshot_id": "65c26cf4cbf5e4532c0fcc05de904763297ae044",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/delta94/react-antd-admin/1414ebe14ed877ff92a1bb620d0d79b2688455b1/src/redux/store/store.test.js",
"visit_date": "2022-12-11T04:24:06.156012",
"added": "2024-11-19T01:53:55.633167+00:00",
"created": "2019-07-29T04:30:16",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz"
}
|
# 👨💻 Git a Dev 👩💻
[](https://opensource.org/licenses/MIT)
[](http://hits.dwyl.com/jonathannsegal/git_a_dev)

A developer recruitment tool where you can filter by language, location, and skill level.
## Overview 🗺️
- `pages/*` - Home, direct to other pages.
- `pages/insight` - Data based on your GitHub profile to optimize it for recruiters.
- `pages/search` - Search for developers with set parameters.
## Running Locally 💻
```bash
$ git clone https://github.com/Jonathannsegal/git_a_dev.git
$ cd git_a_dev
$ yarn
$ yarn dev
```
Create a `.env.local` file similar to `.env`.
```
GH_TOKEN=
```
This token is used to call the github API to get profile information.
## HackISU 🏆
Won best domain name at HACKISU
# [Devpost Page](https://devpost.com/software/hack-isu-2019-recruiter) 👨💻
<img height="200px" src="https://drive.google.com/uc?id=1hpT7o5Y-DrPEN8JZvt5AdZJ5hdFzEiiq"/>
*The Team*
|
d561d1744cc161accdccb02e53a5d70c8271000a
|
{
"blob_id": "d561d1744cc161accdccb02e53a5d70c8271000a",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-07T03:22:59",
"content_id": "eb497b66be86e24e5de038c6dd7c8dae97e31b24",
"detected_licenses": [
"MIT"
],
"directory_id": "89307d5a5eafd672dbee8e083053f02ebacaa2e4",
"extension": "md",
"filename": "README.md",
"fork_events_count": 1,
"gha_created_at": "2019-11-02T01:52:18",
"gha_event_created_at": "2022-02-12T17:06:43",
"gha_language": "JavaScript",
"gha_license_id": null,
"github_id": 219089524,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1148,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0011.json.gz:339722",
"repo_name": "jjroush/hack-isu-2019-recruiter",
"revision_date": "2020-07-07T03:22:59",
"revision_id": "9120866dcd6d9f54d0a58d1518101c31bb3a876a",
"snapshot_id": "87e7fa10f4950a4b0325eac3cc60fc4651bf9a86",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jjroush/hack-isu-2019-recruiter/9120866dcd6d9f54d0a58d1518101c31bb3a876a/README.md",
"visit_date": "2022-02-22T21:13:40.033027",
"added": "2024-11-19T00:08:44.636351+00:00",
"created": "2020-07-07T03:22:59",
"int_score": 3,
"score": 3.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0011.json.gz"
}
|
angular
.module('ionweather.search', [])
.controller('SearchCtrl', function($scope, $http){
$scope.queryChanged = _.debounce(function(){
$http
.get('https://maps.googleapis.com/maps/api/geocode/json', {
params: {address: $scope.query}
})
.success(function(data) {
$scope.cities = data.results;
console.log(data)
});
}, 2000)
})
|
895e40d7d7324949abddd6d9b9cb5a28b16a9778
|
{
"blob_id": "895e40d7d7324949abddd6d9b9cb5a28b16a9778",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-15T22:22:38",
"content_id": "ee962bff0637e72ddf26bdc1f42e3ce4614867a3",
"detected_licenses": [
"MIT"
],
"directory_id": "6e066ee60fd230eb290602f0f3780d6726179042",
"extension": "js",
"filename": "search.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 39081059,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 371,
"license": "MIT",
"license_type": "permissive",
"path": "/www/templates/search/search.js",
"provenance": "stack-edu-0031.json.gz:820404",
"repo_name": "bmacheski/ion-weather",
"revision_date": "2015-07-15T22:22:38",
"revision_id": "b41ab50e50672af784c89c114b6b31fdb77ab897",
"snapshot_id": "9381837adf958f6bdeaf730a20ad208ec4548470",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bmacheski/ion-weather/b41ab50e50672af784c89c114b6b31fdb77ab897/www/templates/search/search.js",
"visit_date": "2021-01-13T01:44:24.730596",
"added": "2024-11-19T00:16:20.691366+00:00",
"created": "2015-07-15T22:22:38",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
from collections import OrderedDict
from anytree import LevelOrderIter, findall
from devito.ir.stree.tree import (ScheduleTree, NodeIteration, NodeConditional,
NodeExprs, NodeSection, NodeHalo, insert)
from devito.ir.support.space import IterationSpace
from devito.mpi import HaloScheme, HaloSchemeException
from devito.parameters import configuration
from devito.tools import flatten
__all__ = ['st_build']
def st_build(clusters):
"""
Create a :class:`ScheduleTree` from a :class:`ClusterGroup`.
"""
# ClusterGroup -> Schedule tree
stree = st_schedule(clusters)
# Add in section nodes
stree = st_section(stree)
# Add in halo update nodes
stree = st_make_halo(stree)
return stree
def st_schedule(clusters):
"""
Arrange an iterable of :class:`Cluster`s into a :class:`ScheduleTree`.
"""
stree = ScheduleTree()
mapper = OrderedDict()
for c in clusters:
pointers = list(mapper)
# Find out if any of the existing nodes can be reused
index = 0
root = stree
for it0, it1 in zip(c.itintervals, pointers):
if it0 != it1 or it0.dim in c.atomics:
break
root = mapper[it0]
index += 1
if it0.dim in c.guards:
break
# The reused sub-trees might acquire some new sub-iterators
for i in pointers[:index]:
mapper[i].ispace = IterationSpace.merge(mapper[i].ispace, c.ispace)
# Later sub-trees, instead, will not be used anymore
for i in pointers[index:]:
mapper.pop(i)
# Add in Iterations
for i in c.itintervals[index:]:
root = NodeIteration(c.ispace.project([i.dim]), root)
mapper[i] = root
# Add in Expressions
NodeExprs(c.exprs, c.shape, c.ops, c.traffic, root)
# Add in Conditionals
for k, v in mapper.items():
if k.dim in c.guards:
node = NodeConditional(c.guards[k.dim])
v.last.parent = node
node.parent = v
return stree
def st_make_halo(stree):
"""
Add :class:`NodeHalo` to a :class:`ScheduleTree`. A halo node describes
what halo exchanges should take place before executing the sub-tree.
"""
if not configuration['mpi']:
# TODO: This will be dropped as soon as stronger analysis will have
# been implemented
return stree
processed = {}
for n in LevelOrderIter(stree, stop=lambda i: i.parent in processed):
if not n.is_Iteration:
continue
exprs = flatten(i.exprs for i in findall(n, lambda i: i.is_Exprs))
try:
halo_scheme = HaloScheme(exprs)
if n.dim in halo_scheme.dmapper:
processed[n] = NodeHalo(halo_scheme)
except HaloSchemeException:
# We should get here only when trying to compute a halo
# scheme for a group of expressions that belong to different
# iteration spaces. We expect proper halo schemes to be built
# as the `stree` visit proceeds.
# TODO: However, at the end, we should check that a halo scheme,
# possibly even a "void" one, has been built for *all* of the
# expressions, and error out otherwise.
continue
except RuntimeError as e:
if configuration['mpi'] is True:
raise RuntimeError(str(e))
for k, v in processed.items():
insert(v, k.parent, [k])
return stree
def st_section(stree):
"""
Add :class:`NodeSection` to a :class:`ScheduleTree`. A section defines a
sub-tree with the following properties: ::
* The root is a node of type :class:`NodeSection`;
* The immediate children of the root are nodes of type :class:`NodeIteration`
and have same parent.
* The :class:`Dimension` of the immediate children are either: ::
* identical, OR
* different, but all of type :class:`SubDimension`;
* The :class:`Dimension` of the immediate children cannot be a
:class:`TimeDimension`.
"""
class Section(object):
def __init__(self, node):
self.parent = node.parent
self.dim = node.dim
self.nodes = [node]
def is_compatible(self, node):
return (self.parent == node.parent
and (self.dim == node.dim or node.dim.is_Sub))
# Search candidate sections
sections = []
for i in range(stree.height):
# Find all sections at depth `i`
section = None
for n in findall(stree, filter_=lambda n: n.depth == i):
if any(p in flatten(s.nodes for s in sections) for p in n.ancestors):
# Already within a section
continue
elif not n.is_Iteration or n.dim.is_Time:
section = None
elif section is None or not section.is_compatible(n):
section = Section(n)
sections.append(section)
else:
section.nodes.append(n)
# Transform the schedule tree by adding in sections
for i in sections:
insert(NodeSection(), i.parent, i.nodes)
return stree
|
82e7666bad89331504bd4dc499b0e761b7d5ef85
|
{
"blob_id": "82e7666bad89331504bd4dc499b0e761b7d5ef85",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-13T18:07:48",
"content_id": "46902e43180ec55f6b69d6a705c74219b2d8ee2a",
"detected_licenses": [
"MIT"
],
"directory_id": "91c6facacb2f1f8203652c1744d85f073d69f4e0",
"extension": "py",
"filename": "algorithms.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": 5321,
"license": "MIT",
"license_type": "permissive",
"path": "/devito/ir/stree/algorithms.py",
"provenance": "stack-edu-0061.json.gz:13231",
"repo_name": "tccw/devito",
"revision_date": "2018-08-13T18:07:48",
"revision_id": "d2e5f7c89a1440a0d530c5e4058f5b9c6b3f896e",
"snapshot_id": "0eae295bf13dd6e8074e1ba37cf8bcf8134efce5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tccw/devito/d2e5f7c89a1440a0d530c5e4058f5b9c6b3f896e/devito/ir/stree/algorithms.py",
"visit_date": "2020-03-27T06:44:51.831107",
"added": "2024-11-18T20:49:40.984712+00:00",
"created": "2018-08-13T18:07:48",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
from time import sleep
from gym.monitoring.demonstrations import DemonstrationReader
from gym.envs.classic_control import rendering
if __name__ == '__main__':
reader = DemonstrationReader('/tmp/atari.demo')
for action, observation in reader:
print(action)
# Render observation
viewer = rendering.SimpleImageViewer()
viewer.imshow(observation)
sleep(0.01)
|
0100386d97789ee8574d7334e876e8f5dfb8307e
|
{
"blob_id": "0100386d97789ee8574d7334e876e8f5dfb8307e",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-21T16:54:36",
"content_id": "bd8b45315ca4e1802e30eb67460da3ff0a025134",
"detected_licenses": [
"MIT"
],
"directory_id": "0d3afaa645c9ed7cacfebce1ec9c8fd27907fcf0",
"extension": "py",
"filename": "replay_demonstration.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": 407,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/utilities/replay_demonstration.py",
"provenance": "stack-edu-0059.json.gz:510832",
"repo_name": "dvcanton/gym",
"revision_date": "2016-08-21T16:54:36",
"revision_id": "ab015249b561bc8b5b43fc4d63f9752a282e41f0",
"snapshot_id": "c61ee401086cb7c2f438496622c7c0533ec75d92",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dvcanton/gym/ab015249b561bc8b5b43fc4d63f9752a282e41f0/examples/utilities/replay_demonstration.py",
"visit_date": "2021-01-13T02:31:05.819921",
"added": "2024-11-19T01:57:16.250607+00:00",
"created": "2016-08-21T16:54:36",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.jhuapl.dorset;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.jhuapl.dorset.agent.Agent;
import edu.jhuapl.dorset.agent.AgentRegistry;
import edu.jhuapl.dorset.agent.AgentRequest;
import edu.jhuapl.dorset.agent.AgentResponse;
import edu.jhuapl.dorset.agent.RegistryEntry;
import edu.jhuapl.dorset.record.NullRecorder;
import edu.jhuapl.dorset.record.Record;
import edu.jhuapl.dorset.record.Recorder;
import edu.jhuapl.dorset.routing.Router;
/**
* Dorset Application
*
*/
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
protected AgentRegistry agentRegistry;
protected Router router;
protected Recorder recorder;
private static Application app;
/**
* Create a Dorset application
*
* Uses a null recorder that ignores new records.
*
* @param agentRegistry registry of the agents available to the app
* @param router a router that finds the appropriate agent for a request
*/
public Application(AgentRegistry agentRegistry, Router router) {
this(agentRegistry, router, new NullRecorder());
}
/**
* Create a Dorset application
* @param agentRegistry registry of the agents available to the app
* @param router a router that finds the appropriate agent for a request
* @param recorder a recorder which logs request handling
*/
public Application(AgentRegistry agentRegistry, Router router, Recorder recorder) {
this.agentRegistry = agentRegistry;
this.router = router;
this.recorder = recorder;
router.initialize(agentRegistry);
}
/**
* Get the active agents in the registry
* @return array of Agent objects
*/
public Agent[] getAgents() {
Collection<RegistryEntry> entries = agentRegistry.asMap().values();
Agent[] agents = new Agent[entries.size()];
int index = 0;
for (RegistryEntry entry : entries) {
agents[index] = entry.getAgent();
index++;
}
return agents;
}
/**
* Process a request
* @param request Request object
* @return Response object
*/
public Response process(Request request) {
logger.info("Processing request: " + request.getText());
Response response = new Response("no response");
Record record = new Record(request);
long startTime = System.nanoTime();
Agent[] agents = router.getAgents(request);
record.setRouteTime(startTime, System.nanoTime());
record.setAgents(agents);
if (agents.length == 0) {
return response;
}
startTime = System.nanoTime();
for (Agent agent : agents) {
AgentResponse agentResponse = agent.process(new AgentRequest(request.getText()));
if (agentResponse != null) {
// take first answer
response.setText(agentResponse.text);
record.setSelectedAgent(agent);
record.setResponse(response);
break;
}
}
record.setAgentTime(startTime, System.nanoTime());
return response;
}
/**
* Set the shared application object
*
* This is useful for web-based use cases.
*
* @param app Application object
*/
public static void setApplication(Application app) {
logger.info("Registering dorset application");
Application.app = app;
}
/**
* Get the shared application object
* @return Application object
*/
public static Application getApplication() {
return Application.app;
}
}
|
359c0ca0088e70f5d1db0b5ba4a41aaa4e79fbee
|
{
"blob_id": "359c0ca0088e70f5d1db0b5ba4a41aaa4e79fbee",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-03T18:36:32",
"content_id": "85407b2cd8bd96a27100f579fcaba6783d2dc193",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6c9dc3f85b20698262fb21bea10d15be348fe0ae",
"extension": "java",
"filename": "Application.java",
"fork_events_count": 0,
"gha_created_at": "2016-01-27T14:32:10",
"gha_event_created_at": "2016-01-27T14:32:11",
"gha_language": null,
"gha_license_id": null,
"github_id": 50513104,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4416,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/core/src/main/java/edu/jhuapl/dorset/Application.java",
"provenance": "stack-edu-0025.json.gz:123328",
"repo_name": "cabishop/dorset-framework",
"revision_date": "2016-02-03T18:36:32",
"revision_id": "4c69bd0cfe28db393495a7a504aa22e41147c81d",
"snapshot_id": "28536170c651201204cf59c6c5c635bda2e27799",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cabishop/dorset-framework/4c69bd0cfe28db393495a7a504aa22e41147c81d/core/src/main/java/edu/jhuapl/dorset/Application.java",
"visit_date": "2020-04-14T01:10:20.513181",
"added": "2024-11-18T21:49:58.975022+00:00",
"created": "2016-02-03T18:36:32",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using ZooKeeperNet;
using Curator;
using CuratorClient;
namespace Curator.NET.Test
{
/**
* <p>
* Utility to simulate a ZK session dying. See: <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4">ZooKeeper FAQ</a>
* </p>
*
* <blockquote>
* In the case of testing we want to cause a problem, so to explicitly expire a session an
* application connects to ZooKeeper, saves the session id and password, creates another
* ZooKeeper handle with that id and password, and then closes the new handle. Since both
* handles reference the same session, the close on second handle will invalidate the session
* causing a SESSION_EXPIRED on the first handle.
* </blockquote>
*/
public class KillSession
{
/**
* Kill the given ZK session
*
* @param client the client to kill
* @param connectString server connection string
* @throws Exception errors
*/
public static void kill(IZooKeeper client, String connectString)
{
kill(client, connectString, new Timing().forWaiting().milliseconds());
}
/**
* Kill the given ZK session
*
* @param client the client to kill
* @param connectString server connection string
* @param maxMs max time ms to wait for kill
* @throws Exception errors
*/
public static void kill(IZooKeeper client, String connectString, int maxMs)
{
System.Diagnostics.Debug.WriteLine ("Kill Start");
long startTicks = (long)TimeSpan.FromTicks(System.DateTime.Now.Ticks).TotalMilliseconds;
var sessionLostLatch = new AutoResetEvent(false);
IWatcher sessionLostWatch = new CuratorWatcher((e)=> { if(e.State == KeeperState.Expired) sessionLostLatch.Set();});
client.Exists("/___CURATOR_KILL_SESSION___" + System.DateTime.Now.Ticks, sessionLostWatch);
var connectionLatch = new AutoResetEvent(false);
var connectionWatcher = new CuratorWatcher((e)=> {
if(e.State == KeeperState.SyncConnected){
connectionLatch.Set();
}
});
IZooKeeper zk = new ZooKeeper(connectString, TimeSpan.FromMilliseconds(maxMs), connectionWatcher, client.SessionId, client.SesionPassword);
try
{
if ( !connectionLatch.WaitOne(maxMs) )
{
throw new Exception("KillSession could not establish duplicate session");
}
try
{
zk.Dispose();
}
finally
{
zk = null;
}
while ( client.State.IsAlive() && !sessionLostLatch.WaitOne(100) )
{
long elapsed = (long)TimeSpan.FromTicks(System.DateTime.Now.Ticks).TotalMilliseconds - startTicks;
if ( elapsed > maxMs )
{
throw new Exception("KillSession timed out waiting for session to expire");
}
}
}
finally
{
if ( zk != null )
{
zk.Dispose();
}
}
System.Diagnostics.Debug.WriteLine ("Kill End");
}
}
}
|
333873d904e2bae9616446d3a96a3f333a5e3fef
|
{
"blob_id": "333873d904e2bae9616446d3a96a3f333a5e3fef",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-30T05:27:26",
"content_id": "48eac5c83d22ef7e3b691595ed6e05257a5121ea",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ddb47e817ad2184486d6147e63b07923e0eacc74",
"extension": "cs",
"filename": "KillSession.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 40998600,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3468,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/curator-client/src/dotnet/CuratorClient.Net/Curator-Client.Test/KillSession.cs",
"provenance": "stack-edu-0012.json.gz:23434",
"repo_name": "yepuv1/curator.net",
"revision_date": "2015-08-30T05:27:26",
"revision_id": "041085cb8e750d3a09da5643c5b36a3e22050ad1",
"snapshot_id": "b7326d85936bb484b848c0ea801cdb8416f9b7e7",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/yepuv1/curator.net/041085cb8e750d3a09da5643c5b36a3e22050ad1/curator-client/src/dotnet/CuratorClient.Net/Curator-Client.Test/KillSession.cs",
"visit_date": "2021-01-17T23:11:43.596717",
"added": "2024-11-19T00:38:21.242819+00:00",
"created": "2015-08-30T05:27:26",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
# Borrowed from https://github.com/xunhuang1995/AdaIN-style/
# The VGG-19 network is obtained by:
# 1. converting vgg_normalised.caffemodel to .t7 using loadcaffe
# 2. inserting a convolutional module at the beginning to preprocess the image
# 3. replacing zero-padding with reflection-padding
# The original vgg_normalised.caffemodel can be obtained with:
# "wget -c --no-check-certificate https://bethgelab.org/media/uploads/deeptextures/vgg_normalised.caffemodel"
cd models
wget -c -O vgg_normalised.t7 "https://www.dropbox.com/s/kh8izr3fkvhitfn/vgg_normalised.t7?dl=1"
cd ..
|
3931411dbbf20890b66efe181872b490c847ea55
|
{
"blob_id": "3931411dbbf20890b66efe181872b490c847ea55",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-19T01:03:24",
"content_id": "d7a972b8330630f71d96d0adafdf9a2085e2e3f7",
"detected_licenses": [
"MIT"
],
"directory_id": "23aeb6355f3f00634d9e61d5fbcb86737a047156",
"extension": "sh",
"filename": "download_vgg.sh",
"fork_events_count": 1,
"gha_created_at": "2018-07-29T00:12:56",
"gha_event_created_at": "2018-07-29T00:12:56",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 142718574,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 579,
"license": "MIT",
"license_type": "permissive",
"path": "/models/download_vgg.sh",
"provenance": "stack-edu-0070.json.gz:202851",
"repo_name": "kobykotiv/WCT-TF",
"revision_date": "2018-11-19T01:03:24",
"revision_id": "ff7a95d930c19d5b19140979db537131b95bf51c",
"snapshot_id": "0b02221839204a48c80b350530e6a0e2dddb7491",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kobykotiv/WCT-TF/ff7a95d930c19d5b19140979db537131b95bf51c/models/download_vgg.sh",
"visit_date": "2020-03-24T12:35:47.556183",
"added": "2024-11-19T01:15:43.297481+00:00",
"created": "2018-11-19T01:03:24",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz"
}
|
/*
The MIT License (MIT)
Copyright (c) 2017 Savoury SnaX
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
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;
using RemoteDebugger.Properties;
namespace RemoteDebugger
{
public partial class Settings : Form
{
public Settings()
{
InitializeComponent();
// Load settings
remoteAddress.Text = Properties.Settings.Default.remoteAddress;
remotePort.Minimum = 1;
remotePort.Maximum = 65535;
remotePort.Increment = 1;
remotePort.Value = Properties.Settings.Default.remotePort;
}
private void clickCancel(object sender, EventArgs e)
{
Close();
}
private void clickOk(object sender, EventArgs e)
{
Properties.Settings.Default.remoteAddress = remoteAddress.Text;
Properties.Settings.Default.remotePort = (int)remotePort.Value;
Properties.Settings.Default.Save();
Program.telnetConnection.UpdateSettings(Properties.Settings.Default.remoteAddress, Properties.Settings.Default.remotePort);
Close();
}
}
}
|
624ea757d8aaf04c1f9c019b373f45e74c27d89e
|
{
"blob_id": "624ea757d8aaf04c1f9c019b373f45e74c27d89e",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-20T10:35:03",
"content_id": "a2eb51b5b944224d0b6be819ef26f7225016aa59",
"detected_licenses": [
"MIT"
],
"directory_id": "0cca943ffc8e9a08643c05403e93a18d1be454ce",
"extension": "cs",
"filename": "Settings.cs",
"fork_events_count": 0,
"gha_created_at": "2018-09-14T18:06:25",
"gha_event_created_at": "2018-09-14T18:06:25",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 148824926,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2417,
"license": "MIT",
"license_type": "permissive",
"path": "/RemoteDebugger/Dialogs/Settings.cs",
"provenance": "stack-edu-0013.json.gz:685065",
"repo_name": "Ckirby101/Remote-Debugger",
"revision_date": "2019-09-20T10:35:03",
"revision_id": "12a2c8b848330e41a94a9757636359a0e01def3a",
"snapshot_id": "2c47ec9e0ec256f89082dc877855b8b8718b2e7c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Ckirby101/Remote-Debugger/12a2c8b848330e41a94a9757636359a0e01def3a/RemoteDebugger/Dialogs/Settings.cs",
"visit_date": "2021-06-22T02:58:09.959711",
"added": "2024-11-18T23:32:58.329030+00:00",
"created": "2019-09-20T10:35:03",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
import sys
import requests
import hashlib
import json
# url = 'http://127.0.0.1:8002/update/doctor/contact'
url = 'http://139.59.224.188:8002/update/doctor/contact'
# headers = {
# 'X-ACCESS-KEY': '85bfbb2e88494e3b7dcd73b678f3928999724b96ecbfb336b2f2e6fa1ff56e85',
# }
# response = requests.get(url, params = {
# "id": 2
# },
headers = {
'X-ACCESS-KEY': '094905ec7a96e18f3bf3add3f8b461cd1debac44cb52f4c4b43e669a9e5a47a1',
}
response = requests.post(url, params = {
"id": 9,
"mobile": "9090909090",
"email": "gdoct@gmail.com",
"address_line_1": "Address line one",
"address_line_2": "Address line two",
"address_line_3": "Address line three",
"area": "Jayanager",
"pincode": "560098",
"state": "Karnataka",
"city": "Bangalore",
"country": "India"
}, headers=headers)
print(response.headers)
print(response.text)
|
0da2255eff7631707c36680eb01b498b478255bd
|
{
"blob_id": "0da2255eff7631707c36680eb01b498b478255bd",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-03T08:37:51",
"content_id": "b0c52b9cc1601ddf45dbd7999f65d369e1f1229c",
"detected_licenses": [
"MIT"
],
"directory_id": "49463f57f86fe893ad7e0015355240b04b590ea4",
"extension": "py",
"filename": "test_update_contact.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 66194685,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 852,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/test_update_contact.py",
"provenance": "stack-edu-0056.json.gz:296467",
"repo_name": "sunilgoli/Meresia",
"revision_date": "2016-12-03T08:37:51",
"revision_id": "6631580611a6be7716ef21dbabfab2a1118c7d98",
"snapshot_id": "1a8d11d133270b45bb9511664dbae91a31ed3dac",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sunilgoli/Meresia/6631580611a6be7716ef21dbabfab2a1118c7d98/tests/test_update_contact.py",
"visit_date": "2021-10-09T00:58:07.455222",
"added": "2024-11-18T19:02:35.184644+00:00",
"created": "2016-12-03T08:37:51",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
/*
* Copyright 2005--2008 Helsinki Institute for Information Technology
*
* This file is a part of Fuego middleware. Fuego middleware is free
* software; you can redistribute it and/or modify it under the terms
* of the MIT license, included as the file MIT-LICENSE in the Fuego
* middleware source distribution. If you did not receive the MIT
* license with the distribution, write to the Fuego Core project at
* fuego-core-users@googlegroups.com.
*/
package fc.xml.xas.index;
import fc.util.Util;
import fc.util.log.Log;
import fc.xml.xas.FragmentPointer;
import fc.xml.xas.StartTag;
import fc.xml.xas.Verifier;
public class VersionNode {
private static final int INSERT = 0;
private static final int DELETE = 1;
private static final int MOVE = 2;
private int kind = -1;
private DeweyKey source;
private FragmentPointer sourcePointer;
private Index.Entry sourceEntry;
private DeweyKey target;
private FragmentPointer targetPointer;
private Index.Entry targetEntry;
private boolean isAfter;
private VersionNode next;
private VersionNode make (int kind, DeweyKey source,
FragmentPointer sourcePointer, DeweyKey target,
FragmentPointer targetPointer, boolean isAfter) {
if (this.kind != -1) {
throw new IllegalStateException("Node already initialized, kind=" + this.kind);
}
if (Log.isEnabled(Log.TRACE)) {
Log.log("make(" + kind + "," + source + "," + target + ")",
Log.TRACE);
}
this.kind = kind;
this.source = source;
this.sourcePointer = copy(sourcePointer);
this.target = target;
this.targetPointer = copy(targetPointer);
this.isAfter = isAfter;
this.next = new VersionNode();
return next;
}
private FragmentPointer copy (FragmentPointer pointer) {
if (pointer != null) {
return pointer.copy();
} else {
return null;
}
}
public boolean isSentinel () {
return next == null;
}
public VersionNode getNext () {
return next;
}
public DeweyKey update (DeweyKey key) {
if (key == null) {
return null;
}
DeweyKey result = key;
switch (kind) {
case INSERT:
if (key.descendantFollowSibling(source)) {
result = key.next(key.commonAncestor(source));
}
break;
case DELETE:
if (key.descendantFollowSibling(source)) {
result = key.prev(key.commonAncestor(source));
} else if (key.isDescendantSelf(source)) {
result = null;
}
break;
case MOVE:
if (Util.equals(result, source)) {
if (target.followSibling(source) || !isAfter) {
result = target;
} else {
result = target.next();
}
} else if (result.isDescendant(source)) {
if (target.followSibling(source) || !isAfter) {
result = result.replaceAncestor(source, target);
} else {
result = result.replaceAncestor(source, target.next());
}
} else {
if (result.descendantFollowSibling(source)) {
result = result.prev(result.commonAncestor(source));
}
if (result.descendantFollowSibling(target)) {
result = result.next(result.commonAncestor(target));
}
}
break;
}
return result;
}
FragmentPointer update (FragmentPointer pointer) {
Verifier.checkNotNull(pointer);
FragmentPointer result = pointer;
switch (kind) {
case INSERT:
if (pointer.behind(sourcePointer)) {
result = pointer.translate(1);
}
break;
case DELETE:
if (pointer.behind(sourcePointer)) {
result = pointer.translate(-1);
}
break;
case MOVE:
if (pointer.inside(sourcePointer)) {
result = pointer.translate(sourcePointer, targetPointer);
} else if (pointer.behind(sourcePointer)
&& !pointer.behind(targetPointer)) {
result = pointer.translate(-1);
} else if (pointer.behind(targetPointer)
&& !pointer.behind(sourcePointer)) {
result = pointer.translate(1);
}
break;
}
return result;
}
private boolean between (int offset1, int offset2, int length2, int length1) {
return offset1 <= offset2 && offset2 + length2 <= offset1 + length1;
}
public Index.Entry update (Index.Entry entry) {
if (entry == null) {
return null;
}
Index.Entry result = entry;
int offset = entry.getOffset();
int length = entry.getLength();
StartTag context = entry.getContext();
int newOffset = offset;
int newLength = length;
StartTag newContext = context;
switch (kind) {
case INSERT:
if (offset >= sourceEntry.getEnd()) {
newOffset += targetEntry.getLength();
} else if (between(offset, sourceEntry.getOffset(), sourceEntry
.getLength(), length)) {
newLength += targetEntry.getLength();
}
break;
case DELETE:
if (offset >= sourceEntry.getEnd()) {
newOffset -= sourceEntry.getLength();
} else if (between(offset, sourceEntry.getOffset(), sourceEntry
.getLength(), length)) {
newLength -= sourceEntry.getLength();
}
break;
case MOVE:
if (targetEntry.getOffset() <= offset
&& offset < sourceEntry.getOffset()) {
newOffset += sourceEntry.getLength();
} else if (sourceEntry.getEnd() <= offset
&& offset < targetEntry.getOffset()) {
newOffset -= sourceEntry.getLength();
} else if (offset == sourceEntry.getOffset()) {
newOffset = targetEntry.getOffset();
newContext = targetEntry.getContext();
} else if (between(offset, sourceEntry.getOffset(), sourceEntry
.getLength(), length)
&& !between(offset, targetEntry.getOffset(), targetEntry
.getLength(), length)) {
newLength -= sourceEntry.getLength();
} else if (between(offset, targetEntry.getOffset(), targetEntry
.getLength(), length)
&& !between(offset, sourceEntry.getOffset(), sourceEntry
.getLength(), length)) {
newLength += sourceEntry.getLength();
} else if (between(sourceEntry.getOffset(), offset, length,
sourceEntry.getLength())) {
newOffset += targetEntry.getOffset() - sourceEntry.getOffset();
}
break;
}
if (offset != newOffset || length != newLength || context != newContext) {
result = new Index.Entry(newOffset, newLength, newContext);
}
return result;
}
public VersionNode insertAfter (DeweyKey key, FragmentPointer pointer) {
Verifier.checkNotNull(key);
Verifier.checkNotNull(pointer);
return make(INSERT, key, pointer, null, null, true);
}
public VersionNode insertAt (DeweyKey key, FragmentPointer pointer) {
Verifier.checkNotNull(key);
Verifier.checkNotNull(pointer);
return make(INSERT, key, pointer, null, null, false);
}
public VersionNode delete (DeweyKey key, FragmentPointer pointer) {
Verifier.checkNotNull(key);
Verifier.checkNotNull(pointer);
return make(DELETE, key, pointer, null, null, true);
}
public VersionNode moveAfter (DeweyKey source,
FragmentPointer sourcePointer, DeweyKey target,
FragmentPointer targetPointer) {
Verifier.checkNotNull(source);
Verifier.checkNotNull(sourcePointer);
Verifier.checkNotNull(target);
Verifier.checkNotNull(targetPointer);
return make(MOVE, source, sourcePointer, target, targetPointer,
true);
}
public VersionNode moveTo (DeweyKey source, FragmentPointer sourcePointer,
DeweyKey target, FragmentPointer targetPointer) {
Verifier.checkNotNull(source);
Verifier.checkNotNull(sourcePointer);
Verifier.checkNotNull(target);
Verifier.checkNotNull(targetPointer);
return make(MOVE, source, sourcePointer, target, targetPointer,
false);
}
public String toString () {
return "Ver(" + kind + "," + source
+ (target != null ? "," + target : "") + "," + isAfter + ")";
}
}
// arch-tag: 1fd67d0c-1c17-455a-9eb3-4fa3e4ddb638
|
b8c72ed43a7a34058d17a878dbd28987c335a78f
|
{
"blob_id": "b8c72ed43a7a34058d17a878dbd28987c335a78f",
"branch_name": "refs/heads/master",
"committer_date": "2010-04-10T09:58:28",
"content_id": "e65bebfef741bbe0371ee83a5a6b5085390dbe60",
"detected_licenses": [
"MIT"
],
"directory_id": "4b4dd42f7b1d2d65ca19f7d9701b8cd32e93e9c2",
"extension": "java",
"filename": "VersionNode.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32139827,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7579,
"license": "MIT",
"license_type": "permissive",
"path": "/branches/java-fp/xas/src/fc/xml/xas/index/VersionNode.java",
"provenance": "stack-edu-0019.json.gz:850636",
"repo_name": "lagerspetz/fc-syxaw",
"revision_date": "2010-04-10T09:58:28",
"revision_id": "45e350e589fd5a8761a993f3110193586e037525",
"snapshot_id": "5919f55799442f9d36f7ba3889be46bf748198b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lagerspetz/fc-syxaw/45e350e589fd5a8761a993f3110193586e037525/branches/java-fp/xas/src/fc/xml/xas/index/VersionNode.java",
"visit_date": "2020-05-18T16:55:04.562543",
"added": "2024-11-19T00:55:03.164293+00:00",
"created": "2010-04-10T09:58:28",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
package com.liveramp.hank.test;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;
import com.liveramp.hank.config.CoordinatorConfigurator;
import com.liveramp.hank.config.InvalidConfigurationException;
import com.liveramp.hank.config.yaml.YamlCoordinatorConfigurator;
import com.liveramp.hank.coordinator.Coordinator;
public class CoreConfigFixtures {
public static String coordinatorConfig(int zkPort,
int sessionTimeout,
String domainsRoot,
String domainGroupsRoot,
String ringGroupsRoot) {
StringBuilder builder = new StringBuilder();
builder.append(
"coordinator:\n" +
" factory: com.liveramp.hank.coordinator.zk.ZooKeeperCoordinator$Factory\n" +
" options:\n" +
" connect_string: localhost:").append(zkPort).append("\n")
.append(" session_timeout: "+sessionTimeout+"\n");
builder.append(" domains_root: ").append(domainsRoot).append("\n");
builder.append(" domain_groups_root: ").append(domainGroupsRoot).append("\n");
builder.append(" ring_groups_root: ").append(ringGroupsRoot).append("\n");
builder.append(" max_connection_attempts: 5\n");
return builder.toString();
}
public static Coordinator createCoordinator(String tmpDir,
int zkPort,
int sessionTimeout,
String domainsRoot,
String domainGroupsRoot,
String ringGroupsRoot) throws IOException, InvalidConfigurationException {
String tmpFile = tmpDir + "/" + UUID.randomUUID().toString();
FileWriter fileWriter = new FileWriter(tmpFile);
fileWriter.append(coordinatorConfig(zkPort, sessionTimeout, domainsRoot, domainGroupsRoot, ringGroupsRoot));
fileWriter.close();
CoordinatorConfigurator config = new YamlCoordinatorConfigurator(tmpFile);
return config.createCoordinator();
}
}
|
507e61b9ad345191b2e2c6656006e5b7fe8a9c33
|
{
"blob_id": "507e61b9ad345191b2e2c6656006e5b7fe8a9c33",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-04T16:48:06",
"content_id": "a8125307305435ee4392be67f72a89f6bbb045ac",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eccc4605af197b53d1e339088d35054fe5b23c5f",
"extension": "java",
"filename": "CoreConfigFixtures.java",
"fork_events_count": 0,
"gha_created_at": "2019-05-09T00:18:11",
"gha_event_created_at": "2019-05-09T00:18:11",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 185696999,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2211,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hank-core/src/main/java/com/liveramp/hank/test/CoreConfigFixtures.java",
"provenance": "stack-edu-0023.json.gz:6670",
"repo_name": "adayNU/hank",
"revision_date": "2019-04-04T16:48:06",
"revision_id": "ebfd8bf8e91e8a3017620ae9f3ef55fbf52f8561",
"snapshot_id": "6831a6af2e108b1e56c709e5602f6a4dfecf28fe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adayNU/hank/ebfd8bf8e91e8a3017620ae9f3ef55fbf52f8561/hank-core/src/main/java/com/liveramp/hank/test/CoreConfigFixtures.java",
"visit_date": "2020-05-20T17:54:15.189791",
"added": "2024-11-18T21:07:02.765389+00:00",
"created": "2019-04-04T16:48:06",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class VentaTrigger extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::unprepared('
CREATE TRIGGER Venta_Producto AFTER INSERT ON `detalle_venta` FOR EACH ROW
BEGIN
UPDATE inventario set stock = (stock - NEW.cantidad) where producto_id = NEW.producto_id;
END
');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::unprepared('DROP TRIGGER IF EXISTS `Venta_Producto`');
}
}
|
49849747ab7e92b743d806b260791336468fe9e6
|
{
"blob_id": "49849747ab7e92b743d806b260791336468fe9e6",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-31T03:42:44",
"content_id": "c982ff1072ca86a1fdf5206e9a12109557d997a3",
"detected_licenses": [
"MIT"
],
"directory_id": "54508b3ff718ed9824ef2318f7734d8ec86f4726",
"extension": "php",
"filename": "2020_10_02_211508_venta_trigger.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 289149292,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 775,
"license": "MIT",
"license_type": "permissive",
"path": "/database/migrations/2020_10_02_211508_venta_trigger.php",
"provenance": "stack-edu-0052.json.gz:819924",
"repo_name": "deivisjl/saf",
"revision_date": "2020-10-31T03:42:44",
"revision_id": "0ecf7cc03b5080a50ce36b216a00fb95379eca8f",
"snapshot_id": "c6ed4aabcb388d35d4bc99289b5e9ad914bb4404",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deivisjl/saf/0ecf7cc03b5080a50ce36b216a00fb95379eca8f/database/migrations/2020_10_02_211508_venta_trigger.php",
"visit_date": "2023-01-04T23:38:02.272177",
"added": "2024-11-19T01:34:24.545421+00:00",
"created": "2020-10-31T03:42:44",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
//queries the forums and prints out the API changes post
package main
import (
"fmt"
"github.com/DrItanium/fakku"
)
func main() {
apiPosts, err := fakku.GetForumPosts("fakku-developers", "fakku-api-changes")
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", apiPosts.Topic.Title)
for i := 0; i < len(apiPosts.Posts); i++ {
curr := apiPosts.Posts[i]
fmt.Printf("\t%d:\t%s\n", i, curr.Text)
}
}
}
|
133db496f5b0df9ed41dca71c46e6be29e3872c9
|
{
"blob_id": "133db496f5b0df9ed41dca71c46e6be29e3872c9",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-11T01:59:04",
"content_id": "d3cbfc243a0e051f38232f0e67506d75ac882a29",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "671b51e2fa8d2ab6ef5df0c22f689709abe29a66",
"extension": "go",
"filename": "fakku-api-changes.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 31994075,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 428,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/fakku-api-changes.go",
"provenance": "stack-edu-0018.json.gz:43543",
"repo_name": "DrItanium/fakku-api-changes",
"revision_date": "2015-03-11T01:59:04",
"revision_id": "79211701e6be2a85ad0203e301fa183567a9a34c",
"snapshot_id": "4d02f02d63112d8ca4320c540a79b4572a6b5bd5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DrItanium/fakku-api-changes/79211701e6be2a85ad0203e301fa183567a9a34c/fakku-api-changes.go",
"visit_date": "2020-11-26T22:50:24.614204",
"added": "2024-11-18T19:13:59.619390+00:00",
"created": "2015-03-11T01:59:04",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
package es.upv.staq.testar.strategyparser;
import java.util.ArrayList;
import es.upv.staq.testar.algorithms.StateManager;
public class SnStateHasNotChanged extends StrategyNodeBoolean {
public SnStateHasNotChanged(ArrayList<StrategyNode> children) {
super(children);
}
@Override
public boolean getValue(StateManager state) {
return state.hasStateNotChanged();
}
}
|
a0a06ba47bc4c586d91163fca065088b00b85c15
|
{
"blob_id": "a0a06ba47bc4c586d91163fca065088b00b85c15",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-20T08:08:02",
"content_id": "7372ab0efe7369c18d839b498a9c7436f19bb421",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9876e1f4eb65e2c0332ea204e824f516e176fec0",
"extension": "java",
"filename": "SnStateHasNotChanged.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130260455,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 380,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/graph/src/es/upv/staq/testar/strategyparser/SnStateHasNotChanged.java",
"provenance": "stack-edu-0024.json.gz:315178",
"repo_name": "pickmybrain/TESTAR-for-ECJ",
"revision_date": "2018-04-20T08:08:02",
"revision_id": "5607c7f42dab744feec85821d032ffb914cbb20d",
"snapshot_id": "24c6bc2974ba21e0440f38f2edb3fbbb3a8d9ec3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pickmybrain/TESTAR-for-ECJ/5607c7f42dab744feec85821d032ffb914cbb20d/src/graph/src/es/upv/staq/testar/strategyparser/SnStateHasNotChanged.java",
"visit_date": "2020-03-11T23:45:36.501982",
"added": "2024-11-19T00:37:36.893812+00:00",
"created": "2018-04-20T08:08:02",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
import { FormGroupProps } from "../form-group";
import { UseFieldApiComponentConfig } from "@data-driven-forms/react-form-renderer";
import { SelectItemProps, SelectProps as CarbonSelectProps } from 'carbon-components-react';
export interface SelectOption extends SelectItemProps {
value: any;
label: string | undefined;
}
interface InternalSelectProps extends CarbonSelectProps {
options: SelectOption[];
isDisabled?: boolean;
}
export type SelectProps = InternalSelectProps & FormGroupProps & UseFieldApiComponentConfig;
declare const Select: React.ComponentType<SelectProps>;
export default Select;
|
88e851d51a78909cf4b151b84221fb96cb2ec6ab
|
{
"blob_id": "88e851d51a78909cf4b151b84221fb96cb2ec6ab",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T07:12:30",
"content_id": "ae59e361e30553929938a32be81a8c75bff8c803",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c534a49a872ae2ff89a0d04ad38d6b7baa3a97f5",
"extension": "ts",
"filename": "select.d.ts",
"fork_events_count": 83,
"gha_created_at": "2019-04-02T07:18:00",
"gha_event_created_at": "2023-09-14T09:27:12",
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 179020919,
"is_generated": false,
"is_vendor": true,
"language": "TypeScript",
"length_bytes": 616,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/packages/carbon-component-mapper/src/select/select.d.ts",
"provenance": "stack-edu-0075.json.gz:1016383",
"repo_name": "data-driven-forms/react-forms",
"revision_date": "2023-08-31T07:12:30",
"revision_id": "10a82a218034f97a22a3e973723236af668fd51d",
"snapshot_id": "5112b585e0f5a29cadf4ae66beaa65042389d156",
"src_encoding": "UTF-8",
"star_events_count": 275,
"url": "https://raw.githubusercontent.com/data-driven-forms/react-forms/10a82a218034f97a22a3e973723236af668fd51d/packages/carbon-component-mapper/src/select/select.d.ts",
"visit_date": "2023-08-31T21:28:54.903139",
"added": "2024-11-19T01:19:06.944813+00:00",
"created": "2023-08-31T07:12:30",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
import Foundation
/**
A `CongestionLevel` indicates the level of traffic congestion along a road segment relative to the normal flow of traffic along that segment. You can color-code a route line according to the congestion level along each segment of the route.
*/
@objc(MBCongestionLevel)
public enum CongestionLevel: Int, CustomStringConvertible {
/**
There is not enough data to determine the level of congestion along the road segment.
*/
case unknown
/**
The road segment has little or no congestion. Traffic is flowing smoothly.
Low congestion levels are conventionally highlighted in green or not highlighted at all.
*/
case low
/**
The road segment has moderate, stop-and-go congestion. Traffic is flowing but speed is impeded.
Moderate congestion levels are conventionally highlighted in yellow.
*/
case moderate
/**
The road segment has heavy, bumper-to-bumper congestion. Traffic is barely moving.
Heavy congestion levels are conventionally highlighted in orange.
*/
case heavy
/**
The road segment has severe congestion. Traffic may be completely stopped.
Severe congestion levels are conventionally highlighted in red.
*/
case severe
public init?(description: String) {
let level: CongestionLevel
switch description {
case "unknown":
level = .unknown
case "low":
level = .low
case "moderate":
level = .moderate
case "heavy":
level = .heavy
case "severe":
level = .severe
default:
return nil
}
self.init(rawValue: level.rawValue)
}
public var description: String {
switch self {
case .unknown:
return "unknown"
case .low:
return "low"
case .moderate:
return "moderate"
case .heavy:
return "heavy"
case .severe:
return "severe"
}
}
}
|
7477f4aae6521823f803d1a0cf4ea586f76b48f8
|
{
"blob_id": "7477f4aae6521823f803d1a0cf4ea586f76b48f8",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-14T03:13:51",
"content_id": "5cbc29be699bf306b9a3bc2fa27587b938fa2aef",
"detected_licenses": [
"MIT",
"ISC"
],
"directory_id": "74064be7d3d51499a37a7c69007d764cebd93465",
"extension": "swift",
"filename": "MBCongestion.swift",
"fork_events_count": 1,
"gha_created_at": "2019-09-03T14:25:00",
"gha_event_created_at": "2023-01-04T08:51:33",
"gha_language": "Objective-C",
"gha_license_id": "MIT",
"github_id": 206096836,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 2097,
"license": "MIT,ISC",
"license_type": "permissive",
"path": "/NavDemo/ios/Carthage/Checkouts/MapboxDirections.swift/Sources/MapboxDirections/MBCongestion.swift",
"provenance": "stack-edu-0071.json.gz:597418",
"repo_name": "ivanliu1989/Mapbox-Navigation-React-Native",
"revision_date": "2019-09-14T03:13:51",
"revision_id": "5611c75b6d36288b1a8ca8ef25bc69305335897b",
"snapshot_id": "33c00b7bf43fc810b85fd4479b22e2ccf06b5fbc",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/ivanliu1989/Mapbox-Navigation-React-Native/5611c75b6d36288b1a8ca8ef25bc69305335897b/NavDemo/ios/Carthage/Checkouts/MapboxDirections.swift/Sources/MapboxDirections/MBCongestion.swift",
"visit_date": "2023-01-07T14:29:42.936734",
"added": "2024-11-19T00:21:23.556413+00:00",
"created": "2019-09-14T03:13:51",
"int_score": 4,
"score": 3.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz"
}
|
import { Component, SimpleChange } from '@angular/core';
import {AppState} from '../../app.service';
@Component({
selector: 'detail',
template: `
<div class="card-container">
<h1>没有详情</h1>
</div>
`
})
export class Detail {
constructor(public appState : AppState ) {
}
/**
* 当 Angular 初始化完数据绑定的输入属性后,用来初始化指令或组件。
*/
ngOnInit() {
console.log('Initial App State', this.appState.state);
}
}
|
ac224f08ca308e463a3744c88aca5304767fd738
|
{
"blob_id": "ac224f08ca308e463a3744c88aca5304767fd738",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-20T03:19:49",
"content_id": "8c76b62df6327a99749c98f565043862ee0446ef",
"detected_licenses": [
"MIT"
],
"directory_id": "648650ad5ba0b906292e94d71ee05c682ccf5128",
"extension": "ts",
"filename": "detail.component.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": 511,
"license": "MIT",
"license_type": "permissive",
"path": "/src/app/containers/+detail/detail.component.ts",
"provenance": "stack-edu-0075.json.gz:718775",
"repo_name": "gogobook/angular2Demo",
"revision_date": "2016-09-20T03:19:49",
"revision_id": "9a58b89d875473355282fd5d4f51ef89b741e7a5",
"snapshot_id": "0c99907399b5b42cb704f009b7d4cf99ce9fc4f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gogobook/angular2Demo/9a58b89d875473355282fd5d4f51ef89b741e7a5/src/app/containers/+detail/detail.component.ts",
"visit_date": "2021-01-13T13:45:57.675129",
"added": "2024-11-19T01:43:32.255100+00:00",
"created": "2016-09-20T03:19:49",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
import Foundation
/**
A token filter of type reverse that simply reverses each token.
[More information](https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-reverse-tokenfilter.html)
*/
public struct ReverseFilter: BasicTokenFilter, BuiltinTokenFilter {
/// :nodoc:
public static var typeKey = TokenFilterType.reverse
/// Holds the string that Elasticsearch uses to identify the filter type
public let type = typeKey.rawValue
/// :nodoc:
public let name: String
public init() {
self.name = self.type
}
}
|
a72e983d22fe75762851a4775fb32cb53f88e8ff
|
{
"blob_id": "a72e983d22fe75762851a4775fb32cb53f88e8ff",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-03T00:10:40",
"content_id": "a612074eafa731ab21866728c6feab4c55634b6a",
"detected_licenses": [
"MIT"
],
"directory_id": "a535eee4177d6c0f4da6470f1538da98b1d803a5",
"extension": "swift",
"filename": "ReverseFilter.swift",
"fork_events_count": 12,
"gha_created_at": "2018-05-31T15:57:38",
"gha_event_created_at": "2019-06-03T20:00:46",
"gha_language": "Swift",
"gha_license_id": "MIT",
"github_id": 135605811,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 582,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/Elasticsearch/Index/Filters/Token/ReverseFilter.swift",
"provenance": "stack-edu-0072.json.gz:140561",
"repo_name": "ryangrimm/VaporElasticsearch",
"revision_date": "2019-06-03T00:10:40",
"revision_id": "fef7dc43bfb419e51f59a8911125c5d90942e8c6",
"snapshot_id": "a92094f6690dbb120c3309b4a627fac71db6dc21",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/ryangrimm/VaporElasticsearch/fef7dc43bfb419e51f59a8911125c5d90942e8c6/Sources/Elasticsearch/Index/Filters/Token/ReverseFilter.swift",
"visit_date": "2020-03-19T02:10:19.030109",
"added": "2024-11-18T19:28:11.325055+00:00",
"created": "2019-06-03T00:10:40",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
import { vec2, vec3 } from "gl-matrix";
type CollisionResult = {
normal: vec2,
restore: vec2,
lineA: vec2,
lineB: vec2,
};
class Vec2 {
private readonly v: vec2 = vec2.create();
get x(): number { return this.v[0]; }
get y(): number { return this.v[1]; }
set x(a: number) { this.v[0] = a; }
set y(a: number) { this.v[1] = a; }
constructor(x: number, y: number) {
this.v[0] = x;
this.v[1] = y;
}
clone(): Vec2 {
return new Vec2(this.x, this.y);
}
scale(n: number): Vec2 {
vec2.scale(this.v, this.v, n);
return this;
}
magnitude2(): number {
return vec2.squaredLength(this.v);
}
normalize(): Vec2 {
vec2.normalize(this.v, this.v);
return this;
}
cross(a: Vec2): number {
return vec2.cross(vec3.create(), this.v, vec2.fromValues(a.x, a.y))[2];
}
add(a: Vec2): Vec2 {
vec2.add(this.v, this.v, vec2.fromValues(a.x, a.y));
return this;
}
getRaw(): vec2 {
return this.v;
}
}
const pointInLinePerpSpace = (ax: number, ay: number, bx: number, by: number, px: number, py: number): boolean => {
let _ax:number, _ay:number, _bx:number, _by:number, _cx:number, _cy:number;
let perpSlope = (ax-bx) / (by-ay);
if (perpSlope > 1) {
_ax = ay; _bx = by; _cx = py;
_ay = ax; _by = bx; _cy = px;
perpSlope = (_ax-_bx)/(_by-_ay);
} else {
_ax = ax; _bx = bx; _cx = px;
_ay = ay; _by = by; _cy = py;
}
let yMin: number, yMax: number;
if (_ay > _by) {
yMin = perpSlope*(_cx - _bx) + _by;
yMax = perpSlope*(_cx - _ax) + _ay;
} else {
yMin = perpSlope*(_cx - _ax) + _ay;
yMax = perpSlope*(_cx - _bx) + _by;
}
return _cy > yMin && _cy < yMax;
}
const projectPointOnLine = (m: number, x: number, y: number): Vec2 => {
if (Math.abs(m) < 1e-9) {
return new Vec2(x, 0);
}
else if (Math.abs (m) > 1e9) {
return new Vec2(0, y);
}
const retY = (y*m+x)*m/(1+m*m);
return new Vec2(retY/m, retY);
};
export const circleCollision = (lines: vec2[], x :number, y :number, r :number) :CollisionResult | null => {
const r2 = r*r;
let lined = false;
let lineA: vec2 | null = null;
let lineB: vec2 | null = null;
let normal: Vec2 | null = null;
let restore: Vec2 | null = null;
for (let i = 0; i < lines.length; i++) {
const ax = lines[i][0];
const ay = lines[i][1];
const bx = lines[(i+1) % lines.length][0];
const by = lines[(i+1) % lines.length][1];
if (pointInLinePerpSpace (ax, ay, bx, by, x, y)) {
const m = (by-ay)/(bx-ax);
const lx = x-ax;
const ly = y-ay;
const pointOnLine = projectPointOnLine (m, lx, ly);
const projection = pointOnLine.clone().scale(-1);
projection.x += lx;
projection.y += ly;
if (projection.magnitude2() < r2) {
normal = projection.clone().normalize();
if (projection.cross (new Vec2 (bx - ax, by - ay)) > 0) {
normal.scale(-1);
}
restore = (new Vec2(ax,ay))
.add(pointOnLine)
.add(normal.clone().scale(r));
lineA = lines[i];
lineB = lines[i+1];
x = restore.x;
y = restore.y;
lined = true;
}
}
}
if (lined) return {
normal: normal!.getRaw(),
restore: restore!.getRaw(),
lineA: lineA!,
lineB: lineB!
};
for (let i = 0; i < lines.length; i++) {
const delta = new Vec2 (x - lines[i][0], y - lines[i][1]);
if (delta.magnitude2() < r2) {
const norm = delta.normalize();
return {
normal: norm.getRaw(),
restore: (new Vec2 (lines[i][0],lines[i][1])).add(norm.clone().scale(r)).getRaw(),
lineA: lines[i],
lineB: lines[i]
};
}
}
return null;
};
|
ee1b15909cc49cae8d4f2450ce6e4c7fe83b6e57
|
{
"blob_id": "ee1b15909cc49cae8d4f2450ce6e4c7fe83b6e57",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-18T06:38:28",
"content_id": "d1cd9dc1234c124d8f3290ed075d6662e19a9fa6",
"detected_licenses": [
"MIT"
],
"directory_id": "60e9707413f63281fe943c903ef24ad72410ca99",
"extension": "ts",
"filename": "collision.ts",
"fork_events_count": 0,
"gha_created_at": "2019-08-01T16:34:14",
"gha_event_created_at": "2020-07-17T21:56:40",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 200085368,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 4171,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gameplay/collision.ts",
"provenance": "stack-edu-0074.json.gz:86772",
"repo_name": "jaburns/LOWREZJAM2019",
"revision_date": "2019-08-18T06:38:28",
"revision_id": "2db65c24fad1313f6f3209dc78eec443e72515ef",
"snapshot_id": "e6cf799643fed8367bb6cf0ad8242472fbc9ac52",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jaburns/LOWREZJAM2019/2db65c24fad1313f6f3209dc78eec443e72515ef/src/gameplay/collision.ts",
"visit_date": "2021-07-25T23:56:40.733091",
"added": "2024-11-18T23:21:52.728878+00:00",
"created": "2019-08-18T06:38:28",
"int_score": 3,
"score": 3.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
using NAudio.Wave.Compression;
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Unicode;
namespace uk.JohnCook.dotnet.StreamController.SharedModels
{
public class SecurePreferences
{
// Byte length constants for AES-256 GCM Mode
private const int KEY_LENGTH = 32;
private const int NONCE_LENGTH = 12;
private const int TAG_LENGTH = 16;
static readonly CspParameters rsaCspParams = new CspParameters()
{
KeyContainerName = "user-preferences"
};
private static readonly RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
private readonly string rsaEncryptedAesKey;
public SecurePreferences()
{
// Create a new AES-256 key on instantiation.
rsaEncryptedAesKey = CreateNewAesKey();
}
/// <summary>
/// Stores a user preference encrypted using AES-256.
/// Method is not static to ensure an instance of the class (and a new AES key) is created.
/// </summary>
/// <param name="preference">The user preference/setting string (i.e. where to store it).</param>
/// <param name="secret">A reference to the data to store. The original data should be zeroed out by this method.</param>
/// <param name="associatedData">Optional associated data. It will need to be stored separately.</param>
/// <returns>True on success.</returns>
public bool StoreString(ref string preference, ref char[] secret, byte[] associatedData = null)
{
if (secret == null) { throw new ArgumentNullException(nameof(secret)); }
// This is not a static method.
// The only way to store a new password is by creating an instance of the class, which creates a new AES key.
using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096, rsaCspParams);
Span<byte> aesKey = AsymmetricDecryptFromBase64(rsaProvider, rsaEncryptedAesKey);
// NIST recommends only using a 12-byte/96-bit nonce for AES-GCM. It shouldn't be reused.
byte[] nonce = new byte[NONCE_LENGTH];
rngCsp.GetBytes(nonce);
// Note: Associated data that is passed in on encryption must also be passed in for decryption. Default is null.
// This data will not be stored with the other data needed to decrypt the message.
// AES-GCM generates output that is the same length as input.
byte[] cipherText = new byte[secret.Length];
// AES-GCM generated tag can be truncated, but its full size is 16-byte/128-bit.
byte[] tag = new byte[TAG_LENGTH];
using AesGcm aesGcm = new AesGcm(aesKey);
// Use UTF-8 Encoding for the secret.
aesGcm.Encrypt(nonce, Encoding.UTF8.GetBytes(secret), cipherText, tag, associatedData);
// Store the length of the original secret, and then wipe the data.
int secretLength = secret.Length;
Array.Clear(secret, 0, secretLength);
// Create a user preference string. The key, nonce, associated data, tag, and cipher text are needed to decrypt.
// Format: Base64(RsaEncrypt(concat(key, nonce, tag, cipherText)))
// Zero out each array once it is no longer needed.
byte[] preferenceString = new byte[secretLength + KEY_LENGTH + NONCE_LENGTH + TAG_LENGTH];
Buffer.BlockCopy(aesKey.ToArray(), 0, preferenceString, 0, aesKey.Length);
aesKey.Clear();
Buffer.BlockCopy(nonce, 0, preferenceString, KEY_LENGTH, NONCE_LENGTH);
Array.Clear(nonce, 0, NONCE_LENGTH);
Buffer.BlockCopy(tag, 0, preferenceString, KEY_LENGTH + NONCE_LENGTH, TAG_LENGTH);
Array.Clear(tag, 0, TAG_LENGTH);
Buffer.BlockCopy(cipherText, 0, preferenceString, KEY_LENGTH + NONCE_LENGTH + TAG_LENGTH, cipherText.Length);
Array.Clear(cipherText, 0, cipherText.Length);
preference = AsymmetricEncryptToBase64(rsaProvider, preferenceString);
// TODO: Return false on failure.
return true;
}
/// <summary>
/// Decrypt an AES-256 encrypted user preference.
/// Method is static as class doesn't need instantiation.
/// </summary>
/// <param name="preference">The user preference/setting string (i.e. where it is stored).</param>
/// <param name="decryptedData">A reference to where to store the decrypted string.</param>
/// <param name="associatedData">Optional associated data that was used during encryption.</param>
public static void GetString(string preference, ref char[] decryptedData, byte[] associatedData = null)
{
if (preference == null) { throw new ArgumentNullException(nameof(preference)); }
if (decryptedData == null) { throw new ArgumentNullException(nameof(decryptedData)); }
using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096, rsaCspParams);
ReadOnlyMemory<byte> preferenceString = AsymmetricDecryptFromBase64(rsaProvider, preference).AsMemory<byte>();
// Slice the decrypted preference string to extract the key, nonce, and tag .
using AesGcm aesGcm = new AesGcm(preferenceString.Slice(0, KEY_LENGTH).ToArray());
ReadOnlyMemory<byte> nonce = preferenceString.Slice(KEY_LENGTH, NONCE_LENGTH);
ReadOnlyMemory<byte> tag = preferenceString.Slice(KEY_LENGTH + NONCE_LENGTH, TAG_LENGTH);
// Calculate the length of the encrypted data.
int dataLength = preferenceString.Length - KEY_LENGTH - NONCE_LENGTH - TAG_LENGTH;
int cipherTextStart = preferenceString.Length - dataLength;
// Create a temporary array to store the decrypted data.
byte[] dataTemp = new byte[dataLength];
// Decrypt the data.
aesGcm.Decrypt(nonce.ToArray(), preferenceString.Slice(cipherTextStart, dataLength).ToArray(), tag.ToArray(), dataTemp, associatedData);
// Use UTF-8 encoding for the decrypted data.
decryptedData = Encoding.UTF8.GetString(dataTemp).ToArray();
// Zero the temporary array.
Array.Clear(dataTemp, 0, dataLength);
}
/// <summary>
/// Creates a new AES-256 Symmetric Key encrypted by a 4096 bit RSA key.
/// </summary>
/// <returns>A base64 string of the RSA-encrypted AES key.</returns>
private static string CreateNewAesKey()
{
using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096, rsaCspParams);
// 32 bytes * 8 = AES-256
byte[] SuperRandomSymmetricKey = new byte[KEY_LENGTH];
rngCsp.GetBytes(SuperRandomSymmetricKey);
using SHA256 sha256 = SHA256.Create();
// SHA256 hash to check consistency
string unencryptedAesKeyHash = BitConverter.ToString(sha256.ComputeHash(SuperRandomSymmetricKey)).ToUpperInvariant().Replace("-", String.Empty, StringComparison.Ordinal);
// SPKI of asymmetric keypair formatted in same way as HTTP-Public-Key-Header to check it doesn't change
X509SubjectKeyIdentifierExtension spki = new X509SubjectKeyIdentifierExtension(rsaProvider.ExportSubjectPublicKeyInfo(), false);
// Encrypted AES key in base 64 should be impossible to decrypt even with the IV
string encryptedAesKeyBase64 = AsymmetricEncryptToBase64(rsaProvider, SuperRandomSymmetricKey);
Array.Clear(SuperRandomSymmetricKey, 0, SuperRandomSymmetricKey.Length);
// SHA256 hash of decrypted AES key to check consistency
Span<byte> decryptedAesKey = AsymmetricDecryptFromBase64(rsaProvider, encryptedAesKeyBase64);
string aesKeyHash = BitConverter.ToString(sha256.ComputeHash(decryptedAesKey.ToArray())).ToUpperInvariant().Replace("-", String.Empty, StringComparison.Ordinal);
return encryptedAesKeyBase64;
}
/// <summary>
/// Encrypts data using RSA.
/// </summary>
/// <param name="rsaProvider">The RSA provider including a private key.</param>
/// <param name="data">The data to encrypt.</param>
/// <returns>A base64 encoded string of the encrypted data.</returns>
private static string AsymmetricEncryptToBase64(RSACryptoServiceProvider rsaProvider, byte[] data)
{
byte[] encryptedBytes = rsaProvider.Encrypt(data, true);
Span<byte> base64 = ArrayPool<byte>.Shared.Rent(encryptedBytes.Length * 4);
Base64.EncodeToUtf8(encryptedBytes, base64, out int _, out int written, true);
string base64String = Encoding.UTF8.GetString(base64.Slice(0, written));
ArrayPool<byte>.Shared.Return(base64.ToArray());
return base64String;
}
/// <summary>
/// Decrypts data using RSA
/// </summary>
/// <param name="rsaProvider">The RSA provider including a private key.</param>
/// <param name="ciphertext">The base64 encoded encrypted data to decrypt.</param>
/// <returns>The decrypted data as a byte array.</returns>
private static byte[] AsymmetricDecryptFromBase64(RSACryptoServiceProvider rsaProvider, string ciphertext)
{
if (ciphertext == null) { throw new ArgumentNullException(nameof(ciphertext)); }
if (ciphertext.Length == 0) { throw new ArgumentException($"{nameof(ciphertext)} has a length of {ciphertext.Length}"); }
using SHA256 sha256 = SHA256.Create();
Span<byte> decryptedData = ArrayPool<byte>.Shared.Rent(ciphertext.Length * 8);
Span<byte> poolRef = decryptedData;
decryptedData = Encoding.UTF8.GetBytes(ciphertext);
Base64.DecodeFromUtf8InPlace(decryptedData, out int written);
ArrayPool<byte>.Shared.Return(poolRef.ToArray());
return rsaProvider.Decrypt(decryptedData.Slice(0, written).ToArray(), true);
}
public static char[] CreateAuthResponse(string preference, string salt, string challenge, byte[] associatedData = null)
{
if (preference == null) { throw new ArgumentNullException(nameof(preference)); }
using SHA256 sha256 = SHA256.Create();
char[] password = new char[preference.Length];
GetString(preference, ref password, associatedData);
char[] secret_string = String.Concat(password.AsSpan(), salt.AsSpan()).ToArray();
Array.Clear(password, 0, password.Length);
byte[] secret_hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(secret_string));
Array.Clear(secret_string, 0, secret_string.Length);
byte[] secret = new byte[preference.Length];
Base64.EncodeToUtf8(secret_hash, secret, out int consumed, out int written);
Array.Clear(secret_hash, 0, secret_hash.Length);
char[] auth_response_string = String.Concat(Encoding.UTF8.GetString(secret.AsSpan().Slice(0, written)), challenge).ToArray();
Array.Clear(secret, 0, written);
byte[] auth_response_hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(auth_response_string));
Array.Clear(auth_response_string, 0, auth_response_string.Length);
byte[] auth_response = new byte[preference.Length];
Base64.EncodeToUtf8(auth_response_hash, auth_response, out consumed, out written);
return Encoding.UTF8.GetString(auth_response.AsSpan().Slice(0, written)).ToCharArray();
}
}
/// <summary>
/// Helper methods for transforming encryption-related variables.
/// </summary>
public static class Transform
{
/// <summary>
/// Converts a hexadecimal string into an array of bytes.
/// </summary>
/// <param name="hexString">The hexadecimal string to transform, with no separator between bytes.</param>
/// <returns>The byte[] representation of the hexadecimal string.</returns>
public static byte[] FromHex(string hexString)
{
if (hexString == null) { throw new ArgumentNullException(nameof(hexString)); }
byte[] inBytes = new byte[hexString.Length / 2];
int bytes = 0;
do
{
inBytes[bytes] = Convert.ToByte(hexString.Substring(bytes * 2, 2), 16);
bytes++;
} while (bytes * 2 < hexString.Length);
return inBytes;
}
/// <summary>
/// Transforms a byte array into a base64-encoded UTF8 string.
/// </summary>
/// <param name="spkiBytes">The byte array to transform, such as an SPKI-formatted public key.</param>
/// <returns>A string in the same format used for HTTP Public-Key Pinning.</returns>
public static string ToBase64(byte[] spkiBytes)
{
if (spkiBytes == null) { throw new ArgumentNullException(nameof(spkiBytes)); }
using SHA256 sha256 = SHA256.Create();
Span<byte> spkiUtf8Bytes = ArrayPool<byte>.Shared.Rent(spkiBytes.Length);
Base64.EncodeToUtf8(sha256.ComputeHash(spkiBytes), spkiUtf8Bytes, out int consumed, out int written, true);
return Encoding.UTF8.GetString(spkiUtf8Bytes.Slice(0, written));
}
}
}
|
6cee2e8944dcf6458ea49ec8785cd7b09d9db34c
|
{
"blob_id": "6cee2e8944dcf6458ea49ec8785cd7b09d9db34c",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-30T13:50:55",
"content_id": "b32b124153a6da8a19a63ab13fd07ac0e23b3927",
"detected_licenses": [
"MIT"
],
"directory_id": "c7a96974c734b7b292bc87662f1c05d972b28b09",
"extension": "cs",
"filename": "SecurePreferences.cs",
"fork_events_count": 0,
"gha_created_at": "2020-06-25T05:49:33",
"gha_event_created_at": "2020-07-06T01:05:05",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 274839316,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 13816,
"license": "MIT",
"license_type": "permissive",
"path": "/SharedModels/SecurePreferences.cs",
"provenance": "stack-edu-0015.json.gz:139545",
"repo_name": "watfordjc/csharp-stream-controller",
"revision_date": "2020-08-30T13:50:55",
"revision_id": "cc0a608911163c525fb0647c3b1daf36cb7014c4",
"snapshot_id": "f6b52300dc5604721179a6e35b2e6a8aed196c60",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/watfordjc/csharp-stream-controller/cc0a608911163c525fb0647c3b1daf36cb7014c4/SharedModels/SecurePreferences.cs",
"visit_date": "2022-12-16T02:51:50.894607",
"added": "2024-11-18T22:02:33.347331+00:00",
"created": "2020-08-30T13:50:55",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
<?php
namespace Luxifer\Leboncoin\Datetime;
class LeboncoinDatetime extends \DateTime
{
/**
* @param string $date date as displayed on the website
* @param string $time time as displayed on the website
*/
public function __construct($date, $time)
{
parent::__construct();
$this->setTimezone(new \DateTimeZone('Europe/Paris'));
$this->fullMatch($date);
list($hour, $second) = explode(':', $time);
$this->setTime($hour, $second);
}
/**
* Transform the date part into a php on
*
* @param string $key date as displayed on the website
*/
private function fullMatch($key)
{
$config = array(
"Aujourd'hui" => 'now',
'Hier' => '-1 day'
);
if (!isset($config[$key])) {
list($day, $month) = explode(' ', $key);
$this->setDate(date('Y'), $this->monthMatch($month), (int) $day);
return;
}
$this->setTimestamp(strtotime($config[$key]));
}
/**
* Transform the month displayed on the website into the corresponding integer value
* @param string $key month
* @return integer month
*/
private function monthMatch($key)
{
$months = array(
'janvier' => 1,
'février' => 2,
'mars' => 3,
'avril' => 4,
'mai' => 5,
'juin' => 6,
'juillet' => 7,
'août' => 8,
'septembre' => 9,
'octobre' => 10,
'novembre' => 11,
'décembre' => 12
);
return $months[$key];
}
/**
* Format the object to a string corresponding at the SQL format
*
* @return string datetime
*/
public function __toString()
{
return $this->format('Y-m-d H:i:s');
}
}
|
22030134b8390d7e98743dba9fd8ce1e7cabd972
|
{
"blob_id": "22030134b8390d7e98743dba9fd8ce1e7cabd972",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-11T14:31:10",
"content_id": "41511cf43fa60b6501fe955ea6be36bfe0252ead",
"detected_licenses": [
"MIT"
],
"directory_id": "3de19fa77079cac433c6e8fa55586737ca508537",
"extension": "php",
"filename": "LeboncoinDatetime.php",
"fork_events_count": 1,
"gha_created_at": "2014-06-04T22:07:23",
"gha_event_created_at": "2014-06-06T07:53:09",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 20502708,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1920,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Luxifer/Leboncoin/Datetime/LeboncoinDatetime.php",
"provenance": "stack-edu-0049.json.gz:903286",
"repo_name": "luxifer/leboncoin-cli",
"revision_date": "2014-06-11T14:31:10",
"revision_id": "5ce4e8275fe05688ab536b40c95d40f72af07e14",
"snapshot_id": "34cb4c338df7f2e252eda7dc99e6ca860e581e0c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/luxifer/leboncoin-cli/5ce4e8275fe05688ab536b40c95d40f72af07e14/src/Luxifer/Leboncoin/Datetime/LeboncoinDatetime.php",
"visit_date": "2021-01-21T11:46:52.587248",
"added": "2024-11-18T22:26:47.750373+00:00",
"created": "2014-06-11T14:31:10",
"int_score": 3,
"score": 3.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
// JavaScript Document
$(document).ready(function() {
$('body').toggleClass('black');
// Toggle day and night
$('#switch').click(function(){
$('body').toggleClass('black');
if($('#switchIs').attr('src')==='images/switch1.png') {
$('#switchIs').attr('src','images/switch2.png');
} else {
$('#switchIs').attr('src','images/switch1.png');
}
return false;
});
});
// shortcut for console.log
function cl(data) {
console.log(data);
}
var scotchApp = angular.module('scotchApp', ['ngRoute', 'ui.unique']);
//var scotchApp = angular.module('scotchApp', ['ui.unique']);
scotchApp.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our assets domain. Notice the difference between * and **.
'http://heli.er.ee/helid/oy/**']);
// The blacklist overrides the whitelist so the open redirect here is blocked.
$sceDelegateProvider.resourceUrlBlacklist([
'http://myapp.example.com/clickThru**']);
});
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/kroonika.html',
controller : 'otsiController'
})
.when('/otsi', {
templateUrl : 'pages/otsi.html',
controller : 'otsiController'
})
.when('/esinejad', {
templateUrl : 'pages/esinejad.html',
controller : 'authorController'
})
.when('/esineja/:esineja', {
templateUrl : 'pages/esineja.html',
controller : 'esinejaController'
})
.when('/teemad', {
templateUrl : 'pages/teemad.html',
controller : 'otsiController'
})
.when('/teema/:tag', {
templateUrl : 'pages/teema.html',
controller : 'tagController'
})
.when('/kroonika', {
templateUrl : 'pages/kroonika.html',
controller : 'otsiController'
})
.when('/loeng/:name', {
templateUrl: 'pages/loeng.html',
controller: 'CMSController'
})
});
scotchApp.filter('searchFilter', function() {
return function(lectures, searchText) {
var regexp = new RegExp(searchText, 'i');
return lectures.filter(function(lecture) {
var found = false;
//!TODO: Add whatever other fields need to be searched
if (lecture.title.search(regexp) > -1) {
found = true;
}
if (lecture.tag.search(regexp) > -1) {
found = true;
}
if (!found) {
lecture.authors.some(function(author) {
found = author.search(regexp) > -1;
return found;
});
}
return found;
});
};
});
scotchApp.filter('relatedFilter', function() {
return function(lectures, searchText) {
var regexp = new RegExp(searchText, 'i');
return lectures.filter(function(lecture) {
var found = false;
//!TODO: Add whatever other fields need to be searched
if (lecture.tag.search(regexp) > -1) {
found = true;
}
if (!found) {
lecture.authors.some(function(author) {
found = author.search(regexp) > -1;
return found;
});
}
return found;
});
};
});
scotchApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
scotchApp.controller('mainController', function($scope) {
});
scotchApp.controller('otsiController', function($scope) {
$scope.db = db;
});
scotchApp.controller('authorController', function($scope) {
// get only single authors from db
var singleAuthors = [];
db.forEach(function(entry) {
var authors = entry.authors.toString().split(", ");
authors.forEach(function(author){
if(singleAuthors.indexOf(author)===-1) {
singleAuthors.push(author);
}
});
});
$scope.singleAuthors = singleAuthors.sort();
});
scotchApp.controller('tagController', function($scope, $route, $routeParams) {
$scope.tag = $routeParams.tag;
$scope.searchText = $scope.tag;
$scope.db = db;
});
scotchApp.controller('esinejaController', function($scope, $route, $routeParams) {
$scope.esineja = $routeParams.esineja;
$scope.searchText = $scope.esineja;
$scope.db = db;
});
scotchApp.controller('CMSController', function($scope, $route, $routeParams) {
var nid = $routeParams.name;
var data = db[nid];
$scope.title = data.title;
$scope.tag = data.tag;
$scope.file = data.file;
$scope.fileUrl = "http://heli.er.ee/helid/oy/"+data.file+".mp3";
$scope.text = data.text;
$scope.year = data.year;
$scope.authors = data.authors;
$scope.sound = data.sound;
$scope.editor = data.editor;
$scope.nid = nid;
$scope.db = db;
});
scotchApp.directive('socialPlugins', ['$timeout', function ($timeout) {
return {
restrict: 'A',
scope: false,
templateUrl: 'pages/social-plugins.html',
link: function(scope, element, attributes) {
$timeout(function () {
FB.XFBML.parse(element.parent()[0])
});
}
}
}]);
|
a55cdc785b0ece181ffd72f334726326938a6e47
|
{
"blob_id": "a55cdc785b0ece181ffd72f334726326938a6e47",
"branch_name": "refs/heads/master",
"committer_date": "2014-04-01T18:34:30",
"content_id": "8b64fdfff47e852d9f9979176186166407d36760",
"detected_licenses": [
"MIT"
],
"directory_id": "df35518be62967e37919836c334c1391ab9bbeda",
"extension": "js",
"filename": "script.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 5965,
"license": "MIT",
"license_type": "permissive",
"path": "/javascripts/script.js",
"provenance": "stack-edu-0035.json.gz:302554",
"repo_name": "martinve/ylikool",
"revision_date": "2014-04-01T18:34:30",
"revision_id": "cda7f97a83d75c5566b84396f8894b3a42c97daa",
"snapshot_id": "05c4de1fcd3c604452b9026c5abf0464d75d0525",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/martinve/ylikool/cda7f97a83d75c5566b84396f8894b3a42c97daa/javascripts/script.js",
"visit_date": "2020-12-01T11:37:43.059910",
"added": "2024-11-19T01:28:18.715535+00:00",
"created": "2014-04-01T18:34:30",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
/************************************************************************************
* @file aaFlash.h
************************************************************************************/
#ifndef aaFlash_h // Start of precompiler check to avoid dupicate inclusion of this code block.
#define aaFlash_h // Precompiler macro used for precompiler check.
/************************************************************************************
* @section aaFlashIncludes Included libraries.
************************************************************************************/
#include <Arduino.h> // Arduino Core for ESP32. Comes with Platform.io.
#include <Preferences.h> // Required for saving variables into Flash memory.
/************************************************************************************
* @class Read/write to/from flash RAM.
************************************************************************************/
class aaFlash // Indicate that we are extending LiquidCrystal_I2C class with our class
{
public:
aaFlash(); // Default constructor for this class.
aaFlash(const char* var1); // Second form of class constructor.
~aaFlash(); // Class destructor.
IPAddress readBrokerIP(); // Read from flash memory.
void writeBrokerIP(IPAddress address); // Write to flash memory.
private:
}; //class aaFlash
#endif // End of precompiler protected code block
|
5c588637f8ef5ed09578d913809bdb96e211c620
|
{
"blob_id": "5c588637f8ef5ed09578d913809bdb96e211c620",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-21T19:35:27",
"content_id": "805d9a1177b4ac4d954e883665b47b429f59d65c",
"detected_licenses": [
"MIT"
],
"directory_id": "d4ae4b93c2bf81567940c51a0c85fd811fd04340",
"extension": "h",
"filename": "aaFlash.h",
"fork_events_count": 0,
"gha_created_at": "2019-11-05T19:32:46",
"gha_event_created_at": "2021-10-21T19:34:04",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 219834635,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1421,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/aaFlash/aaFlash.h",
"provenance": "stack-edu-0008.json.gz:444310",
"repo_name": "va3wam/ZippiTwipi",
"revision_date": "2021-10-21T19:35:27",
"revision_id": "ed0d912b6fd3b0c89437c09fc9292eae96c382ba",
"snapshot_id": "a733e95ca84f6f6e44263c4f1228917ded5accfa",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/va3wam/ZippiTwipi/ed0d912b6fd3b0c89437c09fc9292eae96c382ba/lib/aaFlash/aaFlash.h",
"visit_date": "2021-10-25T08:05:08.435845",
"added": "2024-11-18T21:25:44.311207+00:00",
"created": "2021-10-21T19:35:27",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
import {AppService} from "../service/app-service";
import {ImportFilterDTO} from "../dto/import-filter-dto";
declare var app: AppService;
require('./../../bootstrap.js');
let program = require('commander');
program
.version('1.0.0');
let stdio: any = require('stdio');
let ops: any = stdio.getopt({
'short': {args: 1},
'long': {args: 1},
});
let short: number = ops.short ? +ops.short : 3;
let long: number = ops.long ? +ops.long : 30;
let filter: ImportFilterDTO = new ImportFilterDTO(short, long);
let update: Function = () => {
app.getImportTasksService().import(filter);
};
update();
setInterval(update, 30000);
|
229f1e46b79a7c6a740e66e8f81d603d485ee2e4
|
{
"blob_id": "229f1e46b79a7c6a740e66e8f81d603d485ee2e4",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-20T14:28:24",
"content_id": "a96d1b677b4ba66fb94a3a93b38a9336557c8cd3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5853154ab6c6aa343d1767f040f85031365a262f",
"extension": "ts",
"filename": "import.ts",
"fork_events_count": 0,
"gha_created_at": "2015-11-09T11:36:19",
"gha_event_created_at": "2016-04-20T14:28:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 45834303,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 638,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/server/app/src/task/import.ts",
"provenance": "stack-edu-0075.json.gz:49247",
"repo_name": "Awakehl/team-lead-dashboard",
"revision_date": "2016-04-20T14:28:24",
"revision_id": "a27011a2ee781c69795c4851023192df448eaf5e",
"snapshot_id": "94e36062d562bd0798af795a76498efa20d2a587",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Awakehl/team-lead-dashboard/a27011a2ee781c69795c4851023192df448eaf5e/server/app/src/task/import.ts",
"visit_date": "2021-05-02T10:38:40.689989",
"added": "2024-11-18T21:59:20.655423+00:00",
"created": "2016-04-20T14:28:24",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package looping;
/**
*
* @author nermin.khalefa
*/
import java.util.Scanner;
public class Authentication {
public static void main(String[] args) {
// declare variables for controling number of attempts
String correctPassword = "Pizza";
int numberOfAttempts = 0;
int maxNumberOfAttempts = 5;
String userInput;
// create a scanner and store it in variable of our choice
Scanner scanner = new Scanner(System.in);
// prompt user and get an int from them
System.out.println("*** Authenitcator Revisited ***");
// grab an int from the user and store it
while (numberOfAttempts <= maxNumberOfAttempts) {
System.out.println("Enter the system password to learn the protected information");
userInput = scanner.next();
// comment
if (userInput.equals(correctPassword)) {
System.out.println("Congrats, the password you have entered is correct!!!");
} else {
System.out.println("The password you have entered is incorrect, only 4 attempts left");
}// close else statement
System.out.println("the number of attempts: " + numberOfAttempts);
numberOfAttempts = numberOfAttempts + 1;
} // close while
} // close main
} // close class
|
04e528a7cf1cae68ea043e5bb710e012441cc494
|
{
"blob_id": "04e528a7cf1cae68ea043e5bb710e012441cc494",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-12T18:26:15",
"content_id": "b86e0a81e28e8ff9568d2538edb3c1dc14f75d06",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c9872b65f596332d22500f0bb77182b260a608f8",
"extension": "java",
"filename": "Authentication.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150469333,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1597,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/looping/Authentication.java",
"provenance": "stack-edu-0022.json.gz:313678",
"repo_name": "NerminKhalefa/cit111_ccac",
"revision_date": "2018-12-12T18:26:15",
"revision_id": "66b2d805f4ba41537fb3782ecf6ba7ef6b21d8c1",
"snapshot_id": "f3d38bae9117b1b0504142a121d360f04a152896",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NerminKhalefa/cit111_ccac/66b2d805f4ba41537fb3782ecf6ba7ef6b21d8c1/looping/Authentication.java",
"visit_date": "2020-03-29T23:22:19.580771",
"added": "2024-11-19T00:30:11.566597+00:00",
"created": "2018-12-12T18:26:15",
"int_score": 4,
"score": 3.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
import type { ErrorObject } from 'ajv';
import type { JsonSchema, UISchemaElement } from '../models';
export type Translator = {
(id: string, defaultMessage: string, values?: any): string;
(id: string, defaultMessage: undefined, values?: any): string | undefined;
(id: string, defaultMessage?: string, values?: any): string | undefined;
};
export type ErrorTranslator = (
error: ErrorObject,
translate: Translator,
uischema?: UISchemaElement
) => string;
export interface JsonFormsI18nState {
locale?: string;
translate?: Translator;
translateError?: ErrorTranslator;
}
export type i18nJsonSchema = JsonSchema & { i18n?: string };
|
be887d408a34e8edff1b1adee58e34002ac1f09e
|
{
"blob_id": "be887d408a34e8edff1b1adee58e34002ac1f09e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-21T14:37:29",
"content_id": "64002f393a29e1292bca2527512aef1e1d9206f7",
"detected_licenses": [
"MIT"
],
"directory_id": "d5ff27805fe073b333718334072ad31215d9460f",
"extension": "ts",
"filename": "i18nTypes.ts",
"fork_events_count": 345,
"gha_created_at": "2015-02-13T10:24:06",
"gha_event_created_at": "2023-09-11T11:08:15",
"gha_language": "TypeScript",
"gha_license_id": "NOASSERTION",
"github_id": 30751591,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 653,
"license": "MIT",
"license_type": "permissive",
"path": "/packages/core/src/i18n/i18nTypes.ts",
"provenance": "stack-edu-0072.json.gz:403841",
"repo_name": "eclipsesource/jsonforms",
"revision_date": "2023-08-11T12:17:38",
"revision_id": "c1686c1db33332bd7e820d53fdc29c27439acf1e",
"snapshot_id": "6c34c634c93a7ae8160f5214ca4fa6f0764f584f",
"src_encoding": "UTF-8",
"star_events_count": 1671,
"url": "https://raw.githubusercontent.com/eclipsesource/jsonforms/c1686c1db33332bd7e820d53fdc29c27439acf1e/packages/core/src/i18n/i18nTypes.ts",
"visit_date": "2023-08-29T08:29:25.666201",
"added": "2024-11-19T02:17:06.182550+00:00",
"created": "2023-08-11T12:17:38",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Picker.Core.Spider;
using Picker.Core.Storage;
using Picker.Core.Helpers;
using Picker.Core.Models;
namespace Picker.Postgresql {
public partial class StoreContext {
public void OpenQichachaDatabase( string connString ) {
qichachaContext = new QichachaDataContext( connString );
}
public List<StatisticsItem> Qichacha_LoadStatistics() {
List<StatisticsItem> data = new List<StatisticsItem>();
long companyCount = qichachaContext.QichachaCompany.LongCount();
data.Add( new StatisticsItem() {
Key = "company",
Title = "Company",
Count = companyCount,
ProcessedCount = qichachaContext.QichachaCompany.Where( i => i.Content != null ).LongCount(),
TaskCount = companyCount
} );
long trademarkCount = qichachaContext.QichachaTrademark.LongCount();
data.Add( new StatisticsItem() {
Key = "trademark",
Title = "Trademark",
ProcessedCount = qichachaContext.QichachaTrademark.Where( i => i.Content != null ).LongCount(),
Count = trademarkCount,
TaskCount = qichachaContext.QichachaCompany.Where( i => i.TrademarkUpdated == null ).LongCount()
} );
long patentCount = qichachaContext.QichachaPatent.LongCount();
data.Add( new StatisticsItem() {
Key = "patent",
Title = "Patent",
ProcessedCount = qichachaContext.QichachaPatent.Where( i => i.Content != null ).LongCount(),
Count = patentCount,
TaskCount = qichachaContext.QichachaCompany.Where( i => i.PatentUpdated == null ).LongCount()
} );
long investCount = qichachaContext.QichachaInvest.LongCount();
data.Add( new StatisticsItem() {
Key = "invest",
Title = "Invest",
Count = investCount
} );
long copyrightCount = qichachaContext.QichachaCopyright.LongCount();
data.Add( new StatisticsItem() {
Key = "copyright",
Title = "Copyright",
Count = copyrightCount
} );
long softwareCopyrightCount = qichachaContext.QichachaSoftwareCopyright.LongCount();
data.Add( new StatisticsItem() {
Key = "software-copyright",
Title = "SoftwareCopyright",
Count = softwareCopyrightCount
} );
long certificateCount = qichachaContext.QichachaCertificate.LongCount();
data.Add( new StatisticsItem() {
Key = "certificate",
Title = "Certificate",
ProcessedCount = qichachaContext.QichachaCertificate.Where( i => i.Content != null ).LongCount(),
Count = certificateCount,
TaskCount = qichachaContext.QichachaCompany.Where( i => i.CertificateUpdated == null ).LongCount()
} );
long websiteCount = qichachaContext.QichachaWebsite.LongCount();
data.Add( new StatisticsItem() {
Key = "website",
Title = "Website",
Count = websiteCount
} );
long albumCount = qichachaContext.QichachaAlbum.LongCount();
data.Add( new StatisticsItem() {
Key = "album",
Title = "Company Album",
Count = albumCount,
ProcessedCount = qichachaContext.QichachaAlbum.Where( i => i.ProcessedAt != null ).LongCount()
} );
return data;
}
public async Task<int> Qichacha_SaveChanges() {
int r = 0;
try {
//r = await qichachaContext.SaveChangesAsync();
qichachaContext.SubmitChanges();
return r;
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveChanges" );
Console.WriteLine( ex.Message );
return r;
}
}
public void Qichacha_SaveAlbum( string uri, string title, DateTime? modified, bool updateIfExists, bool saveChanges ) {
try {
QichachaAlbum item = qichachaContext.QichachaAlbum.Where( i => i.Uri == uri ).FirstOrDefault();
if ( item != null && updateIfExists ) {
item.Title = title;
item.ModifiedAt = modified;
}
else if ( item == null ) {
// get id from http://qichacha.com/album_view_id_1050.shtml
int id = ApiHelper.GetInt( uri, "album_view_id_", ".shtml" );
item = new QichachaAlbum();
item.Uri = uri;
item.Id = id;
item.Title = title;
item.ModifiedAt = modified;
item.CreatedAt = DateTime.UtcNow;
qichachaContext.QichachaAlbum.InsertOnSubmit( item );
}
if ( saveChanges )
//return await qichachaContext.SaveChangesAsync();
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveAlbum #uri: " + uri );
Console.WriteLine( ex.Message );
}
}
public string Qichacha_GetAlbumUri_NeedToProcess() {
QichachaAlbum item = qichachaContext.QichachaAlbum
.Where( i => i.ProcessedAt == null || (
i.ModifiedAt != null && i.ProcessedAt.Value < i.ModifiedAt.Value
) )
.FirstOrDefault();
return item == null ? null : item.Uri;
}
public void Qichacha_UpdateTag_Album( string uri, bool saveChanges ) {
try {
QichachaAlbum item = qichachaContext.QichachaAlbum.Where( i => i.Uri == uri ).FirstOrDefault();
if ( item != null ) {
item.ProcessedAt = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_Album #uri: " + uri );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyInvest( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.InvestUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyInvest #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyTrademark( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.TrademarkUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyTrademark #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyPatent( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.PatentUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyPatent #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyCertificate( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.CertificateUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyCertificate #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyCopyright( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.CopyrightUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyCopyright #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanySoftwareCopyright( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.SoftwareCopyrightUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanySoftwareCopyright #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateTag_CompanyWebsite( string id, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null ) {
item.WebsiteUpdated = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateTag_CompanyWebsite #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_UpdateCompanySearch( string keyword, int page, bool saveChanges ) {
try {
QichachaCompanySearch item = qichachaContext.QichachaCompanySearch.Where( i => i.Keyword == keyword ).FirstOrDefault();
if ( item == null ) {
item = new QichachaCompanySearch();
item.Keyword = keyword;
item.CreatedAt = DateTime.UtcNow;
qichachaContext.QichachaCompanySearch.InsertOnSubmit( item );
}
item.ProcessedPage = page;
item.UpdatedAt = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_UpdateCompanySearch #keyword: " + keyword );
Console.WriteLine( ex.Message );
}
}
public KeyValuePair<string, int> Qichacha_GetLast_CompanySearch() {
QichachaCompanySearch item = qichachaContext.QichachaCompanySearch.Where( i => i.ProcessedPage >= 0 ).FirstOrDefault();
if ( item == null )
return new KeyValuePair<string, int>( null, -1 );
return new KeyValuePair<string, int>( item.Keyword, item.ProcessedPage );
}
public async Task<int> Qichacha_SaveCompanyKey( string id, string name, bool updateIfExists, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item != null && updateIfExists ) {
item.Name = name;
item.UpdatedAt = DateTime.UtcNow;
}
else if ( item == null ) {
item = new QichachaCompany();
item.Id = id;
item.Name = name;
item.CreatedAt = DateTime.UtcNow;
item.UpdatedAt = DateTime.UtcNow;
qichachaContext.QichachaCompany.InsertOnSubmit( item );
}
if ( saveChanges )
//return await qichachaContext.SaveChangesAsync();
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveCompanyKey #id: " + id );
Console.WriteLine( ex.Message );
}
return 0;
}
public void Qichacha_SaveTrademarkKey( List<string> idlist ) {
if ( idlist == null || idlist.Count == 0 )
return;
try {
foreach ( string id in idlist ) {
QichachaTrademark item = qichachaContext.QichachaTrademark.Where( i => i.Id == id ).FirstOrDefault();
if ( item == null ) {
item = new QichachaTrademark();
item.Id = id;
item.CreatedAt = DateTime.UtcNow;
qichachaContext.QichachaTrademark.InsertOnSubmit( item );
}
}
// save changes
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveTrademarkKey" );
Console.WriteLine( ex.Message );
}
}
public string Qichacha_GetTaskFromCompany_BasicInfo( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Content == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Invest( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.InvestUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Trademark( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.TrademarkUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Patent( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.PatentUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Certificate( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.CertificateUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Copyright( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.CopyrightUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_SoftwareCopyright( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.SoftwareCopyrightUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTaskFromCompany_Website( out string companyName ) {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.WebsiteUpdated == null ).FirstOrDefault();
companyName = item == null ? null : item.Name;
return item == null ? null : item.Id;
}
public string Qichacha_GetTask_Trademark() {
QichachaTrademark item = qichachaContext.QichachaTrademark.Where( i => i.Content == null ).FirstOrDefault();
return item == null ? null : item.Id;
}
public void Qichacha_SaveCompany_BasicInfo( string id, string name, string regNum, string orgCode, string content, bool saveChanges ) {
try {
QichachaCompany item = qichachaContext.QichachaCompany.Where( i => i.Id == id ).FirstOrDefault();
if ( item == null ) {
item = new QichachaCompany();
item.Id = id;
item.CreatedAt = DateTime.UtcNow;
qichachaContext.QichachaCompany.InsertOnSubmit( item );
}
item.Name = name;
item.RegNum = regNum;
item.OrgCode = orgCode;
item.Content = content;
item.UpdatedAt = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveCompany_BasicInfo #id: " + id );
Console.WriteLine( ex.Message );
}
}
public void Qichacha_SaveDetail_Trademark( string id, string name, string regNo, string applicant, string content, bool saveChanges ) {
try {
QichachaTrademark item = qichachaContext.QichachaTrademark.Where( i => i.Id == id ).FirstOrDefault();
if ( item == null ) {
item = new QichachaTrademark();
item.Id = id;
item.CreatedAt = DateTime.UtcNow;
qichachaContext.QichachaTrademark.InsertOnSubmit( item );
}
item.Name = name;
item.RegNo = regNo;
item.Applicant = applicant;
item.Content = content;
item.UpdatedAt = DateTime.UtcNow;
if ( saveChanges )
qichachaContext.SubmitChanges();
}
catch ( Exception ex ) {
Console.WriteLine( "Qichacha_SaveDetail_Trademark #id: " + id );
Console.WriteLine( ex.Message );
}
}
}
}
|
93d87c6b958fc2e94013d6df42dadf9c1d737420
|
{
"blob_id": "93d87c6b958fc2e94013d6df42dadf9c1d737420",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-14T10:29:12",
"content_id": "02b852a2cf5505cab8398a3c20c53de7202e24e8",
"detected_licenses": [
"MIT"
],
"directory_id": "1acd8c5f4408051d8f004f104eee383e729fd578",
"extension": "cs",
"filename": "StoreContext.Qichacha.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32967927,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 16817,
"license": "MIT",
"license_type": "permissive",
"path": "/Picker/Picker.Postgresql/StoreContext.Qichacha.cs",
"provenance": "stack-edu-0013.json.gz:383332",
"repo_name": "13f/picker",
"revision_date": "2017-12-14T10:29:12",
"revision_id": "97d7d2e112ae4f2d20175b05503828f54ab46818",
"snapshot_id": "b769babab84bc33946a1967b730951dea22bd661",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/13f/picker/97d7d2e112ae4f2d20175b05503828f54ab46818/Picker/Picker.Postgresql/StoreContext.Qichacha.cs",
"visit_date": "2021-05-16T02:25:26.844285",
"added": "2024-11-19T01:01:05.756067+00:00",
"created": "2017-12-14T10:29:12",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
(function($){
var $topNavElements = $('header a');
$('.screen').scrollspy(
{
outCallback: function ($element) {
$topNavElements.filter('[href="#' + $element.attr('id') + '"]').removeClass('active');
$element.find('.side').html('');
},
inCallback: function ($element, side) {
$topNavElements.filter('[href="#' + $element.attr('id') + '"]').addClass('active');
$element.find('.side').html(side);
}
}
);
})(jQuery);
|
cd199aae7335f1d38c55b754ddb1bd77ff3d3d37
|
{
"blob_id": "cd199aae7335f1d38c55b754ddb1bd77ff3d3d37",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-04T09:23:15",
"content_id": "9ed0fba7e2e6c70b31c7abadf25bec25d6b16064",
"detected_licenses": [
"MIT"
],
"directory_id": "ffad0d64a85d713551d0b384588c83a81819fb4a",
"extension": "js",
"filename": "scripts.js",
"fork_events_count": 0,
"gha_created_at": "2017-06-07T16:41:46",
"gha_event_created_at": "2020-05-04T09:21:09",
"gha_language": "JavaScript",
"gha_license_id": "NOASSERTION",
"github_id": 93657620,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 554,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/assets/scripts.js",
"provenance": "stack-edu-0045.json.gz:688785",
"repo_name": "ROCK5GmbH/jquery.r5-scrollspy",
"revision_date": "2020-05-04T09:23:15",
"revision_id": "2dbbf032cbdc5d769eb10f9fc062c3bfa8a72f1c",
"snapshot_id": "08a383afb854c4daea3602645a16980c24f5a2bf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ROCK5GmbH/jquery.r5-scrollspy/2dbbf032cbdc5d769eb10f9fc062c3bfa8a72f1c/examples/assets/scripts.js",
"visit_date": "2021-07-13T16:36:01.698221",
"added": "2024-11-19T02:31:49.704746+00:00",
"created": "2020-05-04T09:23:15",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz"
}
|
import React, { useState, useRef, useCallback } from 'react';
import { ValueNotifier, useListen } from './listenable';
export * from './listenable';
export class SharedState<T> extends ValueNotifier<T> {}
/**
* Hook a shared state to component
*
* @param sharedState Shared state to hook
* @param shouldUpdate Boolean or function to decide whether to re-render current component when the value of the shared state changes
*/
export function useSharedState<T>(
sharedState: SharedState<T>,
shouldUpdate: boolean | ((current: T, previous: T) => boolean) = true,
): [T, React.Dispatch<React.SetStateAction<T>>] {
const [state, setState] = useState<T>(sharedState.getValue());
const stateRef = useRef(state);
stateRef.current = state;
const shouldUpdateRef = useRef(shouldUpdate);
shouldUpdateRef.current = shouldUpdate;
const listener = useCallback((current: T, previous: T) => {
const f = shouldUpdateRef.current;
if (f === false || (f instanceof Function && !f(current, previous))) {
// If the `shouldUpdate` is or returns false, do not update state
return;
}
setState(current);
}, []);
const onListen = useCallback(() => {
// If the state changed before the listener is added, notify the listener
if (sharedState.getValue() !== stateRef.current) {
listener(sharedState.getValue(), stateRef.current);
}
}, [sharedState, listener]);
useListen(sharedState, listener, onListen);
// return the same function object between renderings
const setSharedState = useCallback(
(v: React.SetStateAction<T>) => {
sharedState.setValue(v);
},
[sharedState],
);
return [sharedState.getValue(), setSharedState];
}
|
f62f34bb212eb3f3100b9a020ce35592c51cd33b
|
{
"blob_id": "f62f34bb212eb3f3100b9a020ce35592c51cd33b",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-16T01:46:55",
"content_id": "04fb2fb7774d90d620f45d2b7fae464cc71f7174",
"detected_licenses": [
"MIT"
],
"directory_id": "c22009a66246a5b75baa9e8e5c3a352f62cbd996",
"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": 1704,
"license": "MIT",
"license_type": "permissive",
"path": "/src/index.ts",
"provenance": "stack-edu-0074.json.gz:887832",
"repo_name": "iqingting/use-shared-state",
"revision_date": "2021-08-16T01:46:55",
"revision_id": "cc0094b0f409e1201ab665880e17383f7f381e8f",
"snapshot_id": "ed87e4f045bfc347cae94268b16fe2abd0eab322",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iqingting/use-shared-state/cc0094b0f409e1201ab665880e17383f7f381e8f/src/index.ts",
"visit_date": "2023-07-14T14:02:48.088342",
"added": "2024-11-19T02:17:11.066363+00:00",
"created": "2021-08-16T01:46:55",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
//#define KEYBOARD_MODE
using RotaryHeart.Lib.PhysicsExtension;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using Physics = UnityEngine.Physics;
public class JoyconDemo : MonoBehaviour
{
public enum HandState
{
Idle,
GoingDown,
GoingUp,
ChargingYeet,
Yeeting,
}
public List<Joycon> joycons;
public HandState handState;
// Values made available via Unity
public float[] stick;
public Vector3 gyro;
private Vector3 oldAccel;
public Vector3 accel;
public int jc_ind = 0;
public Quaternion orientation;
public float descentSpeed = 0.05f;
public float ascentSpeed = 0.15f;
private Transform transform;
public float sensitivity;
public float MaxDescentPosition;
public float OriginalYPosition;
public Material material;
private Vector2 materialOffset;
public bool holdingSomethingYeetable
{
get { return currentMergeableObject != null && currentMergeableObject.Yeetable; }
}
public float yeetingPower = 0f;
public float yeetRotMin;
public float yeetRotMax;
public bool yeetDirection;
public Transform yeetingContrainerTransform;
public float yeetingRotationMaxTime;
public float yeetingRotationTimer;
public Transform ourPosition;
public JoyconDemo opponent;
public Transform opponentPosition;
public LayerMask grabbiesLayerMask;
public Transform grabbyPoint;
private MergeableObject currentMergeableObject = null;
public float grabbyYOriginalPoint;
public float grabbySpeedIncrement = 1.1f;
public Transform frontCloud;
public Transform backCloud;
private Joycon.Button holdingButton = Joycon.Button.CAPTURE;
[ShowOnly]
public float startPressTime = 0f;
private float holdDurationRequirement = 0.3f;
private Hover hover1;
private Hover hover2;
[System.Serializable]
public class YeetEvent : UnityEvent<int>
{
}
public YeetEvent onYeetEvent;
private const int MAX_YEETING_POWER = 500;
public float yeetRotOriginal;
void Start()
{
transform = gameObject.transform;
gyro = new Vector3(0, 0, 0);
accel = new Vector3(0, 0, 0);
handState = HandState.Idle;
materialOffset = material.mainTextureOffset;
materialOffset.y = -0.5f;
material.mainTextureOffset = materialOffset;
hover1 = frontCloud.GetComponent<Hover>();
hover2 = backCloud.GetComponent<Hover>();
hover1.UpdateRotation = false;
hover2.UpdateRotation = false;
// get the public Joycon array attached to the JoyconManager in scene
joycons = JoyconManager.Instance.j;
//if (joycons.Count < jc_ind + 1)
//{
// Destroy(gameObject);
//}
}
// Update is called once per frame
void Update()
{
if (GameFlowManager.Instance.GameOver) return;
#if !KEYBOARD_MODE
// make sure the Joycon only gets checked if attached
if (joycons.Count > 0)
{
Joycon j = joycons[jc_ind];
// GetButtonDown checks if a button has been pressed (not held)
//if (j.GetButtonDown(Joycon.Button.SHOULDER_2))
//{
// Debug.Log("Shoulder button 2 pressed");
// // GetStick returns a 2-element vector with x/y joystick components
// Debug.Log(string.Format("Stick x: {0:N} Stick y: {1:N}", j.GetStick()[0], j.GetStick()[1]));
// // Joycon has no magnetometer, so it cannot accurately determine its yaw value. Joycon.Recenter allows the user to reset the yaw value.
// j.Recenter();
//}
//if (j.GetButtonDown(Joycon.Button.DPAD_DOWN))
//{
// Debug.Log("Rumble");
// // Rumble for 200 milliseconds, with low frequency rumble at 160 Hz and high frequency rumble at 320 Hz. For more information check:
// // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
// j.SetRumble(160, 320, 0.6f, 200);
// // The last argument (time) in SetRumble is optional. Call it with three arguments to turn it on without telling it when to turn off.
// // (Useful for dynamically changing rumble values.)
// // Then call SetRumble(0,0,0) when you want to turn it off.
//}
//if (j.GetButtonDown(Joycon.Button.DPAD_LEFT))
//{
// Debug.Log("Rumble");
// // Rumble for 200 milliseconds, with low frequency rumble at 160 Hz and high frequency rumble at 320 Hz. For more information check:
// // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
// int low_freq = Random.Range(100, 150);
// int high_freq = Random.Range(320, 500);
// float amp = Random.Range(0.5f, 1f);
// int time = Random.Range(100, 500);
// j.SetRumble(low_freq, high_freq, amp, time);
// // The last argument (time) in SetRumble is optional. Call it with three arguments to turn it on without telling it when to turn off.
// // (Useful for dynamically changing rumble values.)
// // Then call SetRumble(0,0,0) when you want to turn it off.
//}
stick = j.GetStick();
// Gyro values: x, y, z axis values (in radians per second)
gyro = j.GetGyro();
// Accel values: x, y, z axis values (in Gs)
oldAccel = accel;
accel = j.GetAccel();
orientation = j.GetVector();
var position = transform.position;
float sensitivity = this.sensitivity / 1000;
position.x += stick[0] * sensitivity;
position.z += stick[1] * sensitivity;
ClampPosition(ref position);
hover1.UpdateRotation = false;
hover2.UpdateRotation = false;
if (handState == HandState.Idle)
{
if (j.GetButtonDown(Joycon.Button.SHOULDER_2))
{
holdingButton = Joycon.Button.SHOULDER_2;
startPressTime = Time.time;
}
else if (j.GetButtonDown(Joycon.Button.STICK))
{
holdingButton = Joycon.Button.STICK;
startPressTime = Time.time;
}
else if (holdingButton != Joycon.Button.CAPTURE)
{
if (j.GetButtonUp(holdingButton))
{
holdingButton = Joycon.Button.CAPTURE;
handState = HandState.GoingDown;
startPressTime = 0;
}
else if (holdingSomethingYeetable && Time.time - startPressTime > holdDurationRequirement)
{
handState = HandState.ChargingYeet;
startPressTime = 0;
}
}
//if (j.GetButton(Joycon.Button.SHOULDER_1))
//{
// handState = HandState.GoingDown;
//}
//else if (holdingSomethingYeetable && j.GetButton(Joycon.Button.SHOULDER_2))
//{
// handState = HandState.ChargingYeet;
//}
}
if (handState == HandState.ChargingYeet)
{
if (j.GetButton(holdingButton))
{
yeetingPower += (oldAccel - accel).magnitude;
yeetingPower = Mathf.Clamp(yeetingPower, 0, MAX_YEETING_POWER);
var yeetNormalized = Mathf.Clamp01(yeetingPower / MAX_YEETING_POWER);
var yoteMax = Mathf.Lerp(80, 320, yeetNormalized);
var yoteMin = Mathf.Lerp(80, 160, yeetNormalized);
j.SetRumble(yoteMin, yoteMax, 0.6f);
}
else if (j.GetButtonUp(holdingButton))
{
holdingButton = Joycon.Button.CAPTURE;
//Debug.LogFormat("Yoting {0}", yeetingPower);
handState = HandState.Yeeting;
var yeetNormalized = Mathf.Clamp01(yeetingPower / MAX_YEETING_POWER);
var yoteMax = Mathf.Lerp(80, 320, yeetNormalized);
var yoteMin = Mathf.Lerp(80, 160, yeetNormalized);
j.SetRumble(yoteMin, yoteMax, 0.6f, 200);
var direction = ourPosition.position.x <= opponentPosition.position.x;
if (yeetDirection != direction)
{
yeetRotMin *= -1;
yeetRotMax *= -1;
}
yeetDirection = direction;
}
}
if (handState == HandState.GoingDown)
{
position.y -= descentSpeed * Time.deltaTime;
var grabbyPointPosition = grabbyPoint.localPosition;
grabbyPointPosition.y -= descentSpeed * grabbySpeedIncrement * Time.deltaTime;
grabbyPoint.localPosition = grabbyPointPosition;
var positionTraveled = Mathf.InverseLerp(MaxDescentPosition, OriginalYPosition, position.y);
materialOffset.y = GetTextureOffsetModifier(positionTraveled);
//Debug.LogFormat("GoingDown: Position Traveled = {0} => Mat offset = {1}", positionTraveled, materialOffset.y);
material.mainTextureOffset = materialOffset;
if (position.y <= MaxDescentPosition)
{
position.y = MaxDescentPosition;
DetectObjectCollision();
handState = HandState.GoingUp;
materialOffset.y = 0;
material.mainTextureOffset = materialOffset;
}
}
else if (handState == HandState.GoingUp)
{
position.y += ascentSpeed * Time.deltaTime;
var grabbyPointPosition = grabbyPoint.localPosition;
grabbyPointPosition.y += ascentSpeed * grabbySpeedIncrement * Time.deltaTime;
var positionTraveled = Mathf.InverseLerp(MaxDescentPosition, OriginalYPosition, position.y);
materialOffset.y = GetTextureOffsetModifier(positionTraveled);
//Debug.LogFormat("GoingUp: Position Traveled = {0} => Mat offset = {1}", positionTraveled, materialOffset.y);
material.mainTextureOffset = materialOffset;
if (position.y >= OriginalYPosition)
{
position.y = OriginalYPosition;
handState = HandState.Idle;
materialOffset.y = -0.5f;
material.mainTextureOffset = materialOffset;
grabbyPointPosition.y = grabbyYOriginalPoint;
}
grabbyPoint.localPosition = grabbyPointPosition;
}
else if (handState == HandState.Yeeting)
{
var rotation = yeetingContrainerTransform.rotation;
var euler = rotation.eulerAngles;
yeetingRotationTimer += Time.deltaTime;
var delta = Mathf.Clamp01(yeetingRotationTimer / yeetingRotationMaxTime);
if (delta >= 1)
{
handState = HandState.Idle;
yeetingRotationTimer = 0f;
euler.z = yeetRotOriginal;
yeetingPower = 0;
AudioManager.Instance.PlayYeet();
}
else
{
euler.z = Mathf.Lerp(yeetRotMin, yeetRotMax, delta);
}
if (delta > 0.8f && currentMergeableObject != null)
{
currentMergeableObject.transform.SetParent(null);
currentMergeableObject.hoverScript.UpdateRotation = true;
currentMergeableObject.YeetToPosition.YeetInit(currentMergeableObject.transform.position, opponent.backCloud, 30, 0.5f);
currentMergeableObject.YeetToPosition.Yeet(Mathf.RoundToInt(currentMergeableObject.Damage * yeetingPower), onYeetEvent);
currentMergeableObject = null;
}
rotation.eulerAngles = euler;
yeetingContrainerTransform.rotation = rotation;
}
else if (handState == HandState.ChargingYeet)
{
hover1.UpdateRotation = true;
hover2.UpdateRotation = true;
}
transform.position = position;
}
#endif
#if UNITY_EDITOR && KEYBOARD_MODE
else
{
var position = transform.position;
float sensitivity = this.sensitivity / 1000;
position.x += Input.GetAxis("Horizontal") * sensitivity;
position.z += Input.GetAxis("Vertical") * sensitivity;
ClampPosition(ref position);
hover1.UpdateRotation = false;
hover2.UpdateRotation = false;
if (handState == HandState.Idle)
{
if (Input.GetKeyDown(KeyCode.LeftControl))
{
handState = HandState.GoingDown;
}
else if (holdingSomethingYeetable && Input.GetKeyDown(KeyCode.Space))
{
handState = HandState.ChargingYeet;
}
}
if (handState == HandState.ChargingYeet)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yeetingPower += (oldAccel - accel).magnitude;
yeetingPower = Mathf.Clamp(yeetingPower, 0, MAX_YEETING_POWER);
var yeetNormalized = Mathf.Clamp01(yeetingPower / MAX_YEETING_POWER);
var yoteMax = Mathf.Lerp(80, 320, yeetNormalized);
var yoteMin = Mathf.Lerp(80, 160, yeetNormalized);
}
else if (Input.GetKeyUp(KeyCode.Space))
{
//Debug.LogFormat("Yoting {0}", yeetingPower);
handState = HandState.Yeeting;
var yeetNormalized = Mathf.Clamp01(yeetingPower / MAX_YEETING_POWER);
var yoteMax = Mathf.Lerp(80, 320, yeetNormalized);
var yoteMin = Mathf.Lerp(80, 160, yeetNormalized);
var direction = ourPosition.position.x <= opponentPosition.position.x;
if (yeetDirection != direction)
{
yeetRotMin *= -1;
yeetRotMax *= -1;
}
yeetDirection = direction;
}
}
if (handState == HandState.GoingDown)
{
position.y -= descentSpeed * Time.deltaTime;
var grabbyPointPosition = grabbyPoint.localPosition;
grabbyPointPosition.y -= descentSpeed * grabbySpeedIncrement * Time.deltaTime;
grabbyPoint.localPosition = grabbyPointPosition;
var positionTraveled = Mathf.InverseLerp(MaxDescentPosition, OriginalYPosition, position.y);
materialOffset.y = GetTextureOffsetModifier(positionTraveled);
//Debug.LogFormat("GoingDown: Position Traveled = {0} => Mat offset = {1}", positionTraveled, materialOffset.y);
material.mainTextureOffset = materialOffset;
if (position.y <= MaxDescentPosition)
{
position.y = MaxDescentPosition;
DetectObjectCollision();
handState = HandState.GoingUp;
materialOffset.y = 0;
material.mainTextureOffset = materialOffset;
}
}
else if (handState == HandState.GoingUp)
{
position.y += ascentSpeed * Time.deltaTime;
var grabbyPointPosition = grabbyPoint.localPosition;
grabbyPointPosition.y += ascentSpeed * grabbySpeedIncrement * Time.deltaTime;
var positionTraveled = Mathf.InverseLerp(MaxDescentPosition, OriginalYPosition, position.y);
materialOffset.y = GetTextureOffsetModifier(positionTraveled);
//Debug.LogFormat("GoingUp: Position Traveled = {0} => Mat offset = {1}", positionTraveled, materialOffset.y);
material.mainTextureOffset = materialOffset;
if (position.y >= OriginalYPosition)
{
position.y = OriginalYPosition;
handState = HandState.Idle;
materialOffset.y = -0.5f;
material.mainTextureOffset = materialOffset;
grabbyPointPosition.y = grabbyYOriginalPoint;
}
grabbyPoint.localPosition = grabbyPointPosition;
}
else if (handState == HandState.Yeeting)
{
var rotation = yeetingContrainerTransform.rotation;
var euler = rotation.eulerAngles;
yeetingRotationTimer += Time.deltaTime;
var delta = Mathf.Clamp01(yeetingRotationTimer / yeetingRotationMaxTime);
if (delta >= 1)
{
handState = HandState.Idle;
yeetingRotationTimer = 0f;
euler.z = yeetRotOriginal;
yeetingPower = 0;
}
else
{
euler.z = Mathf.Lerp(yeetRotMin, yeetRotMax, delta);
}
if (delta > 0.8f && currentMergeableObject != null)
{
currentMergeableObject.transform.SetParent(null);
currentMergeableObject.hoverScript.UpdateRotation = true;
currentMergeableObject.YeetToPosition.YeetInit(currentMergeableObject.transform.position, opponent.backCloud, 30, 0.5f);
currentMergeableObject.YeetToPosition.Yeet(Mathf.RoundToInt(currentMergeableObject.Damage * yeetingPower), onYeetEvent);
currentMergeableObject = null;
}
rotation.eulerAngles = euler;
yeetingContrainerTransform.rotation = rotation;
}
else if (handState == HandState.ChargingYeet)
{
hover1.UpdateRotation = true;
hover2.UpdateRotation = true;
}
transform.position = position;
}
#endif
}
public void GameOver(bool winner)
{
if (joycons.Count > 0)
{
Joycon j = joycons[jc_ind];
if (winner)
{
j.SetRumble(80, 320, 0.6f, 200);
}
else
{
j.SetRumble(80, 160, 0.6f, 200);
}
}
}
private float GetTextureOffsetModifier(float positionTraveled)
{
return Mathf.Lerp(0f, -0.5f, positionTraveled);
}
private void DetectObjectCollision()
{
var collisions = Physics.OverlapSphere(transform.position, 1.5f, grabbiesLayerMask);
DebugExtensions.DebugWireSphere(transform.position, Color.black, 1.5f, 2f);
if (collisions.Length == 0)
{
return;
}
var mergeableObject = collisions[0].GetComponentInParent<MergeableObject>();
if (currentMergeableObject == null)
{
currentMergeableObject = mergeableObject;
mergeableObject.transform.SetParent(grabbyPoint);
mergeableObject.transform.localPosition = Vector3.zero;
mergeableObject.transform.localRotation = Quaternion.identity;
mergeableObject.transform.localScale = Vector3.one;
collisions[0].enabled = false;
mergeableObject.GetComponent<FakeGravity>().enabled = false;
AudioManager.Instance.PlayCombineSuccess();
//Close hands
}
else
{
if (currentMergeableObject.UpgradeObjectByAddition(mergeableObject.VectorMaterial))
{
AudioManager.Instance.PlayCombineSuccess();
Destroy(mergeableObject.gameObject);
}
else
{
AudioManager.Instance.PlayCombineFail();
}
}
}
public static void ClampPosition(ref Vector3 position)
{
position.x = Mathf.Clamp(position.x, -13f, 13f);
position.z = Mathf.Clamp(position.z, -13f, 13f);
}
}
|
0b5774e6651b07d3372534b1fe77b233684adb1c
|
{
"blob_id": "0b5774e6651b07d3372534b1fe77b233684adb1c",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-02T15:52:30",
"content_id": "98c150d0fc269175969ae009afe70a12c3fa9d74",
"detected_licenses": [
"MIT"
],
"directory_id": "99af13a90dd60ea2da9107ed50578a9abf97f4d4",
"extension": "cs",
"filename": "JoyconDemo.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237601136,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 21608,
"license": "MIT",
"license_type": "permissive",
"path": "/Assets/1.Scripts/JoyconDemo.cs",
"provenance": "stack-edu-0012.json.gz:741980",
"repo_name": "CM2Walki/UntitledYeetGame",
"revision_date": "2020-02-02T15:52:30",
"revision_id": "3f15bff1fd0a2dc7731f3428034f81a9afd6db01",
"snapshot_id": "7f82c4f7a7820fa3eb10caeb8c890c60c6cb3d06",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CM2Walki/UntitledYeetGame/3f15bff1fd0a2dc7731f3428034f81a9afd6db01/Assets/1.Scripts/JoyconDemo.cs",
"visit_date": "2020-12-26T18:43:25.363512",
"added": "2024-11-19T00:12:56.855650+00:00",
"created": "2020-02-02T15:52:30",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
using System.Linq;
using UnityEngine;
using System.IO.Compression;
using UnityEditor;
namespace HestiaMaterialImporter.Core
{
public class ImageNames
{
internal string[] names;
internal string canonicalName;
public TextureImporterType importType = TextureImporterType.Default;
internal class Result
{
public bool shouldInvert = false;
public ZipArchiveEntry entry;
}
internal Result FindInPackage(string name, ZipArchive archive)
{
var candidates = archive.Entries
.Where(it => it.Name.ToLower().Contains(name.ToLower()))
.Where(it => names.Any(target => it.Name.ToLower().Contains(target.ToLower())));
if (candidates.Count() == 0) return null;
if (candidates.Count() > 1)
{
Debug.LogWarning($"More than one candidate for {names}, {string.Join(", ", candidates.Select(it => it.Name))}");
}
if (candidates.Count() == 0) return null;
var candidate = candidates.First();
if (this == Smoothness && candidate.Name.ToLower().Contains("rough"))
return new Result() { shouldInvert = true, entry = candidate };
return new Result() { entry = candidate };
}
private static readonly string[] albedoNames = { "color", "base", "albedo", "colour" };
public static readonly ImageNames Albedo = new ImageNames() { canonicalName = "Albedo", names = albedoNames };
private static readonly string[] roughnessNames = { "roughness", "rough", "smooth", "smoothness" };
public static readonly ImageNames Smoothness = new ImageNames() { canonicalName = "Smoothness", names = roughnessNames };
private static readonly string[] normalNames = { "normal", "nrm", "tangent" };
public static readonly ImageNames Normal = new ImageNames() { canonicalName = "Normal", names = normalNames, importType = TextureImporterType.NormalMap };
private static readonly string[] aoNames = { "ao", "ambientocclusion", "ambient_occlusion" };
public static readonly ImageNames AmbientOcclusion = new ImageNames() { canonicalName = "AmbientOcclusion", names = aoNames };
private static readonly string[] dispNames = { "disp", "displacement", "bump" };
public static readonly ImageNames Displacement = new ImageNames() { canonicalName = "Displacement", names = dispNames };
private static readonly string[] metalNames = { "metal", "metalness" };
public static readonly ImageNames Metalness = new ImageNames() { canonicalName = "Metalness", names = metalNames };
};
}
|
c498ccde794de7568274489219b07bd337fe991e
|
{
"blob_id": "c498ccde794de7568274489219b07bd337fe991e",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-04T15:21:35",
"content_id": "8c46d4ea2b03cd73d4cc7fe6f8133e9562629c57",
"detected_licenses": [
"MIT"
],
"directory_id": "380878dfa15cac97ef08f2c56d7ffc9751762f1a",
"extension": "cs",
"filename": "ImageNames.cs",
"fork_events_count": 6,
"gha_created_at": "2020-11-08T16:23:41",
"gha_event_created_at": "2021-01-01T13:59:33",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 311104284,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2708,
"license": "MIT",
"license_type": "permissive",
"path": "/Editor/Core/ImageNames.cs",
"provenance": "stack-edu-0014.json.gz:407380",
"repo_name": "oparaskos/unity-material-library",
"revision_date": "2020-12-04T15:21:35",
"revision_id": "1035650ff125f1c89fc8734803e12c72c9843d18",
"snapshot_id": "1f546dbd6c7406d0246b4882e5beeb662f953b8c",
"src_encoding": "UTF-8",
"star_events_count": 31,
"url": "https://raw.githubusercontent.com/oparaskos/unity-material-library/1035650ff125f1c89fc8734803e12c72c9843d18/Editor/Core/ImageNames.cs",
"visit_date": "2023-02-08T01:02:31.893092",
"added": "2024-11-18T21:04:13.298424+00:00",
"created": "2020-12-04T15:21:35",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
import express = require("express");
import ICategoryController = require("./.././controllers/ICategoryController");
import CategoryController = require("./.././controllers/CategoryController");
var router = express.Router();
class CategoryRoutes {
private _controller: ICategoryController;
constructor() {
this._controller = new CategoryController();
}
get routes() {
router.get("/category/child/", this._controller.getChildCategories.bind(this._controller));
router.get("/category/root/", this._controller.getRootCategory.bind(this._controller));
router.get("/category/:id", this._controller.findById.bind(this._controller));
router.get("/category", this._controller.getCategories.bind(this._controller));
router.post("/category", this._controller.createCategory.bind(this._controller));
router.put("/category/:id", this._controller.updateCategory.bind(this._controller));
router.delete("/category/:id", this._controller.removeCategory.bind(this._controller));
return router;
}
}
Object.seal(CategoryRoutes);
export = CategoryRoutes;
|
2aab7ce99a6ac7ab693ebd16b167787d6597483e
|
{
"blob_id": "2aab7ce99a6ac7ab693ebd16b167787d6597483e",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-20T08:10:28",
"content_id": "8c61c6db96eae3b2b9999ad5441f6428df8a6070",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "00e38f6c43b5e53c3fc54affef425fdae3102ff4",
"extension": "ts",
"filename": "CategoryRoutes.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 59103784,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1134,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/app_api/routes/CategoryRoutes.ts",
"provenance": "stack-edu-0075.json.gz:183560",
"repo_name": "JeffreyChan/loma_online_testing",
"revision_date": "2018-03-20T08:10:28",
"revision_id": "2cc44077c5ea3ebc05fceeab19933ea9b902e53d",
"snapshot_id": "04f7744aaf72e38eb7241d50c98e711033ccf0a5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/JeffreyChan/loma_online_testing/2cc44077c5ea3ebc05fceeab19933ea9b902e53d/src/app_api/routes/CategoryRoutes.ts",
"visit_date": "2021-01-17T12:56:41.491192",
"added": "2024-11-18T23:47:21.488254+00:00",
"created": "2018-03-20T08:10:28",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
package io.nettythrift;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.thrift.TBaseProcessor;
import org.apache.thrift.TException;
import io.nettythrift.bootstrap.ServerBootstrap;
import io.nettythrift.core.ThriftServerDef;
public class DemoServer {
public static void main(String[] args) throws Exception {
int port = 8083;
TBaseProcessor<?> processor = new TCalculator.Processor<TCalculator.Iface>(new CalcIfaceImpl());
ThriftServerDef serverDef = ThriftServerDef.newBuilder().listen(port)//
.withProcessor(processor)//
.using(Executors.newCachedThreadPool())//
.clientIdleTimeout(TimeUnit.SECONDS.toMillis(15)).build();
final ServerBootstrap server = new ServerBootstrap(serverDef);
// 启动 Server
server.start();
}
private static class CalcIfaceImpl implements TCalculator.Iface {
@Override
public String ping() throws TException {
System.out.println("*** ping()...");
return "PONG";
}
@Override
public int add(int num1, int num2) throws TException {
System.out.printf("*** add:(%d, %d)\n", num1, num2);
return num1 + num2;
}
@Override
public void zip(String str, int type) throws TException {
System.out.printf("*** zip:(%s, %d)\n", str, type);
}
@Override
public void uploadAction(String str) throws TException {
System.out.printf("*** uploadAction:(%s)\n", str);
}
}
}
|
37f5442419e96e55f6b40afe5b7e42ee8f8a2622
|
{
"blob_id": "37f5442419e96e55f6b40afe5b7e42ee8f8a2622",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-20T02:10:16",
"content_id": "59c5ddc5f880d944cddee58350b5ac5835c4930b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b831ab8817124341220f3652d82e49cce4a8db84",
"extension": "java",
"filename": "DemoServer.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": 1416,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/io.nettythrift/src/test/java/io/nettythrift/DemoServer.java",
"provenance": "stack-edu-0022.json.gz:306453",
"repo_name": "cgb-netty/nettythrift",
"revision_date": "2019-07-20T02:10:16",
"revision_id": "d8adbed53008fca88ffd18649896cc22d8490d5b",
"snapshot_id": "f3f82b9b64234ceb4497277b1824f7d68426b39a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cgb-netty/nettythrift/d8adbed53008fca88ffd18649896cc22d8490d5b/io.nettythrift/src/test/java/io/nettythrift/DemoServer.java",
"visit_date": "2023-03-25T10:18:52.732083",
"added": "2024-11-19T00:43:37.488480+00:00",
"created": "2019-07-20T02:10:16",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Crypt;
use App\cliente;
class clienteController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return cliente::All();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try{
$data = $request->all();
$cliente = new cliente();
$cliente->cedula = $data['cedula'];
$cliente->nombreape = $data['nombreape'];
$cliente->direccion = $data['direccion'];
$cliente->celular = $data['celular'];
$cliente->telefono = $data['telefono'];
$cliente->fechanacimiento = $data['fechanacimiento'];
$cliente->login = $data['login'];
$cliente->clave = Crypt::encrypt($data['clave']);
$cliente->save();
return JsonResponse::create(array('message' => "Cliente Guardado Correctamente", "request" =>json_encode($data)), 200);
}catch (Exception $exc){
return JsonResponse::create(array('message' => "No se pudo guardar el cliente", "exception"=>$exc->getMessage(), "request" =>json_encode($data)), 401);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
return cliente::find($id);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
/*
* autenticamos si el cliente y clave son correctas
*/
public function autenticarcliente(Request $request){
try{
$data = $request->all();
$user = cliente::select('id','cedula','nombreape','login','clave',
'telefono','fechanacimiento','correo')
->where('login',$data['user'])
->first();
if (empty($user)){
return JsonResponse::create(array('message' => "100", "request" =>json_encode('Cliente no esta en el Sistema')), 200);
}
$clave = Crypt::decrypt($user["clave"]);
if($data['clave'] != $clave){
return JsonResponse::create(array('message' => "200", "request" =>json_encode('Clave Incorrecta')), 200);
}
return JsonResponse::create($user);
}catch(Exception $ex){
return JsonResponse::create(array('message' => "No se puedo autenticar el usuario", "request" =>json_encode($data)), 401);
}
}
}
|
39d58aa9e5db82b75cd42bb147ab6bec7bd724b7
|
{
"blob_id": "39d58aa9e5db82b75cd42bb147ab6bec7bd724b7",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-26T01:16:03",
"content_id": "f0cc5fd5bfc18fc8a34f2c503f88b6b1d45ecdf8",
"detected_licenses": [
"MIT"
],
"directory_id": "d13a89e5471b1c302f46271022fb28844f05785f",
"extension": "php",
"filename": "clienteController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46527134,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3654,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/clienteController.php",
"provenance": "stack-edu-0048.json.gz:327983",
"repo_name": "farchenko90/Gpsarduinos",
"revision_date": "2016-01-26T01:16:03",
"revision_id": "6b3f4b5e4e3493869882a0d10d16c46140ab92c4",
"snapshot_id": "2b095b9a6e6a66644e5191d765440d14f052c607",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/farchenko90/Gpsarduinos/6b3f4b5e4e3493869882a0d10d16c46140ab92c4/app/Http/Controllers/clienteController.php",
"visit_date": "2016-08-11T06:32:22.068122",
"added": "2024-11-18T22:55:20.832847+00:00",
"created": "2016-01-26T01:16:03",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
/*
* $URL:https://secure.revolsys.com/svn/open.revolsys.com/rs-gis-dbase/trunk/src/main/java/com/revolsys/gis/format/xbase/io/XbaseDatasetReader.java $
* $Author:paul.austin@revolsys.com $
* $Date:2007-07-03 19:26:54 -0700 (Tue, 03 Jul 2007) $
* $Revision:410 $
* Copyright 2004-2005 Revolution Systems Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.revolsys.io.xbase;
import java.io.File;
import com.revolsys.data.io.AbstractDirectoryReader;
import com.revolsys.data.io.RecordDirectoryReader;
/**
* <p>
* The XbaseDatasetReader is a {@link RecordIterator} that can read .dbf data
* files contained in a single directory. The reader will iterate through the
* .dbf files in alphabetical order returning all features.
* </p>
* <p>
* See the {@link AbstractDirectoryReader} class for examples on how to use
* directory readers.
* </p>
*
* @author Paul Austin
* @see AbstractDirectoryReader
*/
public class XbaseDatasetReader extends RecordDirectoryReader {
/**
* Construct a new XbaseDatasetReader to read .dbf files from the specified
* directory.
*
* @param directory The directory containing the .dbf files.
*/
public XbaseDatasetReader(final File directory) {
setFileExtensions("dbf");
setDirectory(directory);
}
}
|
b3014467707ae0ceea36c56f78d02d16ca50f56e
|
{
"blob_id": "b3014467707ae0ceea36c56f78d02d16ca50f56e",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-21T01:18:19",
"content_id": "4765812d3793d493680a3e9162071b62635e1ce4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3f5d19ac4afb5ce1d38df0aa6638e18103f468e0",
"extension": "java",
"filename": "XbaseDatasetReader.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": 1801,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/com.revolsys.open.core/src/main/java/com/revolsys/io/xbase/XbaseDatasetReader.java",
"provenance": "stack-edu-0029.json.gz:208315",
"repo_name": "lequynhnhu/com.revolsys.open",
"revision_date": "2015-02-21T01:18:19",
"revision_id": "d660384b05a402fb4b62d30d1592563c74ae8df5",
"snapshot_id": "e94a25a8a127f5315a10aad32da6776407857e60",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lequynhnhu/com.revolsys.open/d660384b05a402fb4b62d30d1592563c74ae8df5/com.revolsys.open.core/src/main/java/com/revolsys/io/xbase/XbaseDatasetReader.java",
"visit_date": "2020-12-25T03:39:55.125381",
"added": "2024-11-18T23:14:15.499584+00:00",
"created": "2015-02-21T01:18:19",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateInvoicePaymentCollectionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('invoice_payment_collections', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('payment_mode_id')->nullable();
$table->string('payment_status',50)->nullable();
$table->string('unpaid_payment_reason',50)->nullable();
$table->decimal('paid_amt')->default(0.00);
$table->decimal('outstanding_amt')->default(0.00);
$table->string('bank_name',100)->nullable();
$table->string('cheque_no',50)->nullable();
$table->string('outstanding_amt_type',50)->nullable();
$table->string('recoverable_outstanding_amt_status',50)->nullable();
$table->string('nonrecoverable_outstanding_amt_status',50)->nullable();
$table->dateTime('expected_payment_date')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('invoice_payment_collections');
}
}
|
54a6e04720e4df016131918e3543d736c8bfa29e
|
{
"blob_id": "54a6e04720e4df016131918e3543d736c8bfa29e",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-09T18:47:10",
"content_id": "c0e6777db52e111f3267b4767b5f4ba64e1f9bb9",
"detected_licenses": [
"MIT"
],
"directory_id": "e697dffb3e0304c5766f4d9bf20ae16b545b4c06",
"extension": "php",
"filename": "2016_09_18_210001_create_invoice_payment_collections_table.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87731065,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1366,
"license": "MIT",
"license_type": "permissive",
"path": "/database/migrations/2016_09_18_210001_create_invoice_payment_collections_table.php",
"provenance": "stack-edu-0047.json.gz:138323",
"repo_name": "amitiitm/healthcare-home",
"revision_date": "2017-04-09T18:47:10",
"revision_id": "14615a79d616b004688ee2fbfa4745e00bab9f47",
"snapshot_id": "fbe3fcd6b6e0e2289d42e37aa7721ec9acbe3792",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/amitiitm/healthcare-home/14615a79d616b004688ee2fbfa4745e00bab9f47/database/migrations/2016_09_18_210001_create_invoice_payment_collections_table.php",
"visit_date": "2021-01-19T09:08:46.201226",
"added": "2024-11-18T22:55:17.274447+00:00",
"created": "2017-04-09T18:47:10",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
---
layout: default
---
# 1997-03-11 - Failed mail
## Header Data
From: NTMail<EMAIL_ADDRESS>To: _N/A_<br>
Message Hash: 7e85d46b42698ca51fe66663230ca7a4aa860f4fb8485b764a5c39bffe00dffd<br>
Message ID: \<ca227164.mbx\><br>
Reply To: _N/A_<br>
UTC Datetime: 1997-03-11 15:22:59 UTC<br>
Raw Date: Tue, 11 Mar 1997 07:22:59 -0800 (PST)<br>
## Raw message
```
{% raw %}From: NTMail<EMAIL_ADDRESS>Date: Tue, 11 Mar 1997 07:22:59 -0800 (PST)
Subject: Failed mail
Message-ID: <ca227164.mbx>
MIME-Version: 1.0
Content-Type: text/plain
---------------------------------------------------------------------
Your message to mail.astrobiz.com was rejected.
I said:
RCPT<EMAIL_ADDRESS>And mail.astrobiz.com responded with
553<EMAIL_ADDRESS>Unbalanced '<'
---------------------------------------------------------------------
Your message follows:
>Received: from [<IP_ADDRESS>] by smtp1.abraxis.com (NTMail 3.01.03) id ca227164; Tue, 11 Mar 1997 10:02:44 -0500
>Subject: of rebellion enforce be
>XVI the States
>Date: Tue, 11 Mar 1997 10:02:44 -0500
>Message-Id<EMAIL_ADDRESS>>
>of
>That affect this. Section
>the of AMENDMENT of
>such at died the
>who may. the th
>within importation have XXII
>more office from of
>of. would of shall
>
>.
{% endraw %}
```
## Thread
+ Return to [March 1997](/archive/1997/03)
+ Return to "[NTMail <postmaster<span>@</span>abraxis.com>](/authors/ntmail_postmaster_at_abraxis_com_)"
+ 1997-03-11 (Tue, 11 Mar 1997 07:22:59 -0800 (PST)) - Failed mail - _NTMail<EMAIL_ADDRESS>
|
e32e8da94c327a65156cd7c45199cf54cce80014
|
{
"blob_id": "e32e8da94c327a65156cd7c45199cf54cce80014",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-20T23:03:41",
"content_id": "4ba4bd759f05003d3d4e5fd16d986b21e12e4a40",
"detected_licenses": [
"MIT"
],
"directory_id": "4da3eca681d465f4994e84f43472cf66664e9b02",
"extension": "md",
"filename": "7e85d46b42698ca51fe66663230ca7a4aa860f4fb8485b764a5c39bffe00dffd.md",
"fork_events_count": 2,
"gha_created_at": "2018-06-20T20:02:33",
"gha_event_created_at": "2023-04-12T05:47:06",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 138080116,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1657,
"license": "MIT",
"license_type": "permissive",
"path": "/_emails/1997/03/7e85d46b42698ca51fe66663230ca7a4aa860f4fb8485b764a5c39bffe00dffd.md",
"provenance": "stack-edu-markdown-0016.json.gz:15920",
"repo_name": "cryptoanarchywiki/mailing-list-archive-generator",
"revision_date": "2022-02-20T23:03:41",
"revision_id": "5ee11c76b130aadf0ed74877107df5053ab0361b",
"snapshot_id": "7547cba9dd353f2f6dcc64eab77473ed5967c734",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/cryptoanarchywiki/mailing-list-archive-generator/5ee11c76b130aadf0ed74877107df5053ab0361b/_emails/1997/03/7e85d46b42698ca51fe66663230ca7a4aa860f4fb8485b764a5c39bffe00dffd.md",
"visit_date": "2023-04-16T03:14:42.652593",
"added": "2024-11-18T21:22:59.728908+00:00",
"created": "2022-02-20T23:03:41",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0016.json.gz"
}
|
# :rocket: bookmarks
useful things from around the web
## design
- [checklist.design](https://www.checklist.design/ "https://www.checklist.design/"): a collection of the best UX and UI practices.
- [emoji cheat sheet](https://www.webfx.com/tools/emoji-cheat-sheet/ "https://www.webfx.com/tools/emoji-cheat-sheet/"): list of emoji with markdown codes
- [hatchful](https://hatchful.shopify.com/ "https://hatchful.shopify.com/"): create stunning logos in seconds
## productivity
- [notion.so](https://www.notion.so "https://www.notion.so"): all-in-one workspace
## frontend
## backend
- [learn you a haskell](http://learnyouahaskell.com/chapters): the funkiest way to learn Haskell
## other
- [ethical.net/resources](https://ethical.net/resources/ "https://ethical.net/resources/"): huge repository of ethical alternatives to mainstream stuff
- [intravert.co](https://intravert.co/ "https://intravert.co/"): monetize your community through privacy-preserving and ethical ad spaces
|
3a043920d59ba4cf55e430fa774e4a54be36a747
|
{
"blob_id": "3a043920d59ba4cf55e430fa774e4a54be36a747",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-13T16:06:46",
"content_id": "9491c32f09185c005fe6a508ebcfe277f3fee815",
"detected_licenses": [
"MIT"
],
"directory_id": "f9d0f84672ebc980d41c0d97bc0076f06e598135",
"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": 179996791,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1004,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0015.json.gz:101859",
"repo_name": "rhgrieve/bookmarks",
"revision_date": "2019-04-13T16:06:46",
"revision_id": "416d63bf50e0ba3cafc65ffabb6c769492282501",
"snapshot_id": "0dc00f6a3757e4ea9ed51e396a710f09d2e9c63f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rhgrieve/bookmarks/416d63bf50e0ba3cafc65ffabb6c769492282501/README.md",
"visit_date": "2020-05-05T11:37:23.335620",
"added": "2024-11-18T20:31:13.784148+00:00",
"created": "2019-04-13T16:06:46",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0015.json.gz"
}
|
#include "mods.h"
#include "myhook.h"
#include<list>
#include <unistd.h>
#include <stdlib.h>
#include<signal.h>
extern "C" {
int main(int ac,char** av);
}
static void* old_main;
static std::list<void*> onsht;
void register_shutdown(void* fn) {
onsht.push_back(fn);
}
void call_sht(int d) {
for(auto i:onsht) {
((void(*)())i)();
}
if(d==SIGINT) {
int pipefd[2];
pipe2(pipefd,0);
close(0);
dup2(pipefd[0],0);
write(pipefd[1],"stop\nstop\n",10);
close(pipefd[1]);
printf("\nshuting down... press enter,use stop instead at next time!\n");
}
}
static void shthelper_reg() {
#define sh(a) signal(a,call_sht);
sh(SIGHUP)
sh(SIGINT)
sh(SIGILL)
sh(SIGABRT)
sh(SIGFPE)
sh(SIGSEGV)
}
static int mc_entry(int ac,char** av) {
printf("[MOD] main,start loading mods\n");
mod_loadall();
shthelper_reg();
int fk= ((typeof(&main))old_main)(ac,av);
call_sht(0);
return fk;
}
struct init_d {
init_d() {
printf("[MOD] inject to %p pid %d\n",main,getpid());
old_main=MyHook(fp(main),fp(mc_entry));
}
} _dummy;
|
5b199d33ded29877596473fe9cd376b52b1bc9da
|
{
"blob_id": "5b199d33ded29877596473fe9cd376b52b1bc9da",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-19T15:21:13",
"content_id": "d336b76850a2604f70cf28f42f4b8c34dad21488",
"detected_licenses": [
"MIT"
],
"directory_id": "ef8600eb074198fbb05549a68e9f7b73deb31649",
"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": 222722984,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1150,
"license": "MIT",
"license_type": "permissive",
"path": "/main.cpp",
"provenance": "stack-edu-0005.json.gz:185094",
"repo_name": "SCraft-Community/AlterMod-BE",
"revision_date": "2019-11-19T15:21:13",
"revision_id": "0506b779686c3710a1c8c7be0b8f67b86bfd0464",
"snapshot_id": "366e627009d92b85a4f10320b4f640f847aa95d7",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/SCraft-Community/AlterMod-BE/0506b779686c3710a1c8c7be0b8f67b86bfd0464/main.cpp",
"visit_date": "2020-09-13T09:16:09.671313",
"added": "2024-11-18T21:41:47.887520+00:00",
"created": "2019-11-19T15:21:13",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
load('api_config.js');
load('api_timer.js');
load('api_shadow.js');
load('api_gpio.js');
load('api_dht.js');
load('api_rpc.js');
//output pins
let lightPin = Cfg.get('potbot.lightPin');
let exFanPin = Cfg.get('potbot.exFanPin');
let inFanPin = Cfg.get('potbot.inFanPin');
let watPin = Cfg.get('potbot.watPin');
//GPIO setup
GPIO.set_mode(lightPin, GPIO.MODE_OUTPUT);
GPIO.set_mode(exFanPin, GPIO.MODE_OUTPUT);
GPIO.set_mode(inFanPin, GPIO.MODE_OUTPUT);
GPIO.set_mode(watPin, GPIO.MODE_OUTPUT);
//shadow object
let state = {
name: Cfg.get('potbot.name'),
temperature: 0,
temperatureSetting: 75,
humidity: 0,
humiditySetting: 40,
light: true,
intakeFan: true,
exhaustFan: true,
water: false,
lightOnHour: 0,
lightOnMinute: 0,
lightTime: Cfg.get('potbot.lightTime'),
lightTimer: 16, //hours
waterTime: Cfg.get('potbot.waterTime'),
waterTimer: 20, //seconds
fanTime: Cfg.get('potbot.fanTime'),
fanTimer: 2, //fan alternates every x hours,
manual: false
};
let waterRunning = false; //true when water function is active
//shadow handler
Shadow.addHandler(function (event, obj) {
if (event === 'CONNECTED') {
// Connected to shadow - report our current state.
Shadow.update(0, state);
} else if (event === 'UPDATE_DELTA') {
// Got delta. Iterate over the delta keys, handle those we know about.
for (let key in obj) {
if (key === 'name') {
state.name = obj.name;
print('Device Name: ', state.name);
};
if (key === 'manual') {
state.manual = obj.manual;
print('Manual Mode: ', state.manual);
};
if (key === 'light') {
state.light = obj.light;
print('Light:', state.light);
};
if (key === 'intakeFan') {
state.intakeFan = obj.intakeFan;
print('intake fan:', state.light);
};
if (key === 'exhaustFan') {
state.exhaustFan = obj.exhaustFan;
print('exhaust fan:', state.exhaustFan);
};
if (key === 'water') {
state.water = obj.water;
print('watering:', state.water);
};
if (key === 'temperatureSetting') {
state.temperatureSetting = obj.temperatureSetting;
print('new temperature setting: ', state.temperatureSetting);
}
if (key === 'humiditySetting') {
state.humiditySetting = obj.humiditySetting;
print('new humidity setting: ', state.humiditySetting);
};
if (key === 'lightOnHour') {
state.lightOnHour = obj.lightOnHour;
print('Light On Hour:', state.lightOnHour);
};
if (key === 'lightOnMinute') {
state.lightOnMinute = obj.lightOnMinute;
print('Light On Minute:', state.lightOnMinute);
};
if (key === 'lightTime') {
state.lightTime = obj.lightTime;
Cfg.set({ potbot: { lightTime: state.lightTime } });
print('new light time: ', state.lightTime);
};
if (key === 'lightTimer') {
state.lightTimer = obj.lightTimer;
print('light will stay on for: ', state.lightTimer, ' hours');
}
if (key === 'waterTime') {
state.waterTime = obj.waterTime;
Cfg.set({ potbot: { lightTime: state.waterTime } });
print('new watering time: ', state.waterTime);
};
if (key === 'waterTimer') {
state.waterTimer = obj.waterTimer;
print('will water for (seconds):', state.waterTimer, ' seconds');
};
if (key = 'fanTime') {
state.fanTime = obj.fanTime;
Cfg.set({ potbot: { lightTime: state.lightTime } });
print('fan will turn on initially at: ', state.fanTime);
};
if (key === 'fanTimer') {
state.fanTimer = obj.fanTimer;
print('fan will alternate every', state.fanTimer, 'hours');
};
};
// Once we've done synchronising with the shadow, report our state.
Shadow.update(0, state);
};
});
//this loop sets state values based on sensor and time data
Timer.set(1000, Timer.REPEAT, function () {
//get time
let now = Timer.now(); //returns epoch time (seconds since 1/1/1970)
print('Now: ', now);
let time = now % 86400; //divides epoch time by seconds in a day; remainder is seconds since midnight
print('Time: ', time);
//get seconds since midnight from light on time
let hoursSeconds = state.lightOnHour * 3600;
let minutesSeconds = state.lightOnMinute * 60;
state.lightTime = hoursSeconds + minutesSeconds;
Cfg.set({ potbot: { lightTime: state.lightTime } });
//adjust light off time for overflow into next day
let lightOffTime = function() {
if (state.lightTime + (state.lightTimer * 3600) > 86400) {
return (state.lightTime + (state.lightTimer * 3600)) - 86400;
} else {
return state.lightTime + (state.lightTimer * 3600);
};
};
print('Light Off Time: ', lightOffTime())
//water 10 minutes after light turns on
if (state.lightTime > 0) {
state.waterTime = state.lightTime + 600;
Cfg.set({ potbot: { waterTime: state.waterTime } });
};
//fans turn on initially when light turns on
if (state.fanTime === 0 && state.lightTime > 0) {
state.fanTime = state.lightTime;
}
//get temp/humid
let tempC = ffi(get_temperature());
let tempF = (tempC * 1.8) + 32;
if (Cfg.get('potbot.metric')) {
state.temperature = tempC;
} else {
state.temperature = tempF;
};
print('temperature: ', state.temperature);
state.humidity = ffi(get_humidity());
print('humidity: ', state.humidity);
if (!state.manual) { //if manual mode is off
//compare temp/humid to settings, act accordingly
if (state.temperature > state.temperatureSetting) {
state.intakeFan = true;
state.exhaustFan = true;
};
if (state.temperature < state.temperatureSetting) {
state.intakeFan = false;
state.exhaustFan = false;
};
if (state.humidity > state.humiditySetting) {
state.exhaustFan = true;
};
if (state.humidity < state.humiditySetting) {
state.exhaustFan = false;
};
//compare time to timers, act accordingly
if (time >= state.lightTime && time <= lightOffTime()) {
state.light = true;
};
if (time >= lightOffTime() && time <= state.lightTime) {
state.light = false;
};
if (time === state.fanTime) {
state.intakeFan = true
state.exhaustFan = true;
};
if (time === state.fanTime + (state.fanTimer * 3600)) {
state.intakeFan = false;
state.exhaustFan = false;
state.fanTime = time + (state.fanTimer * 3600); //set fan on time to x hours from now
};
if (time === state.waterTime) {
state.water = true;
};
};
}, null);
RPC.addHandler('Water', function () {
state.water = false;
GPIO.write(watPin, 1);
Timer.set(state.waterTimer * 1000, 0, function () {
GPIO.write(watPin, 0);
}, null);
waterRunning = false;
});
//this loop sets outputs based on state values
Timer.set(1000, Timer.REPEAT, function () {
GPIO.write(lightPin, state.light ? 0 : 1); //change back to 0 : 1 before final versioning
GPIO.write(inFanPin, state.intakeFan ? 1 : 0);
GPIO.write(exFanPin, state.exhaustFan ? 1 : 0);
if (state.water && !waterRunning) {
waterRunning = true;
RPC.call(RPC.LOCAL, 'Water', null, function (resp, err_code, err_msg, ud) {
if (err_code !== 0) {
print("Error: (" + JSON.stringify(err_code) + ') ' + err_msg);
} else {
print('Result: ' + JSON.stringify(result));
}
});
};
}, null);
|
25fd45c14c1d2a6a4369ff248cd4e952f0d1767b
|
{
"blob_id": "25fd45c14c1d2a6a4369ff248cd4e952f0d1767b",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-28T22:36:04",
"content_id": "5ca03fb77989a19ca7c264061555907eabfed611",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "54753735b2dfc35d590b6f4bf9c396fe64bdbe37",
"extension": "js",
"filename": "init.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 240159347,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 8373,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/fw/PB-TC/fs/init.js",
"provenance": "stack-edu-0037.json.gz:468507",
"repo_name": "Landtrain-Designs-LLC/potbot",
"revision_date": "2021-03-28T22:36:04",
"revision_id": "f59131918cb9096d1040abe34479e7a2c5ebf1a0",
"snapshot_id": "69f0fb31ee228ad641fda87914ff738d49c3667b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Landtrain-Designs-LLC/potbot/f59131918cb9096d1040abe34479e7a2c5ebf1a0/fw/PB-TC/fs/init.js",
"visit_date": "2023-01-12T17:56:41.839939",
"added": "2024-11-18T23:39:51.514859+00:00",
"created": "2021-03-28T22:36:04",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz"
}
|
<?php
namespace Webkul\Marketplace\DataGrids\Admin;
use DB;
use Webkul\Ui\DataGrid\DataGrid;
/**
* Seller Data Grid class
*
* @author Jitendra Singh <jitendra@webkul.com>
* @copyright 2018 Webkul Software Pvt Ltd (http://www.webkul.com)
*/
class SellerFlagDataGrid extends DataGrid
{
/**
*
* @var integer
*/
public $index = 'id';
protected $sortOrder = 'desc'; //asc or desc
protected $enableFilterMap = false;
public function prepareQueryBuilder()
{
$queryBuilder = DB::table('marketplace_seller_flags')
->select('marketplace_seller_flags.id', 'marketplace_seller_flags.reason', 'marketplace_seller_flags.name', 'marketplace_seller_flags.email');
$this->addFilter('reason', 'marketplace_seller_flags.reason' );
$this->addFilter('email', 'marketplace_seller_flags.email' );
$this->addFilter('name', 'marketplace_seller_flags.name' );
$this->addFilter('id', 'marketplace_seller_flags.id');
$this->addFilter('created_at', 'marketplace_seller_flags.created_at');
$this->setQueryBuilder($queryBuilder);
}
public function addColumns()
{
$this->addColumn([
'index' => 'id',
'label' => trans('marketplace::app.admin.sellers.id'),
'type' => 'number',
'searchable' => false,
'sortable' => true,
'filterable' => true
]);
$this->addColumn([
'index' => 'name',
'label' => trans('marketplace::app.admin.flag.name'),
'type' => 'string',
'searchable' => true,
'sortable' => true,
'filterable' => true
]);
$this->addColumn([
'index' => 'email',
'label' => trans('marketplace::app.admin.flag.email'),
'type' => 'string',
'searchable' => true,
'sortable' => true,
'filterable' => true
]);
$this->addColumn([
'index' => 'reason',
'label' => trans('marketplace::app.admin.products.flag.reason'),
'type' => 'string',
'searchable' => true,
'sortable' => true,
'filterable' => true,
'closure' => true,
]);
}
}
|
9b235e118cacd526d443c61c2600d7e712607a1a
|
{
"blob_id": "9b235e118cacd526d443c61c2600d7e712607a1a",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-15T09:34:12",
"content_id": "07aded409d020a822b5944ef609b07d2f0d83a95",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "b0779552889929de233a1f18bc162e8d7f755bd0",
"extension": "php",
"filename": "SellerFlagDataGrid.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 365491204,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2296,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/packages/Webkul/Marketplace/src/DataGrids/Admin/SellerFlagDataGrid.php",
"provenance": "stack-edu-0050.json.gz:186222",
"repo_name": "quincykwende/markpedia",
"revision_date": "2021-07-15T09:34:12",
"revision_id": "04c5b268d5841bf018fd46b64b449c27e83ede87",
"snapshot_id": "10a3994b78842d347a8e002cdcabd86b32ac9637",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/quincykwende/markpedia/04c5b268d5841bf018fd46b64b449c27e83ede87/packages/Webkul/Marketplace/src/DataGrids/Admin/SellerFlagDataGrid.php",
"visit_date": "2023-06-16T04:41:33.511456",
"added": "2024-11-19T03:22:05.130320+00:00",
"created": "2021-07-15T09:34:12",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
# Metrics
**Source:** [/server/aws/metrics.tf](https://github.com/cds-snc/covid-alert-server-staging-terraform/blob/master/server/aws/metrics.tf)
## Filters
Metric log filters for the following:
- UnclaimedOneTimeCodeTotal
- ClaimedOneTimeCodeTotal
- DiagnosisKeyTotal
**Note:**
- 8 filter aggregators are required for each because of the app metric log structure
- 1 filter per metric array position, which performs the following: `$.updates[${count.index}].sum`
## Alarms
- Warn and critical alarms for each filter
- Use the [warn/critical SNS topics](sns.md).
|
64e4f809cf225b09e04826bdc9768e2a1679cce5
|
{
"blob_id": "64e4f809cf225b09e04826bdc9768e2a1679cce5",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-26T16:00:48",
"content_id": "e27a58ef8499e7fe3e2be8b9f7a568205b6a2144",
"detected_licenses": [
"MIT"
],
"directory_id": "c25cc9d65f5dc60b7bfbb6e502b6ad8476f445a5",
"extension": "md",
"filename": "metrics.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 361506403,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 568,
"license": "MIT",
"license_type": "permissive",
"path": "/metrics.md",
"provenance": "stack-edu-markdown-0007.json.gz:194429",
"repo_name": "patheard/covid-alert-server-staging-notes",
"revision_date": "2021-04-26T16:00:48",
"revision_id": "9dadcec6b962562ba51dbc65c621b43677a54d51",
"snapshot_id": "f343b9ae5dae94bccd36a34e7a70d69fc148df89",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/patheard/covid-alert-server-staging-notes/9dadcec6b962562ba51dbc65c621b43677a54d51/metrics.md",
"visit_date": "2023-04-17T19:29:16.358374",
"added": "2024-11-19T01:33:19.865683+00:00",
"created": "2021-04-26T16:00:48",
"int_score": 3,
"score": 3.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz"
}
|
#include <pybind11/pybind11.h>
// https://en.wikipedia.org/wiki/Fletcher%27s_checksum#Optimizations
uint16_t fletcher16_wikipedia(const uint8_t *data, size_t len) {
uint32_t c0, c1;
/* Found by solving for c1 overflow: */
/* n > 0 and n * (n+1) / 2 * (2^8-1) < (2^32-1). */
for (c0 = c1 = 0; len > 0; ) {
size_t blocklen = len;
if (blocklen > 5002) {
blocklen = 5002;
}
len -= blocklen;
do {
c0 = c0 + *data++;
c1 = c1 + c0;
} while (--blocklen);
c0 = c0 % 255;
c1 = c1 % 255;
}
return (c1 << 8 | c0);
}
uint16_t fletcher_16(pybind11::buffer input) {
pybind11::buffer_info info = input.request();
return fletcher16_wikipedia((uint8_t*)info.ptr, (size_t)info.size);
}
PYBIND11_MODULE(fletcher_16, m) {
m.doc() = "16 bit fletcher checksum";
m.def("fletcher_16", &fletcher_16, "fletcher_16");
}
|
c17fa867f5423cb2207ed4676f1aadc23f70ee15
|
{
"blob_id": "c17fa867f5423cb2207ed4676f1aadc23f70ee15",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-08T11:40:30",
"content_id": "0937d5264abc0827561d947339164986eafe5aa7",
"detected_licenses": [
"MIT"
],
"directory_id": "0fa91b5e4eb2666cbebe0c832e7555882139ebb2",
"extension": "cpp",
"filename": "fletcher_16.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": 849,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fletcher_16.cpp",
"provenance": "stack-edu-0006.json.gz:94955",
"repo_name": "marieoe/udaq_analysis_lib",
"revision_date": "2021-07-08T11:40:30",
"revision_id": "0b767f2b2824a6b663ee01ed5e52de8d2e9b8f91",
"snapshot_id": "9a9174b9e0b42a6e0c516cf3fb7bb822d8eb03ca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marieoe/udaq_analysis_lib/0b767f2b2824a6b663ee01ed5e52de8d2e9b8f91/src/fletcher_16.cpp",
"visit_date": "2023-06-17T01:07:43.025038",
"added": "2024-11-18T22:29:08.811485+00:00",
"created": "2021-07-08T11:40:30",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
<?php
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace TencentCloud\Cdn\V20180606\Models;
use TencentCloud\Common\AbstractModel;
/**
* IP 属性信息
*
* @method string getIp() 获取指定查询的 IP
* @method void setIp(string $Ip) 设置指定查询的 IP
* @method string getPlatform() 获取IP 归属:
yes:节点归属于腾讯云 CDN
no:节点不属于腾讯云 CDN
* @method void setPlatform(string $Platform) 设置IP 归属:
yes:节点归属于腾讯云 CDN
no:节点不属于腾讯云 CDN
* @method string getLocation() 获取节点所处的省份/国家
unknown 表示节点位置未知
* @method void setLocation(string $Location) 设置节点所处的省份/国家
unknown 表示节点位置未知
* @method array getHistory() 获取节点上下线历史记录
* @method void setHistory(array $History) 设置节点上下线历史记录
* @method string getArea() 获取节点的所在区域
mainland:中国境内加速节点
overseas:中国境外加速节点
unknown:服务地域无法获取
* @method void setArea(string $Area) 设置节点的所在区域
mainland:中国境内加速节点
overseas:中国境外加速节点
unknown:服务地域无法获取
* @method string getCity() 获取节点的所在城市
注意:此字段可能返回 null,表示取不到有效值。
* @method void setCity(string $City) 设置节点的所在城市
注意:此字段可能返回 null,表示取不到有效值。
*/
class CdnIp extends AbstractModel
{
/**
* @var string 指定查询的 IP
*/
public $Ip;
/**
* @var string IP 归属:
yes:节点归属于腾讯云 CDN
no:节点不属于腾讯云 CDN
*/
public $Platform;
/**
* @var string 节点所处的省份/国家
unknown 表示节点位置未知
*/
public $Location;
/**
* @var array 节点上下线历史记录
*/
public $History;
/**
* @var string 节点的所在区域
mainland:中国境内加速节点
overseas:中国境外加速节点
unknown:服务地域无法获取
*/
public $Area;
/**
* @var string 节点的所在城市
注意:此字段可能返回 null,表示取不到有效值。
*/
public $City;
/**
* @param string $Ip 指定查询的 IP
* @param string $Platform IP 归属:
yes:节点归属于腾讯云 CDN
no:节点不属于腾讯云 CDN
* @param string $Location 节点所处的省份/国家
unknown 表示节点位置未知
* @param array $History 节点上下线历史记录
* @param string $Area 节点的所在区域
mainland:中国境内加速节点
overseas:中国境外加速节点
unknown:服务地域无法获取
* @param string $City 节点的所在城市
注意:此字段可能返回 null,表示取不到有效值。
*/
function __construct()
{
}
/**
* For internal only. DO NOT USE IT.
*/
public function deserialize($param)
{
if ($param === null) {
return;
}
if (array_key_exists("Ip",$param) and $param["Ip"] !== null) {
$this->Ip = $param["Ip"];
}
if (array_key_exists("Platform",$param) and $param["Platform"] !== null) {
$this->Platform = $param["Platform"];
}
if (array_key_exists("Location",$param) and $param["Location"] !== null) {
$this->Location = $param["Location"];
}
if (array_key_exists("History",$param) and $param["History"] !== null) {
$this->History = [];
foreach ($param["History"] as $key => $value){
$obj = new CdnIpHistory();
$obj->deserialize($value);
array_push($this->History, $obj);
}
}
if (array_key_exists("Area",$param) and $param["Area"] !== null) {
$this->Area = $param["Area"];
}
if (array_key_exists("City",$param) and $param["City"] !== null) {
$this->City = $param["City"];
}
}
}
|
6738608ce7d8f303d9bfb4b3a6679587aff35424
|
{
"blob_id": "6738608ce7d8f303d9bfb4b3a6679587aff35424",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T02:58:52",
"content_id": "6fb098996b18e8a7804588c42b8f3c74ac77e80e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eef0c54264c0e9a765c9a8e05c920be8f40a30d3",
"extension": "php",
"filename": "CdnIp.php",
"fork_events_count": 329,
"gha_created_at": "2018-04-22T10:10:00",
"gha_event_created_at": "2023-07-25T12:28:20",
"gha_language": "PHP",
"gha_license_id": "Apache-2.0",
"github_id": 130555964,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 4658,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/TencentCloud/Cdn/V20180606/Models/CdnIp.php",
"provenance": "stack-edu-0054.json.gz:444214",
"repo_name": "TencentCloud/tencentcloud-sdk-php",
"revision_date": "2023-09-01T02:58:52",
"revision_id": "895b0eda0883ed1211bba6566db109c442a90073",
"snapshot_id": "f9bdc2235e8a68578191cf80252311586361eafd",
"src_encoding": "UTF-8",
"star_events_count": 362,
"url": "https://raw.githubusercontent.com/TencentCloud/tencentcloud-sdk-php/895b0eda0883ed1211bba6566db109c442a90073/src/TencentCloud/Cdn/V20180606/Models/CdnIp.php",
"visit_date": "2023-09-02T23:46:14.030623",
"added": "2024-11-18T19:09:54.045376+00:00",
"created": "2023-09-01T02:58:52",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
---
date: '2018-11-17'
title: 'Sending SNMP data to Splunk with collectd'
path: '/posts/snmp-splunk-with-collectd/'
category: 'Learning'
layout: post
draft: false
description: 'Using collectd to send SNMP data to Splunk'
image: './workspace.png'
tags:
- 'Splunk'
- 'Admin'
---
Splunk is amazing tool for analyzing data, if you know how to get it inside. Normally Splunk relies on using Forwarders and needed add-ons to collect and add meta-information to data. But sometimes this is not an option, for example SNMP (Splunk supports SNMP traps). For SNMP you can use third-party modular inputs [1](https://splunkbase.splunk.com/app/1537/), [2](https://splunkbase.splunk.com/app/2673/) to solve this. Unfortunately SNMP Modular Input doesn't work reliably, I believe problem lies in very old version of **pysnmp**. And the latter only works for polling interfaces on network devices. There is also option to use PRTG or cacti and then send them to Splunk.
Recently Splunk introduced metrics - very fast compared to traditional event indexes and easy way to ingest them, HTTP Event Collector. On the client side we can use [collectd](https://collectd.org), without installing forwarders. Functionality of collectd can be complemented by array of plugins.
## Configure HEC on Splunk
On the Splunk side we need to enable HEC to receive data sent from collectd enabled host. First create metrics index and then follow this [guide](http://docs.splunk.com/Documentation/Splunk/7.2.1/Metrics/GetMetricsInCollectd#Configure_the_HTTP_Event_Collector_.28HEC.29_data_input).
## collectd configuration
Download and install **collectd** and plugins on the host which will poll SNMP devices:
```bash
# yum install epel-release
# yum install collectd
```
Download [Splunk App for Infrastructure](https://splunkbase.splunk.com/app/3975/) and extract /splunk_app_infrastructure/appserver/static/unix_agent/unix-agent.tgz. Copy **write_splunk.so** to /usr/lib/collectd/. This path can be different consult #PluginDir line in collectd.conf or change it to your liking. The plugin works as write_http, but can add dimensions to sent metrics.
and SNMP packages:
```bash
# yum install net-snmp net-snmp-libs net-snmp-utils
```
To use MIBs, put them in default directories:
```bash
$HOME/.snmp/mibs
/usr/local/share/snmp/mibs
```
Configure SNMP plugin and sending data to Splunk:
```bash
# cd /etc/collectd/collectd.conf.d
# vim snmp.conf
```
```xml
#File: /etc/collectd/collectd.conf.d/snmp.conf
LoadPlugin snmp
<Plugin snmp>
<Data "std_traffic">
Type "if_octets"
Table true
Instance "IF-MIB::ifDescr"
Values "IF-MIB::ifInOctets" "IF-MIB::ifOutOctets"
</Data>
<Host "my.lab.dev">
Address "<IP_ADDRESS>"
Version 2
Community "public"
Collect "std_traffic"
Interval 60
</Host>
</Plugin>
```
```xml
#File: /etc/collectd/collectd.conf.d/write_splunk.conf
<LoadPlugin "write_splunk">
FlushInterval 10
</LoadPlugin>
<Plugin write_splunk>
server "<splunk app server>"
port "8088"
token "<HEC TOKEN from first step>"
ssl true
verifyssl false
key1:value1
</Plugin>
```
Now we enable and start collectd service:
```bash
# systemctl enable collectd.service
# systemctl start collectd.service
```
## Metrics Workspace

The best way to start to work with the metrics vizualisation is to install [Metrics Workspace](https://splunkbase.splunk.com/app/4192/) app. This app will add tab to your search app, it automatically pulls your metrics and gives you easy to use interface for visualizing them.
|
a1d4e63ddf9eddd9635a43da6948e3c70586bab6
|
{
"blob_id": "a1d4e63ddf9eddd9635a43da6948e3c70586bab6",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-17T11:40:24",
"content_id": "50cbe5ca62def128f93252fd967021f781fcc391",
"detected_licenses": [
"MIT"
],
"directory_id": "71c2447f9b6bd4a3b6068361a43647a43bec2d3e",
"extension": "md",
"filename": "index.md",
"fork_events_count": 0,
"gha_created_at": "2017-05-02T08:50:25",
"gha_event_created_at": "2023-02-27T23:47:24",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 90011526,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3581,
"license": "MIT",
"license_type": "permissive",
"path": "/src/pages/articles/2018-11-17-sending-snmp-data-to-splunk-with-collectd/index.md",
"provenance": "stack-edu-markdown-0008.json.gz:232078",
"repo_name": "akilbekov/blog",
"revision_date": "2022-02-17T11:40:24",
"revision_id": "a6ad7b089f012ee41e7781390e02e48867dd5893",
"snapshot_id": "6064658d13c7fdf7063487a75b86f80d4a8365f6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/akilbekov/blog/a6ad7b089f012ee41e7781390e02e48867dd5893/src/pages/articles/2018-11-17-sending-snmp-data-to-splunk-with-collectd/index.md",
"visit_date": "2023-03-05T03:53:55.076603",
"added": "2024-11-18T23:30:06.472948+00:00",
"created": "2022-02-17T11:40:24",
"int_score": 4,
"score": 3.84375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0008.json.gz"
}
|
// Vectors - Resizable arrays
pub fn run() {
let mut numbers: Vec<i32> = vec![1, 2, 3, 4];
// Re-assign value
numbers[2] = 20;
// Add on to vector
numbers.push(5);
numbers.push(6);
// Pop off last value
numbers.pop();
println!("{:?}", numbers);
// Get single val
println!("Single Value: {}", numbers[0]);
// Get Vector length
println!("Vector length: {}", numbers.len());
// Vector are stack(栈) allocated(分配)
println!("Vector occuopies {} bytes", std::mem::size_of_val(&numbers));
// Get Slice
let slice: &[i32] = &numbers[0..2];
println!("Slice: {:?}", slice);
// Loop through vector values
for x in numbers.iter() {
println!("Number: {}", x);
}
// Loop & mutate values
for x in numbers.iter_mut() {
*x *= 2;
}
println!("Numbers Vec: {:?}", numbers);
}
|
ccc4854ec93ae9531cee5b9b8cc8e3126e8a93d9
|
{
"blob_id": "ccc4854ec93ae9531cee5b9b8cc8e3126e8a93d9",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T04:52:47",
"content_id": "0ed57416006fbfb2d812753b1b40d73515f6e6c2",
"detected_licenses": [
"MIT"
],
"directory_id": "4cdf4e243891c0aa0b99dd5ee84f09a7ed6dd8c8",
"extension": "rs",
"filename": "vactors.rs",
"fork_events_count": 0,
"gha_created_at": "2017-08-05T15:56:53",
"gha_event_created_at": "2020-07-17T09:25:44",
"gha_language": "JavaScript",
"gha_license_id": "NOASSERTION",
"github_id": 99432793,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 804,
"license": "MIT",
"license_type": "permissive",
"path": "/rust-l/src/vactors.rs",
"provenance": "stack-edu-0067.json.gz:761433",
"repo_name": "gozeon/code-collections",
"revision_date": "2023-08-10T04:52:47",
"revision_id": "13f07176a6c7b6ac13586228cec4c1e2ed32cae4",
"snapshot_id": "464986c7765df5dca980ac5146b847416b750998",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gozeon/code-collections/13f07176a6c7b6ac13586228cec4c1e2ed32cae4/rust-l/src/vactors.rs",
"visit_date": "2023-08-17T18:53:24.189958",
"added": "2024-11-18T20:31:53.226274+00:00",
"created": "2023-08-10T04:52:47",
"int_score": 4,
"score": 3.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
#pragma once
#include "GameStateId.h"
#include "GameState.h"
#include "GameStateMachine.h"
#include "GameContext.h"
class Game : public GameStateMachine<GameContext, GameStateId>
{
private:
Context context;
State * currentState;
StateId currentStateId;
StateId nextStateId;
public:
void setup(void);
void loop(void);
Context & getContext(void) override;
const Context & getContext(void) const override;
void changeState(const StateId & stateId) override;
private:
State * createState(const StateId & stateId) const;
};
|
0cdf8c524135dc90ac8d2da4f540cddc4e084c20
|
{
"blob_id": "0cdf8c524135dc90ac8d2da4f540cddc4e084c20",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-08T00:33:57",
"content_id": "520e48fbe0609e0eec9505ec819533ed5151d636",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7704f06b4262b37719594c7cd25baa59f1900c85",
"extension": "h",
"filename": "Game.h",
"fork_events_count": 0,
"gha_created_at": "2017-12-19T18:34:01",
"gha_event_created_at": "2018-04-08T00:33:58",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 114798708,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 563,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/EasterPanic/Game.h",
"provenance": "stack-edu-0005.json.gz:172395",
"repo_name": "Pharap/EasterPanic",
"revision_date": "2018-04-08T00:33:57",
"revision_id": "4a7b7245f779ba3a341c8ed3fb50502786677e8e",
"snapshot_id": "2e523a3123a294068e505f486e4177b7979b25b7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Pharap/EasterPanic/4a7b7245f779ba3a341c8ed3fb50502786677e8e/EasterPanic/Game.h",
"visit_date": "2022-04-14T05:01:15.553511",
"added": "2024-11-18T23:27:30.953785+00:00",
"created": "2018-04-08T00:33:57",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
#include <iostream>
#include <raylib.h>
#include <cstdint>
#include <math.h>
#include <cassert>
#include <stdlib.h>
#include <time.h>
#include <unordered_map>
#define ROWS 9
#define COLS 5
#define TILEX 48
#define FONTSIZE 64
#define TILEY 52
#define SPACE 10
#define GRIDX (TILEX + SPACE)
#define GRIDY (TILEY + SPACE)
#define NUMSUITES 4
#define NUMCOLORS 4
#define HEALTHBARWIDTH 20
#define SCREENWIDTH (COLS * GRIDX + SPACE + HEALTHBARWIDTH)
#define SCREENHEIGHT (ROWS * GRIDY + SPACE)
#define CAMERASPEED 0.06
#define GREEN {0x28, 0x96, 0x5A, 0xFF}
#define RED {0xDA, 0x3E, 0x52, 0xFF}
#define WHITE {0xEE, 0xEB, 0xD3, 0xFF}
#define YELLOW {0xEE, 0xC3, 0x3F, 0xFF}
#define BLUE {0x2E, 0x29, 0x6C, 0xFF}
#define BLACK {0x19, 0x15, 0x16, 0xFF}
#define BASESCORE 10
#define POWERSCORE 5
#define ACCELERATION 0.0008
#define SPEEDBOOST 0.003
#define SPEEDSCORE 50
using namespace std;
Font font;
const int ERROR = 'E';
const int STAR = 0x2217;
const int GONE = ' ';
const int SUITES[] = {0x2660, 0x2663, 0x2665, 0x2666};
const Color COLORS[] = {RED, YELLOW, BLACK, BLUE};
const int MOVES[] = {'<', '>'};
const int DIE = 0x2680;
const int SPEED = '+';
bool tap() {
return IsKeyPressed(KEY_SPACE) ||
IsKeyPressed(KEY_ENTER) ||
IsMouseButtonPressed(MOUSE_LEFT_BUTTON) ||
IsMouseButtonPressed(MOUSE_RIGHT_BUTTON) ||
GetGestureDetected() == GESTURE_TAP;
}
bool operator==( const Color& a, const Color& b) {
return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a;
}
int mod(int a, int b) {
return ((a % b) + b) % b;
}
struct Tile {
int display;
Color color;
Tile() {
display = ERROR;
color = PURPLE;
}
Tile(int newDisplay, Color newColor = WHITE) : display(newDisplay), color(newColor) {}
void draw(float x, float y, bool selected = false, bool last = false) {
if (!isGone()) {
Rectangle rec = {GRIDX * x + SPACE, GRIDY * y + SPACE, TILEX, TILEY};
if (last) {
DrawCircle(rec.x + TILEX / 2, rec.y + TILEY / 2, TILEX / 2 + 3, BLACK);
DrawCircle(rec.x + TILEX / 2, rec.y + TILEY / 2, TILEX / 2, WHITE);
}
else {
if (isSuite()) {
DrawRectangleRounded(rec, 0.2, 5, WHITE);
if (selected) {
DrawRectangleRoundedLines(rec, 0.2, 5, 3, BLACK);
}
}
else {
DrawRectangleRounded(rec, 0.2, 5, BLACK);
if (selected) {
DrawRectangleRoundedLines(rec, 0.2, 5, 3, WHITE);
}
}
}
DrawTextCodepoint(font, display, {GRIDX * x + 7 + SPACE, GRIDY * y + 6}, FONTSIZE, color);
}
}
bool isStar() { return display == STAR; }
bool isGone() { return display == GONE; }
bool isSuite() { return (display >= SUITES[0] && display <= SUITES[3]) || isStar(); }
bool isMovement() { return display == MOVES[0] || display == MOVES[1]; }
bool isSpeed() { return display == SPEED; }
bool isDie() { return display >= DIE && display <= DIE + 5; }
bool match(Tile& other) {
assert(isSuite() && other.isSuite());
return display == other.display || color == other.color || isStar() || other.isStar();
}
};
struct Bag {
int suites;
int stars;
int movements;
int speeds;
int dice;
int total;
Bag(int suitesProportion, int starsProportion, int movementsProportion, int speedProportion, int diceProportion) {
suites = suitesProportion;
stars = suites + starsProportion;
movements = movementsProportion + stars;
speeds = speedProportion + movements;
dice = speeds + diceProportion;
total = dice;
}
Tile grab() {
int choice = rand() % total + 1;
if (choice <= suites) {
return Tile(SUITES[rand() % NUMSUITES], COLORS[rand() % NUMCOLORS]);
}
else if (choice <= stars) {
return Tile(STAR, BLACK);
}
else if (choice <= movements) {
return Tile(MOVES[rand() % 2]);
}
else if (choice <= speeds) {
return Tile(SPEED);
}
else if (choice <= dice) {
return Tile(DIE + rand() % 6);
}
return Tile();
}
};
struct Row {
Tile tiles[COLS];
Tile& operator[](int col) {
return tiles[mod(col, COLS)];
}
};
struct Board {
Row rows[ROWS];
Row& operator[](int row) {
return rows[mod(row, ROWS)];
}
};
struct Level {
string text;
Bag bag;
Row examples;
Level(string newText, Bag newBag, Tile a = Tile(GONE), Tile b = Tile(GONE), Tile c = Tile(GONE), Tile d = Tile(GONE), Tile e = Tile(GONE)) :
text(newText), bag(newBag) {
examples[0] = a;
examples[1] = b;
examples[2] = c;
examples[3] = d;
examples[4] = e;
}
};
struct MainData {
Board board;
Bag bag = Bag(32, 3, 12, 1, 4);
float camera;
int x = COLS / 2;
float y = 0;
float speed = 0.015;
float power = 1;
float score;
Tile last = Tile(STAR, BLACK);
int screen = 0, currentLevel = 1, startLevel = 1;
int tickCounter = 0;
bool play = false;
Level levels[6] = {
Level("S H U F F L E P O P\n\nTap or click to continue...",
Bag(0, 0, 0, 0, 1)),
Level("Tap or click to select\n"
"cards as they go past the\n"
"circle at the bottom of\n"
"the screen. Match them by\n"
"color or suite.\n"
"Get 150 points to continue\n"
"to the next tutorial level.\n"
"Tap or click to continue...",
Bag(1, 0, 1, 0, 0),
Tile(SUITES[0], COLORS[0]), Tile(SUITES[1], COLORS[1]), Tile(SUITES[2], COLORS[2]), Tile(SUITES[3], COLORS[3]), Tile(SUITES[0], COLORS[2])),
Level("Star cards can match with\n"
"any other card.\n"
"Tap or click to continue...",
Bag(6, 1, 0, 0, 0),
Tile(GONE), Tile(GONE), Tile(STAR, BLACK)),
Level("Movement cards will allow\n"
"you to move between rows\n"
"and select cards in\n"
"different rows.\n"
"Tap or click to continue...",
Bag(10, 1, 3, 0, 0),
Tile(GONE), Tile(MOVES[0]), Tile(GONE), Tile(MOVES[1])),
Level("Speed cards increase the\n"
"speed, and are worth 50\n"
"points.\n"
"Tap or click to continue...",
Bag(32, 3, 12, 3, 0),
Tile(GONE), Tile(GONE), Tile(SPEED)),
Level("Die cards will shuffle\n"
"some number of cards above\n"
"them.\n"
"You completed the tutorial.\n"
"Tap or click to continue...",
Bag(32, 3, 12, 1, 4),
Tile(DIE + 5), Tile(DIE + 2), Tile(DIE + 4), Tile(DIE), Tile(DIE + 1))
};
void fillRow(int row) {
for (int i = 0; i < COLS; i++) {
board[row][i] = bag.grab();
}
}
void fillBoard() {
for (int i = 0; i < ROWS; i++) {
fillRow(i);
}
}
void init() {
bag = levels[currentLevel].bag;
startLevel = currentLevel;
fillBoard();
x = COLS / 2;
camera = 0;
y = 0;
score = 0;
speed = 0.015;
power = 1;
screen = 0;
tickCounter = 0;
last = Tile(STAR, BLACK);
play = false;
}
void mainLoop() {
tickCounter++;
BeginDrawing();
ClearBackground(GREEN);
if (!play) {
Rectangle window = {SPACE, GRIDY + SPACE, SCREENWIDTH - 2 * SPACE, SCREENHEIGHT - GRIDY - 2 * SPACE};
DrawRectangleRounded(window, 0.04, 5, WHITE);
Level& level = levels[screen];
for (int i = 0; i < COLS; i++) {
level.examples[i].draw(i, 0);
}
DrawTextEx(font, level.text.c_str(), {2 * SPACE, GRIDY + 2 * SPACE}, FONTSIZE / 3.2, 0, BLACK);
if (screen == 0 && score != 0) {
DrawTextEx(font, ("\n\n\nPrevious Score: " + to_string(int(score))).c_str(), {2 * SPACE, GRIDY + 2 * SPACE}, FONTSIZE / 3, 0, BLACK);
}
if (tap()) {
if (screen == 0) {
init();
if (currentLevel < 5) {
screen = currentLevel;
}
else {
play = true;
}
}
else {
bag = levels[currentLevel].bag;
play = true;
}
}
}
else {
if (floor(y - speed) != floor(y)) {
fillRow(y - 2);
}
y -= speed;
if (camera < x - COLS / 2) {
camera = min(camera + CAMERASPEED, double(x - COLS / 2));
}
if (camera > x - COLS / 2) {
camera = max(camera - CAMERASPEED, double(x - COLS / 2));
}
for (int i = 0; i < ROWS; i++) {
for (int j = camera - 1; j < camera + COLS; j++) {
board[floor(y) + i][j % COLS].draw(j - camera, i + floor(y) - y, (j == mod(x, COLS) && i == ROWS - 2));
}
}
if (tap()) {
int rowSelect = floor(y) + ROWS - 2;
Tile popped = board[rowSelect][x];
board[rowSelect][x] = Tile(GONE);
if (popped.isSuite()) {
if (popped.match(last)) {
score += BASESCORE + POWERSCORE * power;
speed += ACCELERATION * power * power;
power += (1 - power) / 10.0f;
}
else {
power -= 0.1;
}
last = popped;
}
else if (popped.display == '>') {
x++;
}
else if (popped.display == '<') {
x--;
}
else if (popped.isSpeed()) {
speed += SPEEDBOOST;
score += SPEEDSCORE;
}
else if (popped.isDie()) {
for (int i = 1; i < popped.display - DIE + 2; i++) {
board[rowSelect - i][x] = bag.grab();
}
}
}
power -= (speed / 50.0f);
if (score > (currentLevel - startLevel + 1) * 150 && currentLevel < 5) {
currentLevel++;
screen = currentLevel;
play = false;
}
if (power < 0) {
screen = 0;
play = false;
}
last.draw(x - camera, ROWS - 2.5, false, true);
DrawRectangle(COLS * GRIDX + SPACE, 0, 20, 10000, WHITE);
if (power > 0.25 || tickCounter / 15 % 2 == 0) {
DrawRectangle(COLS * GRIDX + SPACE + 5, (1 - power) * (ROWS - 1) * GRIDY + 5, 10, 10000, BLACK);
}
else {
DrawRectangle(COLS * GRIDX + SPACE + 5, (1 - power) * (ROWS - 1) * GRIDY + 5, 10, 10000, RED);
}
DrawRectangle(0, (ROWS - 1) * GRIDY + SPACE, COLS * GRIDX + 20 + SPACE, FONTSIZE + SPACE, WHITE);
DrawTextEx(font, to_string(int(score)).c_str(), {0, (ROWS - 1) * GRIDY + SPACE}, FONTSIZE, 0, BLACK);
}
EndDrawing();
}
};
MainData everything;
void doEverything() {
everything.mainLoop();
}
int main(int argc, char** argv) {
InitWindow(SCREENWIDTH, SCREENHEIGHT, "ShufflePop");
SetTargetFPS(60);
srand(time(NULL));
EnableCursor();
everything.init();
if (argc == 2) {
everything.currentLevel = 5;
}
//Extra characters array (e.g. for dice, suites)
int extraChars[] = {0x2680, 0x2681, 0x2682, 0x2683, 0x2684, 0x2685, 0x2660, 0x2663, 0x2665, 0x2666, 0x2217};
//All characters array
int chars[sizeof(extraChars) / sizeof(int) + 128];
//Write extended characters into array
for (int i = 0; i < sizeof(extraChars) / sizeof(int); i++) {
chars[i] = extraChars[i];
}
//Write basic characters into array
for (int i = 0; i < 128; i++) {
chars[sizeof(extraChars) /sizeof(int) + i] = i;
}
//Load all characters
font = LoadFontEx("resources/Cousine-Regular-With-Dice.ttf", FONTSIZE, chars, sizeof(chars) / sizeof(int));
while (!WindowShouldClose()) {
doEverything();
}
}
|
755b8b5452f7bf547bd21a29e523767be1f63ee9
|
{
"blob_id": "755b8b5452f7bf547bd21a29e523767be1f63ee9",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-31T17:24:55",
"content_id": "5a3375d3ace6e7c5dabee75e3b6992855877b1d6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ce8fbde72ed9d54e27886698eae46ac5e5d7789a",
"extension": "cpp",
"filename": "shufflepop.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 332343265,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 12905,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/shufflepop.cpp",
"provenance": "stack-edu-0002.json.gz:86157",
"repo_name": "Andrew-Maxwell/shufflepop",
"revision_date": "2021-03-31T17:24:55",
"revision_id": "1c4bd2864c1153a809e16bd38059ab7bb66b291a",
"snapshot_id": "5a167fe7a10f01b5126610a9688e20eb384640d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Andrew-Maxwell/shufflepop/1c4bd2864c1153a809e16bd38059ab7bb66b291a/shufflepop.cpp",
"visit_date": "2023-03-31T15:28:43.176096",
"added": "2024-11-18T23:19:55.719154+00:00",
"created": "2021-03-31T17:24:55",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
/*
Copyright (c) 2009-2014, Jack Poulson, Lexing Ying,
The University of Texas at Austin, Stanford University, and the
Georgia Insitute of Technology.
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"
namespace El {
DistMap::DistMap()
: numSources_(0), comm_(mpi::COMM_WORLD)
{ SetComm( mpi::COMM_WORLD ); }
DistMap::DistMap( mpi::Comm comm )
: numSources_(0), comm_(mpi::COMM_WORLD)
{ SetComm( comm ); }
DistMap::DistMap( int numSources, mpi::Comm comm )
: numSources_(numSources), comm_(mpi::COMM_WORLD)
{ SetComm( comm ); }
DistMap::~DistMap()
{
if( comm_ != mpi::COMM_WORLD )
mpi::Free( comm_ );
}
void DistMap::StoreOwners
( int numSources, std::vector<int>& localInds, mpi::Comm comm )
{
DEBUG_ONLY(CallStackEntry cse("DistMap::StoreOwners"))
SetComm( comm );
Resize( numSources );
const int commSize = mpi::Size( comm );
const int blocksize = Blocksize();
const int firstLocalSource = FirstLocalSource();
// Exchange via AllToAlls
std::vector<int> sendSizes( commSize, 0 );
const int numLocalInds = localInds.size();
for( int s=0; s<numLocalInds; ++s )
{
const int i = localInds[s];
const int q = RowToProcess( i, blocksize, commSize );
++sendSizes[q];
}
std::vector<int> recvSizes( commSize );
mpi::AllToAll( &sendSizes[0], 1, &recvSizes[0], 1, comm );
std::vector<int> sendOffs( commSize ), recvOffs( commSize );
int numSends=0, numRecvs=0;
for( int q=0; q<commSize; ++q )
{
sendOffs[q] = numSends;
recvOffs[q] = numRecvs;
numSends += sendSizes[q];
numRecvs += recvSizes[q];
}
DEBUG_ONLY(
if( numRecvs != NumLocalSources() )
LogicError("Incorrect number of recv indices");
)
std::vector<int> offs = sendOffs;
std::vector<int> sendInds( numSends );
for( int s=0; s<numLocalInds; ++s )
{
const int i = localInds[s];
const int q = RowToProcess( i, blocksize, commSize );
sendInds[offs[q]++] = i;
}
std::vector<int> recvInds( numRecvs );
mpi::AllToAll
( &sendInds[0], &sendSizes[0], &sendOffs[0],
&recvInds[0], &recvSizes[0], &recvOffs[0], comm );
// Form map
for( int q=0; q<commSize; ++q )
{
const int size = recvSizes[q];
const int off = recvOffs[q];
for( int s=0; s<size; ++s )
{
const int i = recvInds[off+s];
const int iLocal = i - firstLocalSource;
SetLocal( iLocal, q );
}
}
}
void DistMap::Translate( std::vector<int>& localInds ) const
{
DEBUG_ONLY(CallStackEntry cse("DistMap::Translate"))
const int commSize = mpi::Size( comm_ );
const int numLocalInds = localInds.size();
// Count how many indices we need each process to map
std::vector<int> requestSizes( commSize, 0 );
for( int s=0; s<numLocalInds; ++s )
{
const int i = localInds[s];
DEBUG_ONLY(
if( i < 0 )
LogicError("Index was negative");
)
if( i < numSources_ )
{
const int q = RowToProcess( i, blocksize_, commSize );
++requestSizes[q];
}
}
// Send our requests and find out what we need to fulfill
std::vector<int> fulfillSizes( commSize );
mpi::AllToAll( &requestSizes[0], 1, &fulfillSizes[0], 1, comm_ );
// Prepare for the AllToAll to exchange request sizes
int numRequests=0;
std::vector<int> requestOffs( commSize );
for( int q=0; q<commSize; ++q )
{
requestOffs[q] = numRequests;
numRequests += requestSizes[q];
}
int numFulfills=0;
std::vector<int> fulfillOffs( commSize );
for( int q=0; q<commSize; ++q )
{
fulfillOffs[q] = numFulfills;
numFulfills += fulfillSizes[q];
}
// Pack the requested information
std::vector<int> requests( numRequests );
std::vector<int> offs = requestOffs;
for( int s=0; s<numLocalInds; ++s )
{
const int i = localInds[s];
if( i < numSources_ )
{
const int q = RowToProcess( i, blocksize_, commSize );
requests[offs[q]++] = i;
}
}
// Perform the first index exchange
std::vector<int> fulfills( numFulfills );
mpi::AllToAll
( &requests[0], &requestSizes[0], &requestOffs[0],
&fulfills[0], &fulfillSizes[0], &fulfillOffs[0], comm_ );
// Map all of the indices in 'fulfills'
for( int s=0; s<numFulfills; ++s )
{
const int i = fulfills[s];
const int iLocal = i - firstLocalSource_;
DEBUG_ONLY(
if( iLocal < 0 || iLocal >= (int)map_.size() )
{
const int commRank = mpi::Rank( comm_ );
LogicError
("invalid request: i=",i,", iLocal=",iLocal,
", commRank=",commRank,", blocksize=",blocksize_);
}
)
fulfills[s] = map_[iLocal];
}
// Send everything back
mpi::AllToAll
( &fulfills[0], &fulfillSizes[0], &fulfillOffs[0],
&requests[0], &requestSizes[0], &requestOffs[0], comm_ );
// Unpack in the same way we originally packed
offs = requestOffs;
for( int s=0; s<numLocalInds; ++s )
{
const int i = localInds[s];
if( i < numSources_ )
{
const int q = RowToProcess( i, blocksize_, commSize );
localInds[s] = requests[offs[q]++];
}
}
}
void DistMap::FormInverse( DistMap& inverseMap ) const
{
DEBUG_ONLY(CallStackEntry cse("DistMap::FormInverse"))
const int commSize = mpi::Size( comm_ );
const int numLocalSources = map_.size();
// How many pairs of original and mapped indices to send to each process
std::vector<int> sendSizes( commSize, 0 );
for( int s=0; s<numLocalSources; ++s )
{
const int i = map_[s];
const int q = RowToProcess( i, blocksize_, commSize );
sendSizes[q] += 2;
}
// Coordinate all of the processes on their send sizes
std::vector<int> recvSizes( commSize );
mpi::AllToAll( &sendSizes[0], 1, &recvSizes[0], 1, comm_ );
// Prepare for the AllToAll to exchange send sizes
int numSends=0;
std::vector<int> sendOffs( commSize );
for( int q=0; q<commSize; ++q )
{
sendOffs[q] = numSends;
numSends += sendSizes[q];
}
DEBUG_ONLY(
if( numSends != 2*numLocalSources )
LogicError("Miscalculated numSends");
)
int numReceives=0;
std::vector<int> recvOffs( commSize );
for( int q=0; q<commSize; ++q )
{
recvOffs[q] = numReceives;
numReceives += recvSizes[q];
}
DEBUG_ONLY(
if( numReceives != 2*numLocalSources )
LogicError("Mistake in number of receives");
)
// Pack our map information
std::vector<int> sends( numSends );
std::vector<int> offs = sendOffs;
for( int s=0; s<numLocalSources; ++s )
{
const int i = map_[s];
const int q = RowToProcess( i, blocksize_, commSize );
sends[offs[q]++] = s+firstLocalSource_;
sends[offs[q]++] = i;
}
// Send out the map information
std::vector<int> recvs( numReceives );
mpi::AllToAll
( &sends[0], &sendSizes[0], &sendOffs[0],
&recvs[0], &recvSizes[0], &recvOffs[0], comm_ );
// Form our part of the inverse map
inverseMap.numSources_ = numSources_;
inverseMap.SetComm( comm_ );
for( int s=0; s<numReceives; s+=2 )
{
const int origInd = recvs[s];
const int mappedInd = recvs[s+1];
inverseMap.SetLocal( mappedInd-firstLocalSource_, origInd );
}
}
void DistMap::Extend( DistMap& firstMap ) const
{
DEBUG_ONLY(
CallStackEntry cse("DistMap::Extend");
// TODO: Ensure that the communicators are congruent and that the maps
// are compatible sizes.
)
Translate( firstMap.map_ );
}
void DistMap::Extend( const DistMap& firstMap, DistMap& compositeMap ) const
{
DEBUG_ONLY(CallStackEntry cse("DistMap::Extend"))
compositeMap = firstMap;
Extend( compositeMap );
}
int DistMap::NumSources() const { return numSources_; }
void DistMap::SetComm( mpi::Comm comm )
{
if( comm_ != mpi::COMM_WORLD )
mpi::Free( comm_ );
if( comm != mpi::COMM_WORLD )
mpi::Dup( comm, comm_ );
else
comm_ = comm;
const int commRank = mpi::Rank( comm );
const int commSize = mpi::Size( comm );
blocksize_ = numSources_/commSize;
firstLocalSource_ = blocksize_*commRank;
const int numLocalSources =
( commRank<commSize-1 ?
blocksize_ :
numSources_ - (commSize-1)*blocksize_ );
map_.resize( numLocalSources );
}
mpi::Comm DistMap::Comm() const { return comm_; }
int DistMap::Blocksize() const { return blocksize_; }
int DistMap::FirstLocalSource() const { return firstLocalSource_; }
int DistMap::NumLocalSources() const { return map_.size(); }
int DistMap::RowOwner( int i ) const
{ return RowToProcess( i, blocksize_, mpi::Size(comm_) ); }
int DistMap::GetLocal( int localSource ) const
{
DEBUG_ONLY(
CallStackEntry cse("DistMap::GetLocal");
if( localSource < 0 || localSource >= (int)map_.size() )
LogicError("local source is out of bounds");
)
return map_[localSource];
}
void DistMap::SetLocal( int localSource, int target )
{
DEBUG_ONLY(
CallStackEntry cse("DistMap::SetLocal");
if( localSource < 0 || localSource >= (int)map_.size() )
LogicError("local source is out of bounds");
)
map_[localSource] = target;
}
std::vector<int>& DistMap::Map() { return map_; }
const std::vector<int>& DistMap::Map() const { return map_; }
int* DistMap::Buffer() { return &map_[0]; }
const int* DistMap::Buffer() const { return &map_[0]; }
void DistMap::Empty()
{
numSources_ = 0;
blocksize_ = 0;
firstLocalSource_ = 0;
SwapClear( map_ );
}
void DistMap::Resize( int numSources )
{
const int commRank = mpi::Rank( comm_ );
const int commSize = mpi::Size( comm_ );
numSources_ = numSources;
blocksize_ = numSources/commSize;
firstLocalSource_ = commRank*blocksize_;
const int numLocalSources =
( commRank<commSize-1 ? blocksize_
: numSources-blocksize_*(commSize-1) );
map_.resize( numLocalSources );
}
const DistMap& DistMap::operator=( const DistMap& map )
{
numSources_ = map.numSources_;
SetComm( map.comm_ );
map_ = map.map_;
return *this;
}
} // namespace El
|
9b77f190ee098b2bf410b35d9b2b7ee4e6b93b62
|
{
"blob_id": "9b77f190ee098b2bf410b35d9b2b7ee4e6b93b62",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-27T03:56:16",
"content_id": "d80bd43fce049f1aa817315ca0f46884e333858f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7283409830d1a8bc51ccfa755774ecebf65e10c8",
"extension": "cpp",
"filename": "DistMap.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": 10786,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/core/DistMap.cpp",
"provenance": "stack-edu-0003.json.gz:394884",
"repo_name": "tkelman/Elemental",
"revision_date": "2014-11-27T03:56:16",
"revision_id": "7678cff392d08b2ecba80c3f8401071538e476f2",
"snapshot_id": "27ac59dabfea2dac03e8f108a10323197426946d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tkelman/Elemental/7678cff392d08b2ecba80c3f8401071538e476f2/src/core/DistMap.cpp",
"visit_date": "2021-01-21T03:33:40.466965",
"added": "2024-11-18T20:28:33.600786+00:00",
"created": "2014-11-27T03:56:16",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz"
}
|
<?php
namespace Spatie\EventProjector\EventHandlers;
use Exception;
trait HandlesEvents
{
public function handlesEvents(): array
{
return collect($this->handlesEvents ?? [])
->mapWithKeys(function ($methodName, $eventClass) {
if (is_numeric($eventClass)) {
$eventClass = $methodName;
$methodName = 'on'.ucfirst(class_basename($eventClass));
}
return [$eventClass => $methodName];
})
->toArray();
}
public function handlesEventClassNames(): array
{
return array_keys($this->handlesEvents());
}
public function methodNameThatHandlesEvent(object $event): string
{
$handlesEvents = $this->handlesEvents();
$eventClass = get_class($event);
return $handlesEvents[$eventClass] ?? '';
}
public function handleException(Exception $exception)
{
report($exception);
}
}
|
c32b110a290b7164d280a8953695686123fec8de
|
{
"blob_id": "c32b110a290b7164d280a8953695686123fec8de",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-26T18:01:40",
"content_id": "a71af25e022ad0701929023d097b2561d222c9b1",
"detected_licenses": [
"MIT"
],
"directory_id": "3d32caeaf21c72997ccda14b176e561411bf409e",
"extension": "php",
"filename": "HandlesEvents.php",
"fork_events_count": 0,
"gha_created_at": "2018-06-28T21:15:29",
"gha_event_created_at": "2018-06-28T21:29:32",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 139069017,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 988,
"license": "MIT",
"license_type": "permissive",
"path": "/src/EventHandlers/HandlesEvents.php",
"provenance": "stack-edu-0051.json.gz:583826",
"repo_name": "colinc/laravel-event-projector",
"revision_date": "2018-06-26T18:01:40",
"revision_id": "071f1f8e70acae2bc60e0e59c516e1d950ed53e4",
"snapshot_id": "2a50f9184cdf570cea2094e3a528dd5d749b65ce",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/colinc/laravel-event-projector/071f1f8e70acae2bc60e0e59c516e1d950ed53e4/src/EventHandlers/HandlesEvents.php",
"visit_date": "2020-03-21T21:32:19.854466",
"added": "2024-11-18T23:11:00.426546+00:00",
"created": "2018-06-26T18:01:40",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
This blog is based on the [Long Haul](https://github.com/brianmaierjr/long-haul) theme by Brian Maier Jr. and modified by myself to match my requirements in terms of style, SEO, and performance.
## Features
- Minimal, Type Focused Design
- Built with GULP + SASS + BROWSERSYNC + AUTOPREFIXER
- JSON-LD
- SVG Social Icons
- Responsive Nav Menu
- XML Feed for RSS Readers
- Contact Form via Formspree
- Comments via Staticman
- 5 Post Loop with excerpt on Home Page
- Previous / Next Post Navigation
- Estimated Reading Time for posts
- A Better Type Scale for all devices
## Setup
1. [Install Jekyll](http://jekyllrb.com)
2. Fork the [repo](https://github.com/julien731/blog-jekyll)
3. Clone it
4. [Install Bundler](http://bundler.io/)
5. Run `bundle install`
6. Install gulp dependencies by running `npm install`
7. Run Jekyll and watch files by running `gulp`
8. Customize and watch the magic happen!
## License
This is [MIT](LICENSE) with no added caveats, so feel free to use this Jekyll theme on your site without linking back to me or using a disclaimer.
|
112c00df54bc88fa5aa69c4776582ed856418a9a
|
{
"blob_id": "112c00df54bc88fa5aa69c4776582ed856418a9a",
"branch_name": "refs/heads/develop",
"committer_date": "2023-06-14T12:59:19",
"content_id": "35740e9407c76cb3f916488e2cf58e1e484eda2e",
"detected_licenses": [
"MIT"
],
"directory_id": "ab5b058443f023f28f54910824e5848448f89ba5",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": "2018-03-16T16:17:00",
"gha_event_created_at": "2023-06-14T12:59:20",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 125540958,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1066,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:84119",
"repo_name": "julien731/blog-jekyll",
"revision_date": "2023-06-14T12:59:19",
"revision_id": "4cca4cc21b5da1292849983dfd38c2e9f6c8b953",
"snapshot_id": "63a9e7bf772da543440c4a8c185212410219ec04",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/julien731/blog-jekyll/4cca4cc21b5da1292849983dfd38c2e9f6c8b953/README.md",
"visit_date": "2023-06-26T21:35:42.429510",
"added": "2024-11-19T00:17:45.745519+00:00",
"created": "2023-06-14T12:59:19",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTextsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('texts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('status');//0. ditolak, 1. diterima, 2. disetujui(survey), 3. valid
$table->string('nama');
$table->string('keterangan');
$table->integer('rt')->nullable();
$table->integer('rw')->nullable();
$table->string('bujur');
$table->string('lintang');
$table->integer('id_tul')->nullable();
$table->integer('users_id');
$table->integer('photos_id')->nullable();
$table->integer('villages_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('texts');
}
}
|
e09e0f4b62e03be4c7d55a95a98752b5802ef870
|
{
"blob_id": "e09e0f4b62e03be4c7d55a95a98752b5802ef870",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-16T07:04:53",
"content_id": "c0a0676537dc378f5048f58def9915e9815805d5",
"detected_licenses": [
"MIT"
],
"directory_id": "754b4df4d06d29d804d94b0bb37816e4f1716afb",
"extension": "php",
"filename": "2020_05_02_143013_create_texts_table.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 358506760,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1135,
"license": "MIT",
"license_type": "permissive",
"path": "/database/migrations/2020_05_02_143013_create_texts_table.php",
"provenance": "stack-edu-0046.json.gz:647441",
"repo_name": "Mocha1298/lbs_prambanan",
"revision_date": "2021-04-16T07:04:53",
"revision_id": "77e92db6a9db7d151519716e02f4ff8f68d8426a",
"snapshot_id": "19c8e987e1227ee975c2858d0737785747ceeb22",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mocha1298/lbs_prambanan/77e92db6a9db7d151519716e02f4ff8f68d8426a/database/migrations/2020_05_02_143013_create_texts_table.php",
"visit_date": "2023-04-07T08:23:53.068803",
"added": "2024-11-19T02:55:08.426317+00:00",
"created": "2021-04-16T07:04:53",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.cdc.impl;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.pipeline.SourceBuilder;
import com.hazelcast.jet.pipeline.StreamSource;
import org.apache.kafka.connect.data.Values;
import org.apache.kafka.connect.source.SourceRecord;
import java.util.Map.Entry;
import java.util.Properties;
import static com.hazelcast.jet.Util.entry;
public class JsonCdcSource extends CdcSource<Entry<String, String>> {
public JsonCdcSource(Processor.Context context, Properties properties) {
super(context, properties);
}
@Override
protected Entry<String, String> mapToOutput(SourceRecord record) {
String keyJson = Values.convertToString(record.keySchema(), record.key());
String valueJson = Values.convertToString(record.valueSchema(), record.value());
return entry(keyJson, valueJson);
}
public static StreamSource<Entry<String, String>> fromProperties(Properties properties) {
String name = properties.getProperty("name");
return SourceBuilder.timestampedStream(name, ctx -> new JsonCdcSource(ctx, properties))
.fillBufferFn(JsonCdcSource::fillBuffer)
.createSnapshotFn(CdcSource::createSnapshot)
.restoreSnapshotFn(CdcSource::restoreSnapshot)
.destroyFn(CdcSource::destroy)
.build();
}
}
|
feca669913cd54c3823841b51a77e8ae9a4ac4d6
|
{
"blob_id": "feca669913cd54c3823841b51a77e8ae9a4ac4d6",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-30T07:02:10",
"content_id": "4580ead70e0875cb164cb2760165cff3ec98c27a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d682843c7f5eed96204a9b6a331584e97fd0e056",
"extension": "java",
"filename": "JsonCdcSource.java",
"fork_events_count": 0,
"gha_created_at": "2019-11-25T22:20:06",
"gha_event_created_at": "2019-11-25T22:20:07",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 224052392,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2007,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/extensions/cdc-debezium/src/main/java/com/hazelcast/jet/cdc/impl/JsonCdcSource.java",
"provenance": "stack-edu-0026.json.gz:387412",
"repo_name": "frant-hartm/hazelcast-jet",
"revision_date": "2020-12-30T07:02:10",
"revision_id": "91ed1281f3cbb4f7222d2cbf837f0ff5eced3f14",
"snapshot_id": "979184e7b4aa3685f387d057902cc0310b8628f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frant-hartm/hazelcast-jet/91ed1281f3cbb4f7222d2cbf837f0ff5eced3f14/extensions/cdc-debezium/src/main/java/com/hazelcast/jet/cdc/impl/JsonCdcSource.java",
"visit_date": "2023-06-23T15:54:15.799836",
"added": "2024-11-18T23:42:34.160184+00:00",
"created": "2020-12-30T07:02:10",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
# First Exploration into Python
The point of this first exploration is to have the students explore Python through the REPL. I'm going to give them a list of things to type and see what comes out the other side. I'll end with some thinker questions and answers, and maybe a homework.
## The Code
First, as is tradition when learning a new programming language or technology:
```python
>>> "Hello, world!"
```
For the rest of the exploration, it is encouraged to explore. If one of the lines doesn't make sense, play around and try different inputs until what's going on makes sense.
Now, let's play with some numbers:
```python
>>> 2 + 2
>>> 5 - 3
>>> 8 * 8
>>> 25/6
>>> 25//6
>>> 25 % 6
>>> 2**5
```
Next, how about some words.
```python
>>> "cool beans"
>>> 'cool beans'
>>> cool beans
>>> 'He said "cool beans!"'
>>> "Not as cool as Jerry's beans"
>>> "cool" + "beans"
>>> "cool" + " beans"
>>> "cool" + " " + "beans"
```
How about some algebra!?
```python
>>> x = 5 + 3
>>> x
>>> x * 2
>>> y
>>> y = x * 2
>>> y
>>> x = 16
>>> y
>>> x = x + 1
>>> x
>>> 2 = 4
>>> a = 1
>>> b = 4
>>> c = 2
>>> x = (-b + (b**2 - 4*a*c)**.5)/(2*a)
>>> x
```
Lastly, just an example that will help us in the future:
```python
>>> 2 + 2
>>> # 2 + 2
>>> x = 5 # + 6
>>> x
>>> # I can write anything I want here to give you a message
>>> # within the code!
>>> #the extra space isn't needed, but it looks nice
```
## Questions to Ponder
1. Did you encounter anything that didn't make sense?
2. What does the = sign do?
3. What does the # sign do?
4. What does the % sign do?
4. Did you encounter any errors?
5. Did the errors tell you anything useful?
## Homework
Use Python (and Google, where needed) to answer the following questions. Print out your screen and turn it in.
1. Calculate the average density of the planets (Pluto optional)
2. If you were to purchase the top 3 most popular books on Amazon right now, calculate the total price. Assume the tax rate is 11%. You can assume you are a Prime customer, so shipping was free.
3. Convert<PHONE_NUMBER> seconds to years, days, hours, minutes, and seconds.
4. You have one fair 6-sided die. You roll it 4 times. What are the odds that you roll an even number, then an odd number, then a number bigger than 3, then a two?
|
1c0dd94af92677358ee8f220176708d7fb3836ef
|
{
"blob_id": "1c0dd94af92677358ee8f220176708d7fb3836ef",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-08T23:31:53",
"content_id": "f63d46e3b8f577cf233998f34b5bac9d617ea402",
"detected_licenses": [
"MIT"
],
"directory_id": "351e9b54c9d826c33d9786262fbd3dc72af52e76",
"extension": "md",
"filename": "first-exploration.md",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75946478,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2273,
"license": "MIT",
"license_type": "permissive",
"path": "/python1/first-exploration.md",
"provenance": "stack-edu-markdown-0013.json.gz:50226",
"repo_name": "rpalo/teaching",
"revision_date": "2017-10-08T23:31:53",
"revision_id": "acdf46ce5aecdf1442feac94a1be4c683e14ab0f",
"snapshot_id": "f404ea90e02f69d21b5095b71a8c529138cc9902",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rpalo/teaching/acdf46ce5aecdf1442feac94a1be4c683e14ab0f/python1/first-exploration.md",
"visit_date": "2020-06-10T15:51:45.849019",
"added": "2024-11-18T19:15:30.548714+00:00",
"created": "2017-10-08T23:31:53",
"int_score": 3,
"score": 3.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz"
}
|
import React from 'react';
import {FormControl, FormGroup, Col} from 'react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateJobs } from '../../actions/SearchActions';
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
jobs: [],
input: '',
searchExecuted: false
}
}
onSubmit = event => {
event.preventDefault();
this.props.updateJobs(this.state.input);
}
onChange = (event) => {
this.setState({
input: event.target.value,
});
};
render() {
return (
<div className="col-lg-12">
<div className="col-lg-offset-lg-4">
<form onSubmit={(event) => this.onSubmit(event)}>
<Col smOffset={3} sm={6}>
<FormGroup
controlId="formBasicText" onSubmit={(event) => this.onSubmit(event)}>
<h1>Search For A Job:</h1>
<p id="form-helper-text"><em>(try something like "web developer jobs in Raleigh")</em></p>
<FormControl
type="text"
placeholder="Enter text"
onChange={(event) => this.onChange(event)} />
</FormGroup>
</Col>
</form>
</div>
</div>
);
};
}
const mapDispatchToProps = dispatch => {
return bindActionCreators(
{updateJobs}, dispatch
);
};
export default connect(null, mapDispatchToProps)(SearchForm);
|
54cf0a4ed33e8eaf3d154b0b4ecfe6049cb0f034
|
{
"blob_id": "54cf0a4ed33e8eaf3d154b0b4ecfe6049cb0f034",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-10T14:46:25",
"content_id": "0d147bea34ab3f925618f19ab7121cba5fb34836",
"detected_licenses": [
"MIT"
],
"directory_id": "6ecd9e8e6b2f7de847aabff17096e41f50a6c81e",
"extension": "js",
"filename": "SearchForm.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1443,
"license": "MIT",
"license_type": "permissive",
"path": "/client/src/components/containers/SearchForm.js",
"provenance": "stack-edu-0035.json.gz:775767",
"repo_name": "hummusonrails/techMap_v_010",
"revision_date": "2017-10-10T14:46:25",
"revision_id": "1434551d1a82de66b6b5a86180ef1ad201425c75",
"snapshot_id": "85a4923f818f04c0a187127bdd0ac6940eb48643",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hummusonrails/techMap_v_010/1434551d1a82de66b6b5a86180ef1ad201425c75/client/src/components/containers/SearchForm.js",
"visit_date": "2023-04-28T05:32:53.391079",
"added": "2024-11-19T02:59:01.987377+00:00",
"created": "2017-10-10T14:46:25",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
using CarDealership.Utilities;
namespace CarDealership.Models.ViewModels.News
{
public class NewsIndexViewModel
{
private const int ContentLenght = 100;
public string Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string PartialContent => this.GetPartialContent();
private string GetPartialContent()
{
if (this.Content.Length <= ContentLenght)
{
return this.Content;
}
else
{
return this.Content.Substring(0, ContentLenght) + Constants.ThreeDots;
}
}
}
}
|
46c07b6a4d19a0e37fe82b71c021095335b98df4
|
{
"blob_id": "46c07b6a4d19a0e37fe82b71c021095335b98df4",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-10T14:15:09",
"content_id": "47b4692fc916a44837ad23bf10e2bb16c90d842d",
"detected_licenses": [
"MIT"
],
"directory_id": "30a2f3fd2a00cc26b66df11e1f8d2d46af9cf1e7",
"extension": "cs",
"filename": "NewsIndexViewModel.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 161244751,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 691,
"license": "MIT",
"license_type": "permissive",
"path": "/src/CarDealershipWebApp/CarDealership.Models/ViewModels/News/NewsIndexViewModel.cs",
"provenance": "stack-edu-0009.json.gz:256445",
"repo_name": "ShadyObeyd/DealershipWebApp",
"revision_date": "2019-01-10T14:15:09",
"revision_id": "7503f4a1c36f8fd0c23b74461829bc8de9206c56",
"snapshot_id": "f2c60b9b902bbf814a1e00fb7d45002d169d4a57",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ShadyObeyd/DealershipWebApp/7503f4a1c36f8fd0c23b74461829bc8de9206c56/src/CarDealershipWebApp/CarDealership.Models/ViewModels/News/NewsIndexViewModel.cs",
"visit_date": "2020-04-10T19:42:16.891141",
"added": "2024-11-19T02:38:34.154494+00:00",
"created": "2019-01-10T14:15:09",
"int_score": 3,
"score": 2.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
//
//
#include "cbridge/include/smoke/cbridge_Locales.h"
#include "cbridge_internal/include/BaseHandleImpl.h"
#include "cbridge_internal/include/TypeInitRepository.h"
#include "cbridge_internal/include/WrapperCache.h"
#include "gluecodium/Locale.h"
#include "smoke/Locales.h"
#include <memory>
#include <new>
#include <optional>
void smoke_Locales_release_handle(_baseRef handle) {
delete get_pointer<::std::shared_ptr< ::smoke::Locales >>(handle);
}
_baseRef smoke_Locales_copy_handle(_baseRef handle) {
return handle
? reinterpret_cast<_baseRef>(checked_pointer_copy(*get_pointer<::std::shared_ptr< ::smoke::Locales >>(handle)))
: 0;
}
const void* smoke_Locales_get_swift_object_from_wrapper_cache(_baseRef handle) {
return handle
? ::gluecodium::get_wrapper_cache().get_cached_wrapper(get_pointer<::std::shared_ptr< ::smoke::Locales >>(handle)->get())
: nullptr;
}
void smoke_Locales_cache_swift_object_wrapper(_baseRef handle, const void* swift_pointer) {
if (!handle) return;
::gluecodium::get_wrapper_cache().cache_wrapper(get_pointer<::std::shared_ptr< ::smoke::Locales >>(handle)->get(), swift_pointer);
}
void smoke_Locales_remove_swift_object_from_wrapper_cache(_baseRef handle) {
if (!::gluecodium::WrapperCache::is_alive) return;
::gluecodium::get_wrapper_cache().remove_cached_wrapper(get_pointer<::std::shared_ptr< ::smoke::Locales >>(handle)->get());
}
_baseRef smoke_Locales_localeMethod(_baseRef _instance, _baseRef input) {
return Conversion<::gluecodium::Locale>::toBaseRef(get_pointer<::std::shared_ptr< ::smoke::Locales >>(_instance)->get()->locale_method(Conversion<::gluecodium::Locale>::toCpp(input)));
}
_baseRef smoke_Locales_localeProperty_get(_baseRef _instance) {
return Conversion<::gluecodium::Locale>::toBaseRef(get_pointer<::std::shared_ptr< ::smoke::Locales >>(_instance)->get()->get_locale_property());
}
void smoke_Locales_localeProperty_set(_baseRef _instance, _baseRef value) {
return get_pointer<::std::shared_ptr< ::smoke::Locales >>(_instance)->get()->set_locale_property(Conversion<::gluecodium::Locale>::toCpp(value));
}
_baseRef
smoke_Locales_LocaleStruct_create_handle( _baseRef localeField )
{
::smoke::Locales::LocaleStruct* _struct = new ( ::std::nothrow ) ::smoke::Locales::LocaleStruct();
_struct->locale_field = Conversion<::gluecodium::Locale>::toCpp( localeField );
return reinterpret_cast<_baseRef>( _struct );
}
void
smoke_Locales_LocaleStruct_release_handle( _baseRef handle )
{
delete get_pointer<::smoke::Locales::LocaleStruct>( handle );
}
_baseRef
smoke_Locales_LocaleStruct_create_optional_handle(_baseRef localeField)
{
auto _struct = new ( ::std::nothrow ) std::optional<::smoke::Locales::LocaleStruct>( ::smoke::Locales::LocaleStruct( ) );
(*_struct)->locale_field = Conversion<::gluecodium::Locale>::toCpp( localeField );
return reinterpret_cast<_baseRef>( _struct );
}
_baseRef
smoke_Locales_LocaleStruct_unwrap_optional_handle( _baseRef handle )
{
return reinterpret_cast<_baseRef>( &**reinterpret_cast<std::optional<::smoke::Locales::LocaleStruct>*>( handle ) );
}
void smoke_Locales_LocaleStruct_release_optional_handle(_baseRef handle) {
delete reinterpret_cast<std::optional<::smoke::Locales::LocaleStruct>*>( handle );
}
_baseRef smoke_Locales_LocaleStruct_localeField_get(_baseRef handle) {
auto struct_pointer = get_pointer<const ::smoke::Locales::LocaleStruct>(handle);
return Conversion<::gluecodium::Locale>::toBaseRef(struct_pointer->locale_field);
}
|
087c28ec6a908bb1d383c8d7c45c7e717502c7f4
|
{
"blob_id": "087c28ec6a908bb1d383c8d7c45c7e717502c7f4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-24T06:02:15",
"content_id": "128410167ae59dcfd0a48798ffd93244638218db",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d2de6f54bae55578f9d6f6d621b1892efe7eb076",
"extension": "cpp",
"filename": "cbridge_Locales.cpp",
"fork_events_count": 17,
"gha_created_at": "2018-07-04T14:55:33",
"gha_event_created_at": "2023-09-01T11:49:28",
"gha_language": "Dart",
"gha_license_id": "Apache-2.0",
"github_id": 139735719,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3545,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/gluecodium/src/test/resources/smoke/locales/output/cbridge/src/smoke/cbridge_Locales.cpp",
"provenance": "stack-edu-0002.json.gz:526261",
"repo_name": "heremaps/gluecodium",
"revision_date": "2023-08-24T06:02:15",
"revision_id": "92e6a514dc8bdb786ad949f79df249da277c6e88",
"snapshot_id": "812f4b8a6a0f01979d6902b5e0cfe003a5b82347",
"src_encoding": "UTF-8",
"star_events_count": 172,
"url": "https://raw.githubusercontent.com/heremaps/gluecodium/92e6a514dc8bdb786ad949f79df249da277c6e88/gluecodium/src/test/resources/smoke/locales/output/cbridge/src/smoke/cbridge_Locales.cpp",
"visit_date": "2023-08-24T19:34:55.818503",
"added": "2024-11-18T21:26:41.031233+00:00",
"created": "2023-08-24T06:02:15",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
#include "gvmt/internal/gc.hpp"
#include "gvmt/internal/gc_generational.hpp"
#define MAX_NURSERY_SIZE (1 << 24)
namespace generational {
char* xgen_pointers;
char* starts;
size_t size;
char* heap;
char* nursery;
char* nursery_top;
size_t nursery_size;
void init(size_t heap_size) {
heap_size = (heap_size + CARD_SIZE-1) & (~(CARD_SIZE-1));
size = heap_size;
nursery_size = heap_size > MAX_NURSERY_SIZE * 4 ? MAX_NURSERY_SIZE : heap_size/4;
heap = (char*)get_virtual_memory(heap_size);
xgen_pointers = (char*)get_virtual_memory(heap_size/CARD_SIZE);
starts = (char*)get_virtual_memory(heap_size/CARD_SIZE);
Card base_card = card_id(heap);
gvmt_xgen_pointer_table_offset = xgen_pointers - base_card;
gvmt_object_start_table_offset = starts - base_card;
nursery_top = heap + heap_size;
nursery = nursery_top - nursery_size;
}
void clear_cards(char* begin, char*end) {
Card bc = card_id(begin);
Card ec = card_id(end-1)+1;
memset(gvmt_xgen_pointer_table_offset + bc, 0, ec-bc);
}
}
extern "C" {
char* gvmt_xgen_pointer_table_offset;
char* gvmt_object_start_table_offset;
GVMT_CALL GVMT_Object gvmt_fast_allocate(size_t size) {
size_t asize = align(size + sizeof(void*));
char* next = ((char*)gvmt_gc_free_pointer);
if (next + asize < (char*)gvmt_gc_limit_pointer) {
gvmt_gc_free_pointer = (GVMT_StackItem*)(((char*)next) + asize);
((intptr_t*)next)[0] = 0;
return (GVMT_Object)(next + sizeof(void*));
}
return 0;
}
}
|
83aae293e6604d50c8165f646db32fe841f9336f
|
{
"blob_id": "83aae293e6604d50c8165f646db32fe841f9336f",
"branch_name": "refs/heads/master",
"committer_date": "2011-11-14T17:49:18",
"content_id": "104dccd641bdbbae9b164ed611ee465285881350",
"detected_licenses": [
"MIT"
],
"directory_id": "ee8d866a11b6f484bc470558d222ed6be9e31d21",
"extension": "cpp",
"filename": "gc_generational.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": 1701,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/gc_generational.cpp",
"provenance": "stack-edu-0002.json.gz:288782",
"repo_name": "corona10/gvmt",
"revision_date": "2011-11-14T17:49:18",
"revision_id": "566eac01724b687bc5e11317e44230faab15f895",
"snapshot_id": "e00c6f351ea61d7b1b85c13dd376d5845c84bbb1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/corona10/gvmt/566eac01724b687bc5e11317e44230faab15f895/lib/gc_generational.cpp",
"visit_date": "2021-12-08T05:12:08.378130",
"added": "2024-11-18T21:19:21.926677+00:00",
"created": "2011-11-14T17:49:18",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
<?php
/* https://pdapps.org/kanbani/web | License: MIT */
namespace Kanbani;
const JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
// Uncaught exception of this type has its message printed to the visitor.
// Other messages only show the message's class name. See plugins/exception.php.
class PublicException extends \Exception {}
class Hooks implements \ArrayAccess {
// Allows storing any data during callbacks of the same trigger() call.
// Do not read outside of a hook. Do not write (replace the value).
//
// $hooks->registerFirst("event", function () use ($hooks) {
// $hooks->frame->key = 123; // setting
// });
// $hooks->registerAfter("event", function () use ($hooks) {
// echo $hooks->frame->key; // getting
// });
public $frame;
// If not null, all Closure hooks have their $this rebound to this.
protected $context;
protected $frames = [];
// Below, key = event name, value = array of callable.
protected $first = [];
protected $normal = [];
protected $last = [];
protected $after = [];
function __construct(Context $context = null) {
$this->context = $context;
}
// Shortcut to the translate event:
// $hooks("foo %s", "bar");
// $hooks->trigger("translate", ["foo %s", "bar"]);
function __invoke() {
return $this->trigger("translate", func_get_args());
}
// Shortcut to trigger():
// $hooks->event("foo", "bar");
// $hooks->trigger("event", ["foo", "bar"]);
// Do not use if $args has references (&), use trigger():
// $hooks->event(&$wrong);
// $hooks->trigger("event", [&$correct]);
function __call($event, $args) {
return $this->trigger($event, $args);
}
function context() {
return $this->context;
}
function template($name, ...$args) {
ob_start();
$this->trigger("echo_$name", $args);
return ob_get_clean();
}
// Invokes callbacks for $event in order: first, normal, last.
// If any hook returns a non-null value other hooks in all groups are skipped.
// The order in which hooks in the same group are called is unspecified.
// After those 3 groups, after hooks are called, with $args + the return
// value as the first argument; return value of after hooks are ignored and
// all after hooks are always called.
// The combination of first + after hooks can be used to implement caching.
function trigger($event, array $args = []) {
if (preg_match('/^echo_([\w.-]+)$/', $event, $match)) {
if (is_file($file = "templates/$match[1].php")) {
isolatedRequire($file, ["context" => $this->context, "hooks" => $this]);
}
// echo_ events are expected to have first argument as array &$vars
// but for simpler invocation it can be omitted or non-reference:
// $hooks->trigger("echo_foo");
// $hooks->trigger("echo_foo", [$vars]);
// $hooks->echo_foo(["immediate" => "not reference"]);
// Below we make fix first argument, at the same time not breaking
// the reference if $args has it:
// $hooks->trigger("echo_foo", [&$vars]);
// Above, a hook may have changed $vars.
$vars = &$args[0] or $vars = [];
$args[0] = &$vars;
}
try {
array_unshift($this->frames, $this->frame = new \stdClass);
$result = null;
foreach ($this[$event] as $func) {
$result = $this->invoke($func, $args);
if ($result !== null) { break; }
}
array_unshift($args, $result);
foreach ($this->after[$event] ?? [] as $func) {
$result = $this->invoke($func, $args);
}
} finally {
array_shift($this->frames);
$this->frame = $this->frames[0] ?? null;
}
return $result;
}
protected function invoke($func, array $args) {
if ($this->context) {
// ->call() does not preserve references in $args, as does
// $func(...$args). Only call_user_func_array() is usable.
// fromCallable() returns $func if $func is already a Closure so it's fast.
$func = \Closure::fromCallable($func)->bindTo($this->context);
}
return call_user_func_array($func, $args);
}
protected function addTo(&$callbacks, callable $callback) {
if (!$callbacks) { $callbacks = []; }
$callbacks[] = $callback;
return $this;
}
function register($event, callable $func) {
return $this->addTo($this->normal[$event], $func);
}
function registerFirst($event, callable $func) {
return $this->addTo($this->first[$event], $func);
}
function registerLast($event, callable $func) {
return $this->addTo($this->last[$event], $func);
}
function registerAfter($event, callable $func) {
return $this->addTo($this->after[$event], $func);
}
// Checks if there are any hooks registered for an event in any priority
// except after.
function offsetExists($offset) {
return !empty($this->first[$offset]) ||
!empty($this->normal[$offset]) ||
!empty($this->last[$offset]);
}
// Gets array of all callbacks in order of their priorities. After hooks
// are not returned.
function offsetGet($offset) {
return array_merge(
$this->first[$offset] ?? [],
$this->normal[$offset] ?? [],
$this->last[$offset] ?? []);
}
// Adds a new normal hook for an event.
function offsetSet($offset, $value) {
$this->register($offset, $value);
}
// Unregisters all hooks for an event excluding after.
// unset and get can be used to wrap or disable existing hooks:
// $old = $hooks["event"];
// unset($hooks["event"]);
// $hooks->register("wrapper", function () {
// foreach ($old as $callback) ...
// };
// Restoration is currently not possible because get removes priority information.
function offsetUnset($offset) {
unset($this->first[$offset]);
unset($this->normal[$offset]);
unset($this->last[$offset]);
}
}
class Context {
// Properties below are always set to some value.
public $hooks;
public $config = [];
// Object for storing custom data similarly to Kanbani's custom field.
// By convention, keys are "namespace_name", for example, "myplugin_fooBar" for
// a key used in plugins/myplugin.php.
public $custom;
public $tz = "UTC"; // identifier for date_default_timezone_set()
// PHP locale identifier for setlocale(). "C" is universally valid, en_US.UTF-8 is not:
// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/39cwe7zf(v=vs.90)
public $locale = "C";
// Used in <html lang=> and in Accept-Language. Called the "language tag":
// https://www.ietf.org/rfc/bcp/bcp47.txt
public $language = "en";
public $request; // array, $_REQUEST
public $server; // array, $_SERVER
public $files = []; // array, $_FILES omitting failed uploads
// Properties below may be null depending on the type of request.
public $syncFile;
public $syncData;
public $currentBoard; // object, one of $syncData->boards
public $profileID; // string, missing for one-time profiles (imported)
// QrCodeData, missing if profile exists in KWV only and can't be joined for
// collaboration using Kanbani. If this is set then $profileID must be also set.
public $kanbaniQrCode;
// $lists is array, $cards is SplObjectStorage (key is a list object).
// Of both properties, members are arrays with keys "list" or "card" (an
// object inside $currentBoard), "visible" (false if was filtered). Plugins can
// add other keys. Members are properly sorted.
// These fields omit deleted cards/lists and reflect user's preferences while
// $syncData contains profile data verbatim (unfiltered, unsorted, possibly deleted).
public $lists;
public $cards;
function __construct() {
$this->hooks = new Hooks($this);
$this->custom = new \stdClass;
$this->request = $_REQUEST;
$this->server = $_SERVER;
$this->files = $_FILES;
static::cleanFiles($this->files);
}
static function cleanFiles(array &$files) {
foreach ($files as $key => &$value) {
if (!isset($value["error"])) {
static::cleanFiles($value); // <input name="file[]">
} elseif ($value["error"] || !is_uploaded_file($value["tmp_name"])) {
$error = $value["error"] ?: \UPLOAD_ERR_NO_FILE;
foreach (get_defined_constants() as $name => $value) {
if ($error === $value && !strncmp($name, "UPLOAD_ERR_", 11)) {
$error = ucwords(strtolower(strtr(substr($name, 11), "_", " ")));
break;
}
}
throw new PublicException("Problem uploading a file ($key): $error.");
}
}
}
// Shortcut to the translate event:
// $context("foo %s", "bar");
// $context->hooks->trigger("translate", ["foo %s", "bar"]);
function __invoke(...$args) {
return $this->hooks->__invoke(...$args);
}
function cookie($name, $value = null) {
if (func_num_args() === 1) {
return $_COOKIE[$name] ?? null;
} else {
setcookie($name, $value, $value === null ? 1 : 0, "", "", $this->server["HTTPS"] ?? false, true);
return $this;
}
}
function unserialize() {
if (!$this->syncData) {
$this->hooks->trigger("unserialize");
}
return $this;
}
function syncData(SyncData $data = null, SyncFile $file = null) {
$this->syncData = $data ?: new SyncData;
$this->syncFile = $file ?: new SyncFile;
$this->currentBoard = $data->boards[0] ?? null;
return $this;
}
function currentBoard(\stdClass $board) {
if (!in_array($board, $this->syncData->boards, true)) {
throw new \InvalidArgumentException("Board is not part of current \$syncData.");
}
$this->currentBoard = $board;
return $this;
}
function persistentReadOnly($profileID) {
$this->profileID = $profileID;
$this->kanbaniQrCode = null;
return $this;
}
function persistent($profileID, QrCodeData $qrCode) {
$this->profileID = $profileID;
$this->kanbaniQrCode = $qrCode;
return $this;
}
}
function initializeGlobal() {
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}, -1);
error_reporting(-1);
chdir(__DIR__);
// These are required because of unserialize.qrCode in the config.
// https://github.com/PDApps/KanbaniDataPHP
require_once "kanbani-data/sync.php";
require_once "kanbani-data/qrcode.php";
$context = initialize();
date_default_timezone_set($context->tz);
if (!setlocale(LC_ALL, $context->locale)) {
error_log("KWV warning: setlocale($context->locale) has failed. Ensure your /etc/locale.gen has this locale. If it does not then change that file, run locale-gen and restart php-fpm or Apache.");
}
// Our strings are UTF-8 but on Windows setlocale() can't use this encoding,
// which results in wrong sort order:
// setlocale(LC_ALL, "C");
// echo strcoll("а", "б"); -1 (correct)
// setlocale(LC_ALL, "russian");
// echo strcoll("а", "б"); +1
if (!strncasecmp(PHP_OS, "win", 3)) {
setlocale(LC_COLLATE, "C");
}
return $context;
}
function initialize() {
$context = new Context;
if (is_file("config.php")) {
$context->config += isolatedRequire("config.php", compact("context"));
}
$context->config += isolatedRequire("config-defaults.php");
foreach ($context->config["plugins"] as $file) {
isolatedRequire($file, compact("context"));
}
$context->hooks->start();
return $context;
}
function isolatedRequire($file, array $vars = []) {
extract($vars);
return require_once $file;
}
// Remember: file_get_contents() does not respect LOCK_EX of file_put_contents().
function getFileContentsWithLock($path) {
$handle = fopen($path, "rb");
try {
flock($handle, LOCK_SH);
return stream_get_contents($handle);
} finally {
flock($handle, LOCK_UN);
fclose($handle);
}
}
function htmlOptions(array $values, array $titles, $current = null) {
return join(array_map(function ($value, $title) use ($current) {
return '<option value="'.htmlspecialchars($value).'"'.
($value === $current ? " selected" : "").
">".htmlspecialchars($title)."</option>";
}, $values, $titles));
}
function htmlAttributes(array $attrs) {
$result = "";
foreach ($attrs as $attr => $value) {
$result .= " ".htmlspecialchars($attr).'="'.htmlspecialchars($value).'"';
}
return $result;
}
function timeInterval($translator, $to, $now = null) {
if ($now === null) { $now = time(); }
$past = $to < $now;
$ago = $past ? "%s%s ago" : "in %s%s";
$diff = abs($to - $now);
if ($diff > $p = 3600 * 24 * 360) {
return $translator($ago, round($diff / $p), $translator("y"));
} elseif ($diff > $p = 3600 * 24 * 28) {
return $translator($ago, round($diff / $p), $translator("mo"));
} elseif ($diff > $p = 3600 * 24 * 7) {
return $translator($ago, round($diff / $p), $translator("w"));
} elseif ($diff > $p = 3600 * 24) {
return $translator($ago, round($diff / $p), $translator("d"));
} elseif ($diff > $p = 3600) {
return $translator($ago, round($diff / $p), $translator("h"));
} elseif ($diff > $p = 60) {
return $translator($ago, round($diff / $p), $translator("min"));
} elseif ($diff > 5) {
return $translator($ago, $diff, $translator("s"));
} else {
return $translator("just now");
}
}
function formatTime($translator, $time) {
// Omit the date for brevity if $time is today.
$format = date("ymd", $time) === date("ymd") ? "%X" : "%x %X";
return $translator("%s (%s)", strftime($format, $time), timeInterval($translator, $time));
}
function formatNumber($number, $decimals = 0) {
$locale = localeconv();
return number_format($number, $decimals, $locale["decimal_point"], $locale["thousands_sep"]);
}
|
fac798913e0028a582a9e09e961bba526d357958
|
{
"blob_id": "fac798913e0028a582a9e09e961bba526d357958",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-20T13:03:22",
"content_id": "484234d10b7231bc9acf943714e35469ee987aa1",
"detected_licenses": [
"MIT"
],
"directory_id": "91b1b59a294f629cfe74e7335fc19e729d7ceb2e",
"extension": "php",
"filename": "helpers.php",
"fork_events_count": 3,
"gha_created_at": "2020-08-31T20:35:09",
"gha_event_created_at": "2020-10-20T13:03:23",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 291818969,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 14829,
"license": "MIT",
"license_type": "permissive",
"path": "/helpers.php",
"provenance": "stack-edu-0050.json.gz:420572",
"repo_name": "PDApps/KanbaniWebViewer",
"revision_date": "2020-10-20T13:03:22",
"revision_id": "617b639a214f678d4a5196a53b78a883f488031c",
"snapshot_id": "780ee1ab94e3772e915a469f1fcabedfae02f070",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/PDApps/KanbaniWebViewer/617b639a214f678d4a5196a53b78a883f488031c/helpers.php",
"visit_date": "2022-12-30T02:21:55.211084",
"added": "2024-11-18T23:49:46.660697+00:00",
"created": "2020-10-20T13:03:22",
"int_score": 3,
"score": 2.8125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
# ddoc-wizard
Manage your database's design documents using [Grunt](http://gruntjs.com/)!
## Install
To get started, you'll need [node.js](http://nodejs.org/) installed. If you don't already have Grunt installed, you can get it by running `npm install -g grunt-cli`.
Then, to install ddoc-wizard, do this:
git clone git@github.com:garbados/ddoc-wizard.git
cd ddoc-wizard
npm install
grunt init
# answer grunt's questions to configure the wizard
Cool! You're good to go.
## Usage
The `ddocs` folder will contain your design documents, under folders named after the databases they'll go in. Check out `ddocs/examples/derp.js` for an example design doc.
In essence, it's everything you'd write on the server, but as a JavaScript object rather than raw JSON, which lets you verify its correctness more easily. Also, JavaScript is less of a pain to write than raw JSON, or at least that's my opinion.
## Commands
### grunt
To upload your design documents, do this:
grunt
Our example `derp.js` will be uploaded to the `examples` database, since it's stored under the `examples` folder, as `_design/derp`, since it's names `derp.js`.
## grunt ddoc
You can use `grunt ddoc` to create new design docs, like this:
grunt ddoc --db examples --ddoc derp
This will create a `derp.js` file at `ddocs/examples/derp.js`.
## License
[MIT](http://opensource.org/licenses/MIT), yo.
|
891bd3917acf047cd5ca3933aa71672fde6a2411
|
{
"blob_id": "891bd3917acf047cd5ca3933aa71672fde6a2411",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-10T03:32:42",
"content_id": "aca93e20c7866a61d2518273469e29d5e52c75e4",
"detected_licenses": [
"MIT"
],
"directory_id": "2ee8e2287c390e687c42de677b9864ca88946333",
"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": 1410,
"license": "MIT",
"license_type": "permissive",
"path": "/readme.md",
"provenance": "stack-edu-markdown-0000.json.gz:290741",
"repo_name": "garbados/ddoc-wizard",
"revision_date": "2013-11-10T03:32:42",
"revision_id": "d122674fd89d02b9a4fe087c93d3fe24fd39d417",
"snapshot_id": "c413d28bd1f6475414fe84406dc32207d7276e61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/garbados/ddoc-wizard/d122674fd89d02b9a4fe087c93d3fe24fd39d417/readme.md",
"visit_date": "2016-09-06T08:14:43.478712",
"added": "2024-11-19T01:22:05.706895+00:00",
"created": "2013-11-10T03:32:42",
"int_score": 4,
"score": 3.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz"
}
|
/*
* ServiceRegistrationException.java
*
* $Revision$ $Date$
*
* (c) Copyright 2001, 2002 Motorola, Inc. ALL RIGHTS RESERVED.
*/
package javax.bluetooth;
import java.lang.*;
import java.io.IOException;
/**
* The <code>ServiceRegistrationException</code> is thrown when there is a failure to add
* a service record to the local Service Discovery Database (SDDB) or to modify
* an existing service record in the SDDB. The failure could be because the
* SDDB has no room for new records or because the modification being
* attempted to a service record violated one of the rules about
* service record updates. This exception will also be thrown if it
* was not possible to obtain an RFCOMM server channel needed for a
* <code>btspp</code> service record.
*
* @version 1.0 February 11, 2002
*/
public class ServiceRegistrationException extends IOException {
/**
* Creates a <code>ServiceRegistrationException</code> without a
* detailed message.
*/
public ServiceRegistrationException() {
throw new RuntimeException("Not Implemented! Used to compile Code");
}
/**
* Creates a <code>ServiceRegistrationException</code> with a
* detailed message.
*
* @param msg the reason for the exception
*/
public ServiceRegistrationException(String msg) {
throw new RuntimeException("Not Implemented! Used to compile Code");
}
}
|
c5e9c3ce316489c03264cc4a5cd1ba0dfba1e60e
|
{
"blob_id": "c5e9c3ce316489c03264cc4a5cd1ba0dfba1e60e",
"branch_name": "refs/heads/master",
"committer_date": "2011-02-16T15:50:40",
"content_id": "120b0c8cca82bb8021c015e939585c3c2e44f288",
"detected_licenses": [
"MIT"
],
"directory_id": "52463138907797aeed0cdd196085e17eda4d6ea2",
"extension": "java",
"filename": "ServiceRegistrationException.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1374317,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1429,
"license": "MIT",
"license_type": "permissive",
"path": "/javax/bluetooth/ServiceRegistrationException.java",
"provenance": "stack-edu-0030.json.gz:373671",
"repo_name": "dwa012/NXT-Bluetooth",
"revision_date": "2011-02-16T15:50:40",
"revision_id": "7f00758f04d812d9690125f079ab0ed470ef9d8e",
"snapshot_id": "1bc5e505e5c4f73aa0f9ac5413a12216b7798ef8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dwa012/NXT-Bluetooth/7f00758f04d812d9690125f079ab0ed470ef9d8e/javax/bluetooth/ServiceRegistrationException.java",
"visit_date": "2020-05-09T00:30:57.387714",
"added": "2024-11-18T23:24:07.506041+00:00",
"created": "2011-02-16T15:50:40",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz"
}
|
'use strict';
const S3Error = require('../models/error');
exports.parseHeader = function (headers) {
const [, ...components] = headers.authorization.split(' ');
if (components.length !== 1) {
throw new S3Error(
'InvalidArgument',
"Authorization header is invalid -- one and only one ' ' (space) required",
{
ArgumentName: 'Authorization',
ArgumentValue: headers.authorization,
},
);
}
const match = /([^:]*):([^:]+)/.exec(components[0]);
if (!match) {
throw new S3Error(
'InvalidArgument',
'AWS authorization header is invalid. Expected AwsAccessKeyId:signature',
{
ArgumentName: 'Authorization',
ArgumentValue: headers.authorization,
},
);
}
return { accessKeyId: match[1], signatureProvided: match[2] };
};
exports.parseQuery = function (query) {
// authentication param names are case-sensitive
if (!('Expires' in query) || !('AWSAccessKeyId' in query)) {
throw new S3Error(
'AccessDenied',
'Query-string authentication requires the Signature, Expires and ' +
'AWSAccessKeyId parameters',
);
}
const request = {
signature: {
version: 2,
algorithm: 'sha1',
encoding: 'base64',
},
accessKeyId: query.AWSAccessKeyId,
expires: Number(query.Expires),
signatureProvided: query.Signature,
};
const serverTime = new Date();
const expiresTime = new Date(request.expires * 1000);
if (isNaN(expiresTime)) {
throw new S3Error(
'AccessDenied',
`Invalid date (should be seconds since epoch): ${query.Expires}`,
);
}
if (serverTime > expiresTime) {
throw new S3Error('AccessDenied', 'Request has expired', {
Expires: expiresTime.toISOString().replace(/\.\d+/, ''),
ServerTime: serverTime.toISOString().replace(/\.\d+/, ''),
});
}
return request;
};
/**
* Generates a string to be signed for signature version 2.
*
* @param {*} canonicalRequest
*/
exports.getStringToSign = function (canonicalRequest) {
return [
canonicalRequest.method,
canonicalRequest.contentMD5,
canonicalRequest.contentType,
canonicalRequest.timestamp,
...canonicalRequest.amzHeaders,
canonicalRequest.querystring
? `${canonicalRequest.uri}?${canonicalRequest.querystring}`
: canonicalRequest.uri,
].join('\n');
};
|
9f6f8dc01908819eb6a7b95f2e05eab71554f593
|
{
"blob_id": "9f6f8dc01908819eb6a7b95f2e05eab71554f593",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-09T01:52:48",
"content_id": "5dab73e2976103763315316ecefd278ce2abd3fb",
"detected_licenses": [
"MIT"
],
"directory_id": "aaf18a684c3489e45c7959fe40f4bf398615352b",
"extension": "js",
"filename": "v2.js",
"fork_events_count": 0,
"gha_created_at": "2021-09-24T21:55:25",
"gha_event_created_at": "2021-09-24T21:55:26",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 410111483,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2370,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/signature/v2.js",
"provenance": "stack-edu-0043.json.gz:33901",
"repo_name": "jasonprado/s3rver",
"revision_date": "2021-08-08T23:51:26",
"revision_id": "1d2e9e122b3f5be21441d2499b71386ec8e7ee36",
"snapshot_id": "59a31306e19e9a7ed2cf1321e566b2d851e46e7c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jasonprado/s3rver/1d2e9e122b3f5be21441d2499b71386ec8e7ee36/lib/signature/v2.js",
"visit_date": "2023-08-29T23:58:30.504755",
"added": "2024-11-19T00:02:05.121244+00:00",
"created": "2021-08-08T23:51:26",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
# -*- coding: utf-8 -*-
import math
from ROOT import *
from array import array
import glob
gROOT.SetBatch(1)
gStyle.SetOptStat(0)
gStyle.SetTitleOffset(1.4, "xyz")
gStyle.SetMarkerStyle(8)
gStyle.SetMarkerSize(3)
gStyle.SetHistLineWidth(3)
#gStyle.SetErrorX(0)
gStyle.SetStripDecimals(kFALSE)
gROOT.UseCurrentStyle()
gROOT.ForceStyle()
class MCRun:
def __init__(
self,
fname,
eng = 3.0,
):
self.eng = eng
self.fl_list = glob.glob('../build/data/' + fname + '/calo_hits_*.root')
self.h_eng_time = TH1F("eng_time" + fname, "eng_time", 200, 0, 2)
self.h_eng_pos = TH1F("eng_pos" + fname , "eng_time", 250, -50, 200)
self.h_pht_time = TH1F("pht_time" + fname, "pht_time", 200, 0, 2)
self.h_pht_pos = TH1F("pht_pos" + fname, "pht_pos", 250, -50, 200)
def crunch(self):
for fname in self.fl_list:
mc_fl = TFile(fname, 'r')
eng_tree = mc_fl.Get("eng")
pht_tree = mc_fl.Get("pht")
"""
eng_tree_reader = TTreeReader(eng_tree)
time_g = TTreeReaderValue("Float_t")(eng_tree_reader, "eng_dep.time_g")
pos_x = TTreeReaderValue("Float_t")(eng_tree_reader, "eng_dep.pos_x")
eng = TTreeReaderValue("Float_t")(eng_tree_reader, "eng_dep.eng")
while eng_tree_reader.Next():
self.h_eng_time.Fill(time_g.Get()[0])
self.h_eng_pos.Fill(pos_x.Get()[0], eng.Get()[0])
"""
eng_tree.Draw("eng.time_g >> h1(200, 0, 2)")
self.h_eng_time.Add(gDirectory.Get("h1"))
eng_tree.Draw("eng.pos_x >> h2(250,-50,200)", "eng.eng")
self.h_eng_pos.Add(gDirectory.Get("h2"))
pht_tree.Draw("pht.time_g >> h3(200, 0, 2)")
self.h_pht_time.Add(gDirectory.Get("h3"))
pht_tree.Draw("pht.pos_x >> h4(250,-50,200)")
self.h_pht_pos.Add(gDirectory.Get("h4"))
mc_fl.Close()
self.h_eng_time.Print()
self.h_eng_pos.Print()
self.h_pht_time.Print()
self.h_pht_pos.Print()
if __name__ == '__main__':
pos30 = MCRun('pos_30gev', 3.0)
pos20 = MCRun('pos_20gev', 2.0)
for dt in [pos30, pos20]:
dt.crunch()
|
c7f82124b3fa6e97a67c35e9a138e9b58ba14ecf
|
{
"blob_id": "c7f82124b3fa6e97a67c35e9a138e9b58ba14ecf",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-08T15:36:21",
"content_id": "3f78ed59e3271ef6555f796bfe1c516e1e50e6d1",
"detected_licenses": [
"MIT"
],
"directory_id": "baf5117283e59e8725e820b3e67369f685419903",
"extension": "py",
"filename": "dump_plots.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 18250783,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2282,
"license": "MIT",
"license_type": "permissive",
"path": "/ana/dump_plots.py",
"provenance": "stack-edu-0058.json.gz:517226",
"repo_name": "gffs/PbF2Calo",
"revision_date": "2017-02-08T15:36:21",
"revision_id": "87770ab7eec4e40b67bc551e1e6ddf85d01b09dd",
"snapshot_id": "5f771b89f33711e1e0d69771e94b959c1bfae697",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gffs/PbF2Calo/87770ab7eec4e40b67bc551e1e6ddf85d01b09dd/ana/dump_plots.py",
"visit_date": "2021-01-10T20:44:05.356892",
"added": "2024-11-19T01:28:34.943989+00:00",
"created": "2017-02-08T15:36:21",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz"
}
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nwagu.contacts.interactions;
import com.google.common.base.Preconditions;
/**
* Utility methods for interactions and their loaders
*/
public class ContactInteractionUtil {
/**
* @return a string like (?,?,?...) with {@param count} question marks.
*/
public static String questionMarks(int count) {
Preconditions.checkArgument(count > 0);
StringBuilder sb = new StringBuilder("(?");
for (int i = 1; i < count; i++) {
sb.append(",?");
}
return sb.append(")").toString();
}
}
|
21b89a0b8f9c45f8379dad25f918a3a74286beff
|
{
"blob_id": "21b89a0b8f9c45f8379dad25f918a3a74286beff",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-10T20:49:01",
"content_id": "d297b6c6c4ffce3f6ddf9305b964a1a124beac65",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "266cf9c18c6de00113755bf23a4040043702849d",
"extension": "java",
"filename": "ContactInteractionUtil.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": 1184,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/com/nwagu/contacts/interactions/ContactInteractionUtil.java",
"provenance": "stack-edu-0031.json.gz:729760",
"repo_name": "ebukaohaeche/contacts",
"revision_date": "2020-08-10T20:49:01",
"revision_id": "bc7d3115f96ecccfcb131f52a3e65d5fc46b07c7",
"snapshot_id": "3f7057b5b8d5e2881674dd61b5ca898d7a836cb5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ebukaohaeche/contacts/bc7d3115f96ecccfcb131f52a3e65d5fc46b07c7/app/src/main/java/com/nwagu/contacts/interactions/ContactInteractionUtil.java",
"visit_date": "2022-11-29T01:28:00.975286",
"added": "2024-11-18T23:13:48.366468+00:00",
"created": "2020-08-10T20:49:01",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
<?php
class Receiver{
private $db;
public function __construct(){
$this->db=new Database;
}
public function insert($listArray){
if($listArray['type']=='agent'){
//insert for agent
$this->db->query('INSERT INTO agent_cust_receiver(b_fname,b_lname,b_phone,bank,b_actno,b_idtype,b_transfer,agcid,agid,date)
VALUES(:fName,:lName,:rPhone,:bank,:actNo,:modeId,:tMode,:agcid,:agid,:dtime)');
}
//insert for customer
if($listArray['type']=='customer'){
$this->db->query('INSERT INTO receiver(b_fname,b_lname,b_phone,bank,b_actno,b_idtype,b_transfer,cid,date)
VALUES(:fName,:lName,:rPhone,:bank,:actNo,:modeId,:tMode,:cid,:dtime)');
}
$this->db->bind(':fName',$listArray['fName']);
$this->db->bind(':lName',$listArray['lName']);
$this->db->bind(':rPhone',$listArray['rPhone']);
$this->db->bind(':bank',$listArray['bank']);
$this->db->bind(':actNo',$listArray['actNo']);
$this->db->bind(':modeId',$listArray['modeId']);
$this->db->bind(':tMode',$listArray['tMode']);
$this->db->bind(':dtime',$listArray['dtime']);
if($listArray['type']=='agent'){
$this->db->bind(':agcid',$listArray['agcid']);
$this->db->bind(':agid',$listArray['agid']);
}
if($listArray['type']=='customer'){
$this->db->bind(':cid',$listArray['cid']);
}
$this->db->execute();
$id=$this->db->lastInsertId();
$return=array(true,$id);
return $return;
}
public function relist($b_fname,$b_lname){
if(getuser()['type']=='agent'){
$this->db->query('SELECT * FROM agent_cust_receiver WHERE b_fname=:b_fname && b_lname=:b_lname');
}
else {
$this->db->query('SELECT * FROM receiver WHERE b_fname=:b_fname && b_lname=:b_lname');
}
$this->db->bind(':b_fname',$b_fname);
$this->db->bind(':b_lname',$b_lname);
$row=$this->db->resultset();
return $row;
}
public function receiversAgentList($fName,$mName,$lName,$agid){
$table="SELECT agent_new_customer.fname,agent_new_customer.mname,agent_new_customer.lname,agent_new_customer.id,agent_new_customer.id,agent_cust_receiver.agcid,agent_cust_receiver.b_fname,agent_cust_receiver.b_lname FROM agent_new_customer INNER JOIN agent_cust_receiver ON agent_new_customer.id=agent_cust_receiver.agcid WHERE agent_new_customer.fname LIKE '$fName' && agent_new_customer.lname LIKE '$lName' && agent_new_customer.agid='$agid' ORDER BY agent_cust_receiver.b_fname DESC ";
$this->db->query($table);
$row=$this->db->resultset();
return $row;
}
public function receiversCustList($fName,$mName,$lName,$agid){
$table="SELECT new_customer.fname,new_customer.mname,new_customer.lname,new_customer.id,new_customer.id,receiver.cid,receiver.b_fname,receiver.b_lname FROM new_customer INNER JOIN receiver ON new_customer.id=receiver.cid WHERE new_customer.fname LIKE '$fName' && new_customer.lname LIKE '$lName' && new_customer.cid='$agid' ORDER BY receiver.b_fname DESC ";
$this->db->query($table);
$row=$this->db->resultset();
return $row;
}
public function receiversList($cid){
$table="SELECT new_customer.fname,new_customer.mname,new_customer.lname,new_customer.id,new_customer.id,receiver.cid,receiver.b_fname,receiver.b_lname FROM new_customer INNER JOIN receiver ON new_customer.id=receiver.cid WHERE new_customer.id='$cid' ORDER BY receiver.b_fname DESC ";
$this->db->query($table);
$row=$this->db->resultset();
return $row;
}
public function update($listArray,$agrid){
if($listArray['type']=='agent'){
$this->db->query("UPDATE agent_cust_receiver SET b_fname=:fName,b_lname=:lName,b_phone=:rPhone,bank=:bank,b_actno=:actNo,b_idtype=:modeId,b_transfer=:tMode,date=:dtime
WHERE id='$agrid'");
}
if($listArray['type']=='customer'){
$this->db->query("UPDATE receiver SET b_fname=:fName,b_lname=:lName,b_phone=:rPhone,bank=:bank,b_actno=:actNo,b_idtype=:modeId,b_transfer=:tMode,date=:dtime WHERE id='$agrid'");
}
$this->db->bind(':fName',$listArray['fName']);
$this->db->bind(':lName',$listArray['lName']);
$this->db->bind(':rPhone',$listArray['rPhone']);
$this->db->bind(':bank',$listArray['bank']);
$this->db->bind(':actNo',$listArray['actNo']);
$this->db->bind(':modeId',$listArray['modeId']);
$this->db->bind(':tMode',$listArray['tMode']);
$this->db->bind(':dtime',$listArray['dtime']);
$this->db->execute();
return true;
}
public function agent_cust_receiver($agrid){
$this->db->query("SELECT * FROM agent_cust_receiver WHERE id='$agrid'");
$row=$this->db->resultset();
return $row;
}
public function receiver($rid){
$this->db->query("SELECT * FROM receiver WHERE id='$rid'");
$row=$this->db->resultset();
return $row;
}
//fetch result of bank with bank Account option
public function transBank(){
$this->db->query("SELECT bank FROM `bank` WHERE `status`='b' ");
//$row=$this->db->single();
$row=$this->db->resultset();
return $row;
}
}
?>
|
30e8344a219a6f5e6be5bc47548571df7afc062c
|
{
"blob_id": "30e8344a219a6f5e6be5bc47548571df7afc062c",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-04T13:21:20",
"content_id": "7cc2f51b9965d87afac8b435c9768780f7d9bd6e",
"detected_licenses": [
"MIT"
],
"directory_id": "2975d608670155000a3342947e6c080cf65f3ba7",
"extension": "php",
"filename": "Receiver.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143530604,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 4960,
"license": "MIT",
"license_type": "permissive",
"path": "/controllers/users/libraries/Receiver.php",
"provenance": "stack-edu-0051.json.gz:57103",
"repo_name": "da-ogunkoya/Mone_App_v2",
"revision_date": "2018-08-04T13:21:20",
"revision_id": "d1cd744a7550b74e6416131a00a7745022ad49e7",
"snapshot_id": "8b62c08717c5ff5d40618a9129637ad78d65837e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/da-ogunkoya/Mone_App_v2/d1cd744a7550b74e6416131a00a7745022ad49e7/controllers/users/libraries/Receiver.php",
"visit_date": "2020-03-25T06:53:36.852457",
"added": "2024-11-19T02:57:35.717781+00:00",
"created": "2018-08-04T13:21:20",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
package com.qa.choonz.rest.assembler;
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import org.springframework.stereotype.Component;
import org.springframework.hateoas.CollectionModel;
import com.qa.choonz.persistence.domain.Genre;
import com.qa.choonz.persistence.domain.Track;
import com.qa.choonz.rest.controller.GenreController;
import com.qa.choonz.rest.controller.TrackController;
import com.qa.choonz.rest.model.GenreModel;
import com.qa.choonz.rest.model.TrackModel;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class GenreModelAssembler extends RepresentationModelAssemblerSupport<Genre, GenreModel>{
public GenreModelAssembler() {
super(GenreController.class, GenreModel.class);
}
@Override
public GenreModel toModel(Genre entity) {
GenreModel genreModel = instantiateModel(entity);
genreModel.setId(entity.getId());
genreModel.setName(entity.getName());
genreModel.setDescription(entity.getDescription());
genreModel.setTracks(toTrackModel(entity.getTracks()));
genreModel.add(linkTo(
methodOn(GenreController.class)
.findById(entity.getId()))
.withSelfRel());
genreModel.add(linkTo(
methodOn(GenreController.class)
.findAll())
.withRel("genres"));
return genreModel;
}
@Override
public CollectionModel<GenreModel> toCollectionModel(Iterable<? extends Genre> entities)
{
CollectionModel<GenreModel> genreModels = super.toCollectionModel(entities);
genreModels.add(linkTo(methodOn(GenreController.class).findAll()).withSelfRel());
return genreModels;
}
private List<TrackModel> toTrackModel(List<Track> tracks) {
if (tracks == null || tracks.isEmpty()) {
return Collections.emptyList();
}
return tracks.stream().map(track -> TrackModel.builder()
.id(track.getId())
.name(track.getName())
.build()
.add(linkTo(
methodOn(TrackController.class)
.findById(track.getId()))
.withSelfRel()))
.collect(Collectors.toList());
}
}
|
f55c0cb837a82827d7b27ad41235074817e28244
|
{
"blob_id": "f55c0cb837a82827d7b27ad41235074817e28244",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-29T16:16:38",
"content_id": "a76176e918cdb76512198874e85e5be334d2d398",
"detected_licenses": [
"MIT"
],
"directory_id": "264e6c3f10a046112b87351ce7bc7b9a5909232a",
"extension": "java",
"filename": "GenreModelAssembler.java",
"fork_events_count": 1,
"gha_created_at": "2021-01-15T11:02:58",
"gha_event_created_at": "2021-01-29T16:16:39",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 329887901,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2170,
"license": "MIT",
"license_type": "permissive",
"path": "/Choonz_App/src/main/java/com/qa/choonz/rest/assembler/GenreModelAssembler.java",
"provenance": "stack-edu-0023.json.gz:621141",
"repo_name": "JasonFyfe/choonz",
"revision_date": "2021-01-29T16:16:38",
"revision_id": "0c267923b81ad4e582384f5b4a8a57d5efa0a1fe",
"snapshot_id": "68e1e7504bcfc9bfeb29de8e4a8600ce65f37366",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/JasonFyfe/choonz/0c267923b81ad4e582384f5b4a8a57d5efa0a1fe/Choonz_App/src/main/java/com/qa/choonz/rest/assembler/GenreModelAssembler.java",
"visit_date": "2023-02-23T09:23:15.922763",
"added": "2024-11-18T23:08:37.476401+00:00",
"created": "2021-01-29T16:16:38",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
Template.adminLayout.rendered = function() {
require('jquery.initialize');
$.initialize('[data-toggle="tooltip"]', function() {
$(this).tooltip({boundary: 'viewport'});
});
function _iframe() {
$.initialize('iframe', function() {
const width = $(this).width();
const height = parseInt(width * 0.56, 10);
$(this).attr({height: height + 'px'});
});
}
$(document).ready(() => {
_iframe();
});
// Minimize menu when screen is less than 768px
$(window).on('resize load', function() {
const $body = $('body');
if ($(this).width() < 769) {
$body.addClass('body-small');
} else {
$body.removeClass('body-small');
}
});
// Fix height of layout when resize, scroll and load
$(window).on('load resize scroll', () => {
const $body = $('body');
if (!$body.hasClass('body-small')) {
const $wrapper = $('#page-wrapper');
const navbarHeight = $('nav.navbar-default').height();
const wrapperHeight = $wrapper.height();
if (navbarHeight > wrapperHeight) {
$wrapper.css('min-height', navbarHeight + 'px');
}
if (navbarHeight < wrapperHeight) {
$wrapper.css('min-height', $(window).height() + 'px');
}
if ($body.hasClass('fixed-nav')) {
if (navbarHeight > wrapperHeight) {
$wrapper.css('min-height', navbarHeight + 'px');
} else {
$wrapper.css('min-height', $(window).height() - 60 + 'px');
}
}
}
});
};
|
a9679ba5a190b820108d167a4dd30f9f39b9ff35
|
{
"blob_id": "a9679ba5a190b820108d167a4dd30f9f39b9ff35",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-28T09:14:18",
"content_id": "1bb628a5fa0c6e03891b09e81ac7f132d7e30f3a",
"detected_licenses": [
"MIT"
],
"directory_id": "5cc489649f7567d6f20f1c25dc66a30ba7d02bb8",
"extension": "js",
"filename": "admin.js",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115039609,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1509,
"license": "MIT",
"license_type": "permissive",
"path": "/client/views/layouts/admin/admin.js",
"provenance": "stack-edu-0036.json.gz:780834",
"repo_name": "teamco/zeurcv",
"revision_date": "2018-11-28T09:14:18",
"revision_id": "393cbc807928be37d8a08077d8a730565038c65f",
"snapshot_id": "bd662bee928f071e426300531bb0cd95c52f8384",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/teamco/zeurcv/393cbc807928be37d8a08077d8a730565038c65f/client/views/layouts/admin/admin.js",
"visit_date": "2021-10-01T18:27:47.607618",
"added": "2024-11-19T01:42:12.685604+00:00",
"created": "2018-11-28T09:14:18",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz"
}
|
// 华勤科技版权所有 2008-2022
//
// 文件名:UIuiguard.h>
// 功 能:定义核心库的线程哨兵类。
//
// 作 者:MPF开发组
// 时 间:2010-07-02
//
// =========================================================
#ifndef _UIGUARD_H_
#define _UIGUARD_H_
#include <System/Windows/Object.h>
namespace suic
{
template<typename LOCK>
class SUICORE_API UIGuard
{
public:
UIGuard(const LOCK & lock)
: m_lock(lock)
, m_owner(false)
{
m_lock.lock();
m_owner = true;
}
virtual ~UIGuard()
{
Release();
}
bool Acquired() const
{
if (!m_owner)
{
m_lock.lock();
m_owner = true;
}
return true;
}
void Release() const
{
if (m_owner)
{
m_lock.unlock();
m_owner = false;
}
}
protected:
const LOCK & m_lock;
mutable bool m_owner;
friend class ThreadCond;
};
};
#endif
|
60b454372ffdf02eae133fe971972ea66374b949
|
{
"blob_id": "60b454372ffdf02eae133fe971972ea66374b949",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-12T14:17:30",
"content_id": "912670bbc4800d04ee8d0d6b79909dc6e0815305",
"detected_licenses": [
"MIT"
],
"directory_id": "17cc16f379ca934ba055ed36240a0f39d1bef47a",
"extension": "h",
"filename": "Guard.h",
"fork_events_count": 0,
"gha_created_at": "2019-01-08T12:53:51",
"gha_event_created_at": "2019-01-08T12:53:51",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 164648672,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 996,
"license": "MIT",
"license_type": "permissive",
"path": "/include/suic/System/Tools/Guard.h",
"provenance": "stack-edu-0008.json.gz:566608",
"repo_name": "BigPig0/MPFUI",
"revision_date": "2019-01-12T14:17:30",
"revision_id": "7042e0a5527ab323e16d2106d715db4f8ee93275",
"snapshot_id": "91fd95d839e01e60e9154f57d4657de6aaf2a9ce",
"src_encoding": "GB18030",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/BigPig0/MPFUI/7042e0a5527ab323e16d2106d715db4f8ee93275/include/suic/System/Tools/Guard.h",
"visit_date": "2021-08-27T18:26:51.671239",
"added": "2024-11-18T23:39:24.428720+00:00",
"created": "2019-01-12T14:17:30",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
var o = {
A: function f(x) {
'use strict';
// BAD
if (!(this instanceof arguments.callee))
// BAD
return new arguments.callee(x);
// BAD
console.log(f.caller);
// BAD
f.arguments;
this.x = x;
}
};
var D = class extends function() {
// BAD
arguments.callee;
} {};
function g() {
// OK
return arguments.caller.length;
}
(function() {
'use strict';
function h() {
var foo = Math.random() > 0.5 ? h : arguments;
// BAD
foo.caller;
}
})();
|
a393788e4b6360a5d2254c749bd30cd2af5a09aa
|
{
"blob_id": "a393788e4b6360a5d2254c749bd30cd2af5a09aa",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-02T07:43:40",
"content_id": "3d53d5f81fbb456049144588b4a1ce8cae06402b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9f1330409ab56771ff4934823fdb8c8ab28e22f8",
"extension": "js",
"filename": "tst.js",
"fork_events_count": 0,
"gha_created_at": "2018-08-03T12:07:28",
"gha_event_created_at": "2023-08-08T07:36:59",
"gha_language": "C#",
"gha_license_id": "Apache-2.0",
"github_id": 143422705,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 544,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/javascript/ql/test/query-tests/LanguageFeatures/StrictModeCallStackIntrospection/tst.js",
"provenance": "stack-edu-0038.json.gz:319094",
"repo_name": "aschackmull/ql",
"revision_date": "2019-09-02T07:43:40",
"revision_id": "742c9708a9888c59391b49041ebb2f18ef2e1ffb",
"snapshot_id": "a26f4bd82755a5edbef5d7ce413b0fc5e902f522",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/aschackmull/ql/742c9708a9888c59391b49041ebb2f18ef2e1ffb/javascript/ql/test/query-tests/LanguageFeatures/StrictModeCallStackIntrospection/tst.js",
"visit_date": "2023-08-30T23:38:07.249712",
"added": "2024-11-19T00:41:25.656370+00:00",
"created": "2019-09-02T07:43:40",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz"
}
|
let Modal = require('bootstrap.native').Modal;
/**
* @param {NodeList} taskTypeContainers
*/
module.exports = function (taskTypeContainers) {
for (let i = 0; i < taskTypeContainers.length; i++) {
let unavailableTaskType = taskTypeContainers[i];
let taskTypeKey = unavailableTaskType.getAttribute('data-task-type');
let modalId = taskTypeKey + '-account-required-modal';
let modalElement = document.getElementById(modalId);
let modal = new Modal(modalElement);
unavailableTaskType.addEventListener('click', function () {
modal.show();
});
}
};
|
22be71d687edae6de17d1b56fd33b69f54a92191
|
{
"blob_id": "22be71d687edae6de17d1b56fd33b69f54a92191",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-22T16:29:10",
"content_id": "0518b0086b6b0f9aafbde9fbe06321e52eabdd11",
"detected_licenses": [
"MIT"
],
"directory_id": "7784442a734368c1dc0b55dcc2da73313288be5c",
"extension": "js",
"filename": "unavailable-task-type-modal-launcher.js",
"fork_events_count": 1,
"gha_created_at": "2012-08-17T09:27:29",
"gha_event_created_at": "2019-04-22T16:29:11",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 5450309,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 623,
"license": "MIT",
"license_type": "permissive",
"path": "/assets/js/unavailable-task-type-modal-launcher.js",
"provenance": "stack-edu-0033.json.gz:442477",
"repo_name": "webignition/web.client.simplytestable.com",
"revision_date": "2019-04-22T16:29:10",
"revision_id": "d5f31c9052205ca9f93f1a5bd36734edd8e8d58a",
"snapshot_id": "a76d522ba43cd99c4172de5ae1ea8798f2940e06",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/webignition/web.client.simplytestable.com/d5f31c9052205ca9f93f1a5bd36734edd8e8d58a/assets/js/unavailable-task-type-modal-launcher.js",
"visit_date": "2021-06-04T12:06:28.366297",
"added": "2024-11-18T22:25:18.436411+00:00",
"created": "2019-04-22T16:29:10",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
package skateKAPPA;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import skateKAPPA.base.ItemBase;
import javax.annotation.Nonnull;
import java.util.Objects;
public class BanPowder extends ItemBase {
public BanPowder(String name) {
super(name);
}
@Nonnull
@Override
public ActionResult<ItemStack> onItemRightClick(@Nonnull World world, @Nonnull EntityPlayer player, @Nonnull EnumHand hand) {
player.setActiveHand(hand);
return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand));
}
@Nonnull
@Override
public ItemStack onItemUseFinish(@Nonnull ItemStack stack, @Nonnull World world, @Nonnull EntityLivingBase entity) {
if (entity instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) entity;
Objects.requireNonNull(player.getServer()).addScheduledTask(() -> player.connection.disconnect(new TextComponentTranslation("skatekappa.banpowder")));
}
stack.shrink(1);
return stack;
}
public int getMaxItemUseDuration(@Nonnull ItemStack stack)
{
return 4;
}
@Nonnull
public EnumAction getItemUseAction(@Nonnull ItemStack stack) {
return EnumAction.BOW;
}
}
|
36581acd9c04a090b9af3735bfc7a5ed0d94f21d
|
{
"blob_id": "36581acd9c04a090b9af3735bfc7a5ed0d94f21d",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-02T19:07:24",
"content_id": "3b7e30189a07caddde035dcf5c87fd2998c56faf",
"detected_licenses": [
"MIT"
],
"directory_id": "acd56ce06f159ea6a68deac2cac860a3fed3bc51",
"extension": "java",
"filename": "BanPowder.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328415579,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1828,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/skateKAPPA/BanPowder.java",
"provenance": "stack-edu-0020.json.gz:56242",
"repo_name": "noeppi-noeppi/skateKAPPA",
"revision_date": "2021-09-02T19:07:24",
"revision_id": "8b4e8ac8b8bdb8c7c754a710220b9c3d4ea1c51a",
"snapshot_id": "439079a04cac154ae7407e94e8833fec7b8f9724",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/noeppi-noeppi/skateKAPPA/8b4e8ac8b8bdb8c7c754a710220b9c3d4ea1c51a/src/main/java/skateKAPPA/BanPowder.java",
"visit_date": "2023-07-19T12:33:03.284351",
"added": "2024-11-19T01:12:36.314801+00:00",
"created": "2021-09-02T19:07:24",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
import React, { useContext, useEffect } from "react";
import { motion } from "framer-motion";
import ImageContext from "../../context/ImageContext";
import PropTypes from "prop-types";
export default function Loading({ nextComponent }) {
const { loading } = useContext(ImageContext);
useEffect(() => {
if (!loading) {
nextComponent();
}
}, [loading]);
return (
<motion.div
initial={{ x: "+500px", opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: "-500px", opacity: 0 }}
transition={{ type: "tween" }}
className="flex justify-center items-center h-full rounded-lg shadow-inner py-4 md:py-24"
>
<div className="w-full flex flex-col justify-center items-center">
<div className="animate-pulse mb-4">
<div className="bg-gray-400 h-32 w-32"></div>
</div>
<p className="text-blue-800 font-bold text-2xl">Loading...</p>
</div>
</motion.div>
);
}
Loading.propTypes = {
nextComponent: PropTypes.func.isRequired,
};
|
fc7c19c89936a0f24df10a12fd7514aa0eff8200
|
{
"blob_id": "fc7c19c89936a0f24df10a12fd7514aa0eff8200",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-24T16:09:16",
"content_id": "79d20220884e8707458d0177a885253945dc6818",
"detected_licenses": [
"MIT"
],
"directory_id": "0c5ced45f6bdd23498d309d2118df4bcf6999370",
"extension": "js",
"filename": "Loading.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 304398082,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1031,
"license": "MIT",
"license_type": "permissive",
"path": "/front/src/components/Conversion/Loading.js",
"provenance": "stack-edu-0033.json.gz:411873",
"repo_name": "NikVogri/image-resize-api",
"revision_date": "2020-10-24T16:09:16",
"revision_id": "80f2a43095079ec1faebc19e62f76ef2ba6dbfdb",
"snapshot_id": "6c888daef194cf3d1038ea7612408fd465cf2f20",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NikVogri/image-resize-api/80f2a43095079ec1faebc19e62f76ef2ba6dbfdb/front/src/components/Conversion/Loading.js",
"visit_date": "2022-12-31T21:31:57.578576",
"added": "2024-11-19T01:30:54.780958+00:00",
"created": "2020-10-24T16:09:16",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
import { provide } from '../../../../src/modules/header/i18n/header.provider';
describe('i18n for header module', () => {
it('provides translation for de', () => {
const map = provide('de');
expect(map.header_tab_topics_button).toBe('Themen');
expect(map.header_tab_topics_title).toBe('Themen öffnen');
expect(map.header_tab_maps_button).toBe('Ebenenverwaltung');
expect(map.header_tab_maps_title).toBe('Ebenenverwaltung öffnen');
expect(map.header_tab_more_button).toBe('Mehr...');
expect(map.header_tab_more_title).toBe('Mehr anzeigen');
expect(map.header_close_button_title).toBe('Menü schließen');
});
it('provides translation for en', () => {
const map = provide('en');
expect(map.header_tab_topics_button).toBe('Topics');
expect(map.header_tab_topics_title).toBe('Open topics');
expect(map.header_tab_maps_button).toBe('Layers configuration');
expect(map.header_tab_maps_title).toBe('Open layers configuration');
expect(map.header_tab_more_button).toBe('More...');
expect(map.header_tab_more_title).toBe('Show more');
expect(map.header_close_button_title).toBe('Close menu');
});
it('have the expected amount of translations', () => {
const expectedSize = 7;
const deMap = provide('de');
const enMap = provide('en');
const actualSize = (o) => Object.keys(o).length;
expect(actualSize(deMap)).toBe(expectedSize);
expect(actualSize(enMap)).toBe(expectedSize);
});
it('provides an empty map for a unknown lang', () => {
const map = provide('unknown');
expect(map).toEqual({});
});
});
|
15d3e2c6bf99c75c1109f8f8306ee888eef1a5b8
|
{
"blob_id": "15d3e2c6bf99c75c1109f8f8306ee888eef1a5b8",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-01T11:26:51",
"content_id": "da248e3741256e4d21c9efedff0246ad712c9d2b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cfcc6e5586be708807839c0a2f2bfb2821e1e96b",
"extension": "js",
"filename": "header.provider.test.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1562,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/modules/header/i18n/header.provider.test.js",
"provenance": "stack-edu-0035.json.gz:154459",
"repo_name": "urfavdr/bav4-nomigration",
"revision_date": "2021-10-01T11:26:51",
"revision_id": "385fced38f0c1fc8de8d1a4f5b8d97a62e71d635",
"snapshot_id": "8061f35864a5e6db7dce604a738ee82ee64d24de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/urfavdr/bav4-nomigration/385fced38f0c1fc8de8d1a4f5b8d97a62e71d635/test/modules/header/i18n/header.provider.test.js",
"visit_date": "2023-08-06T21:14:18.877508",
"added": "2024-11-19T01:25:33.136390+00:00",
"created": "2021-10-01T11:26:51",
"int_score": 2,
"score": 2,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
package info.jorgeyanesdiez.dnilettercalc.service.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import info.jorgeyanesdiez.dnilettercalc.service.DniNumericPartValidator;
import info.jorgeyanesdiez.dnilettercalc.service.Validity;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DniNumericPartValidatorTest
{
private DniNumericPartValidator sut;
@BeforeTest
public void beforeTest()
{
sut = new DniNumericPartValidator();
}
@Test
public void validate_WithNull_ReturnsExpected()
{
assertThat(sut.validate(null), is(Validity.Invalid));
}
@Test
public void validate_WithWhitespace_ReturnsExpected()
{
assertThat(sut.validate(" "), is(Validity.Invalid));
}
@Test
public void validate_WithNonNumericString_ReturnsExpected()
{
assertThat(sut.validate("A"), is(Validity.Invalid));
}
@Test
public void validate_WithEmptyString_ReturnsExpected()
{
assertThat(sut.validate(""), is(Validity.Partial));
}
@Test
public void validate_WithIncorrectLengthString_ReturnsExpected()
{
assertThat(sut.validate("1"), is(Validity.Partial));
}
@Test
public void validate_WithValidString_ReturnsExpected()
{
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < 8 ; i++) { sb.append("1"); }
assertThat(sut.validate(sb.toString()), is(Validity.Valid));
}
}
|
f672e9fb85abac526c09099becdfa15f76d70fb6
|
{
"blob_id": "f672e9fb85abac526c09099becdfa15f76d70fb6",
"branch_name": "refs/heads/master",
"committer_date": "2014-04-07T13:50:24",
"content_id": "1241183da33639e8ef913035546805df478d7ed3",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "9faca181e26979584e55e83facf154719eca1ffe",
"extension": "java",
"filename": "DniNumericPartValidatorTest.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": 1508,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/dnilettercalc-service/src/test/java/info/jorgeyanesdiez/dnilettercalc/service/test/DniNumericPartValidatorTest.java",
"provenance": "stack-edu-0022.json.gz:844170",
"repo_name": "jorgeyanesdiez/dnilettercalc",
"revision_date": "2014-04-07T13:50:24",
"revision_id": "194f3ecc54502ae8ac2f08c93f627b89827d789c",
"snapshot_id": "dce83447410dfad59f1756605127012178479e00",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jorgeyanesdiez/dnilettercalc/194f3ecc54502ae8ac2f08c93f627b89827d789c/dnilettercalc-service/src/test/java/info/jorgeyanesdiez/dnilettercalc/service/test/DniNumericPartValidatorTest.java",
"visit_date": "2021-01-10T19:43:26.224677",
"added": "2024-11-19T00:50:02.424676+00:00",
"created": "2014-04-07T13:50:24",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
package com.refinedmods.refinedstorage.apiimpl.network.node;
import com.refinedmods.refinedstorage.api.network.INetwork;
import com.refinedmods.refinedstorage.api.network.INetworkNodeVisitor;
import com.refinedmods.refinedstorage.api.network.node.INetworkNode;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
public class RootNetworkNode implements INetworkNode, INetworkNodeVisitor {
private final INetwork network;
private final Level level;
private final BlockPos pos;
public RootNetworkNode(INetwork network, Level level, BlockPos pos) {
this.network = network;
this.level = level;
this.pos = pos;
}
@Override
public ResourceLocation getId() {
return null;
}
@Nullable
@Override
public UUID getOwner() {
return null;
}
@Override
public void setOwner(@Nullable UUID owner) {
// NO OP
}
@Override
public int getEnergyUsage() {
return 0;
}
@Nonnull
@Override
public ItemStack getItemStack() {
BlockState state = level.getBlockState(pos);
@SuppressWarnings("deprecation")
Item item = Item.byBlock(state.getBlock());
return new ItemStack(item, 1);
}
@Override
public void onConnected(INetwork network) {
// NO OP
}
@Override
public void onDisconnected(INetwork network) {
// NO OP
}
@Override
public boolean isActive() {
return false;
}
@Override
public INetwork getNetwork() {
return network;
}
@Override
public void update() {
// NO OP
}
@Override
public CompoundTag write(CompoundTag tag) {
return tag;
}
@Override
public BlockPos getPos() {
return pos;
}
@Override
public Level getLevel() {
return level;
}
@Override
public void markDirty() {
// NO OP
}
@Override
public void visit(Operator operator) {
for (Direction facing : Direction.values()) {
BlockPos relativePos = pos.relative(facing);
if (!level.isLoaded(relativePos)) {
continue;
}
operator.apply(level, relativePos, facing.getOpposite());
}
}
}
|
ad4c1bafa29c15f4a9c5cd58d27bb77d621a7db0
|
{
"blob_id": "ad4c1bafa29c15f4a9c5cd58d27bb77d621a7db0",
"branch_name": "refs/heads/develop",
"committer_date": "2023-07-08T13:02:37",
"content_id": "ecf25684da92ea92c53dd3f4856d99df3a9023c7",
"detected_licenses": [
"MIT"
],
"directory_id": "12daebd5e6399d367c147ff88fad236c66b40786",
"extension": "java",
"filename": "RootNetworkNode.java",
"fork_events_count": 115,
"gha_created_at": "2015-12-07T16:05:16",
"gha_event_created_at": "2023-07-05T09:32:58",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 47563072,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2658,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/node/RootNetworkNode.java",
"provenance": "stack-edu-0019.json.gz:311800",
"repo_name": "refinedmods/refinedstorage",
"revision_date": "2023-07-08T13:02:37",
"revision_id": "e46046418fca514b58c3abb93e1b9b98d5361ce7",
"snapshot_id": "767b2acbcc2bd498d7633308f589062b89e77ab8",
"src_encoding": "UTF-8",
"star_events_count": 181,
"url": "https://raw.githubusercontent.com/refinedmods/refinedstorage/e46046418fca514b58c3abb93e1b9b98d5361ce7/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/node/RootNetworkNode.java",
"visit_date": "2023-09-01T14:33:35.870033",
"added": "2024-11-18T22:00:44.947358+00:00",
"created": "2023-07-08T13:02:37",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
import * as path from "path"
import { promises as fs } from "fs"
import DiscordClient from "../client/client"
import { Constants } from "discord.js"
export async function registerCommands(client: DiscordClient, dir: string = '') {
const filePath = path.join(__dirname, dir);
const files = await fs.readdir(filePath);
for (const file of files) {
const stat = await fs.lstat(path.join(filePath, file));
if (stat.isDirectory()) registerCommands(client, path.join(dir, file));
if (file.endsWith('.js') || file.endsWith('.ts')) {
const { default: Command } = await import(path.join(dir, file));
const command = new Command();
if (command.options.disabled) continue
console.log(`[Commands] registering ${path.join(dir, file)}`)
if (command.init instanceof Function) {
command.init(client)
}
client.commands.set(command.getName(), command);
command.options.aliases?.forEach((alias: string) => {
client.commands.set(alias, command);
});
}
}
}
export async function registerEvents(client: DiscordClient, dir: string = '') {
const filePath = path.join(__dirname, dir);
const files = await fs.readdir(filePath);
for (const file of files) {
const stat = await fs.lstat(path.join(filePath, file));
if (stat.isDirectory()) registerEvents(client, path.join(dir, file));
if (file.endsWith('.js') || file.endsWith('.ts')) {
const { default: Event } = await import(path.join(dir, file));
const event = new Event();
if (Object.keys(Constants.Events).includes(event.getName())) {
console.log(`[Events] registering discord event => ${path.join(dir, file)}`);
client.events.set(event.getName(), event);
client.on(event.getName(), event.run.bind(event, client));
} else {
console.log(`[Events] registering custom event => ${path.join(dir, file)}`);
client.customEvents.set(event.getName(), event);
global.ws.on(event.getName(), event.run.bind(event, client));
}
if (event.init instanceof Function) {
event.init(client);
}
}
}
}
|
a63097b532c18e6eae0053e94f2619123a0856b4
|
{
"blob_id": "a63097b532c18e6eae0053e94f2619123a0856b4",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-05T00:28:43",
"content_id": "c0dfd9d20f051926e08f28d76cedf819a32f8474",
"detected_licenses": [
"MIT"
],
"directory_id": "26a0819bcd230fd15b9cfabb87898fd175e4c1fd",
"extension": "ts",
"filename": "registry.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 373983425,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2013,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/registry.ts",
"provenance": "stack-edu-0076.json.gz:309120",
"repo_name": "th1m0/ts-discordjs-template",
"revision_date": "2021-06-05T00:28:43",
"revision_id": "eabac362e20486f65be04655d0a68f764612a86c",
"snapshot_id": "916bfde7ef0906a6e95ff7fb5e71d7d030e99e40",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/th1m0/ts-discordjs-template/eabac362e20486f65be04655d0a68f764612a86c/src/utils/registry.ts",
"visit_date": "2023-05-14T14:01:21.377496",
"added": "2024-11-18T22:31:52.246302+00:00",
"created": "2021-06-05T00:28:43",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz"
}
|
(function ($) {
function init(plot) {
function autoMarkingsFunction(plot, offset) {
plot.getOptions().grid.markings = new Array();
$(plot.getData()).each(function () {
if (this.autoMarkings && this.autoMarkings.enabled === true) {
if (plot.getOptions().grid.markings == null) plot.getOptions().grid.markings = new Array();
if (this.autoMarkings.showMinMax === true || this.autoMarkings.showAvg === true) {
if (this.autoMarkings.min == null || this.autoMarkings.max == null || this.autoMarkings.avg == null) {
var min = Number.MAX_VALUE;
var max = 0;
var sum = 0;
var count = 0;
$(this.data).each(function () {
if (this[1] < min) min = this[1];
if (this[1] > max) max = this[1];
count++;
sum += this[1];
});
if (this.autoMarkings.min == null) this.autoMarkings.min = min;
if (this.autoMarkings.max == null) this.autoMarkings.max = max;
if (this.autoMarkings.avg == null) this.autoMarkings.avg = sum / count;
}
if (this.autoMarkings.lineWidth) {
plot.getOptions().grid.markingsLineWidth = parseInt(this.autoMarkings.lineWidth);
}
}
var seriesColor = this.autoMarkings.color || this.color;
var avgseriesColor = this.autoMarkings.avgcolor || this.color;
var axis = "y" + (this.yaxis.n > 1 ? this.yaxis.n : "") + "axis";
if (this.autoMarkings.showMinMax === true && this.autoMarkings.min != Number.MAX_VALUE && this.autoMarkings.max != 0) {
var marking = {color: seriesColor.replace('rgb(', 'rgba(').replace(')', ',' + this.autoMarkings.minMaxAlpha + ')')};
marking[axis] = {from: this.autoMarkings.min, to: this.autoMarkings.max};
plot.getOptions().grid.markings.push(marking);
}
if (this.autoMarkings.showAvg === true && this.autoMarkings.avg != Number.NaN) {
var marking = {color: avgseriesColor};
marking[axis] = {from: this.autoMarkings.avg, to: this.autoMarkings.avg};
plot.getOptions().grid.markings.push(marking);
}
}
});
}
plot.hooks.processOffset.push(autoMarkingsFunction);
}
var options = {series: {autoMarkings: {enabled: false, minMaxAlpha: 0.2, lineWidth: 2}}};
/** Options
* enabled
* color
* avgcolor
* showMinMax
* minMaxAlpha
* showAvg
* min
* max
* avg
*/
$.plot.plugins.push({
init: init,
options: options,
name: "autoMarkings",
version: "0.2.2"
});
})(jQuery);
function RefreshChart($thisObj, $obj) {
$($thisObj).find('.glyphicon').addClass('glyphicon-refresh-animate');
LoadSpeedChart($obj);
setTimeout(function () {
$($thisObj).find('.glyphicon').removeClass('glyphicon-refresh-animate');
}, 500);
}
function LoadSpeedChart(chartSelector, options) {
$.ajax({
url: options.url,
type: 'get',
dataType: "json",
data: {Type: options.type, Duration: options.duration},
contentType: "application/json; charset=utf-8",
beforeSend: function () {
//$(".loading-image").css("visibility", "visible");
},
complete: function (response) {
//$(".loading-image").css("visibility", "hidden");
},
success: function (chartData) {
if (typeof(chartData) == "object" && typeof chartData.data != undefined) {
if (chartData.data.length > 0) {
DrawTPSChart(chartSelector, chartData, options);
} else {
//ShowError(element, options.customoptions.NoDataFound);
}
} else {
//ShowError(element, options.customoptions.UnknownError);
}
},
error: function (request, status, error) {
}
})
}
function DrawTPSChart(chartSelector, chartData, options) {
var defaultOptions = {
averageLineColor: "#51a351",
barColor: '#3b6998',
barLabel: 'TPS',
lineWidth: 5,
barWidth: 0,
averageLabel: 'Average Speed',
aboveData: true
}
$.each(defaultOptions, function (key, val) {
if (key in options) {
defaultOptions[key] = options[key];
}
});
var selectorID = chartSelector.substring(1, chartSelector.length);
var data = [];
var chartTpsData = chartData.data;
for (var i = 0; i < chartData.data.length; i++) {
var dateTime = new Date(chartData.data[i][0]);
var tps = chartData.data[i][1];
data.push([dateTime, tps]);
}
var average = chartData.average;
var maxDate = chartData.maxDate;
var minDate = chartData.minDate;
var maxTps = chartData.maxTps;
var minTps = chartData.minTps;
var plot = $.plot(chartSelector, [
{data: data, label: " " + defaultOptions.barLabel, color: defaultOptions.barColor}
], {
series: {
autoMarkings: {
enabled: true,
showAvg: true,
avgcolor: defaultOptions.averageLineColor,
avg: average
},
bars: {
show: true,
lineWidth: defaultOptions.lineWidth, // in pixels
barWidth: defaultOptions.barWidth, // in units of the x axis
fill: true,
align: "left", // "left", "right", or "center"
horizontal: false,
zero: true
},
lines: {
show: false,
horizontal: true
},
points: {
show: true,
radius: 2
}
},
grid: {
hoverable: true,
clickable: true,
show: true,
borderWidth: 1,
borderColor: '#3b6998',
aboveData: defaultOptions.aboveData
},
xaxis: {
mode: "time",
minTickSize: [1, "second"],
min: new Date(minDate).getTime(),
max: new Date(maxDate).getTime(),
twelveHourClock: false,
tickFormatter: function (value, axis) {
var dt = new Date(value);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
return time;
}
},
yaxis: {
min: (parseInt(minTps) - 1),
max: (parseInt(maxTps) + 1)
}
});
$("<div id='" + selectorID + "billingTooltip'></div>").css({
position: "absolute",
display: "none",
border: "2px solid #fff",
"border-radius": '5px',
padding: "2px 5px",
"background-color": "#000",
color: '#fff',
opacity: 0.8
}).appendTo("body");
$(chartSelector).bind("plothover", average, function (event, pos, item) {
if ((Math.floor(pos.y1)) == Math.floor(average) || (Math.ceil(pos.y1)) == Math.ceil(average) || pos.y1 == average) {
$("#" + selectorID + "billingTooltip").html(defaultOptions.averageLabel + " : " + average)
.css({top: pos.pageY + 0, left: pos.pageX + 5, background: '#000'})
.fadeIn(200);
} else {
$("#" + selectorID + "billingTooltip").hide();
$("#" + selectorID + "billingTooltip").css('background', '#000');
}
if (item) {
var x = item.datapoint[0];
y = item.datapoint[1].toFixed(4);
var dt = new Date(x);
var time = AddZero(dt.getHours()) + ":" + AddZero(dt.getMinutes()) + ":" + AddZero(dt.getSeconds());
$("#" + selectorID + "billingTooltip").html(item.series.label + " " + Language.translate('of') + " " + time + " = " + y)
.css({top: item.pageY + 5, left: item.pageX + 5, background: '#000'})
.fadeIn(200);
} else {
$("#" + selectorID + "billingTooltip").hide();
}
});
}
function FormatDateTime(timeStamp, format) {
if (isNaN(parseInt(timeStamp))) return null;
var parsedDateTime = new Date(parseInt(timeStamp));
if (isNaN(parsedDateTime)) return null;
var d = AddZero(parsedDateTime.getDate());
var m = AddZero(parsedDateTime.getMonth() + 1);
var Y = parsedDateTime.getFullYear();
var D = parsedDateTime.getDay();
var H = AddZero(parsedDateTime.getHours());
var M = AddZero(parsedDateTime.getMinutes());
var S = AddZero(parsedDateTime.getSeconds());
format = format.replace("%d", d);
format = format.replace("%m", m);
format = format.replace("%Y", Y);
format = format.replace("%D", D);
format = format.replace("%H", H);
format = format.replace("%M", M);
format = format.replace("%S", S);
return format;
}
function AddZero(value) {
value = parseInt(value);
if (value <= 9) {
value = "0" + value;
}
return value;
}
|
d9a390fb8edaf974dff7bac156e9bf1eb275340b
|
{
"blob_id": "d9a390fb8edaf974dff7bac156e9bf1eb275340b",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-14T01:51:15",
"content_id": "707f6e712e9f5dc1900933288d33026de162b702",
"detected_licenses": [
"MIT"
],
"directory_id": "ef671fc88a515957cc412478fe81530c10271277",
"extension": "js",
"filename": "SpeedChart.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 94276337,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 9677,
"license": "MIT",
"license_type": "permissive",
"path": "/VasupDemoSender/includes/scripts/SpeedChart.js",
"provenance": "stack-edu-0043.json.gz:310216",
"repo_name": "suman-adhikari/demosender",
"revision_date": "2017-06-14T01:51:15",
"revision_id": "73f5afb4ce0285b084cd173366af6a262696012f",
"snapshot_id": "cd6e7cf5f97b063a22d0fb70a5a65143572c9007",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/suman-adhikari/demosender/73f5afb4ce0285b084cd173366af6a262696012f/VasupDemoSender/includes/scripts/SpeedChart.js",
"visit_date": "2020-07-12T05:00:44.847382",
"added": "2024-11-18T23:50:49.920303+00:00",
"created": "2017-06-14T01:51:15",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
using System;
namespace Aggregates.Exceptions
{
public class ConflictingCommandException : Exception
{
public ConflictingCommandException() { }
public ConflictingCommandException(string message) : base(message) { }
public ConflictingCommandException(string message, Exception innerException) : base(message, innerException) { }
}
}
|
965a9e3f1d29eb9a2a73ff3ac3360d1a9e621e7e
|
{
"blob_id": "965a9e3f1d29eb9a2a73ff3ac3360d1a9e621e7e",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-12T23:27:55",
"content_id": "77b4effef0d7b1388194c8bd2ee4a1a54b9e015e",
"detected_licenses": [
"MIT"
],
"directory_id": "0787d90ae7c52a50f7571aef7aee5fd0461f0c91",
"extension": "cs",
"filename": "ConflictResolutionFailedException.cs",
"fork_events_count": 0,
"gha_created_at": "2018-05-09T06:10:22",
"gha_event_created_at": "2018-05-09T06:10:23",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 132709862,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 372,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Aggregates.NET/Exceptions/ConflictResolutionFailedException.cs",
"provenance": "stack-edu-0014.json.gz:447707",
"repo_name": "virajs/Aggregates.NET",
"revision_date": "2018-04-12T23:27:55",
"revision_id": "d8cf2aff75ee5f9bd8da0703257e56881d960b0d",
"snapshot_id": "2c13f2199bbfbb1c15f82186abd85778ec721e20",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/virajs/Aggregates.NET/d8cf2aff75ee5f9bd8da0703257e56881d960b0d/src/Aggregates.NET/Exceptions/ConflictResolutionFailedException.cs",
"visit_date": "2020-03-16T14:11:11.944829",
"added": "2024-11-19T03:03:03.986788+00:00",
"created": "2018-04-12T23:27:55",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
<?php
declare(strict_types = 1);
namespace unreal4u\TelegramAPI\Telegram\Types;
use unreal4u\TelegramAPI\Abstracts\TelegramTypes;
use unreal4u\TelegramAPI\Telegram\Types\Custom\StickerSetArray;
/**
* This object represents a sticker set
*
* Objects defined as-is july 2017
*
* @see https://core.telegram.org/bots/api#stickerset
*/
class StickerSet extends TelegramTypes
{
/**
* Sticker set name
* @var string
*/
public $name = '';
/**
* Sticker set title
* @var string
*/
public $title = '';
/**
* True, if the sticker set contains masks
* @var bool
*/
public $is_masks = false;
/**
* List of all set stickers
* @var Sticker[]
*/
public $stickers = [];
protected function mapSubObjects(string $key, array $data): TelegramTypes
{
switch ($key) {
case 'stickers':
return new StickerSetArray($data, $this->logger);
}
return parent::mapSubObjects($key, $data);
}
}
|
493727caedfc173eac63bbcb6b9d38e30c4d72bb
|
{
"blob_id": "493727caedfc173eac63bbcb6b9d38e30c4d72bb",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-03T15:34:16",
"content_id": "5c769b75a7530ce0c133180756936c48eba02e33",
"detected_licenses": [
"MIT"
],
"directory_id": "a01ab158eed971c8e6d0dca04a45735a763676a0",
"extension": "php",
"filename": "StickerSet.php",
"fork_events_count": 1,
"gha_created_at": "2020-03-07T15:33:12",
"gha_event_created_at": "2023-04-19T21:16:17",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 245658079,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1032,
"license": "MIT",
"license_type": "permissive",
"path": "/public/telegram/vendor/unreal4u/telegram-api/src/Telegram/Types/StickerSet.php",
"provenance": "stack-edu-0049.json.gz:708636",
"repo_name": "TA3/bearicade",
"revision_date": "2022-05-03T15:34:16",
"revision_id": "9fac9dcce22630ad9d4de3b20eeaa3fb97702324",
"snapshot_id": "83952f016e26c96e22ea2d7ae2b4ceed5c31259f",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/TA3/bearicade/9fac9dcce22630ad9d4de3b20eeaa3fb97702324/public/telegram/vendor/unreal4u/telegram-api/src/Telegram/Types/StickerSet.php",
"visit_date": "2023-04-28T19:22:57.252942",
"added": "2024-11-18T22:42:57.904347+00:00",
"created": "2022-05-03T15:34:16",
"int_score": 3,
"score": 2.78125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from .models import HeritageSite, HeritageSiteCategory
class IndexViewTest(TestCase):
def test_view_route_redirection(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
class HomeViewTest(TestCase):
def test_view_route(self):
response = self.client.get('/heritagesites/')
self.assertEqual(response.status_code, 200)
def test_view_route_name(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
def test_view_template(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'heritagesites/home.html')
class AboutViewTest(TestCase):
def test_view_route(self):
response = self.client.get('/heritagesites/about/')
self.assertEqual(response.status_code, 200)
def test_view_route_fail(self):
response = self.client.get('/about/')
self.assertEqual(response.status_code, 404)
def test_view_route_name(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
def test_view_template(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'heritagesites/about.html')
class SiteModelTest(TestCase):
def setUp(self):
HeritageSiteCategory.objects.create(category_name='Cultural')
category = HeritageSiteCategory.objects.get(pk=1)
HeritageSite.objects.create(
# TODO restore missing properties and values
heritage_site_id=1,
site_name='Cultural Landscape and Archaeological Remains of the Bamiyan Valley',
heritage_site_category_id=1,
description='The cultural landscape and archaeological remains of the Bamiyan Valley ...',
justification='The Buddha statues and the cave art in Bamiyan Valley are ...',
date_inscribed='2003',
longitude='67.82525000',
latitude='34.84694000',
area_hectares='158.9265',
transboundary=0)
def test_site_name(self):
site = HeritageSite.objects.get(pk=1)
expected_object_name = f'{site.site_name}'
self.assertEqual(expected_object_name, 'Cultural Landscape and Archaeological Remains of the Bamiyan Valley')
class SiteListViewTest(TestCase):
def test_view_route(self):
response = self.client.get('/heritagesites/sites/')
self.assertEqual(response.status_code, 200)
def test_view_route_fail(self):
response = self.client.get('/sites/')
self.assertEqual(response.status_code, 404)
def test_view_route_name(self):
response = self.client.get(reverse('sites'))
self.assertEqual(response.status_code, 200)
def test_view_template(self):
response = self.client.get(reverse('sites'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'heritagesites/site.html')
|
736c766e320827e71f5a1fc73b7dc5c2fb99355a
|
{
"blob_id": "736c766e320827e71f5a1fc73b7dc5c2fb99355a",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-04T19:29:54",
"content_id": "ed2eefa7a8619c28a5f3e34d98f0beace9099376",
"detected_licenses": [
"MIT"
],
"directory_id": "e3cd5c58275eafbacd0ef2ba2e1d5e631aaf4d3f",
"extension": "py",
"filename": "tests.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157316185,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2890,
"license": "MIT",
"license_type": "permissive",
"path": "/heritagesites/tests.py",
"provenance": "stack-edu-0056.json.gz:1784",
"repo_name": "p1ho/heritagesites",
"revision_date": "2019-01-04T19:29:54",
"revision_id": "0345e06c67717460d9cc412313297ba967823209",
"snapshot_id": "748ac9dacbdded9da3aba3daf2f1a263318174a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/p1ho/heritagesites/0345e06c67717460d9cc412313297ba967823209/heritagesites/tests.py",
"visit_date": "2020-04-06T08:48:25.728524",
"added": "2024-11-18T20:58:17.307697+00:00",
"created": "2019-01-04T19:29:54",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
+++
date = "2013-07-02 16:50:39+00:00"
draft = false
tags = ["python", "ssl", "https", "flask"]
title = "SSL for flask local development "
url = "/post/54437887454/ssl-for-flask-local-development"
+++
Recently at <a href="https://blog.hasgeek.com/2013/https-everywhere-at-hasgeek" target="_blank">HasGeek</a> we moved all our web application to `` https ``. So I wanted to have all my development environment urls to have `` https ``.
_How to have `` https `` in <a href="http://flask.pocoo.org" target="_blank">flask</a> app_
_Method 1_
from flask import Flask
app = Flask(__name__)
app.run('<IP_ADDRESS>', debug=True, port=8100, ssl_context='adhoc')
In the above piece of code, `` ssl_context `` variable is passed to `` werkezug.run_simple `` which creates SSL certificates using `` OpenSSL ``, you may need to install `` pyopenssl ``. I had issues with this method, so I generated self signed certificate.
_Method 2_
* Generate a private key
` openssl genrsa -des3 -out server.key 1024 `
*
Generate a CSR
` openssl req -new -key server.key -out server.csr `
*
Remove Passphrase from key
`cp server.key server.key.org `
`openssl rsa -in server.key.org -out server.key `
*
Generate self signed certificate
`openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt `
_code_
from flask import Flask
app = Flask(__name__)
app.run('<IP_ADDRESS>', debug=True, port=8100, ssl_context=('/Users/kracekumarramaraju/certificates/server.crt', '/Users/kracekumarramaraju/certificates/server.key'))
`` ssl_context `` can take option `` adhoc `` or `` tuple of the form (cert_file, pkey_file) ``.
In case you are using `` /etc/hosts ``, add something similar <code><IP_ADDRESS> <a href="https://hacknight.local" target="_blank">https://hacknight.local</a></code> for accessing the web application locally.
Here is much detailed post about generating self signed <a href="http://www.akadia.com/services/ssh_test_certificate.html" target="_blank">certificates</a>.
|
00066aba23a58f837c92829edc1a83124277686c
|
{
"blob_id": "00066aba23a58f837c92829edc1a83124277686c",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-29T17:59:06",
"content_id": "054a010cdb36522a33f7d5e45d6fadde43d9a001",
"detected_licenses": [
"MIT"
],
"directory_id": "0598cead58c6a54c38792687beb6c84eb2c2eaa6",
"extension": "md",
"filename": "ssl-for-flask-local-development.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 267919776,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2043,
"license": "MIT",
"license_type": "permissive",
"path": "/content/post/ssl-for-flask-local-development.md",
"provenance": "stack-edu-markdown-0014.json.gz:89199",
"repo_name": "kracekumar/kracekumar.github.io",
"revision_date": "2020-05-29T17:59:06",
"revision_id": "75e355bb6c4d62f9834740098012ee489e400f58",
"snapshot_id": "5e2ab10b55de1300f234cab89497629e74758d64",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kracekumar/kracekumar.github.io/75e355bb6c4d62f9834740098012ee489e400f58/content/post/ssl-for-flask-local-development.md",
"visit_date": "2022-08-21T03:38:08.108569",
"added": "2024-11-19T01:17:48.557359+00:00",
"created": "2020-05-29T17:59:06",
"int_score": 3,
"score": 3.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0014.json.gz"
}
|
# Copyright 2023 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TestCase
from scheduler.utils import space_events_and_recordings
class TestSpaceEventAndRecordings(TestCase):
def test_space_events_and_recordings(self):
events = space_events_and_recordings(
{
'space_id': 4991,
'start_dt': '2015-12-02T08:00:00.000Z'
})
self.assertEqual(len(events), 1)
|
3b50dadaa61912ba4cd851b195541f6c974f9b7c
|
{
"blob_id": "3b50dadaa61912ba4cd851b195541f6c974f9b7c",
"branch_name": "refs/heads/main",
"committer_date": "2023-05-23T22:07:24",
"content_id": "4c06c94813bae4e84597c63a92d74ef471eeeae7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8868c7832c6503af9d20e7e67c528a943f72cfb6",
"extension": "py",
"filename": "test_space_event_and_recordings.py",
"fork_events_count": 2,
"gha_created_at": "2015-09-29T23:21:45",
"gha_event_created_at": "2023-05-23T22:07:25",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 43400013,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 478,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/scheduler/test/test_space_event_and_recordings.py",
"provenance": "stack-edu-0063.json.gz:464035",
"repo_name": "uw-it-aca/django-panopto-scheduler",
"revision_date": "2023-05-23T22:07:24",
"revision_id": "147e75147a058378ffe9646e791fbe230b9e8a9b",
"snapshot_id": "cd8081a62b5812a1c101ccb8d13e03eeb6611d50",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/uw-it-aca/django-panopto-scheduler/147e75147a058378ffe9646e791fbe230b9e8a9b/scheduler/test/test_space_event_and_recordings.py",
"visit_date": "2023-06-08T18:16:55.713446",
"added": "2024-11-19T03:22:32.026882+00:00",
"created": "2023-05-23T22:07:24",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
const express = require('express')
const router = require('./router')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(function(req, res, next) {
// 允许请求的源
res.setHeader('Access-Control-Allow-Origin', "*")
// 允许请求的方法
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
// 允许所有的头
res.setHeader("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
next()
})
app.use(router)
app.listen(9999, () => {
console.log('你的服务端已经上线了')
})
|
fbab0f7ed0a09f952a95c9dac56f3f5c35d3048d
|
{
"blob_id": "fbab0f7ed0a09f952a95c9dac56f3f5c35d3048d",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-20T02:27:48",
"content_id": "e0f566fe2331805efabc48485507ef784262fac1",
"detected_licenses": [
"MIT"
],
"directory_id": "1abd4ff5c7bfe0d278916f2f54d0efb9ea15ae22",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 733,
"license": "MIT",
"license_type": "permissive",
"path": "/heima/2018olive/20-vue/brandserver/app.js",
"provenance": "stack-edu-0033.json.gz:305050",
"repo_name": "yanglichuan/OLJavaScript",
"revision_date": "2019-08-20T02:27:48",
"revision_id": "f98096e04e445e1a477ba4de54b1230bfe2cfe1f",
"snapshot_id": "bf382a126f3a60e4ecdfc2a7654f42c6147bbd69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yanglichuan/OLJavaScript/f98096e04e445e1a477ba4de54b1230bfe2cfe1f/heima/2018olive/20-vue/brandserver/app.js",
"visit_date": "2020-07-07T08:56:07.645645",
"added": "2024-11-19T00:05:09.807856+00:00",
"created": "2019-08-20T02:27:48",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
# ECC.jl
Elliptic Curve Cryptography in Julia
[](https://gitlab.com/braneproject/ecc.jl/commits/master) [](https://gitlab.com/braneproject/ecc.jl/commits/master)
## Documentation
https://braneproject.gitlab.io/ecc.jl
## Buy me a cup of coffee
[Donate Bitcoin](bitcoin:34nvxratCQcQgtbwxMJfkmmxwrxtShTn67)
|
d70cf52177d276724402c85d124bab7472b514e3
|
{
"blob_id": "d70cf52177d276724402c85d124bab7472b514e3",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-11T23:55:17",
"content_id": "e81aa410034e3897ce433d2f6bf3c0b019cd9d66",
"detected_licenses": [
"MIT"
],
"directory_id": "55712c0507003282375dfa8fecfbe20ee9ff2ace",
"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": 481,
"license": "MIT",
"license_type": "permissive",
"path": "/packages/ECC/4cJby/README.md",
"provenance": "stack-edu-markdown-0000.json.gz:156969",
"repo_name": "gazfaris/dot_julia",
"revision_date": "2021-05-11T23:55:17",
"revision_id": "16556fb0b477220d92568078bfcb4f569594a947",
"snapshot_id": "9873339a70fe82ac70bac0c0ee948b04ee0b59d0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gazfaris/dot_julia/16556fb0b477220d92568078bfcb4f569594a947/packages/ECC/4cJby/README.md",
"visit_date": "2023-07-15T22:31:16.873041",
"added": "2024-11-18T21:28:22.419432+00:00",
"created": "2021-05-11T23:55:17",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0000.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.