hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24f7b4aaa4c08298300742408e67f3db4443435a
| 27,936
|
hpp
|
C++
|
plugins/community/repos/ErraticInstruments/src/QuadMPEToCV.hpp
|
guillaume-plantevin/VeeSeeVSTRack
|
76fafc8e721613669d6f5ae82a0f58ce923a91e1
|
[
"Zlib",
"BSD-3-Clause"
] | 233
|
2018-07-02T16:49:36.000Z
|
2022-02-27T21:45:39.000Z
|
plugins/community/repos/ErraticInstruments/src/QuadMPEToCV.hpp
|
guillaume-plantevin/VeeSeeVSTRack
|
76fafc8e721613669d6f5ae82a0f58ce923a91e1
|
[
"Zlib",
"BSD-3-Clause"
] | 24
|
2018-07-09T11:32:15.000Z
|
2022-01-07T01:45:43.000Z
|
plugins/community/repos/ErraticInstruments/src/QuadMPEToCV.hpp
|
guillaume-plantevin/VeeSeeVSTRack
|
76fafc8e721613669d6f5ae82a0f58ce923a91e1
|
[
"Zlib",
"BSD-3-Clause"
] | 24
|
2018-07-14T21:55:30.000Z
|
2021-05-04T04:20:34.000Z
|
#include "global_pre.hpp"
#include "Erratic.hpp"
#include "midi.hpp"
#include "dsp/digital.hpp"
#include "MPEBaseWidget.hpp"
#include "global_ui.hpp"
struct MidiValue {
int val = 0; // Controller value
// TransitionSmoother tSmooth;
bool changed = false; // Value has been changed by midi message (only if it is in sync!)
};
struct MidiNote {
int pitch = 60;
int vel = 0; // velocity
bool gate = false;
int channel ;
bool noteOn, noteOff ;
bool changed = false;
};
struct MPEPlusValue {
uint16_t val = 0; // Controller value
int MSB = 0 ;
int LSB = 0;
bool changed = false; // Value has been changed by midi message (only if it is in sync!)
};
struct MidiPedalValue {
int val = 0; // Controller value
int cc ; // need to set it
bool changed = false; // Value has been changed by midi message (only if it is in sync!)
};
struct MPEChannel { // This contains the required info for each channel, each note in practical terms
int MIDIChannel; // must initialize
MidiNote note;
MidiValue mod;
MidiValue afterTouch;
MidiValue pitchWheel;
MidiValue Yaxis ;
MPEPlusValue MPEPlusyAxis, MPEPluszAxis;
bool changed = false;
};
struct QuadMPEToCV : Module {
enum ParamIds {
RESET_PARAM,
NUM_PARAMS,
BEND_RANGE_PARAM
};
enum InputIds {
NUM_INPUTS
};
enum OutputIds {
PITCH_OUTPUT = 0,
GATE_OUTPUT = 4,
VELOCITY_OUTPUT = 8,
PRESSURE_OUTPUT = 12,
Y_OUTPUT = 16,
PEDAL_OUTPUT = 20,
NUM_OUTPUTS = 21
};
enum LightIds {
RESET_LIGHT,
VELOCITY_LIGHT,
PRESSURE_LIGHT,
Y_AXIS_LIGHT,
PEDAL_LIGHT,
NUM_LIGHTS
};
MidiInputQueue midiInput;
int polyphony = 4;
std::vector<MPEChannel> mpeChannels;
// MPEChannel mpeChannels[4] ; // using this here instead of a container
bool noteOffReset = true; // Our default
int baseMIDIChannel = 2 ;
int bendRange = 48; // our default is 48 (common for ROLI), Continuum defaults to 96. This is a global parameter (for now)
int globalMIDIChannel = 16; // Our default channel is 16. ROLI users will want to set this is 1
bool MPEPlus = false ; // This is specially useful for Haken Continuum
int YaxisCC = 74 ;
bool pedal = false;
// int note = 60; // C4, most modules should use 261.626 Hz
int vel = 0;
MidiPedalValue midiPedalOne ;
SchmittTrigger resetTrigger;
QuadMPEToCV() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {
// for (int p=0; p < polyphony ; p++) {
// pitchWheel[p].val = 64;
// //pitchWheel[p].tSmooth.set(0, 0);
// }
mpeChannels.reserve(polyphony);
midiPedalOne.cc = 12; // By default we use 12 (barrel i on the Haken Continuum)
this->setupMIDIChannels();
}
~QuadMPEToCV() {
};
void step() override;
void pressNote(MidiNote note);
void releaseNote(MidiNote note);
void processMessage(MidiMessage msg) ;
void setupMIDIChannels();
json_t *toJson() override {
json_t *rootJ = json_object();
json_object_set_new(rootJ, "midi", midiInput.toJson());
json_object_set_new(rootJ, "bendRange", json_integer(bendRange));
json_object_set_new(rootJ, "baseMIDIChannel", json_integer(baseMIDIChannel));
json_object_set_new(rootJ, "globalMidiChannel", json_integer(globalMIDIChannel));
json_object_set_new(rootJ, "MPEMode", json_integer(MPEPlus));
json_object_set_new(rootJ, "noteOffReset", json_boolean(noteOffReset));
return rootJ;
}
void fromJson(json_t *rootJ) override {
json_t *midiJ = json_object_get(rootJ, "midi");
midiInput.fromJson(midiJ);
json_t *bendRangeJ = json_object_get(rootJ, "bendRange");
if (bendRangeJ) {
bendRange = json_integer_value(bendRangeJ);
}
json_t *baseMIDIChannelJ = json_object_get(rootJ, "baseMIDIChannel");
if (baseMIDIChannelJ) {
baseMIDIChannel = json_integer_value(baseMIDIChannelJ);
}
json_t *globalMidiChannelJ = json_object_get(rootJ, "globalMidiChannel");
if (globalMidiChannelJ) {
globalMIDIChannel = json_integer_value(globalMidiChannelJ);
}
json_t *MPEModeJ = json_object_get(rootJ, "MPEMode");
if (MPEModeJ) {
MPEPlus = json_integer_value(MPEModeJ);
}
json_t *noteOffResetJ = json_object_get(rootJ, "noteOffReset");
if (noteOffResetJ) {
noteOffReset = json_integer_value(noteOffResetJ);
}
}
// void fromJson(json_t *rootJ) override {
// json_t *bendRangeJ = json_object_get(rootJ, "bendRange");
// if (bendRangeJ)
// bendRange = json_integer_value(bendRangeJ);
// json_t *baseMIDIChannelJ = json_object_get(rootJ, "baseMIDIChannel");
// if (baseMIDIChannelJ)
// baseMIDIChannel = json_integer_value(baseMIDIChannelJ);
// json_t *globalMIDIChannelJ = json_object_get(rootJ, "globalMIDIChannel");
// if (globalMIDIChannelJ)
// globalMIDIChannel = json_integer_value(globalMIDIChannelJ);
// json_t *noteOffResetJ = json_object_get(rootJ, "noteOffReset");
// if (noteOffResetJ)
// noteOffReset = json_boolean_value(noteOffResetJ);
// json_t *MPEPlusModeJ = json_object_get(rootJ, "MPEPlusMode");
// if (MPEPlusModeJ)
// MPEPlus = json_boolean_value(MPEPlusModeJ);
// this->setupMIDIChannels();
// }
// json_t *toJson() override {
// json_t *rootJ = json_object();
// // Semitones
// // std::cout<< "We set bendRange to " << bendRange << std::endl;
// json_object_set_new(rootJ, "noteOffReset", json_boolean(noteOffReset));
// json_object_set_new(rootJ, "MPEPlusMode", json_boolean(MPEPlus));
// json_object_set_new(rootJ, "bendRange", json_integer(bendRange));
// json_object_set_new(rootJ, "baseMIDIChannel", json_integer(baseMIDIChannel));
// json_object_set_new(rootJ, "globalMIDIChannel", json_integer(globalMIDIChannel));
// return rootJ;
// }
// void reset() override {
// resetMidi();
// }
// void resetMidi() override;
};
struct QuadMPEToCVWidget : ModuleWidget {
QuadMPEToCVWidget(QuadMPEToCV *module);
// Reset Notes or not
void appendContextMenu(Menu *menu) override {
QuadMPEToCV *module = dynamic_cast<QuadMPEToCV*>(this->module);
struct ResetNoteItem : MenuItem {
QuadMPEToCV *module;
bool resetNoteBool;
void onAction(EventAction &e) override {
module->noteOffReset = ! resetNoteBool;
}
};
ResetNoteItem *item = MenuItem::create<ResetNoteItem>("Reset Note", CHECKMARK(module->noteOffReset == true));
item->module = module;
item->resetNoteBool = module->noteOffReset;
menu->addChild(item);
}
};
void QuadMPEToCV::setupMIDIChannels() {
// std::cout << " Setting up MIDI channels with baseMIDIChannel set to " << baseMIDIChannel << std::endl;
for (int p=0 ; p < polyphony ; p++) {
// std::cout << " p MIDIChannel " << p << " " << p + baseMIDIChannel - 1 << std::endl;
mpeChannels[p].MIDIChannel = p + baseMIDIChannel - 1; // MPE channels start at 2 onwards. We are using MIDI channel starting at 0
}
}
// void QuadMPEToCV::resetMidi() {
// for (int p=0; p < polyphony ; p++) {
// mpeChannels[p].mod.val = 0;
// mpeChannels[p].pitchWheel.val = 0;
// mpeChannels[p].afterTouch.val = 0;
// }
// // mod.val = 0;
// // mod.tSmooth.set(0, 0);
// // pitchWheel.val = 64;
// // pitchWheel.tSmooth.set(0, 0);
// // afterTouch.val = 0;
// // afterTouch.tSmooth.set(0, 0);
// //vel = 0;
// //gate = false;
// //notes.clear();
// }
void QuadMPEToCV::step() {
// if (isPortOpen()) {
// std::vector<unsigned char> message;
// int msgsProcessed = 0;
// // midiIn->getMessage returns empty vector if there are no messages in the queue
// // Original Midi to CV limits processing to 4 midi msgs, we should log how many we do at a time to look for
// // potential issues, specially with MPE+
// getMessage(&message);
// while (msgsProcessed < 4 && message.size() > 0) {
// processMidi(message);
// getMessage(&message);
// msgsProcessed++;
// }
// }
MidiMessage msg;
while (midiInput.shift(&msg)) {
processMessage(msg);
}
// if (resetTrigger.process(params[RESET_PARAM].value)) {
// resetMidi();
// return;
// }
// lights[RESET_LIGHT].value -= lights[RESET_LIGHT].value / 0.55 / engineGetSampleRate(); // fade out light
for (int ci=0; ci < polyphony; ci++) {
if (mpeChannels[ci].changed) {
if (mpeChannels[ci].note.changed) {
// std::cout << "New note on ci " << ci << std::endl;
// std::cout << "gate is " << mpeChannels[ci].note.gate << std::endl;
outputs[GATE_OUTPUT+ci].value = mpeChannels[ci].note.gate ? 10.0 : 0.0;
// std::cout << "outputs[GATE_OUTPUT+ci].value is " << outputs[GATE_OUTPUT+ci].value << std::endl;
outputs[VELOCITY_OUTPUT+ci].value = mpeChannels[ci].note.vel / 127.f * 10.f;
outputs[PITCH_OUTPUT+ci].value = (((mpeChannels[ci].note.pitch - 60)) / 12.0) + ((mpeChannels[ci].pitchWheel.val - 8192 ) / 8192.0 / 12.0 * (float)bendRange ) ;
// std::cout << "outputs[VELOCITY_OUTPUT+ci].value is " << outputs[VELOCITY_OUTPUT+ci].value << std::endl;
if (mpeChannels[ci].note.noteOff && noteOffReset) { // We reset all info when the note goes off
mpeChannels[ci].note.noteOff = false;
if (noteOffReset) {
//std::cout << "We execute the note off reset" << std::endl;
mpeChannels[ci].pitchWheel.val = 0;
mpeChannels[ci].pitchWheel.changed = false;
outputs[PITCH_OUTPUT+ci].value = 0 ;
mpeChannels[ci].afterTouch.val = 0;
mpeChannels[ci].afterTouch.changed = false;
outputs[PRESSURE_OUTPUT+ci].value = 0 ;
mpeChannels[ci].Yaxis.val = 0;
mpeChannels[ci].Yaxis.changed = false;
outputs[Y_OUTPUT+ci].value = 0 ;
}
}
mpeChannels[ci].note.changed = false;
}
if (mpeChannels[ci].note.gate) {
if (mpeChannels[ci].pitchWheel.changed && mpeChannels[ci].note.gate ) {
// std::cout << "mpeChannels[ci].pitch is " << mpeChannels[ci].note.pitch << std::endl;
outputs[PITCH_OUTPUT+ci].value = (((mpeChannels[ci].note.pitch - 60)) / 12.0) + ((mpeChannels[ci].pitchWheel.val - 8192 ) / 8192.0 / 12.0 * (float)bendRange ) ;
mpeChannels[ci].pitchWheel.changed = false;
// std::cout << "Setting pitch on ci " << ci << " to " << outputs[PITCH_OUTPUT+ci].value << std::endl;
}
if (MPEPlus) { // We process MPE+ or not here
if (mpeChannels[ci].MPEPluszAxis.changed) {
// Combine two 7 bit into 14bit
mpeChannels[ci].MPEPluszAxis.val = ( (uint16_t)mpeChannels[ci].MPEPluszAxis.MSB << 7) | ( (uint16_t)mpeChannels[ci].MPEPluszAxis.LSB ) ;
outputs[PRESSURE_OUTPUT+ci].value = mpeChannels[ci].MPEPluszAxis.val / 16384.0 * 10.f;
mpeChannels[ci].MPEPluszAxis.changed = false;
//std::cout << "Setting pressure on ci " << ci << " to " << outputs[PRESSURE_OUTPUT+ci].value << std::endl;
}
if (mpeChannels[ci].MPEPlusyAxis.changed) {
// Combine two 7 bit into 14bit
mpeChannels[ci].MPEPlusyAxis.val = ( (uint16_t)mpeChannels[ci].MPEPlusyAxis.MSB << 7) | ( (uint16_t)mpeChannels[ci].MPEPlusyAxis.LSB ) ;
outputs[Y_OUTPUT+ci].value = mpeChannels[ci].MPEPlusyAxis.val / 16384.0 * 10.f;
// std::cout << "Y axis is " << outputs[Y_OUTPUT].value << std::endl;
mpeChannels[ci].MPEPlusyAxis.changed = false;
}
} else {
if (mpeChannels[ci].afterTouch.changed ) {
outputs[PRESSURE_OUTPUT+ci].value = mpeChannels[ci].afterTouch.val / 127.f * 10.f;
mpeChannels[ci].afterTouch.changed = false;
// std::cout << "outputs[PRESSURE_OUTPUT+ci].value is " << outputs[PRESSURE_OUTPUT+ci].value << std::endl;
}
if (mpeChannels[ci].Yaxis.changed ) {
outputs[Y_OUTPUT+ci].value = mpeChannels[ci].Yaxis.val / 127.f * 10.f;
mpeChannels[ci].Yaxis.changed = false;
// std::cout << "outputs[Y_OUTPUT+ci].value is " << outputs[Y_OUTPUT+ci].value << std::endl;
}
}
}
mpeChannels[ci].changed = false;
}
}
// Pedal
if (midiPedalOne.changed) {
outputs[PEDAL_OUTPUT].value = midiPedalOne.val / 127.f * 10.f ;
// std::cout << " We set the output outputs[PEDAL_OUTPUT].value to " << outputs[PEDAL_OUTPUT].value << std::endl;
midiPedalOne.changed = false;
}
/*
outputs[GATE_OUTPUT].value = gate ? 10.0 : 0.0;
outputs[VELOCITY_OUTPUT].value = vel / 127.0 * 10.0;
// Pressure
if (MPEPlus) {
if (MPEPluszAxis.changed) {
// Combine two 7 bit into 14bit
MPEPluszAxis.val = ( (uint16_t)MPEPluszAxis.MSB << 7) | ( (uint16_t)MPEPluszAxis.LSB ) ;
outputs[PRESSURE_OUTPUT].value = MPEPluszAxis.val / 16384.0 * 10.f;
MPEPluszAxis.changed = false;
}
if (MPEPlusyAxis.changed) {
// Combine two 7 bit into 14bit
MPEPlusyAxis.val = ( (uint16_t)MPEPlusyAxis.MSB << 7) | ( (uint16_t)MPEPlusyAxis.LSB ) ;
outputs[Y_OUTPUT].value = MPEPlusyAxis.val / 16384.0 * 10.f;
std::cout << "Y axis is " << outputs[Y_OUTPUT].value << std::endl;
MPEPlusyAxis.changed = false;
}
} else { // Standard resolution MPE
if (afterTouch.changed) {
outputs[PRESSURE_OUTPUT].value = afterTouch.val / 127.0 * 10;
afterTouch.changed = false;
}
if (Yaxis.changed) {
outputs[Y_OUTPUT].value = Yaxis.val / 127.0 * 10;
Yaxis.changed = false;
}
}
// 1/V incorporates pitch wheel changes
if (pitchWheel.changed | this->newNote) {
outputs[PITCH_OUTPUT].value = (((note - 60)) / 12.0) + ((pitchWheel.val - 8192 ) / 8192.0 / 12.0 * (float)bendRange ) ;
pitchWheel.changed = false;
this->newNote = false;
}
*/
}
void QuadMPEToCV::processMessage(MidiMessage msg) {
int8_t channel = msg.channel(); // starts at 0
int8_t status = msg.status(); //(msg[0] >> 4) & 0xf;
int8_t data1 = msg.data1;
int8_t data2 = msg.data2;
if (status == 0xb && ( data1 == 111 || data1 == 118)) {
return;
}
// fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1, data2);
// Filter only the channels of our polyphony, it must be within our boundaries :)
// std::cout << "MIDI channel and mpeChannels[0].MIDIChannel " << channel << " " << mpeChannels[0].MIDIChannel << std::endl;
// std::cout << "polyphony is " << polyphony << std::endl;
// std::cout << "mpeChannels[0].MIDIChannel is " << mpeChannels[0].MIDIChannel << " and mpeChannels[polyphony].MIDIChannel "
// << mpeChannels[polyphony-1].MIDIChannel << std::endl;
// for (int p=0; p < polyphony ; p++ ) {
// std::cout << " mpeChannels[" << p << "].MIDIChannel: " << mpeChannels[p].MIDIChannel << std::endl;
// }
if ( channel >= mpeChannels[0].MIDIChannel && channel <= mpeChannels[polyphony-1].MIDIChannel ) { // Only process the channel we want
// std::cout << "We process" << std::endl;
// std::cout << "channel is " << channel << " baseMIDIChannel is " << baseMIDIChannel << " ci is " << ci << std::endl;
// start ci channel
// 1 0 0
// 1 1 1
// 2 0 1
// 2 1 2
// 3 0 2
// 3 1 3
int ci = channel - baseMIDIChannel + 1;
switch (status) {
// note off
case 0x8: {
// std::cout << "Note off" << std::endl;
mpeChannels[ci].note.gate= false;
mpeChannels[ci].note.vel = data2;
mpeChannels[ci].note.gate = false;
mpeChannels[ci].note.noteOff = true;
mpeChannels[ci].note.changed = true;
mpeChannels[ci].changed = true;
}
break;
case 0x9: // note on
// std::cout << "Note on" << std::endl;
// fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1, data2);
// std::cout << "ci is " << ci << std::endl;
// for (int p=0 ; p < polyphony ; p++) {
// std::cout << " p MIDIChannel " << p << " " << mpeChannels[p].MIDIChannel << std::endl;
// // mpeChannels[p].MIDIChannel = p + baseMIDIChannel - 1; // MPE channels start at 2 onwards. We are using MIDI channel starting at 0
// }
if (data2 > 0) { // note ON
mpeChannels[ci].note.gate= true;
mpeChannels[ci].note.pitch = data1;
mpeChannels[ci].note.vel = data2;
mpeChannels[ci].note.changed = true;
mpeChannels[ci].changed = true;
} else { // note off
// For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released.
mpeChannels[ci].note.gate= false;
mpeChannels[ci].note.vel = 0;
mpeChannels[ci].note.noteOff = true;
mpeChannels[ci].note.changed = true;
mpeChannels[ci].changed = true;
}
break;
case 0xe: // pitch wheel, we combine two 7 bit in two bytes into a 14bit msg
{
// We want 2 bytes but variable size may change with platform, maybe we should do a more robust way
uint16_t twoBytes ; // Initialize our final pitchWheel variable.
// we don't need to shift the first byte because it's 7 bit (always starts with 0)
twoBytes = ( (uint16_t)msg.data2 << 7) | ( (uint16_t)msg.data1 ) ;
// std::cout << "Pitch wheel " << twoBytes << " on channel and -1 : " << channel << " " << channel -1 << std::endl;
mpeChannels[ci].pitchWheel.val = twoBytes;
mpeChannels[ci].changed = true;
mpeChannels[ci].pitchWheel.changed = true;
}
break;
}
if (MPEPlus) { // Processing MPE+ data
// Note from the Haken Continuum Manual:
// (To avoid the glitches, the synthesizer can do synchronous 14-bit updates with output from the Continuum:
// simply save the least significant data, and do not apply it until the most significant data is received.)
switch (data1) {
case 74: // Y axis
mpeChannels[ci].MPEPlusyAxis.MSB = data2;
mpeChannels[ci].MPEPlusyAxis.changed = true;
mpeChannels[ci].changed = true;
break;
case 106:
mpeChannels[ci].MPEPlusyAxis.LSB = data2;
mpeChannels[ci].MPEPlusyAxis.changed = true;
mpeChannels[ci].changed = true;
break;
case 70: // Z or Pressure
mpeChannels[ci].MPEPluszAxis.MSB = data2;
mpeChannels[ci].MPEPluszAxis.changed = true;
mpeChannels[ci].changed = true;
break;
case 102:
mpeChannels[ci].MPEPluszAxis.LSB = data2;
mpeChannels[ci].MPEPluszAxis.changed = true;
mpeChannels[ci].changed = true;
break;
}
} else { // Non MPE+ data
if (status == 0xd) { // Channel Pressure
// std::cout << " We parse channel aftertouch data that is " << data1 << std::endl;
mpeChannels[ci].afterTouch.val = data1;
mpeChannels[ci].afterTouch.changed = true;
mpeChannels[ci].changed = true;
}
if (status == 0xb && data1 == 0x4a) { // CC (oxb) #74 <- we should probably make this assignable if neeed.
// std::cout << " We parse CC 74 data that is " << data1 << std::endl;
mpeChannels[ci].Yaxis.val = data2;
mpeChannels[ci].Yaxis.changed = true;
mpeChannels[ci].changed = true;
}
} // End MPE or MPE+ switch
} // End note processing
if (this->globalMIDIChannel == (channel + 1) ) { // If we're on global midi channel
// std::cout <<"Global channel!" << std::endl;
if (data1 == midiPedalOne.cc) {
// std::cout <<"Pedal One value is " << data2 << std::endl;
midiPedalOne.val = data2;
midiPedalOne.changed = true;
}
}
/*
switch (status) {
case 0xb: // cc
if (MPEPlus) { // Processing MPE+ data
// Note from the Haken Continuum Manual:
// (To avoid the glitches, the synthesizer can do synchronous 14-bit updates with output from the Continuum:
// simply save the least significant data, and do not apply it until the most significant data is received.)
switch (data1) {
case 74: // Y axis
MPEPlusyAxis.MSB = data2;
MPEPlusyAxis.changed = true;
break;
case 106:
MPEPlusyAxis.LSB = data2;
MPEPlusyAxis.changed = true;
break;
case 70: // Z or Pressure
MPEPluszAxis.MSB = data2;
MPEPluszAxis.changed = true;
break;
case 102:
MPEPluszAxis.LSB = data2;
MPEPluszAxis.changed = true;
break;
}
} else { // Non MPE+ data
switch (data1) {
case 0x01: // mod
mod.val = data2;
mod.changed = true;
// std::cout << "mod" << std::endl;
break;
case 0x4a: // CC 74 <- we should probably make this assignable if neeed.
Yaxis.val = data2;
Yaxis.changed = true;
break ;
}
} // End MPE or MPE+ switch
if (data1== 0x40 ) {
pedal = (data2 >= 64);
if (!pedal) {
releaseNote(-1);
}
} // sustain
break;
case 0xe: // pitch wheel, we combine two 7 bit in two bytes into a 14bit msg
{
int nBytes;
// double stamp;
nBytes = msg.size();
// for ( i=0; i<nBytes; i++ )
// std::cout << "Byte " << i << " = " << (int)msg[i] << ", ";
// if ( nBytes > 0 )
// std::cout << "stamp = " << stamp << std::endl;
// We want 2 bytes but variable size may change with platform, maybe we should do a more robust way
uint16_t twoBytes ; // Initialize our final pitchWheel variable.
// we don't need to shift the first byte because it's 7 bit (always starts with 0)
twoBytes = ( (uint16_t)msg[2] << 7) | ( (uint16_t)msg[1] ) ;
// std::cout << sizeof(int) << std::endl;
// std::bitset<8> msgOne(msg[1]);
// std::bitset<8> msgTwo(msg[2]);
// std::bitset<16> x(twoBytes);
//std::cout << "msg[1] and 2 are " << msgOne << " " << msgTwo << " and shifted is " << x << std::endl;
//std::cout << "twoBytes is " << (int)twoBytes << std::endl;
pitchWheel.val = twoBytes;
pitchWheel.changed = true;
}
break;
case 0xd: // channel aftertouch
afterTouch.val = data1;
afterTouch.changed = true;
break;
}
}
// std::cout <<" midi input is on " << Global channel!"
if (this->globalMIDIChannel == (channel + 1) ) {
std::cout <<"Global channel!" << std::endl;
if (data1 == midiPedalOne.cc) {
std::cout <<"Pedal One value is " << data2 << std::endl;
midiPedalOne.val = data2;
midiPedalOne.changed = true;
}
}
*/
}
// MPEMidiWidget stuff
struct QuadBendRangeItem : MenuItem {
QuadMPEToCV *quadmpetocv;
int bendRange ;
void onAction(EventAction &e) override {
// debug("We trigger action with %d", bendRange);
quadmpetocv->bendRange = bendRange;
}
};
struct QuadBendRangeChoice : LedDisplayChoice {
// QuadMPEToCVWidget *quadmpetocvwidget;
QuadMPEToCV *quadmpetocv;
int bendRange ;
void onAction(EventAction &e) override {
#ifdef USE_VST2
Menu *menu = rack::global_ui->ui.gScene->createMenu();
#else
Menu *menu = gScene->createMenu();
#endif // USE_VST2
menu->addChild(construct<MenuLabel>(&MenuLabel::text, "Bend Range"));
std::vector<int> bendRanges = {1,2,3,4,12,24,48,96}; // The bend range we use
for (auto const& bendRangeValue: bendRanges) {
QuadBendRangeItem *item = new QuadBendRangeItem();
item->quadmpetocv = quadmpetocv;
item->text = std::to_string(bendRangeValue);
item->bendRange = bendRangeValue;
menu->addChild(item);
}
// quadmpetocv->bendRange = bendRange;
}
void step() override {
color = nvgRGB(0xff, 0x00, 0x00);
color.a = 0.8f;
text = stringf("%d", quadmpetocv->bendRange);
}
};
struct QuadMidiChannelItem : MenuItem {
QuadMPEToCV *quadmpetocv;
int channel ;
void onAction(EventAction &e) override {
quadmpetocv->baseMIDIChannel = channel;
}
};
struct QuadMidiChannelChoice : LedDisplayChoice {
// QuadMPEToCVWidget *quadmpetocvwidget;
QuadMPEToCV *quadmpetocv;
int channel ;
void onAction(EventAction &e) override {
#ifdef USE_VST2
Menu *menu = rack::global_ui->ui.gScene->createMenu();
#else
Menu *menu = gScene->createMenu();
#endif // USE_VST2
menu->addChild(construct<MenuLabel>(&MenuLabel::text, "Midi channel"));
std::vector<int> bendRanges = {1,2,3,4,12,24,48,96}; // The bend range we use
for (int c=1; c <= 16 ; c++) {
QuadMidiChannelItem *item = new QuadMidiChannelItem();
item->quadmpetocv = quadmpetocv;
item->text = std::to_string(c);
item->channel = c;
menu->addChild(item);
}
}
void step() override {
color = nvgRGB(0xff, 0x00, 0x00);
color.a = 0.8f;
text = std::to_string(quadmpetocv->baseMIDIChannel);
}
};
struct QuadGlobalMidiChannelItem : MenuItem {
QuadMPEToCV *quadmpetocv;
int channel ;
void onAction(EventAction &e) override {
quadmpetocv->globalMIDIChannel = channel;
}
};
struct QuadGlobalMidiChannelChoice : LedDisplayChoice {
// QuadMPEToCVWidget *quadmpetocvwidget;
QuadMPEToCV *quadmpetocv;
int channel ;
void onAction(EventAction &e) override {
#ifdef USE_VST2
Menu *menu = rack::global_ui->ui.gScene->createMenu();
#else
Menu *menu = gScene->createMenu();
#endif // USE_VST2
menu->addChild(construct<MenuLabel>(&MenuLabel::text, "Global Midi channel"));
for (int c=1; c <= 16 ; c++) {
QuadGlobalMidiChannelItem *item = new QuadGlobalMidiChannelItem();
item->quadmpetocv = quadmpetocv;
item->text = std::to_string(c);
item->channel = c;
menu->addChild(item);
}
}
void step() override {
color = nvgRGB(0xff, 0x00, 0x00);
color.a = 0.8f;
text = std::to_string(quadmpetocv->globalMIDIChannel);
}
};
struct QuadMPEModeItem : MenuItem {
QuadMPEToCV *quadmpetocv;
bool MPEPlus ;
void onAction(EventAction &e) override {
quadmpetocv->MPEPlus = MPEPlus;
}
};
struct QuadMPEModeChoice : LedDisplayChoice {
// QuadMPEToCVWidget *quadmpetocvwidget;
QuadMPEToCV *quadmpetocv;
bool MPEPlus ;
void onAction(EventAction &e) override {
#ifdef USE_VST2
Menu *menu = rack::global_ui->ui.gScene->createMenu();
#else
Menu *menu = gScene->createMenu();
#endif // USE_VST2
menu->addChild(construct<MenuLabel>(&MenuLabel::text, "MPE mode"));
// MPE
QuadMPEModeItem *MPE = new QuadMPEModeItem();
MPE->quadmpetocv = quadmpetocv;
MPE->text = "MPE - Standard (ROLI, etc)";
MPE->MPEPlus = false;
menu->addChild(MPE);
// MPE Plus
QuadMPEModeItem *MPEPlus = new QuadMPEModeItem();
MPEPlus->quadmpetocv = quadmpetocv;
MPEPlus->text = "MPE+ - High Res for Haken Continuum";
MPEPlus->MPEPlus = true;
menu->addChild(MPEPlus);
}
void step() override {
// color = nvgRGB(0xff, 0x00, 0x00);
// color.a = 0.8f;
if (quadmpetocv->MPEPlus) {
text = "MPE+";
} else {
text = "MPE";
}
}
};
// We extend the midi to follow similar design
struct QuadMPEMidiWidget : MPEBaseWidget {
LedDisplaySeparator *hSeparators[2];
LedDisplaySeparator *vSeparators[3];
// LedDisplayChoice *ccChoices[4][4];
QuadMPEToCV *quadmpetocv ;
QuadBendRangeChoice *bendRangeChoice ;
QuadMidiChannelChoice *midiChannelChoice ;
QuadGlobalMidiChannelChoice *globalMidiChannelChoice ;
QuadMPEModeChoice *mpeModeChoice ;
QuadMPEMidiWidget() {
}
void initialize(QuadMPEToCV *quadmpetocv) {
this->quadmpetocv = quadmpetocv;
Vec pos = deviceChoice->box.getBottomLeft();
for (int y = 0; y < 2; y++) {
hSeparators[y] = Widget::create<LedDisplaySeparator>(pos);
addChild(hSeparators[y]);
}
midiChannelChoice = Widget::create<QuadMidiChannelChoice>(pos);
midiChannelChoice->quadmpetocv = quadmpetocv ;
addChild(midiChannelChoice);
globalMidiChannelChoice = Widget::create<QuadGlobalMidiChannelChoice>(pos);
globalMidiChannelChoice->quadmpetocv = quadmpetocv ;
addChild(globalMidiChannelChoice);
bendRangeChoice = Widget::create<QuadBendRangeChoice>(pos);
bendRangeChoice->quadmpetocv = quadmpetocv ;
addChild(bendRangeChoice);
mpeModeChoice = Widget::create<QuadMPEModeChoice>(pos);
mpeModeChoice->quadmpetocv = quadmpetocv ;
addChild(mpeModeChoice);
for (int x = 1; x < 3; x++) {
vSeparators[x] = Widget::create<LedDisplaySeparator>(pos);
addChild(vSeparators[x]);
}
for (int x = 1; x < 3; x++) {
vSeparators[x]->box.size.y = midiChannelChoice->box.size.y;
}
}
void step() override {
MPEBaseWidget::step();
midiChannelChoice->box.size.x = box.size.x/4;
midiChannelChoice->box.pos.x = 0;
globalMidiChannelChoice->box.size.x = box.size.x/4;
globalMidiChannelChoice->box.pos.x = box.size.x/4;
bendRangeChoice->box.size.x = box.size.x/4;
bendRangeChoice->box.pos.x = box.size.x/4 * 2 ;
mpeModeChoice->box.size.x = box.size.x/4;
mpeModeChoice->box.pos.x = box.size.x/4 * 3 - 5 ;
for (int y = 0; y < 2; y++) {
hSeparators[y]->box.size.x = box.size.x;
}
for (int x = 1; x < 3; x++) {
vSeparators[x]->box.pos.x = box.size.x / 4 * x;
}
}
};
| 32.827262
| 165
| 0.655248
|
daaef7ef3f307f0a96b9a901ef2491e70e2d7d0d
| 3,906
|
php
|
PHP
|
magento2ce/app/code/Magento/Sales/Block/Order/Items.php
|
downjse/magento2
|
7bebd5c24d613426159638cd5f7b6b927a017fb4
|
[
"MIT"
] | null | null | null |
magento2ce/app/code/Magento/Sales/Block/Order/Items.php
|
downjse/magento2
|
7bebd5c24d613426159638cd5f7b6b927a017fb4
|
[
"MIT"
] | null | null | null |
magento2ce/app/code/Magento/Sales/Block/Order/Items.php
|
downjse/magento2
|
7bebd5c24d613426159638cd5f7b6b927a017fb4
|
[
"MIT"
] | null | null | null |
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Sales order view items block
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace Magento\Sales\Block\Order;
class Items extends \Magento\Sales\Block\Items\AbstractItems
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* Order items per page.
*
* @var int
*/
private $itemsPerPage;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory
*/
private $itemCollectionFactory;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\Item\Collection|null
*/
private $itemCollection;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param array $data
* @param \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory|null $itemCollectionFactory
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = [],
\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollectionFactory = null
) {
$this->_coreRegistry = $registry;
$this->itemCollectionFactory = $itemCollectionFactory ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory::class);
parent::__construct($context, $data);
}
/**
* Init pager block and item collection with page size and current page number
*
* @return $this
*/
protected function _prepareLayout()
{
$this->itemsPerPage = $this->_scopeConfig->getValue('sales/orders/items_per_page');
$this->itemCollection = $this->itemCollectionFactory->create();
$this->itemCollection->setOrderFilter($this->getOrder());
$this->itemCollection->filterByParent(null);
/** @var \Magento\Theme\Block\Html\Pager $pagerBlock */
$pagerBlock = $this->getChildBlock('sales_order_item_pager');
if ($pagerBlock) {
$pagerBlock->setLimit($this->itemsPerPage);
//here pager updates collection parameters
$pagerBlock->setCollection($this->itemCollection);
$pagerBlock->setAvailableLimit([$this->itemsPerPage]);
$pagerBlock->setShowAmounts($this->isPagerDisplayed());
}
return parent::_prepareLayout();
}
/**
* Determine if the pager should be displayed for order items list
* To be called from templates(after _prepareLayout())
*
* @return bool
*/
public function isPagerDisplayed()
{
$pagerBlock = $this->getChildBlock('sales_order_item_pager');
return $pagerBlock && ($this->itemCollection->getSize() > $this->itemsPerPage);
}
/**
* Get visible items for current page.
* To be called from templates(after _prepareLayout())
*
* @return \Magento\Framework\DataObject[]
*/
public function getItems()
{
return $this->itemCollection->getItems();
}
/**
* Get pager HTML according to our requirements
* To be called from templates(after _prepareLayout())
*
* @return string HTML output
*/
public function getPagerHtml()
{
/** @var \Magento\Theme\Block\Html\Pager $pagerBlock */
$pagerBlock = $this->getChildBlock('sales_order_item_pager');
return $pagerBlock ? $pagerBlock->toHtml() : '';
}
/**
* Retrieve current order model instance
*
* @return \Magento\Sales\Model\Order
*/
public function getOrder()
{
return $this->_coreRegistry->registry('current_order');
}
}
| 30.046154
| 116
| 0.636457
|
e26d2f4814f8400cddd48edd4d557ae5c4aa2336
| 341
|
py
|
Python
|
source/python/SortingWithoutDuplicates.py
|
JoHyukJun/algorithm-analysis
|
3eda22ce0eeb52490702206d73c04cff1eb3e72d
|
[
"Apache-2.0"
] | null | null | null |
source/python/SortingWithoutDuplicates.py
|
JoHyukJun/algorithm-analysis
|
3eda22ce0eeb52490702206d73c04cff1eb3e72d
|
[
"Apache-2.0"
] | null | null | null |
source/python/SortingWithoutDuplicates.py
|
JoHyukJun/algorithm-analysis
|
3eda22ce0eeb52490702206d73c04cff1eb3e72d
|
[
"Apache-2.0"
] | null | null | null |
'''
main.py
Created by Jo Hyuk Jun on 2020
Copyright © 2020 Jo Hyuk Jun. All rights reserved.
'''
import sys
n = int(sys.stdin.readline())
coordinate = (list(map(int, sys.stdin.readline().rstrip().split(' '))))
coordinate = sorted(list(set(coordinate)))
for i in range(len(coordinate)):
print(coordinate[i], end=' ')
| 17.05
| 71
| 0.648094
|
ed5ed03cb00e46594e59b69a8155eba56d12bcd9
| 439
|
go
|
Go
|
Lesson3/concise-switch.go
|
huegli/GetProgramingWithGo
|
fc704c2068521afc9a781f8c306b37335d8d11a9
|
[
"MIT"
] | null | null | null |
Lesson3/concise-switch.go
|
huegli/GetProgramingWithGo
|
fc704c2068521afc9a781f8c306b37335d8d11a9
|
[
"MIT"
] | null | null | null |
Lesson3/concise-switch.go
|
huegli/GetProgramingWithGo
|
fc704c2068521afc9a781f8c306b37335d8d11a9
|
[
"MIT"
] | null | null | null |
package main
import "fmt"
func main() {
fmt.Println("There is a cavern entrance here and a path to the east.")
var command = "go inside"
switch command {
case "go east":
fmt.Println("You head further up the mountain.")
case "enter cave", "go inside":
fmt.Println("You find yourself in a dimly lit cavern.")
case "read sign":
fmt.Println("The sign reads 'No Minors'.")
default:
fmt.Println("Didn't quite get that.")
}
}
| 20.904762
| 71
| 0.678815
|
c94b4cd22b9b42b75c30042b3757660e88490302
| 646
|
ts
|
TypeScript
|
src/tweet/rocketman.ts
|
UpsidePotential/SlickBot
|
ba917f88e358944b03c081f3bc1c76c8cc555733
|
[
"WTFPL"
] | 4
|
2020-08-17T13:29:52.000Z
|
2020-08-20T00:30:47.000Z
|
src/tweet/rocketman.ts
|
UpsidePotential/SlickBot
|
ba917f88e358944b03c081f3bc1c76c8cc555733
|
[
"WTFPL"
] | 21
|
2020-08-17T13:51:18.000Z
|
2021-03-01T21:49:13.000Z
|
src/tweet/rocketman.ts
|
SlickyCorp-Heavy-Manufacturing/SlickBot
|
ae5163f53f56b45863cd58add70e0ac393e14e02
|
[
"WTFPL"
] | 8
|
2020-08-17T13:30:05.000Z
|
2020-08-20T00:32:27.000Z
|
import { Message } from 'discord.js';
import { ICommand } from '../icommand';
import { TweetGen } from './tweet-generator';
const commandString = '!elon';
export const RocketManCommand: ICommand = {
name: commandString,
helpDescription: 'Bot will respond with a tweet from the rocket man',
showInHelp: true,
trigger: (msg: Message) => msg.content.startsWith(commandString),
command: async (msg: Message) => {
const text = msg.cleanContent.substring(commandString.length);
await TweetGen.tweet(msg, {
nickname: 'elonmusk',
text,
retweets: 420,
retweetsWithComments: 0,
likes: 69,
});
},
};
| 26.916667
| 71
| 0.667183
|
dd58ccae1cd1d4aafbbec9ccee168ac8e53de89c
| 5,769
|
java
|
Java
|
src/dateCalculator/AniversaryList.java
|
kejsardamberg/AniversaryCalculator
|
4fc0b664da07b689e9dbc32a17cee184abd2e8da
|
[
"Apache-2.0"
] | null | null | null |
src/dateCalculator/AniversaryList.java
|
kejsardamberg/AniversaryCalculator
|
4fc0b664da07b689e9dbc32a17cee184abd2e8da
|
[
"Apache-2.0"
] | null | null | null |
src/dateCalculator/AniversaryList.java
|
kejsardamberg/AniversaryCalculator
|
4fc0b664da07b689e9dbc32a17cee184abd2e8da
|
[
"Apache-2.0"
] | null | null | null |
package dateCalculator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class AniversaryList
{
public DateOfImportance dateOfImportance;
public boolean includeEventsInThePast = false;
public boolean everyThousandDays = true;
public boolean everyYear = true;
public boolean specialDays = true;
public boolean includeHalfYears = true;
public List<AniversaryDay> aniversaries = new ArrayList<AniversaryDay>();
public AniversaryList (DateOfImportance dateOfImportance)
{
this.dateOfImportance = dateOfImportance;
CreateAniversaryList();
}
public AniversaryList(){
}
public void CreateAniversaryList()
{
// PopulateListByDayDifference(100, 2);
if (everyThousandDays) { PopulateListByDayDifference(1000, 20); }
if (specialDays) {
PopulateListBySpecialDays();
PopulateListByMonthDifference(100, 20);
PopulateListByMonthDifference(42, 4);
}
if (everyYear) { PopulateListByYearDifference(1, 20); }
if (includeHalfYears) {PopulateListByHalfYearDifference(20);}
if (!includeEventsInThePast) { this.RemoveDatesInThePast(); }
this.SortListByDate();
// PopulateListByYearDifference(10, 50);
}
private void PopulateListByHalfYearDifference(int numberOfYearsForward){
Date today = new Date();
Date aniversaryDate = MonthAdder(this.dateOfImportance.date, 6);
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, aniversaryDate, "Half a year since occasion of " + this.dateOfImportance.name + "."));
int numberOfYears = 1;
while (aniversaryDate.before(YearAdder(today, numberOfYearsForward)))
{
aniversaryDate = YearAdder(aniversaryDate, 1);
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, aniversaryDate, numberOfYears + " and a half years since occasion of " + this.dateOfImportance.name + "."));
numberOfYears++;
}
}
private void PopulateListBySpecialDays(){
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, DayAdder(this.dateOfImportance.date, 42), "42 days since occasion " + this.dateOfImportance.name + "."));
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, DayAdder(this.dateOfImportance.date, 666), "666 days since occasion " + this.dateOfImportance.name + "."));
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, DayAdder(this.dateOfImportance.date, 6666), "6666 days since occasion of " + this.dateOfImportance.name + "."));
}
private void PopulateListByDayDifference(int dayIntervals, int numberOfYearsForward){
Date today = new Date();
int days = dayIntervals;
Date aniversaryDate = this.dateOfImportance.date;
while (aniversaryDate.before(YearAdder(today, numberOfYearsForward)))
{
aniversaryDate = DayAdder(this.dateOfImportance.date, days);
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, aniversaryDate, days + " days since occasion of " + this.dateOfImportance.name + "."));
days = days + dayIntervals;
}
}
private void PopulateListByMonthDifference(int monthIntervals, int numberOfYearsForward){
Date today = new Date();
int months = monthIntervals;
Date aniversaryDate = this.dateOfImportance.date;
while (aniversaryDate.before(YearAdder(today, numberOfYearsForward)))
{
aniversaryDate = MonthAdder(this.dateOfImportance.date, months);
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, aniversaryDate, months + " months since occasion of " + this.dateOfImportance.name + "."));
months += monthIntervals;
}
}
private void PopulateListByYearDifference(int yearIntervals, int numberOfYearsForward){
Date today = new Date();
int years = yearIntervals;
Date aniversaryDate = this.dateOfImportance.date;
while (aniversaryDate.before(YearAdder(today, numberOfYearsForward)))
{
aniversaryDate = YearAdder(this.dateOfImportance.date, years);
this.aniversaries.add(new AniversaryDay(this.dateOfImportance, aniversaryDate, years + " years since occasion of " + this.dateOfImportance.name + "."));
years += yearIntervals;
}
}
private Date YearAdder(Date date, int numberOfYears){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, numberOfYears);
return new Date(c.getTimeInMillis());
}
private Date MonthAdder(Date date, int numberOfMonths){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, numberOfMonths);
return new Date(c.getTimeInMillis());
}
private Date DayAdder(Date date, int numberOfDays){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, numberOfDays);
return new Date(c.getTimeInMillis());
}
private void SortListByDate(){
Collections.sort(this.aniversaries);
}
private void RemoveDatesInThePast(){
//AniversaryList cleanedList = new AniversaryList(this.dateOfImportance);
Date today = new Date();
for(int i = 0; i < this.aniversaries.size(); i++){
if (year(this.aniversaries.get(i).date) < year(today)){
this.aniversaries.remove(i);
i = i - 1;
}
}
}
private static int year(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public void toIcsFiles(String folderForFiles){
for(AniversaryDay day : this.aniversaries){
day.toIcsFile(folderForFiles);
}
}
public void PrintList(){
RemoveDatesInThePast();
SortListByDate();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
for(AniversaryDay day : this.aniversaries){
System.out.println("The date " + dateFormat.format(day.date) + " should be honored because it's " + day.reason + " (" + dateFormat.format(this.dateOfImportance.date) + ")");
}
}
}
| 35.611111
| 177
| 0.746577
|
b283f1ac689bb2cf922b69238b71e8355413b63e
| 1,388
|
css
|
CSS
|
css/register.css
|
douglasCajueiro/PI-SpaceTrip
|
6524aed1bf7a69a2b8a11daef003c2a580c8af9a
|
[
"MIT"
] | null | null | null |
css/register.css
|
douglasCajueiro/PI-SpaceTrip
|
6524aed1bf7a69a2b8a11daef003c2a580c8af9a
|
[
"MIT"
] | 4
|
2020-10-11T19:15:54.000Z
|
2020-10-13T23:23:25.000Z
|
css/register.css
|
douglasCajueiro/PI-SpaceTrip
|
6524aed1bf7a69a2b8a11daef003c2a580c8af9a
|
[
"MIT"
] | null | null | null |
@import url('https://fonts.googleapis.com/css2?family=Gugi&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
font-family: 'swap', sans-serif;
overflow: hidden;
}
body {
background-image: url("../imagens/index/fundo.jpg");
background-size: cover;
background-repeat: no-repeat;
height: 100vh;
}
.wrapper {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
padding: 0 20px;
}
.register-form {
max-width: 400px;
margin: 0 auto;
background: rgba(0, 0, 0, 0.8);
padding: 30px;
border-radius: 2%;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
a {
text-align: center;
color: white;
}
.input-fields{
display: flex;
flex-direction: column;
margin-right: 4%;
}
.input-fields .input,
.msg textarea {
margin: 10px 0;
background: transparent;
border: 0;
border-bottom: 2px solid white;
padding: 10px;
color: white;
width: 100%;
}
.msg textarea{
height: 212px;
}
::-webkit-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
::-moz-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
::-ms-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
| 18.506667
| 75
| 0.571326
|
8c366b5cd4d242e37b11cb4412e34373f22356cc
| 1,863
|
rb
|
Ruby
|
apache_kafka/recipes/configure.rb
|
albertcbrown/cookbooks
|
abea254a529dad892e369b2aaad56723996c59b9
|
[
"Apache-2.0"
] | null | null | null |
apache_kafka/recipes/configure.rb
|
albertcbrown/cookbooks
|
abea254a529dad892e369b2aaad56723996c59b9
|
[
"Apache-2.0"
] | null | null | null |
apache_kafka/recipes/configure.rb
|
albertcbrown/cookbooks
|
abea254a529dad892e369b2aaad56723996c59b9
|
[
"Apache-2.0"
] | null | null | null |
# encoding: UTF-8
# Cookbook Name:: apache_kafka
# Recipe:: configure
#
[
node["apache_kafka"]["config_dir"],
node["apache_kafka"]["bin_dir"],
node["apache_kafka"]["data_dir"],
node["apache_kafka"]["log_dir"]
].each do |dir|
directory dir do
recursive true
owner node["apache_kafka"]["user"]
end
end
%w{ kafka-server-start.sh kafka-run-class.sh kafka-topics.sh }.each do |bin|
template ::File.join(node["apache_kafka"]["bin_dir"], bin) do
source "bin/#{bin}.erb"
owner "kafka"
action :create
mode "0755"
variables(
:config_dir => node["apache_kafka"]["config_dir"],
:bin_dir => node["apache_kafka"]["bin_dir"]
)
notifies :restart, "service[kafka]", :delayed
end
end
broker_id = node["apache_kafka"]["broker.id"]
broker_id = 0 if broker_id.nil?
zookeeper_connect = node["apache_kafka"]["zookeeper.connect"]
zookeeper_connect = "localhost:2181" if zookeeper_connect.nil?
template ::File.join(node["apache_kafka"]["config_dir"],
node["apache_kafka"]["conf"]["server"]["file"]) do
source "properties/server.properties.erb"
owner "kafka"
action :create
mode "0644"
variables(
:broker_id => broker_id,
:port => node["apache_kafka"]["port"],
:zookeeper_connect => zookeeper_connect,
:log_dirs => node["apache_kafka"]["data_dir"],
:entries => node["apache_kafka"]["conf"]["server"]["entries"]
)
notifies :restart, "service[kafka]", :delayed
end
template ::File.join(node["apache_kafka"]["config_dir"],
node["apache_kafka"]["conf"]["log4j"]["file"]) do
source "properties/log4j.properties.erb"
owner "kafka"
action :create
mode "0644"
variables(
:log_dir => node["apache_kafka"]["log_dir"],
:entries => node["apache_kafka"]["conf"]["log4j"]["entries"]
)
notifies :restart, "service[kafka]", :delayed
end
| 28.227273
| 76
| 0.653247
|
2244896e44c1c285ddc72fc5b411b05b1a54e647
| 342
|
cs
|
C#
|
Net45/SuperSocketClient1.6/SuperSocket.ClientEngine-master/Core/SecurityOption.Silverlight.cs
|
AelousDing/Mature.WPF
|
7b01d84f34803b037707098c7ceee87df0cb963d
|
[
"MIT"
] | 3
|
2021-09-27T01:37:44.000Z
|
2022-02-20T12:41:21.000Z
|
Libraries/WebSocket4Net/SuperSocket.ClientEngine/Core/SecurityOption.Silverlight.cs
|
WamWooWam/Unicord.Legacy
|
dd7dd8d591217fffa6e7e2bc85102848d6cdf22b
|
[
"MIT"
] | null | null | null |
Libraries/WebSocket4Net/SuperSocket.ClientEngine/Core/SecurityOption.Silverlight.cs
|
WamWooWam/Unicord.Legacy
|
dd7dd8d591217fffa6e7e2bc85102848d6cdf22b
|
[
"MIT"
] | 1
|
2021-06-16T07:28:47.000Z
|
2021-06-16T07:28:47.000Z
|
using System;
using System.Collections.Generic;
namespace SuperSocket.ClientEngine
{
/// <summary>
/// Security options
/// </summary>
public class SecurityOption
{
/// <summary>
/// The SslProtocols want to be enabled
/// </summary>
public bool EnabledSslProtocols { get; set; }
}
}
| 20.117647
| 53
| 0.599415
|
fd673ef66f87727dcac4c4cd802ac36140d28f7f
| 2,253
|
css
|
CSS
|
regenesis/static/css/style.css
|
crijke/regenesis
|
e53a0c6302aa458ff9ae95f573d5594351e5434c
|
[
"MIT"
] | 16
|
2015-04-09T14:40:53.000Z
|
2021-07-13T15:03:35.000Z
|
regenesis/static/css/style.css
|
crijke/regenesis
|
e53a0c6302aa458ff9ae95f573d5594351e5434c
|
[
"MIT"
] | 1
|
2018-06-25T07:51:18.000Z
|
2018-06-25T07:51:18.000Z
|
regenesis/static/css/style.css
|
crijke/regenesis
|
e53a0c6302aa458ff9ae95f573d5594351e5434c
|
[
"MIT"
] | 3
|
2015-12-20T18:24:21.000Z
|
2018-06-24T16:57:25.000Z
|
/*
* Palette:
*
* Purple: #46336B
* Red: #BA4B37
* Yellow: #F5DE14
* Green: #4C9923
* Blue: #265475 (Dark: #08c)
* #0F81FE
*/
html, body {
background-color: #fff;
color: #222;
line-height: 1.4em;
}
body, h1, h2, h3, h4, h5, h6 {
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
@media (min-width: 1200px) {
.container {
max-width: 940px;
}
}
/*
a {
color: #08c;
}
a:hover, a:active {
color: #08c;
}
*/
a {
color: #BA4B37;
}
a:hover {
text-decoration: none;
}
#airlock ul {
list-style-type: square;
padding: 0;
}
#airlock li, .list-item {
margin: 0 0 10px;
}
h1, h2, h3, h4, h5, h6 {
font-weight: normal;
line-height: 1.8em;
margin-bottom: 0.6em;
}
.well.mono {
font-family: monospace;
font-size: 0.8em;
padding: 0.3em;
word-break: break-all;
}
/* Header Area */
.navbar .navbar-brand {
/*font-weight: bold;*/
}
/* Footer area */
footer {
padding: 5em 0 5em 0;
color: #666;
text-align: right;
}
/* Sidebar */
#sidebar {
font-size: 0.9em;
color: #666;
overflow: hidden;
}
#sidebar h3 {
font-size: 1.2em;
margin: 0.5em 0 0.7em 0;
text-transform: lowercase;
}
#sidebar h3.first {
margin-top: 0em;
}
#sidebar {
word-wrap: break-word;
-moz-hyphens:auto;
-webkit-hyphens:auto;
-o-hyphens:auto;
hyphens:auto;
}
#sidebar ul {
list-style-type: none;
margin: 0;
}
#sidebar ul li {
margin: 0 0 1em 0;
}
/* Front page listings */
.content .section {
margin: -0.4em 0 2em 0;
}
.content h2, h2.page-title {
margin: 0 0 0.5em 0;
text-transform: uppercase;
font-size: 1.4em;
}
.content h3 {
margin: 0 0 0.5em 0;
text-transform: uppercase;
font-size: 1.2em;
}
.content .bullets {
margin-left: 2em;
}
.content .entries {
list-style-type: none;
margin: 0;
}
.content .entries li {
text-indent: -3em;
padding-left: 3em;
}
.content .entries .date {
color: #666;
}
.content .entries .title {
font-weight: 600;
}
/* Post page */
.post-date {
color: #666;
}
.related-posts {
}
#post ul {
padding: 0 0 0 2em;
}
.captioned {
margin: 1em 0 1em 0;
}
.captioned.pull-right {
margin: 0em 0em 1em 1em;
}
.captioned .caption {
font-size: 0.9em;
margin: 0.5em 0 0 0;
color: #666;
}
| 11.795812
| 39
| 0.592099
|
f4499837ca895933f55ed7dc4990c1048ad29964
| 1,261
|
cs
|
C#
|
src/HeavenlyWind.Base/Preference.Data.cs
|
ly931003/ing
|
440e191cd8d4d532435e496d19dff64099e92bdc
|
[
"MIT"
] | null | null | null |
src/HeavenlyWind.Base/Preference.Data.cs
|
ly931003/ing
|
440e191cd8d4d532435e496d19dff64099e92bdc
|
[
"MIT"
] | null | null | null |
src/HeavenlyWind.Base/Preference.Data.cs
|
ly931003/ing
|
440e191cd8d4d532435e496d19dff64099e92bdc
|
[
"MIT"
] | null | null | null |
using Sakuno.KanColle.Amatsukaze.Models.Preferences;
namespace Sakuno.KanColle.Amatsukaze
{
partial class Preference
{
public Property<string> Language { get; } = new Property<string>("main.language", StringResources.Instance.GetDefaultLanguage().Directory);
public Property<string> ExtraResourceLanguage { get; private set; } = new Property<string>("main.language_extra", StringResources.Instance.GetDefaultLanguage().Directory);
public Property<bool> FirstRun { get; } = new Property<bool>("main.first_run", true);
public UpdatePreference Update { get; } = new UpdatePreference();
public NetworkPreference Network { get; } = new NetworkPreference();
public UserInterfacePreference UI { get; } = new UserInterfacePreference();
public GamePreference Game { get; } = new GamePreference();
public CachePreference Cache { get; } = new CachePreference();
public BrowserPreference Browser { get; } = new BrowserPreference();
public NotificationPreference Notification { get; } = new NotificationPreference();
public WindowsPreference Windows { get; } = new WindowsPreference();
public OtherPreference Other { get; } = new OtherPreference();
}
}
| 39.40625
| 179
| 0.702617
|
822c9025a3788ba6ca316080bf7b0910bf4acf88
| 1,166
|
swift
|
Swift
|
TMDSample/TMDSample/Networking/Services/ConfigurationService.swift
|
arslanFaisal/TMDMovies
|
3138d942532573143d11b28261f3fa2f955c094a
|
[
"MIT"
] | null | null | null |
TMDSample/TMDSample/Networking/Services/ConfigurationService.swift
|
arslanFaisal/TMDMovies
|
3138d942532573143d11b28261f3fa2f955c094a
|
[
"MIT"
] | null | null | null |
TMDSample/TMDSample/Networking/Services/ConfigurationService.swift
|
arslanFaisal/TMDMovies
|
3138d942532573143d11b28261f3fa2f955c094a
|
[
"MIT"
] | null | null | null |
//
// ConfigurationService.swift
// TMDSample
//
// Created by Arslan Faisal on 23/10/2019.
// Copyright © 2019 Arslan Faisal. All rights reserved.
//
import Foundation
typealias ConfigurationCompletionBlock = (_ configuration: configuration?,_ error: String?)-> ()
struct ConfigurationService {
var networkHandler: NetworkHandler
init(_ networkHandle: NetworkHandler) {
networkHandler = networkHandle
}
}
extension ConfigurationService {
func fetchConfiguration(completion: @escaping ConfigurationCompletionBlock) {
networkHandler.fetchData(TMDApi.configuration, completion: {(data, error) in
guard let data = data else {
completion(nil,error)
return
}
do {
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let apiResponse = try jsonDecoder.decode(configurationApiResponse.self, from: data)
completion(apiResponse.images, nil)
} catch {
completion(nil, NetworkResponse.unableToDecode.rawValue)
}
})
}
}
| 31.513514
| 99
| 0.644082
|
eb1b37eba68d8fab7e3927636923e140f25632ef
| 127
|
css
|
CSS
|
EmyTestGame/Tool/LogStyle.css
|
TheJemy191/EmyGameEngine
|
cbefe9bc8e59533e4de96623a5916835846af8cd
|
[
"MIT"
] | null | null | null |
EmyTestGame/Tool/LogStyle.css
|
TheJemy191/EmyGameEngine
|
cbefe9bc8e59533e4de96623a5916835846af8cd
|
[
"MIT"
] | null | null | null |
EmyTestGame/Tool/LogStyle.css
|
TheJemy191/EmyGameEngine
|
cbefe9bc8e59533e4de96623a5916835846af8cd
|
[
"MIT"
] | 1
|
2019-09-03T16:49:50.000Z
|
2019-09-03T16:49:50.000Z
|
.Message
{
color: skyblue;
}
.Warning
{
color: yellow;
}
.Error
{
color: orange;
}
.Fatal_Error
{
color: red;
}
| 7.9375
| 19
| 0.566929
|
d075e389e5d1cce583be41b567b3f6b92397a942
| 6,831
|
cc
|
C++
|
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
|
Nik-Menendez/L1Trigger
|
5336631cc0a517495869279ed7d3a4cac8d4e5e5
|
[
"Apache-2.0"
] | 3
|
2018-08-24T19:10:26.000Z
|
2019-02-19T11:45:32.000Z
|
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
|
Nik-Menendez/L1Trigger
|
5336631cc0a517495869279ed7d3a4cac8d4e5e5
|
[
"Apache-2.0"
] | 3
|
2018-08-23T13:40:24.000Z
|
2019-12-05T21:16:03.000Z
|
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
|
Nik-Menendez/L1Trigger
|
5336631cc0a517495869279ed7d3a4cac8d4e5e5
|
[
"Apache-2.0"
] | 5
|
2018-08-21T16:37:52.000Z
|
2020-01-09T13:33:17.000Z
|
// -*- C++ -*-
//
// Package: CastorDbProducer
// Class: CastorDbProducer
//
/**\class CastorDbProducer CastorDbProducer.h CalibFormats/CastorDbProducer/interface/CastorDbProducer.h
Description: <one line class summary>
Implementation:
<Notes on implementation>
*/
//
// Original Author: Fedor Ratnikov
// Created: Tue Aug 9 19:10:10 CDT 2005
// Adapted for CASTOR by L. Mundim
//
//
// system include files
#include <iostream>
#include <fstream>
#include "FWCore/Framework/interface/ESHandle.h"
#include "CalibCalorimetry/CastorCalib/interface/CastorDbASCIIIO.h"
#include "CalibFormats/CastorObjects/interface/CastorDbService.h"
#include "CalibFormats/CastorObjects/interface/CastorDbRecord.h"
#include "CondFormats/CastorObjects/interface/AllObjects.h"
#include "CastorDbProducer.h"
CastorDbProducer::CastorDbProducer(const edm::ParameterSet& fConfig)
: ESProducer(), mDumpRequest(), mDumpStream(nullptr) {
//the following line is needed to tell the framework what
// data is being produced
setWhatProduced(this);
//now do what ever other initialization is needed
mDumpRequest = fConfig.getUntrackedParameter<std::vector<std::string> >("dump", std::vector<std::string>());
if (!mDumpRequest.empty()) {
std::string otputFile = fConfig.getUntrackedParameter<std::string>("file", "");
mDumpStream = otputFile.empty() ? &std::cout : new std::ofstream(otputFile.c_str());
}
}
CastorDbProducer::~CastorDbProducer() {
// do anything here that needs to be done at desctruction time
// (e.g. close files, deallocate resources etc.)
if (mDumpStream != &std::cout)
delete mDumpStream;
}
//
// member functions
//
// ------------ method called to produce the data ------------
std::shared_ptr<CastorDbService> CastorDbProducer::produce(const CastorDbRecord& record) {
auto host = holder_.makeOrGet([]() { return new HostType; });
bool needBuildCalibrations = false;
bool needBuildCalibWidths = false;
host->ifRecordChanges<CastorElectronicsMapRcd>(
record, [this, h = host.get()](auto const& rec) { setupElectronicsMap(rec, h); });
host->ifRecordChanges<CastorChannelQualityRcd>(
record, [this, h = host.get()](auto const& rec) { setupChannelQuality(rec, h); });
host->ifRecordChanges<CastorGainWidthsRcd>(record, [this, h = host.get(), &needBuildCalibWidths](auto const& rec) {
setupGainWidths(rec, h);
needBuildCalibWidths = true;
});
host->ifRecordChanges<CastorQIEDataRcd>(
record, [this, h = host.get(), &needBuildCalibrations, &needBuildCalibWidths](auto const& rec) {
setupQIEData(rec, h);
needBuildCalibrations = true;
needBuildCalibWidths = true;
});
host->ifRecordChanges<CastorPedestalWidthsRcd>(record,
[this, h = host.get(), &needBuildCalibWidths](auto const& rec) {
setupPedestalWidths(rec, h);
needBuildCalibWidths = true;
});
host->ifRecordChanges<CastorGainsRcd>(record, [this, h = host.get(), &needBuildCalibrations](auto const& rec) {
setupGains(rec, h);
needBuildCalibrations = true;
});
host->ifRecordChanges<CastorPedestalsRcd>(record, [this, h = host.get(), &needBuildCalibrations](auto const& rec) {
setupPedestals(rec, h);
needBuildCalibrations = true;
});
if (needBuildCalibWidths) {
host->buildCalibWidths();
}
if (needBuildCalibrations) {
host->buildCalibrations();
}
return host; // automatically converts to std::shared_ptr<CastorDbService>
}
void CastorDbProducer::setupPedestals(const CastorPedestalsRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorPedestals> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("Pedestals")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR Pedestals set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupPedestalWidths(const CastorPedestalWidthsRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorPedestalWidths> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("PedestalWidths")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR Pedestals set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupGains(const CastorGainsRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorGains> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("Gains")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR Gains set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupGainWidths(const CastorGainWidthsRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorGainWidths> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("GainWidths")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR GainWidths set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupQIEData(const CastorQIEDataRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorQIEData> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("QIEData")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR QIEData set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupChannelQuality(const CastorChannelQualityRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorChannelQuality> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("ChannelQuality")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR ChannelQuality set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
void CastorDbProducer::setupElectronicsMap(const CastorElectronicsMapRcd& fRecord, CastorDbService* service) {
edm::ESHandle<CastorElectronicsMap> item;
fRecord.get(item);
service->setData(item.product());
if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("ElectronicsMap")) != mDumpRequest.end()) {
*mDumpStream << "New HCAL/CASTOR Electronics Map set" << std::endl;
CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product()));
}
}
| 38.8125
| 117
| 0.693456
|
2c6c5166c533f27f5d4191386ad1210f82de7b26
| 777
|
py
|
Python
|
stocks_api/views/company.py
|
IndigoShock/stocks_api
|
8d0b1fea8fc9637d9580e0f69d9a6585c04472d8
|
[
"MIT"
] | null | null | null |
stocks_api/views/company.py
|
IndigoShock/stocks_api
|
8d0b1fea8fc9637d9580e0f69d9a6585c04472d8
|
[
"MIT"
] | null | null | null |
stocks_api/views/company.py
|
IndigoShock/stocks_api
|
8d0b1fea8fc9637d9580e0f69d9a6585c04472d8
|
[
"MIT"
] | null | null | null |
from pyramid_restful.viewsets import APIViewSet
from pyramid.response import Response
class CompanyAPIViewset(APIViewSet):
def retrieve(self, request, id=None):
"""this will retrieve the company's API view. And populate into the
database. At the moment, this will show whether the user correctly
typed in the 4 letter symbol and retrieved information.
"""
# http :6543/api/v1/company/{id}/
# Use the 'id' to lookup that resource in the dB,
# Formulate a response and send it back to the client
return Response(
json={'message': 'Provided a single resource'},
status=200
)
# # Example
# def list(self, request):
# # http :6543/api/v1/company/
# pass
| 32.375
| 75
| 0.634492
|
cdc9fbae9988ffcd00cdf7a880753597c1eb7372
| 11,488
|
cs
|
C#
|
src/csharp/Intel/Generator/TypeIds.cs
|
q60/iced
|
200439b3b30527102313d92643e3c6ab8a81e1c1
|
[
"MIT"
] | 2
|
2022-01-02T16:16:58.000Z
|
2022-01-09T09:39:08.000Z
|
src/csharp/Intel/Generator/TypeIds.cs
|
q60/iced
|
200439b3b30527102313d92643e3c6ab8a81e1c1
|
[
"MIT"
] | null | null | null |
src/csharp/Intel/Generator/TypeIds.cs
|
q60/iced
|
200439b3b30527102313d92643e3c6ab8a81e1c1
|
[
"MIT"
] | null | null | null |
// SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
namespace Generator {
static class TypeIds {
public static readonly TypeId OrigCodeValues = new(nameof(OrigCodeValues));
public static readonly TypeId RemovedCodeValues = new(nameof(RemovedCodeValues));
public static readonly TypeId InstructionDefs = new(nameof(InstructionDefs));
public static readonly TypeId EncoderTypes = new(nameof(EncoderTypes));
public static readonly TypeId InstrInfoTypes = new(nameof(InstrInfoTypes));
public static readonly TypeId GasCtorInfos = new(nameof(GasCtorInfos));
public static readonly TypeId IntelCtorInfos = new(nameof(IntelCtorInfos));
public static readonly TypeId MasmCtorInfos = new(nameof(MasmCtorInfos));
public static readonly TypeId NasmCtorInfos = new(nameof(NasmCtorInfos));
public static readonly TypeId FastFmtTblInfos = new(nameof(FastFmtTblInfos));
public static readonly TypeId MemorySizeDefs = new(nameof(MemorySizeDefs));
public static readonly TypeId RegisterDefs = new(nameof(RegisterDefs));
public static readonly TypeId DecoderTables = new(nameof(DecoderTables));
public static readonly TypeId TupleTypeTable = new(nameof(TupleTypeTable));
public static readonly TypeId OpCodeOperandKindDefs = new(nameof(OpCodeOperandKindDefs));
public static readonly TypeId IcedConstants = new(nameof(IcedConstants));
public static readonly TypeId DecoderTestParserConstants = new(nameof(DecoderTestParserConstants));
public static readonly TypeId DecoderConstants = new(nameof(DecoderConstants));
public static readonly TypeId ExportedPythonTypes = new(nameof(ExportedPythonTypes));
public static readonly TypeId Code = new(nameof(Code));
public static readonly TypeId CodeSize = new(nameof(CodeSize));
public static readonly TypeId CpuidFeature = new(nameof(CpuidFeature));
public static readonly TypeId CpuidFeatureInternal = new(nameof(CpuidFeatureInternal));
public static readonly TypeId DecoderError = new(nameof(DecoderError));
public static readonly TypeId DecoderOptions = new(nameof(DecoderOptions));
public static readonly TypeId DecoderTestOptions = new(nameof(DecoderTestOptions));
public static readonly TypeId EvexOpCodeHandlerKind = new(nameof(EvexOpCodeHandlerKind));
public static readonly TypeId HandlerFlags = new(nameof(HandlerFlags));
public static readonly TypeId LegacyHandlerFlags = new(nameof(LegacyHandlerFlags));
public static readonly TypeId MemorySize = new(nameof(MemorySize));
public static readonly TypeId BroadcastToKind = new(nameof(BroadcastToKind));
public static readonly TypeId FastMemoryKeywords = new(nameof(FastMemoryKeywords));
public static readonly TypeId IntelMemoryKeywords = new(nameof(IntelMemoryKeywords));
public static readonly TypeId MasmMemoryKeywords = new(nameof(MasmMemoryKeywords));
public static readonly TypeId NasmMemoryKeywords = new(nameof(NasmMemoryKeywords));
public static readonly TypeId OpCodeHandlerKind = new(nameof(OpCodeHandlerKind));
public static readonly TypeId PseudoOpsKind = new(nameof(PseudoOpsKind));
public static readonly TypeId Register = new(nameof(Register));
public static readonly TypeId RegisterKind = new(nameof(RegisterKind));
public static readonly TypeId RegisterClass = new(nameof(RegisterClass));
public static readonly TypeId SerializedDataKind = new(nameof(SerializedDataKind));
public static readonly TypeId TupleType = new(nameof(TupleType));
public static readonly TypeId VexOpCodeHandlerKind = new(nameof(VexOpCodeHandlerKind));
public static readonly TypeId Mnemonic = new(nameof(Mnemonic));
public static readonly TypeId GasCtorKind = new(nameof(GasCtorKind));
public static readonly TypeId IntelCtorKind = new(nameof(IntelCtorKind));
public static readonly TypeId MasmCtorKind = new(nameof(MasmCtorKind));
public static readonly TypeId NasmCtorKind = new(nameof(NasmCtorKind));
public static readonly TypeId GasSizeOverride = new(nameof(GasSizeOverride));
public static readonly TypeId GasInstrOpInfoFlags = new(nameof(GasInstrOpInfoFlags));
public static readonly TypeId IntelSizeOverride = new(nameof(IntelSizeOverride));
public static readonly TypeId IntelBranchSizeInfo = new(nameof(IntelBranchSizeInfo));
public static readonly TypeId IntelInstrOpInfoFlags = new(nameof(IntelInstrOpInfoFlags));
public static readonly TypeId MasmInstrOpInfoFlags = new(nameof(MasmInstrOpInfoFlags));
public static readonly TypeId NasmSignExtendInfo = new(nameof(NasmSignExtendInfo));
public static readonly TypeId NasmSizeOverride = new(nameof(NasmSizeOverride));
public static readonly TypeId NasmBranchSizeInfo = new(nameof(NasmBranchSizeInfo));
public static readonly TypeId NasmInstrOpInfoFlags = new(nameof(NasmInstrOpInfoFlags));
public static readonly TypeId NasmMemorySizeInfo = new(nameof(NasmMemorySizeInfo));
public static readonly TypeId NasmFarMemorySizeInfo = new(nameof(NasmFarMemorySizeInfo));
public static readonly TypeId FastFmtFlags = new(nameof(FastFmtFlags));
public static readonly TypeId RoundingControl = new(nameof(RoundingControl));
public static readonly TypeId OpKind = new(nameof(OpKind));
public static readonly TypeId InstrScale = new(nameof(InstrScale));
public static readonly TypeId InstrFlags1 = new(nameof(InstrFlags1));
public static readonly TypeId VectorLength = new(nameof(VectorLength));
public static readonly TypeId MandatoryPrefixByte = new(nameof(MandatoryPrefixByte));
public static readonly TypeId StateFlags = new(nameof(StateFlags));
public static readonly TypeId EncodingKind = new(nameof(EncodingKind));
public static readonly TypeId FlowControl = new(nameof(FlowControl));
public static readonly TypeId OpCodeOperandKind = new(nameof(OpCodeOperandKind));
public static readonly TypeId RflagsBits = new(nameof(RflagsBits));
public static readonly TypeId ImpliedAccess = new(nameof(ImpliedAccess));
public static readonly TypeId RflagsInfo = new(nameof(RflagsInfo));
public static readonly TypeId OpInfo0 = new(nameof(OpInfo0));
public static readonly TypeId OpInfo1 = new(nameof(OpInfo1));
public static readonly TypeId OpInfo2 = new(nameof(OpInfo2));
public static readonly TypeId OpInfo3 = new(nameof(OpInfo3));
public static readonly TypeId OpInfo4 = new(nameof(OpInfo4));
public static readonly TypeId InfoFlags1 = new(nameof(InfoFlags1));
public static readonly TypeId InfoFlags2 = new(nameof(InfoFlags2));
public static readonly TypeId InstrInfoConstants = new(nameof(InstrInfoConstants));
public static readonly TypeId OpAccess = new(nameof(OpAccess));
public static readonly TypeId ConditionCode = new(nameof(ConditionCode));
public static readonly TypeId MiscInstrInfoTestConstants = new(nameof(MiscInstrInfoTestConstants));
public static readonly TypeId InstructionInfoKeys = new(nameof(InstructionInfoKeys));
public static readonly TypeId RflagsBitsConstants = new(nameof(RflagsBitsConstants));
public static readonly TypeId MemorySizeFlags = new(nameof(MemorySizeFlags));
public static readonly TypeId RegisterFlags = new(nameof(RegisterFlags));
public static readonly TypeId MiscSectionNames = new(nameof(MiscSectionNames));
public static readonly TypeId LegacyOpCodeTable = new(nameof(LegacyOpCodeTable));
public static readonly TypeId VexOpCodeTable = new(nameof(VexOpCodeTable));
public static readonly TypeId XopOpCodeTable = new(nameof(XopOpCodeTable));
public static readonly TypeId EvexOpCodeTable = new(nameof(EvexOpCodeTable));
public static readonly TypeId LegacyOpKind = new(nameof(LegacyOpKind));
public static readonly TypeId VexOpKind = new(nameof(VexOpKind));
public static readonly TypeId XopOpKind = new(nameof(XopOpKind));
public static readonly TypeId EvexOpKind = new(nameof(EvexOpKind));
public static readonly TypeId MandatoryPrefix = new(nameof(MandatoryPrefix));
public static readonly TypeId OpCodeTableKind = new(nameof(OpCodeTableKind));
public static readonly TypeId DisplSize = new(nameof(DisplSize));
public static readonly TypeId ImmSize = new(nameof(ImmSize));
public static readonly TypeId EncoderFlags = new(nameof(EncoderFlags));
public static readonly TypeId EncFlags1 = new(nameof(EncFlags1));
public static readonly TypeId EncFlags2 = new(nameof(EncFlags2));
public static readonly TypeId EncFlags3 = new(nameof(EncFlags3));
public static readonly TypeId OpCodeInfoFlags1 = new(nameof(OpCodeInfoFlags1));
public static readonly TypeId OpCodeInfoFlags2 = new(nameof(OpCodeInfoFlags2));
public static readonly TypeId DecOptionValue = new(nameof(DecOptionValue));
public static readonly TypeId InstrStrFmtOption = new(nameof(InstrStrFmtOption));
public static readonly TypeId WBit = new(nameof(WBit));
public static readonly TypeId LBit = new(nameof(LBit));
public static readonly TypeId OpCodeInfoKeys = new(nameof(OpCodeInfoKeys));
public static readonly TypeId OpCodeInfoFlags = new(nameof(OpCodeInfoFlags));
public static readonly TypeId LKind = new(nameof(LKind));
public static readonly TypeId RepPrefixKind = new(nameof(RepPrefixKind));
public static readonly TypeId OpSize = new(nameof(OpSize));
public static readonly TypeId RelocKind = new(nameof(RelocKind));
public static readonly TypeId BlockEncoderOptions = new(nameof(BlockEncoderOptions));
public static readonly TypeId NumberBase = new(nameof(NumberBase));
public static readonly TypeId MemorySizeOptions = new(nameof(MemorySizeOptions));
public static readonly TypeId FormatMnemonicOptions = new(nameof(FormatMnemonicOptions));
public static readonly TypeId PrefixKind = new(nameof(PrefixKind));
public static readonly TypeId DecoratorKind = new(nameof(DecoratorKind));
public static readonly TypeId NumberKind = new(nameof(NumberKind));
public static readonly TypeId FormatterTextKind = new(nameof(FormatterTextKind));
public static readonly TypeId SymbolFlags = new(nameof(SymbolFlags));
public static readonly TypeId GasInstrOpKind = new(nameof(GasInstrOpKind));
public static readonly TypeId IntelInstrOpKind = new(nameof(IntelInstrOpKind));
public static readonly TypeId MasmInstrOpKind = new(nameof(MasmInstrOpKind));
public static readonly TypeId NasmInstrOpKind = new(nameof(NasmInstrOpKind));
public static readonly TypeId FormatterFlowControl = new(nameof(FormatterFlowControl));
public static readonly TypeId OptionsProps = new(nameof(OptionsProps));
public static readonly TypeId MasmSymbolTestFlags = new(nameof(MasmSymbolTestFlags));
public static readonly TypeId FormatterSyntax = new(nameof(FormatterSyntax));
public static readonly TypeId CC_b = new(nameof(CC_b));
public static readonly TypeId CC_ae = new(nameof(CC_ae));
public static readonly TypeId CC_e = new(nameof(CC_e));
public static readonly TypeId CC_ne = new(nameof(CC_ne));
public static readonly TypeId CC_be = new(nameof(CC_be));
public static readonly TypeId CC_a = new(nameof(CC_a));
public static readonly TypeId CC_p = new(nameof(CC_p));
public static readonly TypeId CC_np = new(nameof(CC_np));
public static readonly TypeId CC_l = new(nameof(CC_l));
public static readonly TypeId CC_ge = new(nameof(CC_ge));
public static readonly TypeId CC_le = new(nameof(CC_le));
public static readonly TypeId CC_g = new(nameof(CC_g));
public static readonly TypeId CodeAsmMemoryOperandSize = new(nameof(CodeAsmMemoryOperandSize));
public static readonly TypeId TestInstrFlags = new(nameof(TestInstrFlags));
}
}
| 72.251572
| 101
| 0.802054
|
41e87f9913be369270cc6c1329d6a1f396c53092
| 520
|
sql
|
SQL
|
gretljobs/afu_grundwassergeometrie/grundwasser_tiefstand.sql
|
sogis/migration-sogis-db
|
be5437259cccfce6cc8ea760950111dec1e6749c
|
[
"MIT"
] | null | null | null |
gretljobs/afu_grundwassergeometrie/grundwasser_tiefstand.sql
|
sogis/migration-sogis-db
|
be5437259cccfce6cc8ea760950111dec1e6749c
|
[
"MIT"
] | 13
|
2020-08-31T12:23:05.000Z
|
2020-11-12T13:18:07.000Z
|
gretljobs/afu_grundwassergeometrie/grundwasser_tiefstand.sql
|
sogis/migration-sogis-db
|
be5437259cccfce6cc8ea760950111dec1e6749c
|
[
"MIT"
] | null | null | null |
SELECT
wkb_geometry AS geometrie,
CASE
WHEN maechtigke = '2-10m'
THEN 'm_2_10'
WHEN maechtigke = '10-20m'
THEN 'm_10_20'
WHEN maechtigke = '20-30m'
THEN 'm_20_30'
WHEN maechtigke = '30-40m'
THEN 'm_30_40'
WHEN maechtigke = '40-50m'
THEN 'm_40_50'
WHEN maechtigke = '>50m' OR maechtigke = '> 50m'
THEN 'm_groesser_50'
END AS maechtigkeit
FROM
public.aww_gstira
WHERE
archive = 0
;
| 23.636364
| 56
| 0.538462
|
f154dc06ce00e2bfaf6b3d05960ce89ec6a14f16
| 4,455
|
kt
|
Kotlin
|
nugu-login-kit/src/main/java/com/skt/nugu/sdk/platform/android/login/auth/Credentials.kt
|
Yuseon-Han/nugu-android
|
51155b9e6c3811f9f6d1566ea15ad8d96da65335
|
[
"Apache-2.0"
] | null | null | null |
nugu-login-kit/src/main/java/com/skt/nugu/sdk/platform/android/login/auth/Credentials.kt
|
Yuseon-Han/nugu-android
|
51155b9e6c3811f9f6d1566ea15ad8d96da65335
|
[
"Apache-2.0"
] | null | null | null |
nugu-login-kit/src/main/java/com/skt/nugu/sdk/platform/android/login/auth/Credentials.kt
|
Yuseon-Han/nugu-android
|
51155b9e6c3811f9f6d1566ea15ad8d96da65335
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (c) 2019 SK Telecom Co., Ltd. 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.skt.nugu.sdk.platform.android.login.auth
import org.json.JSONException
import org.json.JSONObject
import java.util.*
/**
* base class for an authorized identity
**/
data class Credentials(
/** The NUGU auth token **/
var accessToken: String,
/** The NUGU refresh token **/
var refreshToken: String,
/** The lifetime in seconds of the access token **/
var expiresIn: Long,
/** The issued Time **/
var issuedTime: Long,
/** The access Token Type **/
var tokenType: String,
/** The scope string **/
var scope: String?
) {
/**
* clear all of the elements from this list.
*/
fun clear() {
accessToken = ""
refreshToken = ""
expiresIn = 0
issuedTime = 0
tokenType = ""
scope = null
}
/**
* Returns a string representation of the object.
*/
override fun toString(): String {
val json = JSONObject()
json.put("access_token", accessToken)
json.put("token_type", tokenType)
json.put("expires_in", expiresIn)
json.put("issued_time", issuedTime)
json.put("refresh_token", refreshToken)
json.put("scope", scope)
return json.toString()
}
/**
* Companion objects
*/
companion object {
/**
* Default constructor of Credentials
**/
fun DEFAULT() = Credentials(
accessToken = "",
refreshToken = "",
expiresIn = 0,
issuedTime = 0,
tokenType = "",
scope = null
)
/**
* Parse to a Credentials
* @param string is json format
* @return a Credentials
* @throws JSONException if the parse fails or doesn't yield a JSONObject
*/
@Throws(JSONException::class)
fun parse(string: String): Credentials {
if (string.isBlank()) {
return DEFAULT()
}
JSONObject(string).apply {
return Credentials(
accessToken = getString("access_token"),
expiresIn = getLong("expires_in"),
issuedTime = if(!has("issued_time")) Date().time else getLong("issued_time"),
tokenType = getString("token_type"),
refreshToken = if (!has("refresh_token")) "" else getString("refresh_token"),
scope = if (!has("scope")) null else getString("scope")
)
}
}
}
/**
* Constructs a new [Credentials] builder,
*/
class Builder {
/**
* The NUGU auth token.
*/
private var accessToken: String = ""
/**
* The NUGU refresh token.
*/
private var refreshToken: String = ""
/**
* The lifetime in seconds of the access token.
* A time when credentials should be considered expired.
*/
private var expiresIn: Long = 0
/**
* The issue time associated with the access token.
*/
private var issuedTime: Long = 0
/**
* OAuth Access Token Type
* @see [https://tools.ietf.org/html/rfc6750]
*/
private var tokenType: String = ""
/**
* A space-delimited set of scopes used to determine the scope of any returned tokens.
* @see [https://tools.ietf.org/html/rfc6749#section-3.3]
*/
private var scope: String? = null
/**
* Returns a new instance of an Credentials based on this builder.
*/
fun build() = Credentials(
accessToken,
refreshToken,
expiresIn,
issuedTime,
tokenType,
scope
)
}
}
| 29.7
| 97
| 0.552637
|
729ce67b319a21b9b557df3f31eeef64eb8c9c82
| 11,914
|
cs
|
C#
|
src/Core.Tests/Threading/PartitionedTaskSchedulerTests.cs
|
cbaxter/infrastructure
|
508a9cc59c046c0fb615df717a484df58cc66a82
|
[
"MIT"
] | null | null | null |
src/Core.Tests/Threading/PartitionedTaskSchedulerTests.cs
|
cbaxter/infrastructure
|
508a9cc59c046c0fb615df717a484df58cc66a82
|
[
"MIT"
] | null | null | null |
src/Core.Tests/Threading/PartitionedTaskSchedulerTests.cs
|
cbaxter/infrastructure
|
508a9cc59c046c0fb615df717a484df58cc66a82
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Spark.Threading;
using Xunit;
/* Copyright (c) 2015 Spark Software Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Test.Spark.Threading
{
namespace UsingPartitionedTaskScheduler
{
public class WhenInitializing
{
[Fact]
public void SetMaximumConcurrencyLevelToNumberOfWorkerThreads()
{
Int32 workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Assert.Equal(workerThreads, new PartitionedTaskScheduler().MaximumConcurrencyLevel);
}
[Fact]
public void DefaultMaximumQueuedTasksToNumberOfWorkerThreads()
{
Int32 workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Assert.Equal(workerThreads, new PartitionedTaskScheduler().BoundedCapacity);
}
}
public class WhenQueuingTask
{
[Fact]
public void QueueImmediatelyIfBelowBoundedCapacity()
{
var taskScheduler = new PartitionedTaskScheduler(_ => 0, 1);
var task = Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
});
Assert.True(task.Wait(TimeSpan.FromMilliseconds(100)));
Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
}
[Fact]
public void BlockQueueUntilBelowBoundedCapacity()
{
var monitor = new FakeMonitor();
var threadPool = new FakeThreadPool();
var blocked = new ManualResetEvent(false);
var released = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler(_ => 0, 1, 1, threadPool, monitor);
monitor.BeforeWait = () => blocked.Set();
monitor.AfterPulse = () => released.Set();
Task.Factory.StartNew(() =>
{
// Schedule first task (non-blocking).
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
// Schedule second task (blocking).
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
});
// Wait for second task to be blocked.
Assert.True(blocked.WaitOne(TimeSpan.FromMilliseconds(100)));
Assert.Equal(1, threadPool.UserWorkItems.Count);
threadPool.RunNext();
// Wait for second task to be released.
Assert.True(released.WaitOne(TimeSpan.FromMilliseconds(100)));
threadPool.RunNext();
Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
}
[Fact]
public void RunOnDedicatedThreadIfLongRunning()
{
var isThreadPool = false;
var taskComplete = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler();
Task.Factory.StartNew(() => { isThreadPool = Thread.CurrentThread.IsThreadPoolThread; taskComplete.Set(); }, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, taskScheduler);
Assert.True(taskComplete.WaitOne(TimeSpan.FromMilliseconds(100)));
Assert.False(isThreadPool);
}
[Fact]
public void RunOnBackgroundThreadIfLongRunning()
{
var isBackground = false;
var taskComplete = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler();
Task.Factory.StartNew(() => { isBackground = Thread.CurrentThread.IsBackground; taskComplete.Set(); }, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, taskScheduler);
Assert.True(taskComplete.WaitOne(TimeSpan.FromMilliseconds(100)));
Assert.True(isBackground);
}
[Fact]
public void RunOnThreadPoolThreadIfNotLongRunning()
{
var isThreadPool = false;
var taskComplete = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler();
Task.Factory.StartNew(() => { isThreadPool = Thread.CurrentThread.IsThreadPoolThread; taskComplete.Set(); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
Assert.True(taskComplete.WaitOne(TimeSpan.FromMilliseconds(100)));
Assert.True(isThreadPool);
}
[Fact]
public void RunAllTasksOnSamePartitionInOrder()
{
var tasks = new Task[200];
var taskGroup1Order = new List<Int32>();
var taskGroup2Order = new List<Int32>();
var tasksQueued = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler(task => task.AsyncState, 2, tasks.Length);
for (var i = 0; i < tasks.Length; i++)
{
var taskGroupOrder = i % 2 == 0 ? taskGroup1Order : taskGroup2Order;
var taskId = i;
tasks[taskId] = Task.Factory.StartNew(state =>
{
taskGroupOrder.Add(taskId);
tasksQueued.WaitOne();
Thread.Sleep(1);
}, taskId, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, taskScheduler);
}
tasksQueued.Set();
Task.WaitAll(tasks);
Assert.Equal(tasks.Length / 2, taskGroup1Order.Where((ordinal, index) => ordinal == (index * 2)).Count());
Assert.Equal(tasks.Length / 2, taskGroup2Order.Where((ordinal, index) => ordinal == (index * 2) + 1).Count());
}
[Fact]
public void RunTasksOnDifferentPartitionsInParallel()
{
var tasks = new Task[200];
var taskOrder = new List<Int32>(tasks.Length);
var tasksQueued = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler(task => task.AsyncState, 2, tasks.Length);
for (var i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew(state =>
{
var taskId = (Int32)state;
lock (taskOrder)
{
taskOrder.Add(taskId);
}
tasksQueued.WaitOne();
Thread.Sleep(taskId % 3);
}, i, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, taskScheduler);
}
tasksQueued.Set();
Task.WaitAll(tasks);
Assert.NotEqual(tasks.Length, taskOrder.Where((ordinal, index) => ordinal == index).Count());
}
[Fact]
public void WillDeadlockIfForceSynchronousExecutionsAcrossPartitions()
{
var tasksQueued = new ManualResetEvent(false);
var partition1Active = new ManualResetEvent(false);
var partition2Active = new ManualResetEvent(false);
var task1 = new Task(_ => { }, 1, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
var task2 = new Task(_ => { }, 2, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
var taskScheduler = new PartitionedTaskScheduler(task => task.AsyncState, 2, 4);
var task3 = Task.Factory.StartNew(_ =>
{
tasksQueued.WaitOne();
partition1Active.Set();
partition2Active.WaitOne();
task1.RunSynchronously();
}, 2, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);
var task4 = Task.Factory.StartNew(_ =>
{
tasksQueued.WaitOne();
partition2Active.Set();
partition1Active.WaitOne();
task2.RunSynchronously();
}, 1, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);
tasksQueued.Set();
Assert.False(Task.WaitAll(new[] { task1, task2, task3, task4 }, 100));
}
}
public class WhenRunningTaskSynchronously
{
[Fact]
public void AllowsInlineExecutionAfterBeingQueued()
{
var executions = 0;
var taskScheduler = new PartitionedTaskScheduler();
var task = new Task(() => { executions++; }, CancellationToken.None, TaskCreationOptions.AttachedToParent);
task.RunSynchronously(taskScheduler);
Assert.Equal(1, executions);
Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
}
[Fact]
public void WaitForPreceedingTasksIfRequired()
{
var executionOrder = new List<Int32>();
var tasksQueued = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler();
Task.Factory.StartNew(() => { executionOrder.Add(0); tasksQueued.WaitOne(); Thread.Sleep(25); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
Task.Factory.StartNew(() => executionOrder.Add(1), CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
var synchronousTask = new Task(() => executionOrder.Add(2), CancellationToken.None, TaskCreationOptions.AttachedToParent);
tasksQueued.Set();
synchronousTask.RunSynchronously(taskScheduler);
Assert.Equal(3, executionOrder.Where((value, index) => value == index).Count());
}
}
}
}
| 45.64751
| 236
| 0.58234
|
14faf0f651a7a300fecc5f5d09654c6fe4dd5772
| 9,128
|
ts
|
TypeScript
|
tests/unit/Private/Functionalities.spec.ts
|
gimyboya/Apostille-library
|
19c68e37e54de061df2d52a31635c54900f9ea8e
|
[
"MIT"
] | null | null | null |
tests/unit/Private/Functionalities.spec.ts
|
gimyboya/Apostille-library
|
19c68e37e54de061df2d52a31635c54900f9ea8e
|
[
"MIT"
] | null | null | null |
tests/unit/Private/Functionalities.spec.ts
|
gimyboya/Apostille-library
|
19c68e37e54de061df2d52a31635c54900f9ea8e
|
[
"MIT"
] | null | null | null |
import { Account, NetworkType, TransactionType } from 'nem2-sdk';
import { Apostille, Initiator } from '../../../index';
import { Errors } from '../../../src/Errors';
const seed = '.N:@N%5SVjj3Wkmr-';
// A funny but valid private key
const sk = 'aaaaaaaaaaeeeeeeeeeebbbbbbbbbb5555555555dddddddddd1111111111aaee';
const generator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
beforeAll(() => {
jest.setTimeout(10000);
});
describe('Create functionn should work properly', () => {
it('should throw an error if you try to create an apostille more than once', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
return privateApostille.create(initiator, 'raw').catch((e) => {
expect(e.message).toMatch(Errors[Errors.APOSTILLE_ALREADY_CREATED]);
});
});
it('should create a transfer transaction', () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
return privateApostille.create(initiator, 'raw').then(() => {
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.TRANSFER);
});
});
it('should create an aggregate complete transaction', () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator, creator.publicAccount, true);
return privateApostille.create(initiator, 'raw').then(() => {
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_COMPLETE);
});
});
it('should create an aggregate bounded transaction', () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator, creator.publicAccount, false);
return privateApostille.create(initiator, 'raw').then(() => {
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_BONDED);
});
});
});
describe('update function should work properly', () => {
it('should throw an error if we try to update before creating', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
expect.assertions(1);
return privateApostille.update(initiator, 'raw').catch((e) => {
expect(e.message).toMatch(Errors[Errors.APOSTILLE_NOT_CREATED]);
});
});
it('should create a transfer transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
await privateApostille.update(initiator, 'update');
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][1].type).toEqual(TransactionType.TRANSFER);
});
it('should create an aggregate complete transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator, creator.publicAccount, true);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
await privateApostille.update(initiator, 'update');
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_COMPLETE);
});
it('should create an aggregate bounded transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator, creator.publicAccount, false);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
await privateApostille.update(initiator, 'update');
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_BONDED);
});
});
describe('associate function should work properly', () => {
it('should create an aggregate bounded transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator, creator.publicAccount, false);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
await privateApostille.update(initiator, 'update');
privateApostille.associate([initiator.account.publicAccount], 1, 1);
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][2].type).toEqual(TransactionType.MODIFY_MULTISIG_ACCOUNT);
});
});
describe('transfer function should work properly', () => {
it('should create an aggregate complete transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
// const initiator = new Initiator(creator, creator.publicAccount, false);
expect.assertions(1);
privateApostille.transfer([creator], true, [creator.publicAccount], [creator.publicAccount], 0, 0);
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_COMPLETE);
});
it('should create an aggregate complete transaction', async () => {
const privateApostille = Apostille.init(seed, generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
// const initiator = new Initiator(creator, creator.publicAccount, false);
expect.assertions(1);
privateApostille.transfer([creator], false, [], [], 0, 0);
// tslint:disable-next-line:no-string-literal
expect(privateApostille['transactions'][0].type).toEqual(TransactionType.AGGREGATE_BONDED);
});
});
describe('isCreated function should work properly', () => {
it('should return false before creation', async () => {
const privateApostille = Apostille.init('QUleqZedaOUtlSh', generator);
expect.assertions(1);
return privateApostille.isCreated().then((result) => {
expect(result).toBeFalsy();
});
});
it('should return true after creation', async () => {
const privateApostille = Apostille.init('new random seed', generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
expect.assertions(1);
await privateApostille.create(initiator, 'raw');
return privateApostille.isCreated().then((result) => {
expect(result).toBeTruthy();
});
});
it('should return true for an already created apostille', async () => {
const privateApostille = Apostille.init('MIJIN_TEST', generator);
expect.assertions(1);
return privateApostille.isCreated().then((result) => {
expect(result).toBeTruthy();
});
});
it('should throw an error if we don\'t specefy mijin endpoint url', () => {
const MJgenerator = Account.createFromPrivateKey(sk, NetworkType.MIJIN);
try {
return Apostille.init('k7u*VTsVCk6h,FdN', MJgenerator);
} catch (e) {
expect(e.message).toMatch(Errors[Errors.MIJIN_ENDPOINT_NEEDED]);
}
});
it('should return false before an announce', () => {
const MTgenerator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const apostilleMT = Apostille.init('QUleqZedaOUtlSh', MTgenerator);
return apostilleMT.isCreated().then((MT) => {
expect(MT).toBeFalsy();
});
});
it('should return true after an announce', async () => {
const privateApostille = Apostille.init('_934@Ve*,tM(3MN-', generator);
const creator = Account.createFromPrivateKey(sk, NetworkType.MIJIN_TEST);
const initiator = new Initiator(creator);
privateApostille.created = true;
await privateApostille.update(initiator, 'update');
await privateApostille.announce();
return privateApostille.isCreated().then((result) => {
expect(result).toBeTruthy();
});
});
it('should return true for an already announced apostille', () => {
const privateApostille = Apostille.init('MIJIN_TEST', generator);
return privateApostille.isCreated().then((result) => {
expect(result).toBeTruthy();
});
});
});
// TODO: check the order of transactions
// TODO: no transfer transaction should exist after a multisig modification
| 42.654206
| 103
| 0.711547
|
db9d9b55c68deafd5dd619b497fc26f420433f5e
| 1,641
|
php
|
PHP
|
resources/views/welcome.blade.php
|
Scelvin/LCRUD
|
70919fd1747af5b4bfa2771d046baee8fa060e42
|
[
"MIT"
] | null | null | null |
resources/views/welcome.blade.php
|
Scelvin/LCRUD
|
70919fd1747af5b4bfa2771d046baee8fa060e42
|
[
"MIT"
] | null | null | null |
resources/views/welcome.blade.php
|
Scelvin/LCRUD
|
70919fd1747af5b4bfa2771d046baee8fa060e42
|
[
"MIT"
] | null | null | null |
@extends('layouts.main')
@section('content')
@if (session('successMsg'))
<div class="alert alert-success" role="alert">
{{ session('successMsg') }}
</div>
@endif
<div class="container">
<h1>Dashboard</h1>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<th scope="row">{{ $student->id }}</th>
<td>{{ $student->first_name }}</td>
<td>{{ $student->last_name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->phone }}</td>
<td><a href="{{ route('edit', $student->id) }}"
style="background-color: khaki; color:black; border:2px solid black; padding:2px 15px; display:inline-block;">Edit</a> |
<form method="POST" id="delete-form-{{ $student->id }}" action="{{ route('delete', $student->id) }}"
style="display: none;">
{{ csrf_field() }}
{{ method_field('delete') }}
</form>
<button onclick="if (confirm('Are you sure you want to delete?!')) {
event.preventDefault();
document.getElementById('delete-form-{{ $student->id }}').submit();
} else {
event.preventDefault();
}">Delete
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
| 30.962264
| 131
| 0.493601
|
388da5e4e2d982840560f3943c92e64238a567bc
| 484
|
php
|
PHP
|
resources/views/home.blade.php
|
inf1nitev0id/inf1nite_v0ids_site
|
7a85963f79662c3dab01f488a817e7d39f2ddf2b
|
[
"MIT"
] | null | null | null |
resources/views/home.blade.php
|
inf1nitev0id/inf1nite_v0ids_site
|
7a85963f79662c3dab01f488a817e7d39f2ddf2b
|
[
"MIT"
] | null | null | null |
resources/views/home.blade.php
|
inf1nitev0id/inf1nite_v0ids_site
|
7a85963f79662c3dab01f488a817e7d39f2ddf2b
|
[
"MIT"
] | null | null | null |
@extends('layouts.main')
@section('title') Главная @endsection
@section('content')
<h5>Добро пожаловать на мой личный сайт!</h5>
<p>
И всего хорошего, потому что тут нет абсолютно ничего интересного, так что лучше идите займитесь своими делами.<br />
Возможно когда-нибудь тут что-то и появится, но только не сегодня.<br />
Не имею ни малейшего понятия, что ещё можно написать на этой странице.<br />
<i>Upd 08.12.2020:</i> теперь есть форум, но кому он нужен?
</p>
@endsection
| 34.571429
| 118
| 0.735537
|
cdd9b740acaf0cfc0679434ec64e613dc655427f
| 3,228
|
swift
|
Swift
|
Demo/Demo/ContentView.swift
|
damienvieira/BottomSheet
|
782b470a2980ff6230ee4ff690b1d54984119710
|
[
"MIT"
] | null | null | null |
Demo/Demo/ContentView.swift
|
damienvieira/BottomSheet
|
782b470a2980ff6230ee4ff690b1d54984119710
|
[
"MIT"
] | null | null | null |
Demo/Demo/ContentView.swift
|
damienvieira/BottomSheet
|
782b470a2980ff6230ee4ff690b1d54984119710
|
[
"MIT"
] | null | null | null |
//
// ContentView.swift
// Demo
//
// Created by Daniel Saidi on 2021-05-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
import BottomSheet
struct ContentView: View {
@State private var isExpanded = false
@State private var useTallerMinHeight = false
@State private var useShorterMaxHeight = false
@State private var sheetStyle = BottomSheetStyle.standard
var body: some View {
NavigationView {
List {
Section(header: Text("").frame(height: 1)) {
Toggle("Is expanded", isOn: $isExpanded)
Toggle("Use taller min height", isOn: $useTallerMinHeight)
Toggle("Use shorter max height", isOn: $useShorterMaxHeight)
}
Section(header: Text("Sheet Styles").frame(height: 1)) {
sheetStyleButton("Standard", style: .standard)
sheetStyleButton("(Demo) Red", style: .demoRed)
sheetStyleButton("(Demo) Green", style: .demoGreen)
sheetStyleButton("(Demo) Blue", style: .demoBlue)
sheetStyleButton("(Demo) Larger Corner Radius", style: .demoRound)
}
Section(header: Text("Sheet Handle Styles").frame(height: 1), footer: bottomPadding) {
sheetHandleStyleButton("Standard", style: .standard)
sheetHandleStyleButton("(Demo) Red", style: .demoRed)
sheetHandleStyleButton("(Demo) Green", style: .demoGreen)
sheetHandleStyleButton("(Demo) Blue", style: .demoBlue)
sheetHandleStyleButton("(Demo) Large Yellow", style: .demoLargeYellow)
}
}
.buttonStyle(PlainButtonStyle())
.navigationTitle("Bottom Sheet Demo")
.listStyle(InsetGroupedListStyle())
}
.bottomSheet(sheet)
}
}
private extension ContentView {
var bottomPadding: some View {
Color.clear.frame(height: useTallerMinHeight ? 280 : 130)
}
var sheet: some BottomSheetView {
BottomSheet(
isExpanded: $isExpanded,
minHeight: useTallerMinHeight ? .points(300) : .points(150),
maxHeight: useShorterMaxHeight ? .percentage(0.5) : .available,
style: sheetStyle) {
DemoSheetContent(style: sheetStyle)
}
}
func listButton(_ text: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack {
Text(text)
Spacer()
}.background(Color.white.opacity(0.0001))
}
}
func sheetStyleButton(_ text: String, style: BottomSheetStyle) -> some View {
listButton(text) {
sheetStyle = style
}
}
func sheetHandleStyleButton(_ text: String, style: BottomSheetHandleStyle) -> some View {
listButton(text) {
sheetStyle = BottomSheetStyle(handleStyle: style)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 33.978947
| 102
| 0.566914
|
028b1367da7d6732cf3b5ecc7b50b8a429414aa5
| 747
|
sql
|
SQL
|
Database/Tables/EntityProjectMeasureValue.sql
|
gianadda/ZenPRM
|
3fb4ef986ad01d3a1604226282dcb81892f145d0
|
[
"WTFPL"
] | 1
|
2021-07-31T19:02:54.000Z
|
2021-07-31T19:02:54.000Z
|
Database/Tables/EntityProjectMeasureValue.sql
|
gianadda/ZenPRM
|
3fb4ef986ad01d3a1604226282dcb81892f145d0
|
[
"WTFPL"
] | null | null | null |
Database/Tables/EntityProjectMeasureValue.sql
|
gianadda/ZenPRM
|
3fb4ef986ad01d3a1604226282dcb81892f145d0
|
[
"WTFPL"
] | 2
|
2016-09-19T01:59:48.000Z
|
2016-09-21T13:28:18.000Z
|
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'EntityProjectMeasureValue')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE EntityProjectMeasureValue
GO
CREATE TABLE EntityProjectMeasureValue (
Ident BIGINT IDENTITY (1,1) ,
EntityProjectMeasureIdent BIGINT ,
Value1 NVARCHAR(MAX),
ValueCount BIGINT,
AddASUserIdent BIGINT,
AddDateTime SMALLDATETIME,
EditASUserIdent BIGINT,
EditDateTime SMALLDATETIME,
Active BIT
)
CREATE UNIQUE CLUSTERED INDEX idx_EntityProjectMeasureValue_Ident ON dbo.EntityProjectMeasureValue(Ident)
GO
CREATE NONCLUSTERED INDEX idx_EntityProjectMeasureValue_EntityProjectMeasureIdent ON dbo.EntityProjectMeasureValue(EntityProjectMeasureIdent)
INCLUDE(Ident,Value1,ValueCount,Active)
GO
| 32.478261
| 141
| 0.840696
|
820652696214b0053d560e63ef5eb77a8689379f
| 4,366
|
dart
|
Dart
|
lib/src/index_service/index_service.dart
|
uris77/firesearch_sdk
|
6a6c0c171c679f532ccafae4090f821315c2eca5
|
[
"Apache-2.0"
] | 1
|
2021-07-18T14:38:16.000Z
|
2021-07-18T14:38:16.000Z
|
lib/src/index_service/index_service.dart
|
uris77/firesearch_sdk
|
6a6c0c171c679f532ccafae4090f821315c2eca5
|
[
"Apache-2.0"
] | null | null | null |
lib/src/index_service/index_service.dart
|
uris77/firesearch_sdk
|
6a6c0c171c679f532ccafae4090f821315c2eca5
|
[
"Apache-2.0"
] | null | null | null |
import 'dart:convert';
import 'package:firesearch_sdk/firesearch_sdk.dart';
import 'package:firesearch_sdk/src/index_service/put_doc_request.dart';
/// IndexService provides the ability to create and manage full-text indexes, as
/// well as populate them with data, and perform searches.
class IndexService {
/// Default Constructor
IndexService(this.client);
/// The firesearch client
final Client client;
Map<String, String> _headers() {
var _h = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
if (client.apiKey != null && client.apiKey!.isNotEmpty) {
_h['X-API-KEY'] = client.apiKey!;
}
return _h;
}
/// CreateIndex creates a new index.
Future<CreateIndexResponse> createIndex(
CreateIndexRequest createIndexRequest) async {
var response = await client.httpClient.post('/api/IndexService.CreateIndex',
headers: _headers(), body: jsonEncode(createIndexRequest));
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.CreateIndex: ${response.statusCode} ${response.body}');
}
return CreateIndexResponse.fromJson(jsonDecode(response.body));
}
/// DeleteDoc removes a document from an Index. Once deleted, it will stop appearing
/// in search results.
Future<DeleteDocResponse> deleteDoc(DeleteDocRequest deleteDocRequest) async {
var body = jsonEncode(deleteDocRequest);
var response = await client.httpClient
.post('/api/IndexService.DeleteDoc', headers: _headers(), body: body);
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.DeleteDoc: ${response.statusCode} ${response.body}');
}
return DeleteDocResponse.fromJson(jsonDecode(response.body));
}
/// DeleteIndex deletes the Index. All index data, as well as any metadata about
/// this Index will be completely deleted.
Future<DeleteIndexResponse> deleteIndex(
DeleteIndexRequest deleteIndexRequest) async {
var body = jsonEncode(deleteIndexRequest);
var response = await client.httpClient
.post('/api/IndexService.DeleteIndex', headers: _headers(), body: body);
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.DeleteIndex: ${response.statusCode} ${response.body}');
}
return DeleteIndexResponse.fromJson(jsonDecode(response.body));
}
/// GetIndex gets an Index.
Future<GetIndexResponse> getIndex(GetIndexRequest getIndexRequest) async {
var body = jsonEncode(getIndexRequest);
var response = await client.httpClient
.post('/api/IndexService.GetIndex', headers: _headers(), body: body);
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.GetIndex: ${response.statusCode} ${response.body}');
}
return GetIndexResponse.fromJson(jsonDecode(response.body));
}
/// GetIndexes gets a list of Indexes.
Future<GetIndexesResponse> getIndexes() async {
var response = await client.httpClient.post('/api/IndexService.GetIndexes',
headers: _headers(), body: jsonEncode({}));
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.GetIndexes: ${response.statusCode} ${response.body}');
}
return GetIndexesResponse.fromJson(jsonDecode(response.body));
}
/// PutDoc puts a document into an Index.
Future<PutDocResponse> putDoc(PutDocRequest putDocRequest) async {
var body = jsonEncode(putDocRequest);
var response = await client.httpClient
.post('/api/IndexService.PutDoc', headers: _headers(), body: body);
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.PutDoc ${response.statusCode} ${response.body}');
}
return PutDocResponse.fromJson(jsonDecode(response.body));
}
/// Search performs a search on an Index.
Future<SearchResponse> search(SearchRequest searchRequest) async {
var body = jsonEncode(searchRequest);
var response = await client.httpClient
.post('/api/IndexService.Search', headers: _headers(), body: body);
if (response.statusCode != 200) {
throw Exception(
'firesearch: IndexService.search ${response.statusCode} ${response.body}');
}
return SearchResponse.fromJson(jsonDecode(response.body));
}
}
| 35.495935
| 91
| 0.696519
|
6405adc42dcd7f2f4a6a096a4b0fe06d93f65c53
| 4,144
|
py
|
Python
|
project/plant_fight/game/plane.py
|
Firekiss/python_learn
|
15922af566a08924834ff924982a36a65b724bbf
|
[
"MIT"
] | null | null | null |
project/plant_fight/game/plane.py
|
Firekiss/python_learn
|
15922af566a08924834ff924982a36a65b724bbf
|
[
"MIT"
] | null | null | null |
project/plant_fight/game/plane.py
|
Firekiss/python_learn
|
15922af566a08924834ff924982a36a65b724bbf
|
[
"MIT"
] | null | null | null |
import pygame
import constants
import re, random
from game.bullet import Bullet
frame_regex = re.compile(r'^\d*[0-4]$')
class Plane(pygame.sprite.Sprite):
# 飞机的绘制图片列表
plane_imgs = []
# 飞机毁灭时用来绘制的图片
destory_imgs = []
# 飞机毁灭时的音乐
destory_sound = None
# 飞机当前的状态
active = True
# 飞机的子弹组
bullets = pygame.sprite.Group()
def __init__(self, screen, speed=2):
super().__init__()
# 主屏幕
self.screen = screen
self.screen_wd, self.screen_ht = self.screen.get_size()
self._imgs = []
self._destory_imgs = []
self._destory_sound = None
# 加载静态资源
self.source_load()
# 设置飞机飞行速度
self.speed = speed
# 设置飞机位置
self.rect = self._imgs[0].get_rect()
self.wd, self.ht = self._imgs[0].get_size()
self.rect.left = int((self.screen_wd - self.wd) / 2)
self.rect.top = int(self.screen_ht - self.ht - 10)
def source_load(self):
for img in self.plane_imgs:
self._imgs.append(pygame.image.load(img))
for img in self.destory_imgs:
self._destory_imgs.append(pygame.image.load(img))
if self.destory_sound:
self._destory_sound = pygame.mixer.Sound(self.destory_sound)
def blit_self(self):
self.screen.blit(self._imgs[0], self.rect)
def move_up(self):
self.rect.top -= self.speed
def move_down(self):
self.rect.top += self.speed
def move_left(self):
self.rect.left -= self.speed
def move_right(self):
self.rect.left += self.speed
# 飞机坠毁
def borken_down(self):
if self._destory_sound:
self._destory_sound.play()
for img in self._destory_imgs:
self.screen.blit(img, self.rect)
self.active = False
# 飞机的射击功能
def shoot(self):
bul = Bullet(self.screen, self)
self.bullets.add(bul)
class OurPlane(Plane):
plane_imgs = [constants.PLANE_IMG_1, constants.PLANE_IMG_2]
destory_imgs = constants.PLANE_DESTORY_IMGS
destory_sound = constants.PLANE_DESTORY_SOUND
def update(self, frame, enemies_group, key_down):
# 保证持续移动
self.move(key_down)
# 切换飞机的动画效果
if frame_regex.match(str(frame)):
self.screen.blit(self._imgs[0], self.rect)
else:
self.screen.blit(self._imgs[1], self.rect)
# 检测飞机是否撞击到了敌方飞机
if pygame.sprite.spritecollide(self, enemies_group, False):
self.borken_down()
self.active = False
# 返回 False 代表游戏已经结束了
return True
return False
def move(self, key):
if key == pygame.K_DOWN:
self.move_down()
elif key == pygame.K_UP:
self.move_up()
elif key == pygame.K_LEFT:
self.move_left()
elif key == pygame.K_RIGHT:
self.move_right()
def move_up(self):
super().move_up()
if self.rect.top <= 0:
self.rect.top = 0
def move_left(self):
super().move_left()
if self.rect.left <= 0:
self.rect.left = 0
def move_down(self):
super().move_down()
if self.rect.top + self.ht >= self.screen_ht:
self.rect.top = self.screen_ht - self.ht
def move_right(self):
super().move_right()
if self.rect.left + self.wd >= self.screen_wd:
self.rect.left = self.screen_wd - self.wd
class SmallEnemyPlane(Plane):
# 飞机的绘制图片列表
plane_imgs = [constants.SMALL_ENEMY_PLANE_IMG]
# 飞机毁灭时用来绘制的图片
destory_imgs = constants.SMALL_ENEMY_PLANE_DESTORY_IMGS
# 飞机毁灭时的音乐
destory_sound = constants.SMALL_ENEMY_PLANE_DESTORY_SOUND
# 飞机当前的状态
active = True
def __init__(self, screen, speed=3):
super().__init__(screen, speed)
self.rect.left = random.randint(0, self.screen_wd - self.wd)
self.rect.top = random.randint(-5 * self.ht, -self.ht)
def update(self):
self.move_down()
self.blit_self()
if self.rect.top > self.screen_ht:
self.active = False
self.kill()
| 27.443709
| 72
| 0.594353
|
b8f96d0a59d72054cb247c9164d55f6a0646911c
| 1,230
|
h
|
C
|
24. 2022-05-21-2022-06-06 (ShadowMap)/header/CubeRenderTarget.h
|
Mawi1e/DirectX12Study
|
82e4ae728b58087e75b85be09bc87d089691cdca
|
[
"MIT"
] | null | null | null |
24. 2022-05-21-2022-06-06 (ShadowMap)/header/CubeRenderTarget.h
|
Mawi1e/DirectX12Study
|
82e4ae728b58087e75b85be09bc87d089691cdca
|
[
"MIT"
] | null | null | null |
24. 2022-05-21-2022-06-06 (ShadowMap)/header/CubeRenderTarget.h
|
Mawi1e/DirectX12Study
|
82e4ae728b58087e75b85be09bc87d089691cdca
|
[
"MIT"
] | null | null | null |
#pragma once
#include "VertexBuffer.h"
template <class _Tp> _Tp& unmove(_Tp&& __val) { return __val; }
class CubeRenderTarget {
public:
CubeRenderTarget(ID3D12Device* Device, UINT ScreenWidth, UINT ScreenHeight, DXGI_FORMAT RtvFormat);
CubeRenderTarget(const CubeRenderTarget&) = delete;
CubeRenderTarget& operator=(const CubeRenderTarget&) = delete;
~CubeRenderTarget();
ID3D12Resource* Resource() const;
RECT GetScissorRect() const;
D3D12_VIEWPORT GetViewport() const;
CD3DX12_GPU_DESCRIPTOR_HANDLE SrvHandle() const;
CD3DX12_CPU_DESCRIPTOR_HANDLE RtvHandle(int rtvIndex) const;
void OnResize(UINT newWidth, UINT newHeight);
void BuildDescriptor(
CD3DX12_CPU_DESCRIPTOR_HANDLE CpuSrvHandle,
CD3DX12_GPU_DESCRIPTOR_HANDLE GpuSrvHandle,
CD3DX12_CPU_DESCRIPTOR_HANDLE CpuRtvHandle[6]);
private:
void BuildResource();
void BuildDescriptor();
private:
ID3D12Device* m_Device;
D3D12_RECT m_ScissorRect;
D3D12_VIEWPORT m_Viewport;
UINT m_ScreenWidth, m_ScreenHeight;
DXGI_FORMAT m_BackbufferFormat;
CD3DX12_CPU_DESCRIPTOR_HANDLE m_CpuSrvHandle;
CD3DX12_GPU_DESCRIPTOR_HANDLE m_GpuSrvHandle;
CD3DX12_CPU_DESCRIPTOR_HANDLE m_CpuRtvHandle[6];
Microsoft::WRL::ComPtr<ID3D12Resource> m_CubeMap;
};
| 25.625
| 100
| 0.813821
|
c63dbb815b72e0c97f379011ac8a60ab61426d81
| 143
|
rb
|
Ruby
|
lib/paper_trail_globalid/rails/controller.rb
|
hajder/paper_trail-globalid
|
c2ef6ebd87f32945ec011b49676ceacd0cfa9664
|
[
"MIT"
] | null | null | null |
lib/paper_trail_globalid/rails/controller.rb
|
hajder/paper_trail-globalid
|
c2ef6ebd87f32945ec011b49676ceacd0cfa9664
|
[
"MIT"
] | null | null | null |
lib/paper_trail_globalid/rails/controller.rb
|
hajder/paper_trail-globalid
|
c2ef6ebd87f32945ec011b49676ceacd0cfa9664
|
[
"MIT"
] | null | null | null |
module PaperTrailGlobalid
module Rails
module Controller
def user_for_paper_trail
current_user
end
end
end
end
| 14.3
| 30
| 0.685315
|
0dbe8d097187a2bde64ef9512a7f9167272398fa
| 655
|
cs
|
C#
|
IF-Tools/Data/Types/GradeInfo.cs
|
gzhynko/IF-Tools
|
5acd322e6c7ad1c679b41e222f196b40f1dd0e3e
|
[
"MIT"
] | 2
|
2021-04-16T14:43:54.000Z
|
2021-04-19T23:23:12.000Z
|
IF-Tools/Data/Types/GradeInfo.cs
|
gzhynko/IF-Tools
|
5acd322e6c7ad1c679b41e222f196b40f1dd0e3e
|
[
"MIT"
] | 1
|
2021-04-14T06:47:35.000Z
|
2021-04-21T04:39:32.000Z
|
IF-Tools/Data/Types/GradeInfo.cs
|
if-tools/IF-Tools
|
5acd322e6c7ad1c679b41e222f196b40f1dd0e3e
|
[
"MIT"
] | null | null | null |
using Newtonsoft.Json;
namespace IFTools.Data.Types
{
public class GradeInfo
{
[JsonProperty("gradeDetails")]
public GradeConfiguration GradeDetails { get; set; }
[JsonProperty("reports")]
public ReportEntry[] Reports { get; set; }
[JsonProperty("violations")]
public ViolationEntry[] Violations { get; set; }
[JsonProperty("totalXP")]
public int TotalXp { get; set; }
[JsonProperty("atcOperations")]
public int AtcOperations { get; set; }
[JsonProperty("atcRank")]
public AtcRank? AtcRank { get; set; }
}
}
| 25.192308
| 60
| 0.574046
|
059fc2ae32f7195731da76c10336090f4ec03510
| 797
|
swift
|
Swift
|
build/src/Models/ReportingTurnKnowledgeSearch.swift
|
MyPureCloud/platform-client-sdk-ios
|
d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b
|
[
"MIT"
] | null | null | null |
build/src/Models/ReportingTurnKnowledgeSearch.swift
|
MyPureCloud/platform-client-sdk-ios
|
d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b
|
[
"MIT"
] | null | null | null |
build/src/Models/ReportingTurnKnowledgeSearch.swift
|
MyPureCloud/platform-client-sdk-ios
|
d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b
|
[
"MIT"
] | 1
|
2021-05-11T21:57:38.000Z
|
2021-05-11T21:57:38.000Z
|
//
// ReportingTurnKnowledgeSearch.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class ReportingTurnKnowledgeSearch: Codable {
/** The ID of this knowledge search. */
public var searchId: String?
/** The list of search documents captured during this reporting turn. */
public var documents: [ReportingTurnKnowledgeDocument]?
/** The search query that was used to search the Knowledge Base documents for a matching question. */
public var query: String?
public init(searchId: String?, documents: [ReportingTurnKnowledgeDocument]?, query: String?) {
self.searchId = searchId
self.documents = documents
self.query = query
}
}
| 23.441176
| 105
| 0.675031
|
433fb3b73c73da4332e9a9009eb4ce7605777d2e
| 663
|
ts
|
TypeScript
|
src/facebookManager.d.ts
|
comapi/comapi-sdk-js-bower
|
ccaec077348c827ec11862a865034603316f5636
|
[
"MIT"
] | null | null | null |
src/facebookManager.d.ts
|
comapi/comapi-sdk-js-bower
|
ccaec077348c827ec11862a865034603316f5636
|
[
"MIT"
] | null | null | null |
src/facebookManager.d.ts
|
comapi/comapi-sdk-js-bower
|
ccaec077348c827ec11862a865034603316f5636
|
[
"MIT"
] | null | null | null |
import { IComapiConfig, IRestClient, IFacebookManager } from "./interfaces";
export declare class FacebookManager implements IFacebookManager {
private _restClient;
private _comapiConfig;
/**
* FacebookManager class constructor.
* @class FacebookManager
* @ignore
* @classdesc Class that implements all the FacebookManager functionality.
* @parameter {IRestClient} restClient
* @parameter {IComapiConfig} comapiConfig
*/
constructor(_restClient: IRestClient, _comapiConfig: IComapiConfig);
/**
* @param {any} [data] - the data to post
*/
createSendToMessengerState(data?: any): Promise<any>;
}
| 34.894737
| 78
| 0.704374
|
785cd9150e6167e45e86ec95db660c2ded95619b
| 6,978
|
lua
|
Lua
|
dynamic_bcspline/dynamic-bcspline.lua
|
skaminp/mpv-scripts
|
131df4efa07455db9f4ba37fd29a9a2267706f85
|
[
"MIT"
] | 2
|
2021-05-21T00:46:12.000Z
|
2021-09-15T23:14:58.000Z
|
dynamic_bcspline/dynamic-bcspline.lua
|
skaminp/mpv-scripts
|
131df4efa07455db9f4ba37fd29a9a2267706f85
|
[
"MIT"
] | null | null | null |
dynamic_bcspline/dynamic-bcspline.lua
|
skaminp/mpv-scripts
|
131df4efa07455db9f4ba37fd29a9a2267706f85
|
[
"MIT"
] | null | null | null |
local options = {
offset = 1.5,
cutoff = 0,
dscale_nearest = true,
dscale_nearest_level = -3,
debug_message = false,
}
(require 'mp.options').read_options(options)
local cutoff_check = true
local dscale_nearest_check = false
local offset_list = {
0,
0.1,
0.25,
0.333,
0.5,
0.75,
1,
1.25,
1.5,
1.75,
2,
}
function get_video_dimensions()
local video_params = mp.get_property_native("video-out-params")
if not video_params then
_video_dimensions = nil
return nil
end
_video_dimensions = {
top_left = { 0, 0 },
bottom_right = { 0, 0 },
size = { 0, 0 },
ratios = { 0, 0 }, -- by how much the original video got scaled
}
local keep_aspect = mp.get_property_bool("keepaspect")
local w = video_params["w"]
local h = video_params["h"]
local dw = video_params["dw"]
local dh = video_params["dh"]
if mp.get_property_number("video-rotate") % 180 == 90 then
w, h = h,w
dw, dh = dh, dw
end
local window_w, window_h = mp.get_osd_size()
if keep_aspect then
local unscaled = mp.get_property_native("video-unscaled")
local panscan = mp.get_property_number("panscan")
local fwidth = window_w
local fheight = math.floor(window_w / dw * dh)
if fheight > window_h or fheight < h then
local tmpw = math.floor(window_h / dh * dw)
if tmpw <= window_w then
fheight = window_h
fwidth = tmpw
end
end
local vo_panscan_area = window_h - fheight
local f_w = fwidth / fheight
local f_h = 1
if vo_panscan_area == 0 then
vo_panscan_area = window_h - fwidth
f_w = 1
f_h = fheight / fwidth
end
if unscaled or unscaled == "downscale-big" then
vo_panscan_area = 0
if unscaled or (dw <= window_w and dh <= window_h) then
fwidth = dw
fheight = dh
end
end
local scaled_width = fwidth + math.floor(vo_panscan_area * panscan * f_w)
local scaled_height = fheight + math.floor(vo_panscan_area * panscan * f_h)
local split_scaling = function (dst_size, scaled_src_size, zoom, align, pan)
scaled_src_size = math.floor(scaled_src_size * 2 ^ zoom)
align = (align + 1) / 2
local dst_start = math.floor((dst_size - scaled_src_size) * align + pan * scaled_src_size)
if dst_start < 0 then
--account for C int cast truncating as opposed to flooring
dst_start = dst_start + 1
end
local dst_end = dst_start + scaled_src_size
if dst_start >= dst_end then
dst_start = 0
dst_end = 1
end
return dst_start, dst_end
end
local zoom = mp.get_property_number("video-zoom")
local align_x = mp.get_property_number("video-align-x")
local pan_x = mp.get_property_number("video-pan-x")
_video_dimensions.top_left[1], _video_dimensions.bottom_right[1] = split_scaling(window_w, scaled_width, zoom, align_x, pan_x)
local align_y = mp.get_property_number("video-align-y")
local pan_y = mp.get_property_number("video-pan-y")
_video_dimensions.top_left[2], _video_dimensions.bottom_right[2] = split_scaling(window_h, scaled_height, zoom, align_y, pan_y)
else
_video_dimensions.top_left[1] = 0
_video_dimensions.bottom_right[1] = window_w
_video_dimensions.top_left[2] = 0
_video_dimensions.bottom_right[2] = window_h
end
_video_dimensions.size[1] = _video_dimensions.bottom_right[1] - _video_dimensions.top_left[1]
_video_dimensions.size[2] = _video_dimensions.bottom_right[2] - _video_dimensions.top_left[2]
_video_dimensions.ratios[1] = _video_dimensions.size[1] / w
_video_dimensions.ratios[2] = _video_dimensions.size[2] / h
return _video_dimensions
end
function dynamic_scale()
local video_dimensions = get_video_dimensions()
if not video_dimensions then return end
local ratio
if video_dimensions.keep_aspect then
ratio = video_dimensions.ratios[1]
else
ratio = (video_dimensions.ratios[1] + video_dimensions.ratios[2])/2
end
local log_ratio = math.log(ratio) / math.log(2)
if options.dscale_nearest and options.dscale_nearest_level <= 0 and options.offset==1.5 and options.cutoff == 0 then
if log_ratio <= options.dscale_nearest_level then
if not options.dscale_nearest_check then
mp.command("no-osd set dscale nearest")
dscale_nearest_check = true
end
else
if dscale_nearest_check then
mp.command("no-osd set dscale bcspline")
dscale_nearest_check = false
end
if log_ratio >= options.cutoff then
cutoff_check = true
set_params(log_ratio)
end
end
if log_ratio < options.cutoff and cutoff_check then
set_params(options.cutoff)
cutoff_check = false;
end
else -- default without transition to nearest
if log_ratio >= options.cutoff then
cutoff_check = true
set_params(log_ratio)
elseif cutoff_check then
set_params(options.cutoff)
cutoff_check = false;
end
end
if debug_message then
mp.osd_message("B: "..mp.get_property_osd("scale-param1").." C: "..mp.get_property_osd("scale-param2").." Offset: "..string.format("%.3f", options.offset).." Cutoff: "..string.format("%.3f", options.cutoff).." dscale: "..mp.get_property_osd("dscale"))
end
end
function set_params(log_ratio)
local x = log_ratio * options.offset
local B = x / (1 + math.abs(x))
local C = 0.5 * -B + 0.5 --C = (1 - B) / 2
if log_ratio >= 0 then
mp.command("no-osd set scale-param1 "..B.."; no-osd set scale-param2 "..C)
else
mp.command("no-osd set dscale-param1 "..B.."; no-osd set dscale-param2 "..C)
end
end
function on_scale()
dynamic_scale()
end
function on_load()
mp.command("no-osd set scale bcspline; no-osd set dscale bcspline")
dynamic_scale()
end
local function cycle_offset()
local i, index = 1
for i = 1, #offset_list do
if (offset_list[i] == options.offset) then
index = i + 1
if index > #offset_list then
index = 1
end
break
end
end
options.offset = offset_list[index]
mp.osd_message(offset_list[index])
dynamic_scale()
end
mp.observe_property("osd-dimensions", "native", on_scale)
mp.observe_property("dwidth", "native", on_load) --video size after filters and aspect, not windows output
mp.register_script_message('cycle-offset', function() cycle_offset() end)
| 33.38756
| 259
| 0.617512
|
258a100526a48d6723e0e0bf5ef68e668e7102dc
| 1,416
|
js
|
JavaScript
|
core-ui/src/resources/Secrets/SecretDetails.js
|
mrCherry97/busola
|
cb145ab3e2c52b86cc64c8f4438d8a1e07457463
|
[
"Apache-2.0"
] | null | null | null |
core-ui/src/resources/Secrets/SecretDetails.js
|
mrCherry97/busola
|
cb145ab3e2c52b86cc64c8f4438d8a1e07457463
|
[
"Apache-2.0"
] | null | null | null |
core-ui/src/resources/Secrets/SecretDetails.js
|
mrCherry97/busola
|
cb145ab3e2c52b86cc64c8f4438d8a1e07457463
|
[
"Apache-2.0"
] | null | null | null |
import React from 'react';
import { useTranslation } from 'react-i18next';
import { ControlledBy } from 'shared/components/ControlledBy/ControlledBy';
import { ResourceDetails } from 'shared/components/ResourceDetails/ResourceDetails';
import SecretData from 'shared/components/Secret/SecretData';
import { HelmReleaseData } from 'components/HelmReleases/HelmReleaseData';
import { CertificateData } from './CertificateData';
import { SecretCreate } from './SecretCreate';
function HelmReleaseDataWrapper(secret) {
if (secret.type !== 'helm.sh/release.v1') {
return null;
}
return (
<HelmReleaseData
key="helm-release-data"
encodedRelease={secret.data.release}
/>
);
}
export function SecretDetails(props) {
const { t } = useTranslation();
const Secret = resource => <SecretData key="secret-data" secret={resource} />;
const customColumns = [
{
header: t('secrets.headers.type'),
value: secret => {
return secret.type;
},
},
{
header: t('common.headers.owner'),
value: secret => (
<ControlledBy ownerReferences={secret.metadata.ownerReferences} />
),
},
];
return (
<ResourceDetails
customComponents={[Secret, CertificateData, HelmReleaseDataWrapper]}
customColumns={customColumns}
createResourceForm={SecretCreate}
{...props}
/>
);
}
export default SecretDetails;
| 26.222222
| 84
| 0.675847
|
21ba7afe41b69a8822ad453482e9c0b7fce7e37d
| 3,743
|
js
|
JavaScript
|
aura-impl/src/test/components/expressionTest/simpleValue/simpleValueTest.js
|
ShekharGadewar/aura
|
fb6322fe7cc11d56dbae6cdf08a5bcd9828f6dd5
|
[
"Apache-2.0"
] | 1
|
2016-01-20T21:24:36.000Z
|
2016-01-20T21:24:36.000Z
|
aura-impl/src/test/components/expressionTest/simpleValue/simpleValueTest.js
|
ShekharGadewar/aura
|
fb6322fe7cc11d56dbae6cdf08a5bcd9828f6dd5
|
[
"Apache-2.0"
] | null | null | null |
aura-impl/src/test/components/expressionTest/simpleValue/simpleValueTest.js
|
ShekharGadewar/aura
|
fb6322fe7cc11d56dbae6cdf08a5bcd9828f6dd5
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2013 salesforce.com, 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.
*/
({
assertChangeEvent: function(component, value){
$A.test.assertTrue(undefined !== component._log, "change handler not invoked");
$A.test.assertEquals(1, component._log.length, "unexpected number of change events recorded");
$A.test.assertEquals(value , component._log[0].value, "unexpected value of change");
component._log = undefined; // reset log
},
testCreateSimpleValue:{
test:[
function(component){
var value = $A.expressionService.create(null, true);
$A.test.assertNotNull(value);
//Initial Value is TRUE
$A.test.assertTrue(value);
component.set("v.booleanValue", false);
//Set value to FALSE
$A.test.assertFalse(component.get("v.booleanValue"), "get() should reflect latest value");
},
function(component){
var val = $A.expressionService.create(null, undefined);
$A.test.assertUndefined(val, "expected undefined as value");
val = $A.expressionService.create(null, null);
$A.test.assertNull(val, "expected null as value");
}
]
},
testGetSetSimpleValues: {
attributes : {
booleanValue : true, integerValue : 180 , stringValue : "Tesla"
},
test: [function(component){
//Try setting Boolean Values
$A.test.assertTrue(component.get("v.booleanValue"), "Boolean: Failed to initialize the value object");
component.set("v.booleanValue", false);
this.assertChangeEvent(component, false)
$A.test.assertFalse(component.get("v.booleanValue"), "Boolean: Failed to get most recent value");
//Try setting Integer Values
$A.test.assertEquals(180, component.get("v.integerValue"), "Integer: Failed to initialize the value object");
component.set("v.integerValue", 789);
this.assertChangeEvent(component, 789)
$A.test.assertEquals(789, component.get("v.integerValue"), "Integer: Failed to get most recent value");
//Try setting String Values
$A.test.assertEquals("Tesla", component.get("v.stringValue"), "String: Failed to initialize the value object");
component.set("v.stringValue", "newString");
this.assertChangeEvent(component, "newString")
$A.test.assertEquals("newString", component.get("v.stringValue"), "String: Failed to get most recent value");
},function(component){
component.set("v.booleanValue", undefined);
this.assertChangeEvent(component, undefined)
$A.test.assertUndefined(component.get("v.booleanValue"), "expected undefined as value");
component.set("v.booleanValue", null);
this.assertChangeEvent(component, null)
$A.test.assertNull(component.get("v.booleanValue"), "expected null as value");
}]
},
//W-2251248
_testVerifyTypeChecking:{
attributes:{
integerValue : 180
},
test:function(component){
$A.test.assertEquals(180, component.get("v.integerValue"), "Integer: Failed to initialize the value object");
try{
//TODO: W-795089 & W-2251248
component.set("v.integerValue", "String");
$A.test.fail("Should have validation to check that a string cannot be assigned to integer attribute");
}catch(e){
}
}
}
})
| 40.247312
| 115
| 0.688752
|
6b24dc995099e1205b1a062969566ee56719c9bd
| 6,469
|
cpp
|
C++
|
CO2-Ampel/rtc.cpp
|
lrswss/co2ampel
|
0b100135be16b2deed420f5e8bc618478783c075
|
[
"Apache-2.0"
] | 2
|
2021-01-08T13:21:58.000Z
|
2021-01-08T18:38:58.000Z
|
CO2-Ampel/rtc.cpp
|
lrswss/co2ampel
|
0b100135be16b2deed420f5e8bc618478783c075
|
[
"Apache-2.0"
] | null | null | null |
CO2-Ampel/rtc.cpp
|
lrswss/co2ampel
|
0b100135be16b2deed420f5e8bc618478783c075
|
[
"Apache-2.0"
] | 1
|
2021-03-20T14:54:35.000Z
|
2021-03-20T14:54:35.000Z
|
/***************************************************************************
Copyright (c) 2020-2021 Lars Wessels
This file a part of the "CO2-Ampel" source code.
https://github.com/lrswss/co2ampel
Published under Apache License 2.0
***************************************************************************/
#include "rtc.h"
#include "led.h"
#include "logging.h"
#include "utils.h"
RTC_DS3231 rtc;
// setup the ntp udp client
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, 0);
// TimeZone Settings Details https://github.com/JChristensen/Timezone
TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120};
TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60};
Timezone CE(CEST, CET); // Frankfurt, Paris
bool rtcOK = false;
sysprefs_t settings;
uEEPROMLib rtceeprom(0x57);
// preset settings struct with defaults from config.h
static void setDefault(sysprefs_t *s) {
// an explicit memset is required to ensure zeroed padding
// bytes in struct which would otherwise break CRC
memset(s, 0, sizeof(*s));
s->scd30TempOffset = SCD30_TEMP_OFFSET;
s->co2MediumThreshold = CO2_MEDIUM_THRESHOLD;
s->co2HighThreshold = CO2_HIGH_THRESHOLD;
s->co2AlarmThreshold = CO2_ALARM_THRESHOLD;
s->co2ThresholdHysteresis = CO2_THRESHOLD_HYSTERESIS;
s->co2ReadingInterval = SCD30_INTERVAL_SECS;
s->co2MedianSamples = SCD30_NUM_SAMPLES_MEDIAN;
s->beginSleep = BEGIN_SLEEP_HOUR;
s->endSleep = END_SLEEP_HOUR;
s->loggingInterval = LOGGING_INTERVAL_SECS;
s->altitude = ALTITUDE_ABOVE_SEELEVEL;
s->medianFilter = true;
#ifdef ENABLE_NOOP
s->enableNOOP = true;
#endif
#ifdef ENABLE_AUTH
s->enableAuth = true;
#endif
#ifdef ENABLE_LOGGING
s->enableLogging = true;
#endif
#if defined(SETTINGS_USERNAME) && defined(SETTINGS_PASSWORD)
strncpy(s->authUsername, SETTINGS_USERNAME, sizeof(s->authUsername));
strncpy(s->authPassword, SETTINGS_PASSWORD, sizeof(s->authPassword));
#endif
s->crc = crc16((uint8_t *) s, offsetof(sysprefs_t, crc));
}
static bool printGeneralSettings(sysprefs_t *s) {
#ifdef SETTINGS_DEBUG
Serial.printf("scd30TempOffset: %d\n", s->scd30TempOffset);
Serial.printf("co2MediumThreshold: %d\n", s->co2MediumThreshold);
Serial.printf("co2HighThreshold: %d\n", s->co2HighThreshold);
Serial.printf("co2AlarmThreshold: %d\n", s->co2AlarmThreshold);
Serial.printf("co2ThresholdHysteresis: %d\n", s->co2ThresholdHysteresis);
Serial.printf("co2ReadingInterval: %d\n", s->co2ReadingInterval);
Serial.printf("co2MedianSamples: %d\n", s->co2MedianSamples);
Serial.printf("medianFilter: %d\n", s->medianFilter);
Serial.printf("enableNOOP: %d\n", s->enableNOOP);
Serial.printf("beginSleep: %d\n", s->beginSleep);
Serial.printf("endSleep: %d\n", s->endSleep);
Serial.printf("enableAuth: %d\n", s->enableAuth);
Serial.printf("authUsername: %s\n", s->authUsername);
Serial.printf("authPassword: %s\n", s->authPassword);
Serial.printf("enableLogging: %d\n", s->enableLogging);
Serial.printf("loggingInterval: %d\n", s->loggingInterval);
Serial.printf("altitude: %d\n", s->altitude);
Serial.printf("CRC: %d\n", s->crc);
#endif
return true;
}
void rtc_init() {
if (!rtc.begin()) {
Serial.println(F("Couldn't find RTC...system halted."));
logMsg("rtc error");
while (1) {
blink_leds(HALF_RING, RED, 500, 2, false);
delay(2000);
}
}
rtc.disable32K();
rtc_temperature();
blink_leds(SYSTEM_LEDS, GREEN, 100, 2, false);
rtcOK = true;
delay(1000);
}
void rtc_temperature() {
Serial.print(F("DS3231: temp("));
Serial.print(rtc.getTemperature(), 1);
Serial.println("C)");
}
// returns ptr to array with current time
char* getTimeString(bool showsecs) {
static char strTime[9]; // HH:MM:SS
uint32_t epochTime = 0;
DateTime now;
time_t t;
if (rtcOK) {
now = rtc.now();
epochTime = now.unixtime();
}
t = CE.toLocal(epochTime);
memset(strTime, 0, sizeof(strTime));
if (epochTime > 1605441600) { // 15.11.2020
if (showsecs)
sprintf(strTime, "%.2d:%.2d:%.2d", hour(t), minute(t), second(t));
else
sprintf(strTime, "%.2d:%.2d", hour(t), minute(t));
} else {
if (showsecs)
strncpy(strTime, "--:--:--", 8);
else
strncpy(strTime, "--:--", 5);
}
return strTime;
}
// returns ptr to array with current date
char* getDateString() {
static char strDate[11]; // DD.MM.YYYY
uint32_t epochTime = 0;
DateTime now;
time_t t;
if (rtcOK) {
now = rtc.now();
epochTime = now.unixtime();
}
t = CE.toLocal(epochTime);
if (epochTime > 1605441600) {
sprintf(strDate, "%.2d.%.2d.%4d", day(t), month(t), year(t));
} else {
strncpy(strDate, "--.--.----", 10);
}
return strDate;
}
// return current hour (local time)
int8_t getHourLocal() {
if (rtcOK) {
return hour(CE.toLocal(rtc.now().unixtime()));
} else {
return -1;
}
}
// start ntp client and update RTC
bool startNTPSync() {
Serial.print(F("Syncing RTC with NTP-Server..."));
timeClient.begin();
timeClient.forceUpdate(); // takes a while
if (timeClient.getEpochTime() > 1000) {
Serial.println(F("OK."));
rtc.adjust(DateTime(timeClient.getEpochTime()));
logMsg("ntp sync");
delay(1000);
return true;
} else {
Serial.println(F("failed!"));
return false;
}
}
void stopNTPSync() {
timeClient.end();
}
// read general device settings from DS3231 EEPROM
void loadGeneralSettings() {
sysprefs_t buf;
memset(&settings, 0, sizeof(settings));
setDefault(&settings); // set struct with defaults values from config.h
loadSettings(&settings, &buf, offsetof(sysprefs_t, crc), EEPROM_SYSTEM_PREFS_ADDR, "general settings");
printGeneralSettings(&settings);
}
// store general settings in DS3231 EEPROM
bool saveGeneralSettings() {
if (settings.crc) { // use an existing crc as flag for a valid settings struct
settings.crc = crc16((uint8_t *) &settings, offsetof(sysprefs_t, crc)); // to reflect changes (web ui)
return saveSettings(settings, EEPROM_SYSTEM_PREFS_ADDR, "general settings") && printGeneralSettings(&settings);
}
return false;
}
// reset general settings to default values and store them in EEPROM
bool resetGeneralSettings() {
Serial.println(F("Reset general settings."));
logMsg("reset general settings");
memset(&settings, 0, sizeof(settings));
setDefault(&settings);
return saveSettings(settings, EEPROM_SYSTEM_PREFS_ADDR, "general settings") && printGeneralSettings(&settings);
}
| 28.248908
| 115
| 0.671356
|
8338ff6510e86b42adc157e36410bce21a91a223
| 2,728
|
ts
|
TypeScript
|
src/sql/parts/queryPlan/queryPlan.ts
|
meonBot/azuredatastudio
|
5c3eb96ffc15e04993a1b60106c31fa2e2881717
|
[
"MIT"
] | 1
|
2019-01-13T23:01:07.000Z
|
2019-01-13T23:01:07.000Z
|
src/sql/parts/queryPlan/queryPlan.ts
|
meonBot/azuredatastudio
|
5c3eb96ffc15e04993a1b60106c31fa2e2881717
|
[
"MIT"
] | 5
|
2019-01-13T23:04:43.000Z
|
2022-03-28T07:27:08.000Z
|
src/sql/parts/queryPlan/queryPlan.ts
|
meonBot/azuredatastudio
|
5c3eb96ffc15e04993a1b60106c31fa2e2881717
|
[
"MIT"
] | 1
|
2020-10-30T02:12:49.000Z
|
2020-10-30T02:12:49.000Z
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as QP from 'html-query-plan';
import { IPanelView, IPanelTab } from 'sql/base/browser/ui/panel/panel';
import { Dimension } from 'vs/base/browser/dom';
import { localize } from 'vs/nls';
import { Builder } from 'vs/base/browser/builder';
import { dispose, Disposable } from 'vs/base/common/lifecycle';
export class QueryPlanState {
xml: string;
dispose() {
}
}
export class QueryPlanTab implements IPanelTab {
public readonly title = localize('queryPlanTitle', 'Query Plan');
public readonly identifier = 'QueryPlanTab';
public readonly view: QueryPlanView;
constructor() {
this.view = new QueryPlanView();
}
public dispose() {
dispose(this.view);
}
public clear() {
this.view.clear();
}
}
export class QueryPlanView implements IPanelView {
private qp: QueryPlan;
private xml: string;
private container = document.createElement('div');
private _state: QueryPlanState;
public render(container: HTMLElement): void {
if (!this.qp) {
this.qp = new QueryPlan(this.container);
if (this.xml) {
this.qp.xml = this.xml;
}
}
container.appendChild(this.container);
this.container.style.overflow = 'scroll';
}
dispose() {
this.container.remove();
this.qp = undefined;
this.container = undefined;
}
public layout(dimension: Dimension): void {
this.container.style.width = dimension.width + 'px';
this.container.style.height = dimension.height + 'px';
}
public clear() {
if (this.qp) {
this.qp.xml = undefined;
}
}
public showPlan(xml: string) {
if (this.qp) {
this.qp.xml = xml;
} else {
this.xml = xml;
}
if (this.state) {
this.state.xml = xml;
}
}
public set state(val: QueryPlanState) {
this._state = val;
if (this.state.xml) {
this.showPlan(this.state.xml);
}
}
public get state(): QueryPlanState {
return this._state;
}
}
export class QueryPlan {
private _xml: string;
constructor(private container: HTMLElement) {
}
public set xml(xml: string) {
this._xml = xml;
new Builder(this.container).empty();
if (this.xml) {
QP.showPlan(this.container, this._xml, {
jsTooltips: false
});
(<any>this.container.querySelectorAll('div.qp-tt')).forEach(toolTip => {
toolTip.classList.add('monaco-editor');
toolTip.classList.add('monaco-editor-hover');
});
}
}
public get xml(): string {
return this._xml;
}
}
| 22.545455
| 96
| 0.630132
|
a33d7acfa8848315be1009be373da4ca37f90f53
| 5,098
|
java
|
Java
|
Bluetooth/Bluetooth_lib/src/main/java/com/ramimartin/multibluetooth/activity/BluetoothActivity.java
|
mingunpark/GITHUB-study
|
1e7e45b88b80e88a021f3a7abe986fc6dc53d9bb
|
[
"Beerware"
] | null | null | null |
Bluetooth/Bluetooth_lib/src/main/java/com/ramimartin/multibluetooth/activity/BluetoothActivity.java
|
mingunpark/GITHUB-study
|
1e7e45b88b80e88a021f3a7abe986fc6dc53d9bb
|
[
"Beerware"
] | null | null | null |
Bluetooth/Bluetooth_lib/src/main/java/com/ramimartin/multibluetooth/activity/BluetoothActivity.java
|
mingunpark/GITHUB-study
|
1e7e45b88b80e88a021f3a7abe986fc6dc53d9bb
|
[
"Beerware"
] | null | null | null |
package com.ramimartin.multibluetooth.activity;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import com.ramimartin.multibluetooth.bluetooth.mananger.BluetoothManager;
import com.ramimartin.multibluetooth.bus.BluetoothCommunicator;
import com.ramimartin.multibluetooth.bus.BondedDevice;
import com.ramimartin.multibluetooth.bus.ClientConnectionFail;
import com.ramimartin.multibluetooth.bus.ClientConnectionSuccess;
import com.ramimartin.multibluetooth.bus.ServeurConnectionFail;
import com.ramimartin.multibluetooth.bus.ServeurConnectionSuccess;
import de.greenrobot.event.EventBus;
/**
* Created by Rami MARTIN on 13/04/2014.
*/
public abstract class BluetoothActivity extends Activity {
protected BluetoothManager mBluetoothManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBluetoothManager = new BluetoothManager(this);
checkBluetoothAviability();
}
@Override
protected void onStart() {
super.onStart();
if(!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
mBluetoothManager.setNbrClientMax(myNbrClientMax());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
closeAllConnexion();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BluetoothManager.REQUEST_DISCOVERABLE_CODE) {
if (resultCode == BluetoothManager.BLUETOOTH_REQUEST_REFUSED) {
} else if (resultCode == BluetoothManager.BLUETOOTH_REQUEST_ACCEPTED) {
onBluetoothStartDiscovery();
} else {
}
}
}
public void closeAllConnexion(){
mBluetoothManager.closeAllConnexion();
}
public void checkBluetoothAviability(){
if(!mBluetoothManager.checkBluetoothAviability()){
onBluetoothNotAviable();
}
}
public void setTimeDiscoverable(int timeInSec){
mBluetoothManager.setTimeDiscoverable(timeInSec);
}
public void startDiscovery(){
mBluetoothManager.startDiscovery();
}
public void scanAllBluetoothDevice(){
mBluetoothManager.scanAllBluetoothDevice();
}
public void disconnectClient(){
mBluetoothManager.disconnectClient();
}
public void disconnectServer(){
mBluetoothManager.disconnectServer();
}
public void createServeur(String address){
mBluetoothManager.createServeur(address);
}
public void selectServerMode(){
mBluetoothManager.selectServerMode();
}
public void selectClientMode(){
mBluetoothManager.selectClientMode();
}
public BluetoothManager.TypeBluetooth getTypeBluetooth(){
return mBluetoothManager.mType;
}
public BluetoothManager.TypeBluetooth getBluetoothMode(){
return mBluetoothManager.mType;
}
public void createClient(String addressMac){
mBluetoothManager.createClient(addressMac);
}
public void sendMessage(String message){
mBluetoothManager.sendMessage(message);
}
public boolean isConnected(){
return mBluetoothManager.isConnected;
}
public abstract int myNbrClientMax();
public abstract void onBluetoothDeviceFound(BluetoothDevice device);
public abstract void onClientConnectionSuccess();
public abstract void onClientConnectionFail();
public abstract void onServeurConnectionSuccess();
public abstract void onServeurConnectionFail();
public abstract void onBluetoothStartDiscovery();
public abstract void onBluetoothCommunicator(String messageReceive);
public abstract void onBluetoothNotAviable();
public void onEventMainThread(BluetoothDevice device){
onBluetoothDeviceFound(device);
createServeur(device.getAddress());
}
public void onEventMainThread(ClientConnectionSuccess event){
mBluetoothManager.isConnected = true;
onClientConnectionSuccess();
}
public void onEventMainThread(ClientConnectionFail event){
mBluetoothManager.isConnected = false;
onClientConnectionFail();
}
public void onEventMainThread(ServeurConnectionSuccess event){
mBluetoothManager.isConnected = true;
mBluetoothManager.onServerConnectionSuccess(event.mClientAdressConnected);
onServeurConnectionSuccess();
}
public void onEventMainThread(ServeurConnectionFail event){
mBluetoothManager.onServerConnectionFailed(event.mClientAdressConnectionFail);
onServeurConnectionFail();
}
public void onEventMainThread(BluetoothCommunicator event){
onBluetoothCommunicator(event.mMessageReceive);
}
public void onEventMainThread(BondedDevice event){
//mBluetoothManager.sendMessage("BondedDevice");
}
}
| 30.89697
| 86
| 0.724598
|
4407a782738ce245647a8597d2606c89bac051bb
| 131
|
py
|
Python
|
packages/PIPS/validation/Top-level/spaces01.py
|
DVSR1966/par4all
|
86b33ca9da736e832b568c5637a2381f360f1996
|
[
"MIT"
] | 51
|
2015-01-31T01:51:39.000Z
|
2022-02-18T02:01:50.000Z
|
packages/PIPS/validation/Top-level/spaces01.py
|
DVSR1966/par4all
|
86b33ca9da736e832b568c5637a2381f360f1996
|
[
"MIT"
] | 7
|
2017-05-29T09:29:00.000Z
|
2019-03-11T16:01:39.000Z
|
packages/PIPS/validation/Top-level/spaces01.py
|
DVSR1966/par4all
|
86b33ca9da736e832b568c5637a2381f360f1996
|
[
"MIT"
] | 12
|
2015-03-26T08:05:38.000Z
|
2022-02-18T02:01:51.000Z
|
from pyps import workspace
workspace.delete("bb")
workspace("a a a /spaces01.c",name="bb",recoverInclude=False).fun.main.display()
| 32.75
| 80
| 0.763359
|
cf066da52586fb950f04cf1ff906e72cde817058
| 149
|
php
|
PHP
|
app/Salesfly/Entities/Year.php
|
godsaveme/salesfly-gohard
|
5a2d150206b7fe75ef70707de5e24b3ce1862cc1
|
[
"MIT"
] | null | null | null |
app/Salesfly/Entities/Year.php
|
godsaveme/salesfly-gohard
|
5a2d150206b7fe75ef70707de5e24b3ce1862cc1
|
[
"MIT"
] | null | null | null |
app/Salesfly/Entities/Year.php
|
godsaveme/salesfly-gohard
|
5a2d150206b7fe75ef70707de5e24b3ce1862cc1
|
[
"MIT"
] | null | null | null |
<?php
namespace Salesfly\Salesfly\Entities;
class Year extends \Eloquent {
protected $table = 'years';
protected $fillable = ['year'];
}
| 14.9
| 37
| 0.671141
|
79beedbea03ba93738122287ddc03ea93c909f14
| 322
|
php
|
PHP
|
resources/views/pages/artikel.blade.php
|
rabbanisidiq14/corona
|
a9f17eacb08e01c09621717ed4511af45e39235d
|
[
"MIT"
] | null | null | null |
resources/views/pages/artikel.blade.php
|
rabbanisidiq14/corona
|
a9f17eacb08e01c09621717ed4511af45e39235d
|
[
"MIT"
] | 4
|
2021-02-02T19:21:21.000Z
|
2022-02-27T06:10:14.000Z
|
resources/views/pages/artikel.blade.php
|
rabbanisidiq14/corona
|
a9f17eacb08e01c09621717ed4511af45e39235d
|
[
"MIT"
] | null | null | null |
@extends('assets.app')
@section('title')
{{$konten[0]->judul}}
@endsection
@section('content')
<body class="artikel1">
<div class="row justify-content-center">
<h2>{{$konten[0]->judul}}</h2>
</div>
<div class="card">
<div class="card-body">
{{$konten[0]->konten}}
</div>
</div>
</body>
@endsection
| 16.1
| 40
| 0.596273
|
ed447605bad24996264f9b36b00bc764e1df74b4
| 469
|
h
|
C
|
context.h
|
cventeic/scalable-log-trace
|
71a2cde2af4052c57b1553b00204d6cf6c287c5b
|
[
"MIT"
] | 4
|
2017-02-22T14:01:58.000Z
|
2021-11-15T12:38:54.000Z
|
context.h
|
cventeic/scalable-log-trace
|
71a2cde2af4052c57b1553b00204d6cf6c287c5b
|
[
"MIT"
] | null | null | null |
context.h
|
cventeic/scalable-log-trace
|
71a2cde2af4052c57b1553b00204d6cf6c287c5b
|
[
"MIT"
] | null | null | null |
#include <netinet/in.h>
// global socket to communicate with trace server
struct log_context {
char *prog_name;
uint64_t prog_hash;
int pub_fd;
struct sockaddr_in pub_addr;
int pub_send_buf_size;
int publish_context_ready;
int pub_sendmsg_flags;
int discovery_fd;
int discovery_context_ready;
int writeable_previous;
int msg_sent;
int msg_bytes_sent;
int payload_bytes_sent;
int verbose;
};
struct log_context * get_log_context();
| 17.37037
| 49
| 0.75693
|
8358285b37efd05f441688fc863057d365fdfb1d
| 1,397
|
ts
|
TypeScript
|
src/app/app.routing.module.ts
|
devzom/angular-learn
|
afb4d68f16faf057d3bb9e4b89c034f0c57691e7
|
[
"MIT"
] | null | null | null |
src/app/app.routing.module.ts
|
devzom/angular-learn
|
afb4d68f16faf057d3bb9e4b89c034f0c57691e7
|
[
"MIT"
] | null | null | null |
src/app/app.routing.module.ts
|
devzom/angular-learn
|
afb4d68f16faf057d3bb9e4b89c034f0c57691e7
|
[
"MIT"
] | null | null | null |
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {HomepageComponent} from "./views/homepage/homepage.component";
import {PageNotFoundComponent} from "./views/page-not-found/page-not-found.component";
import {CheckoutGuard} from "./guards/checkout.guard";
import {AuthGuard} from "./guards/auth.guard";
import {SignupComponent} from "./auth/signup/signup.component";
import {SigninComponent} from "./auth/signin/signin.component";
import {ProfileComponent} from "./profile/profile.component";
const routes: Routes = [
{path: '', component: HomepageComponent},
{
path: 'vehicles',
loadChildren: () => import('./vehicles/vehicles-routing.module').then(m => m.VehiclesRoutingModule),
},
{
path: 'checkout',
loadChildren: () => import('./checkout/checkout.module').then(m => m.CheckoutModule),
canLoad: [CheckoutGuard]
},
{path: 'register', component: SignupComponent},
{path: 'login', component: SigninComponent},
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard],
},
{path: '**', component: PageNotFoundComponent}, // Wildcard route for a 404 page
]; // sets up routes constant where you define your routes
// configures NgModule imports and exports
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
| 34.073171
| 104
| 0.711525
|
5e5c7e8e608beaa6cfdc8cbf7d24182b827f23ee
| 8,708
|
lua
|
Lua
|
Spellshock2/Data/Scripts/Pyroblast Ability Server.lua
|
Core-Team-META/Game-Spellshock-2
|
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
|
[
"Apache-2.0"
] | 1
|
2021-11-02T16:01:38.000Z
|
2021-11-02T16:01:38.000Z
|
Spellshock2/Data/Scripts/Pyroblast Ability Server.lua
|
Core-Team-META/Game-Spellshock-2
|
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
|
[
"Apache-2.0"
] | null | null | null |
Spellshock2/Data/Scripts/Pyroblast Ability Server.lua
|
Core-Team-META/Game-Spellshock-2
|
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
|
[
"Apache-2.0"
] | 1
|
2021-11-02T17:17:10.000Z
|
2021-11-02T17:17:10.000Z
|
-- Author: Ooccoo - (https://www.coregames.com/user/a136c0d1d9454d539c9932354198fc29)
-- Date: 04/02/2021
-- Version: 0.0.1
--===========================================================================================
-- Module dependencies
local MODULE = require(script:GetCustomProperty("ModuleManager"))
function COMBAT()
return MODULE:Get("standardcombo.Combat.Wrap")
end
local API_SE = require(script:GetCustomProperty("APIStatusEffects"))
local function META_AP()
return _G["Meta.Ability.Progression"]
end
local Equipment = script:GetCustomProperty("Equipment"):WaitForObject()
local SpecialAbility = script:GetCustomProperty("SpecialAbility"):WaitForObject()
local ProjectileSpeed = script:GetCustomProperty("ProjectileSpeed")
local DEFAULT_DamageAmount = script:GetCustomProperty("DamageAmount")
local DEFAULT_DamageRadius = script:GetCustomProperty("DamageRadius")
local DEFAULT_TargetingRange = script:GetCustomProperty("TargetingRange")
local HOMING_ACCELERATION = 50000
local EventListeners = {}
local ProjectileImpactEvent = nil
local BindingPressedEvent = nil
local CurrentTarget = nil
local CurrentProjectile = nil
local MoveTarget = false
local PlayerVFX = nil
function OnProjectileImpact(projectile, other, hitResult)
Reset(false)
if SpecialAbility:GetCurrentPhase() == AbilityPhase.READY then return end
if not SpecialAbility.owner or not Object.IsValid(SpecialAbility.owner) then
return
end
META_AP().SpawnAsset(PlayerVFX.Impact, {position = projectile:GetWorldPosition()})
-- Damage enemies
local DamageRadius =
META_AP().GetAbilityMod(
SpecialAbility.owner,
META_AP().R,
"mod2",
DEFAULT_DamageRadius,
SpecialAbility.name .. ": Radius"
)
local nearbyEnemies =
Game.FindPlayersInSphere(
projectile:GetWorldPosition(),
DamageRadius,
{ignoreTeams = SpecialAbility.owner.team, ignoreDead = true}
)
CoreDebug.DrawSphere(projectile:GetWorldPosition(), DamageRadius, {duration = 5})
for _, enemy in pairs(nearbyEnemies) do
local dmg = Damage.New()
local player = SpecialAbility.owner
dmg.amount =
META_AP().GetAbilityMod(
player,
META_AP().R,
"mod1",
DEFAULT_DamageAmount,
SpecialAbility.name .. ": Damage Amount"
)
dmg.reason = DamageReason.COMBAT
dmg.sourcePlayer = SpecialAbility.owner
dmg.sourceAbility = SpecialAbility
local directionVector = enemy:GetWorldPosition() - SpecialAbility.owner:GetWorldPosition()
directionVector = directionVector / directionVector.size
directionVector.z = 0.7
--#TODO Fix the magic number
local impulseVector = directionVector * META_AP().GetAbilityMod(SpecialAbility.owner, META_AP().R, "mod4", 100000, SpecialAbility.name .. ": Enemy Impulse")
local attackData = {
object = enemy,
damage = dmg,
source = dmg.sourcePlayer,
position = nil,
rotation = nil,
tags = {id = "Mage_R"}
}
COMBAT().ApplyDamage(attackData)
enemy:ResetVelocity()
enemy:AddImpulse(impulseVector)
end
end
function OnLifespanEnded(thisProjectile)
Reset(false)
end
function OnSpecialAbilityExecute(thisAbility)
Reset(true)
-- Spawn a new target object where the camera is looking
local viewRotation = thisAbility.owner:GetViewWorldRotation()
local viewPosition = thisAbility.owner:GetViewWorldPosition()
local targetingRange = 100000
local endPoint = viewPosition + (viewRotation * Vector3.FORWARD * targetingRange)
local hitResult = World.Raycast(viewPosition, endPoint, {ignoreTeams = thisAbility.owner.team})
if hitResult then
endPoint = hitResult:GetImpactPosition()
end
CurrentTarget = META_AP().SpawnAsset(PlayerVFX.Target)
-- Spawn a new projectile
local playerPosition = thisAbility.owner:GetWorldPosition()
local playerRotation = thisAbility.owner:GetLookWorldRotation()
local forwardVector = playerRotation * Vector3.FORWARD
local spawnPosition = playerPosition + Vector3.New(0, 0, 200) --+ (forwardVector * 20)
spawnPosition.z = spawnPosition.z + 50
local differenceVector = endPoint - spawnPosition
local directionVector = differenceVector:GetNormalized()
CurrentProjectile = Projectile.Spawn(PlayerVFX.Projectile, spawnPosition, directionVector)
--local distanceVector = CurrentTarget:GetWorldPosition() - CurrentProjectile:GetWorldPosition()
CurrentProjectile.owner = thisAbility.owner
CurrentProjectile.speed = ProjectileSpeed
CurrentProjectile.lifeSpan = 20 --distanceVector.size / ProjectileSpeed + 1.5
CurrentProjectile.capsuleLength = 50
CurrentProjectile.capsuleRadius = 50
CurrentProjectile.gravityScale = 0
CurrentProjectile.homingAcceleration = HOMING_ACCELERATION
--CurrentProjectile.drag = -0.5
EventListeners["impactEvent"] = CurrentProjectile.impactEvent:Connect(OnProjectileImpact)
EventListeners["bindingPressedEvent"] = thisAbility.owner.bindingPressedEvent:Connect(OnBindingPressed)
EventListeners["bindingReleasedEvent"] = thisAbility.owner.bindingReleasedEvent:Connect(OnBindingReleased)
EventListeners["lifeSpanEndedEvent"] = CurrentProjectile.lifeSpanEndedEvent:Connect(OnLifespanEnded)
end
function SetCooldownOverride(value)
SpecialAbility:SetNetworkedCustomProperty("CooldownOverride", value)
end
function OnSpecialAbilityCooldown(thisAbility)
local Cooldown = META_AP().GetAbilityMod(thisAbility.owner, META_AP().R, "mod6", 90, thisAbility.name..": Cooldown")
SetCooldownOverride(Cooldown)
Task.Spawn(function ()
if Object.IsValid(thisAbility) and thisAbility:GetCurrentPhase() == AbilityPhase.COOLDOWN then
thisAbility:AdvancePhase()
end
end, Cooldown)
end
function OnBindingPressed(player, binding)
if binding == "ability_secondary" then
MoveTarget = true
end
end
function OnBindingReleased(player, binding)
if binding == "ability_secondary" then
MoveTarget = false
end
end
function Reset(hardReset)
if EventListeners["impactEvent"] then
EventListeners["impactEvent"]:Disconnect()
EventListeners["impactEvent"] = nil
end
if EventListeners["bindingPressedEvent"] then
EventListeners["bindingPressedEvent"]:Disconnect()
EventListeners["bindingPressedEvent"] = nil
end
if EventListeners["bindingReleasedEvent"] then
EventListeners["bindingReleasedEvent"]:Disconnect()
EventListeners["bindingReleasedEvent"] = nil
end
if EventListeners["lifeSpanEndedEvent"] then
EventListeners["lifeSpanEndedEvent"]:Disconnect()
EventListeners["lifeSpanEndedEvent"] = nil
end
if Object.IsValid(CurrentProjectile) and hardReset then
CurrentProjectile:Destroy()
end
if Object.IsValid(CurrentTarget) then
CurrentTarget:Destroy()
end
MoveTarget = false
end
function OnPlayerDied(player, _)
Reset(false)
end
function OnPlayerRespawn(player)
Reset(false)
end
function OnEquip(equipment, player)
EventListeners["diedEvent"] = player.diedEvent:Connect(OnPlayerDied)
EventListeners["respawnedEvent"] = player.respawnedEvent:Connect(OnPlayerRespawn)
EventListeners["cooldownEvent"] = SpecialAbility.cooldownEvent:Connect( OnSpecialAbilityCooldown )
local skin = Equipment:GetCustomProperty("RID") or 1
PlayerVFX = META_AP().VFX.GetCosmeticMuid(player, META_AP().MAGE, player.team, skin, META_AP().R)
end
function OnUnequip(equipment, player)
for _, listener in pairs(EventListeners) do
listener:Disconnect()
end
EventListeners = {}
Reset(true)
end
Equipment.equippedEvent:Connect(OnEquip)
Equipment.unequippedEvent:Connect(OnUnequip)
function Tick(deltaTime)
if Object.IsValid(CurrentProjectile) and SpecialAbility.owner
and Object.IsValid(SpecialAbility.owner) then
if MoveTarget and CurrentTarget and Object.IsValid(CurrentTarget) then
local viewRotation = CurrentProjectile.owner:GetViewWorldRotation()
local viewPosition = CurrentProjectile.owner:GetViewWorldPosition()
local targetingRange = META_AP().GetAbilityMod(SpecialAbility.owner, META_AP().R, "mod3", DEFAULT_TargetingRange, SpecialAbility.name .. ": Targeting Range")
local projectileDistance = (CurrentProjectile:GetWorldPosition() - viewPosition).size
targetingRange = math.min(targetingRange, projectileDistance + 1000)
local endPoint = viewPosition + (viewRotation * Vector3.FORWARD * targetingRange)
local hitResult = World.Raycast(viewPosition, endPoint, {ignoreTeams = CurrentProjectile.owner.team})
if hitResult then
endPoint = hitResult:GetImpactPosition()
end
CurrentTarget:SetWorldPosition(endPoint)
CurrentProjectile.homingTarget = CurrentTarget
CurrentProjectile.homingAcceleration = HOMING_ACCELERATION
CurrentProjectile.drag = 10
else
-- Disable homing
CurrentProjectile.homingTarget = nil
CurrentProjectile.homingAcceleration = 0
CurrentProjectile.speed = ProjectileSpeed
CurrentProjectile.drag = -0.1
end
end
end
SpecialAbility.executeEvent:Connect(OnSpecialAbilityExecute)
| 33.363985
| 160
| 0.782154
|
effabe715c4ade3176706322a863866df6185d2d
| 3,898
|
lua
|
Lua
|
test/functional/shell/viml_system_spec.lua
|
bobtwinkles/neovim
|
5e65e3eae079d4765124ce791ce79649444ca403
|
[
"Vim"
] | null | null | null |
test/functional/shell/viml_system_spec.lua
|
bobtwinkles/neovim
|
5e65e3eae079d4765124ce791ce79649444ca403
|
[
"Vim"
] | null | null | null |
test/functional/shell/viml_system_spec.lua
|
bobtwinkles/neovim
|
5e65e3eae079d4765124ce791ce79649444ca403
|
[
"Vim"
] | null | null | null |
-- Specs for
-- - `system()`
-- - `systemlist()`
local helpers = require('test.functional.helpers')
local eq, clear, eval, feed =
helpers.eq, helpers.clear, helpers.eval, helpers.feed
local function create_file_with_nuls(name)
return function()
feed('ipart1<C-V>000part2<C-V>000part3<ESC>:w '..name..'<CR>')
end
end
local function delete_file(name)
return function()
eval("delete('"..name.."')")
end
end
describe('system()', function()
before_each(clear)
describe('passing no input', function()
it('returns the program output', function()
eq("echoed", eval('system("echo -n echoed")'))
end)
end)
describe('passing input', function()
it('returns the program output', function()
eq("input", eval('system("cat -", "input")'))
end)
end)
describe('passing number as input', function()
it('stringifies the input', function()
eq('1', eval('system("cat", 1)'))
end)
end)
describe('with output containing NULs', function()
local fname = 'Xtest'
setup(create_file_with_nuls(fname))
teardown(delete_file(fname))
it('replaces NULs by SOH characters', function()
eq('part1\001part2\001part3\n', eval('system("cat '..fname..'")'))
end)
end)
describe('passing list as input', function()
it('joins list items with linefeed characters', function()
eq('line1\nline2\nline3',
eval("system('cat -', ['line1', 'line2', 'line3'])"))
end)
-- Notice that NULs are converted to SOH when the data is read back. This
-- is inconsistent and is a good reason for the existence of the
-- `systemlist()` function, where input and output map to the same
-- characters(see the following tests with `systemlist()` below)
describe('with linefeed characters inside list items', function()
it('converts linefeed characters to NULs', function()
eq('l1\001p2\nline2\001a\001b\nl3',
eval([[system('cat -', ["l1\np2", "line2\na\nb", 'l3'])]]))
end)
end)
describe('with leading/trailing whitespace characters on items', function()
it('preserves whitespace, replacing linefeeds by NULs', function()
eq('line \nline2\001\n\001line3',
eval([[system('cat -', ['line ', "line2\n", "\nline3"])]]))
end)
end)
end)
end)
describe('systemlist()', function()
-- behavior is similar to `system()` but it returns a list instead of a
-- string.
before_each(clear)
describe('passing string with linefeed characters as input', function()
it('splits the output on linefeed characters', function()
eq({'abc', 'def', 'ghi'}, eval([[systemlist("cat -", "abc\ndef\nghi")]]))
end)
end)
describe('with output containing NULs', function()
local fname = 'Xtest'
setup(create_file_with_nuls(fname))
teardown(delete_file(fname))
it('replaces NULs by newline characters', function()
eq({'part1\npart2\npart3'}, eval('systemlist("cat '..fname..'")'))
end)
end)
describe('passing list as input', function()
it('joins list items with linefeed characters', function()
eq({'line1', 'line2', 'line3'},
eval("systemlist('cat -', ['line1', 'line2', 'line3'])"))
end)
-- Unlike `system()` which uses SOH to represent NULs, with `systemlist()`
-- input and ouput are the same
describe('with linefeed characters inside list items', function()
it('converts linefeed characters to NULs', function()
eq({'l1\np2', 'line2\na\nb', 'l3'},
eval([[systemlist('cat -', ["l1\np2", "line2\na\nb", 'l3'])]]))
end)
end)
describe('with leading/trailing whitespace characters on items', function()
it('preserves whitespace, replacing linefeeds by NULs', function()
eq({'line ', 'line2\n', '\nline3'},
eval([[systemlist('cat -', ['line ', "line2\n", "\nline3"])]]))
end)
end)
end)
end)
| 30.936508
| 79
| 0.629041
|
127b29afca2def0f3955bb3cecb89305203c90e3
| 7,946
|
cs
|
C#
|
WPFSKillTree/ViewModels/MetroMessageBoxViewModel.cs
|
nikibobi/PoESkillTree
|
061d0eb01d161a0ea1b3eab3126dea2146dacf67
|
[
"MIT"
] | 3
|
2021-05-18T12:17:01.000Z
|
2021-05-18T23:46:01.000Z
|
WPFSKillTree/ViewModels/MetroMessageBoxViewModel.cs
|
nikibobi/PoESkillTree
|
061d0eb01d161a0ea1b3eab3126dea2146dacf67
|
[
"MIT"
] | null | null | null |
WPFSKillTree/ViewModels/MetroMessageBoxViewModel.cs
|
nikibobi/PoESkillTree
|
061d0eb01d161a0ea1b3eab3126dea2146dacf67
|
[
"MIT"
] | null | null | null |
using POESKillTree.Model;
using POESKillTree.Views;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace POESKillTree.ViewModels
{
public class MetroMessageBoxViewModel : Notifier, INotifyPropertyChanged
{
#region fields
private string _title;
private string _message;
private MessageBoxButton _buttons;
private MessageBoxImage _image;
private ImageSource _imageSource;
private MetroMessageBoxView _view;
private bool _isYesVisible;
private bool _isNoVisible;
private bool _isOKVisible;
private bool _isCancelVisible;
private bool _isYesDefault;
private bool _isNoDefault;
private bool _isOKDefault;
private bool _isCancelDefault;
private ICommand _yesCommand;
private ICommand _noCommand;
private ICommand _okCommand;
private ICommand _cancelCommand;
private ICommand _escapeCommand;
private ICommand _closeCommand;
#endregion
public MetroMessageBoxViewModel(MetroMessageBoxView mmbView, string message, string title, MessageBoxButton buttons, ImageSource imageSource)
{
_view = mmbView;
Message = message;
BoxTitle = title;
Buttons = buttons;
NotificationImageSource = imageSource;
}
#region properties
public MessageBoxButton Buttons
{
get { return _buttons; }
set
{
_buttons = value;
switch (_buttons)
{
case MessageBoxButton.YesNo:
IsYesVisible = IsNoVisible = true;
IsYesDefault = true;
break;
case MessageBoxButton.YesNoCancel:
IsYesVisible = IsNoVisible = IsCancelVisible = true;
IsYesDefault = true;
break;
case MessageBoxButton.OK:
IsOKVisible = true;
IsOKDefault = true;
break;
case MessageBoxButton.OKCancel:
IsOKVisible = IsCancelVisible = true;
IsOKDefault = true;
break;
}
}
}
#region commands
public ICommand YesCommand
{
get
{
if (_yesCommand == null)
{
_yesCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.Yes;
_view.Close();
});
}
return _yesCommand;
}
}
public ICommand NoCommand
{
get
{
if (_noCommand == null)
{
_noCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.No;
_view.Close();
});
}
return _noCommand;
}
}
public ICommand CancelCommand
{
get
{
if (_cancelCommand == null)
{
_cancelCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.Cancel;
_view.Close();
});
}
return _cancelCommand;
}
}
public ICommand OKCommand
{
get
{
if (_okCommand == null)
{
_okCommand = new RelayCommand(args =>
{
this.Result = MessageBoxResult.OK;
_view.Close();
});
}
return _okCommand;
}
}
public ICommand EscapeCommand
{
get
{
if (_escapeCommand == null)
{
_escapeCommand = new RelayCommand(args =>
{
this.Result = IsCancelVisible ? MessageBoxResult.Cancel :
(IsNoVisible ? MessageBoxResult.No : MessageBoxResult.OK);
_view.Close();
});
}
return _escapeCommand;
}
}
#endregion
#region elements content
public string Message
{
get { return _message; }
set
{
_message = value;
NotifyPropertyChanged("Message");
}
}
public string BoxTitle
{
get { return _title; }
set
{
_title = value;
NotifyPropertyChanged("BoxTitle");
}
}
public MessageBoxResult Result
{
get;
set;
}
public ImageSource NotificationImageSource
{
get { return _imageSource; }
set
{
_imageSource = value;
NotifyPropertyChanged("NotificationImageSource");
}
}
public string ImageColumnWidth
{
get { return _imageSource == null ? "0" : "Auto"; }
}
#endregion
#region buttons visibility
public bool IsYesVisible
{
get { return _isYesVisible; }
set
{
_isYesVisible = value;
NotifyPropertyChanged("IsYesVisible");
}
}
public bool IsNoVisible
{
get { return _isNoVisible; }
set
{
_isNoVisible = value;
NotifyPropertyChanged("IsNoVisible");
}
}
public bool IsOKVisible
{
get { return _isOKVisible; }
set
{
_isOKVisible = value;
NotifyPropertyChanged("IsOKVisible");
}
}
public bool IsCancelVisible
{
get { return _isCancelVisible; }
set
{
_isCancelVisible = value;
NotifyPropertyChanged("IsCancelVisible");
}
}
#endregion
#region buttons defaults
public bool IsYesDefault
{
get { return _isYesDefault; }
set
{
_isYesDefault = value;
NotifyPropertyChanged("IsYesDefault");
}
}
public bool IsNoDefault
{
get { return _isNoDefault; }
set
{
_isNoDefault = value;
NotifyPropertyChanged("IsNoDefault");
}
}
public bool IsOKDefault
{
get { return _isOKDefault; }
set
{
_isOKDefault = value;
NotifyPropertyChanged("IsOKDefault");
}
}
public bool IsCancelDefault
{
get { return _isCancelDefault; }
set
{
_isCancelDefault = value;
NotifyPropertyChanged("IsCancelDefault");
}
}
#endregion
#endregion
}
}
| 28.177305
| 150
| 0.427259
|
ef690cfe0aba3cacf54a12e7004dd056f4041aec
| 3,647
|
h
|
C
|
lib/Basics/Result.h
|
Deckhandfirststar01/arangodb
|
a8c079252f9c7127ef6860f5ad46ec38055669ce
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
lib/Basics/Result.h
|
Deckhandfirststar01/arangodb
|
a8c079252f9c7127ef6860f5ad46ec38055669ce
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
lib/Basics/Result.h
|
Deckhandfirststar01/arangodb
|
a8c079252f9c7127ef6860f5ad46ec38055669ce
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1
|
2021-07-12T06:29:34.000Z
|
2021-07-12T06:29:34.000Z
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGODB_BASICS_RESULT_H
#define ARANGODB_BASICS_RESULT_H 1
#include "Basics/Common.h"
namespace arangodb {
class Result {
public:
Result() : _errorNumber(TRI_ERROR_NO_ERROR) {}
Result(int errorNumber)
: _errorNumber(errorNumber){
if (errorNumber != TRI_ERROR_NO_ERROR) {
_errorMessage = TRI_errno_string(errorNumber);
}
}
Result(int errorNumber, std::string const& errorMessage)
: _errorNumber(errorNumber), _errorMessage(errorMessage) {}
Result(int errorNumber, std::string&& errorMessage)
: _errorNumber(errorNumber), _errorMessage(std::move(errorMessage)) {}
// copy
Result(Result const& other)
: _errorNumber(other._errorNumber),
_errorMessage(other._errorMessage) {}
Result& operator=(Result const& other) {
_errorNumber = other._errorNumber;
_errorMessage = other._errorMessage;
return *this;
}
// move
Result(Result&& other) noexcept
: _errorNumber(other._errorNumber),
_errorMessage(std::move(other._errorMessage)) {}
Result& operator=(Result&& other) noexcept {
_errorNumber = other._errorNumber;
_errorMessage = std::move(other._errorMessage);
return *this;
}
virtual ~Result() {}
public:
bool ok() const { return _errorNumber == TRI_ERROR_NO_ERROR; }
bool fail() const { return !ok(); }
int errorNumber() const { return _errorNumber; }
bool is(int errorNumber) const { return _errorNumber == errorNumber; }
bool isNot(int errorNumber) const { return !is(errorNumber); }
Result& reset(int errorNumber = TRI_ERROR_NO_ERROR) {
_errorNumber = errorNumber;
if (errorNumber != TRI_ERROR_NO_ERROR) {
_errorMessage = TRI_errno_string(errorNumber);
} else {
_errorMessage.clear();
}
return *this;
}
Result& reset(int errorNumber, std::string const& errorMessage) {
_errorNumber = errorNumber;
_errorMessage = errorMessage;
return *this;
}
Result& reset(int errorNumber, std::string&& errorMessage) noexcept {
_errorNumber = errorNumber;
_errorMessage = std::move(errorMessage);
return *this;
}
Result& reset(Result const& other) {
_errorNumber = other._errorNumber;
_errorMessage = other._errorMessage;
return *this;
}
Result& reset(Result&& other) noexcept {
_errorNumber = other._errorNumber;
_errorMessage = std::move(other._errorMessage);
return *this;
}
// the default implementation is const, but sub-classes might
// really do more work to compute.
virtual std::string errorMessage() const& { return _errorMessage; }
virtual std::string errorMessage() && { return std::move(_errorMessage); }
protected:
int _errorNumber;
std::string _errorMessage;
};
}
#endif
| 28.944444
| 80
| 0.666575
|
f45419a18e02ff97adce89115983058960f93dc6
| 1,916
|
cs
|
C#
|
Alone in Space/Alone in Space/Particles/ParticleSource.cs
|
AleksandarDev/LD22AloneInSpace
|
bcc688b450d9279fe45decd223658dfc653c31f9
|
[
"MIT"
] | null | null | null |
Alone in Space/Alone in Space/Particles/ParticleSource.cs
|
AleksandarDev/LD22AloneInSpace
|
bcc688b450d9279fe45decd223658dfc653c31f9
|
[
"MIT"
] | null | null | null |
Alone in Space/Alone in Space/Particles/ParticleSource.cs
|
AleksandarDev/LD22AloneInSpace
|
bcc688b450d9279fe45decd223658dfc653c31f9
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using SquaredEngine.Diagnostics.Debug;
using SquaredEngine.Diagnostics.Log;
using System.Threading.Tasks;
namespace Alone_in_Space.Particles {
public class ParticleSource : ScreenObject {
public static Int32 MaxParticles = 100;
public Queue<Particle> deadParticles;
public List<Particle> liveParticles;
public Action<Particle> RandomizerMethod;
public ParticleSource(Game game)
: base(game) {
deadParticles = new Queue<Particle>(MaxParticles);
liveParticles = new List<Particle>(MaxParticles);
}
protected override void LoadContent() {
base.LoadContent();
}
public override void Update(GameTime gameTime) {
Parallel.ForEach(liveParticles, (particle) => {
particle.Update(gameTime);
});
for (int index = 0; index < liveParticles.Count; index++) {
if (!liveParticles[index].IsAlive) {
deadParticles.Enqueue(liveParticles[index]);
liveParticles.RemoveAt(index--);
}
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime) {
sb.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, null, null, null, null, ScreenTransform.Transform);
for (int index = liveParticles.Count - 1; index >= 0; index--) {
liveParticles[index].Draw(sb);
}
sb.End();
//base.Draw(gameTime);
}
public virtual void NewParticle() {
if (deadParticles.Count > 0) {
Particle particle = deadParticles.Dequeue();
RandomizerMethod(particle);
liveParticles.Add(particle);
}
}
}
}
| 26.985915
| 118
| 0.704071
|
ed0e76df566e1c781f3a5e95e6c2dff0e5f24246
| 3,889
|
c
|
C
|
Estructuras-de-Datos/Estructuras-lineales/queue/t_linked_queue/t_link_queue.c
|
DaniFuerte/Programaci-n-en-C
|
90b43ab172f41846f9f61ff2218b33c674b3cdac
|
[
"Apache-2.0"
] | null | null | null |
Estructuras-de-Datos/Estructuras-lineales/queue/t_linked_queue/t_link_queue.c
|
DaniFuerte/Programaci-n-en-C
|
90b43ab172f41846f9f61ff2218b33c674b3cdac
|
[
"Apache-2.0"
] | null | null | null |
Estructuras-de-Datos/Estructuras-lineales/queue/t_linked_queue/t_link_queue.c
|
DaniFuerte/Programaci-n-en-C
|
90b43ab172f41846f9f61ff2218b33c674b3cdac
|
[
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "t_link_queue.h"
t_link_queue new_queue () {
t_link_queue queue;
queue.head = NULL;
queue.tail = NULL;
queue.size = 0;
return queue;
}
void add_element (t_link_queue * queue, t_element e) {
t_node * new = malloc(sizeof(t_node));
new->info = e;
new->prev = NULL;
new->next = NULL;
if(queue->head == NULL) {
queue->head = new;
} else {
new->prev = queue->tail;
queue->tail->next = new;
}
queue->tail = new;
++queue->size;
}
int is_empty (t_link_queue queue) {
if(queue.head == NULL || queue.size == 0)
return true;
return false;
}
int size (t_link_queue queue) {
return queue.size;
}
t_element get_first (t_link_queue queue) {
t_element exit = new_element(-1);
if(queue.head != NULL)
exit = queue.head->info;
return exit;
}
t_element take (t_link_queue * queue) {
t_element exit = new_element(-1);
if(queue->head != NULL) {
exit = queue->head->info;
queue->head = queue->head->next;
--queue->size;
}
return exit;
}
t_link_queue concatenate (t_link_queue queue1, t_link_queue queue2) {
t_link_queue result = new_queue();
t_node * paux = NULL;
if(queue1.head != NULL) {
paux = queue1.head;
while(paux != NULL) {
add_element(&result, paux->info);
paux = paux->next;
}
}
if(queue2.head != NULL) {
paux = queue2.head;
while(paux != NULL) {
add_element(&result,paux->info);
paux = paux->next;
}
}
return result;
}
t_link_queue concatenate_reverse (t_link_queue queue1, t_link_queue queue2) {
t_link_queue reverse = new_queue();
t_node * paux = NULL;
if(queue1.head != NULL) {
paux = queue1.tail;
while(paux != NULL) {
add_element(&reverse, paux->info);
paux = paux->prev;
}
}
if(queue2.head != NULL) {
paux = queue2.tail;
while(paux != NULL) {
add_element(&reverse, paux->info);
paux = paux->prev;
}
}
return reverse;
}
void clear_queue (t_link_queue * queue) {
t_node * paux = NULL;
while(queue->head != NULL) {
paux = queue->head;
queue->head = queue->head->next;
free(paux);
--queue->size;
}
}
void debug_queue (t_link_queue queue) {
t_node * paux = NULL;
if(queue.head != NULL) {
printf("\n*********************************************");
printf("\n* DEBUG *");
printf("\n*********************************************\n\n");
paux = queue.head;
while(paux != NULL) {
debug_element(paux->info);
paux = paux->next;
}
printf("\n\n");
printf("SIZE -> %d \n\n", queue.size);
printf("\n*********************************************\n\n\n");
} else {
printf("EMPTY");
}
}
void debug_queue_reverse (t_link_queue queue) {
t_node * paux = NULL;
if(queue.head != NULL) {
printf("\n*********************************************");
printf("\n* DEBUG-REVERSE *");
printf("\n*********************************************\n\n");
paux = queue.tail;
while(paux != NULL) {
debug_element(paux->info);
paux = paux->prev;
}
printf("\n\n");
printf("SIZE -> %d \n\n", queue.size);
printf("\n*********************************************\n\n\n");
} else {
printf("EMPTY");
}
}
| 22.74269
| 81
| 0.453844
|
f39bd1eec08d248b97aa17fd70e16006db1f0835
| 631
|
dart
|
Dart
|
generated-sources/dart-jaguar/mojang-api/lib/model/upload_skin_request.dart
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
generated-sources/dart-jaguar/mojang-api/lib/model/upload_skin_request.dart
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
generated-sources/dart-jaguar/mojang-api/lib/model/upload_skin_request.dart
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
import 'package:jaguar_serializer/jaguar_serializer.dart';
import 'package:openapi/model/skin_model.dart';
part 'upload_skin_request.jser.dart';
class UploadSkinRequest {
@Alias('model')
final SkinModel model;
/* The skin image in PNG format */
@Alias('file')
final MultipartFile file;
UploadSkinRequest(
{
this.model = null,
this.file = null
}
);
@override
String toString() {
return 'UploadSkinRequest[model=$model, file=$file, ]';
}
}
@GenSerializer()
class UploadSkinRequestSerializer extends Serializer<UploadSkinRequest> with _$UploadSkinRequestSerializer {
}
| 18.028571
| 108
| 0.700475
|
c6cab4a868fb10bd80c897456777eb07eff97a98
| 1,580
|
py
|
Python
|
PolTools/utils/heatmap_utils/set_matrix_bounds.py
|
GeoffSCollins/PolTools
|
1ea9b166efc56610c385802f9491b4c8ec25a1d0
|
[
"MIT"
] | null | null | null |
PolTools/utils/heatmap_utils/set_matrix_bounds.py
|
GeoffSCollins/PolTools
|
1ea9b166efc56610c385802f9491b4c8ec25a1d0
|
[
"MIT"
] | null | null | null |
PolTools/utils/heatmap_utils/set_matrix_bounds.py
|
GeoffSCollins/PolTools
|
1ea9b166efc56610c385802f9491b4c8ec25a1d0
|
[
"MIT"
] | null | null | null |
from PolTools.utils.make_random_filename import generate_random_filename
def set_matrix_bounds(matrix_filename, minimum_value, maximum_value):
"""
Sets minimum and maximum values for the matrix by replacing values smaller than the minimum value with the minimum
value and replacing values larger than the maximum value with the maximum value
:param matrix_filename:
:type matrix_filename: str
:param minimum_value:
:type minimum_value: float
:param maximum_value:
:type maximum_value: float
:return: new matrix filename
:rtype: str
"""
original_matrix = []
with open(matrix_filename) as file:
for line in file:
original_matrix.append([float(val) for val in line.rstrip().split()])
width = len(original_matrix[0])
height = len(original_matrix)
new_matrix = []
for row in range(height):
new_matrix.append([0 for _ in range(width)])
for row in range(height):
for col in range(width):
curr_value = original_matrix[row][col]
if curr_value > maximum_value:
new_matrix[row][col] = maximum_value
elif curr_value < minimum_value:
new_matrix[row][col] = minimum_value
else:
new_matrix[row][col] = curr_value
new_matrix_filename = generate_random_filename()
with open(new_matrix_filename, 'w') as file:
for row in new_matrix:
str_row = [str(val) for val in row]
file.write("\t".join(str_row) + "\n")
return new_matrix_filename
| 30.980392
| 118
| 0.656329
|
f6c19a3a2b1c972c0f46966aa0e94f65720ad52e
| 140
|
sql
|
SQL
|
sql/mysql/dex.sql
|
grengojbo/pipeline-installer
|
eef4f5cf4efac1fb876573e8d9e15b90bcc9e947
|
[
"Apache-2.0"
] | null | null | null |
sql/mysql/dex.sql
|
grengojbo/pipeline-installer
|
eef4f5cf4efac1fb876573e8d9e15b90bcc9e947
|
[
"Apache-2.0"
] | null | null | null |
sql/mysql/dex.sql
|
grengojbo/pipeline-installer
|
eef4f5cf4efac1fb876573e8d9e15b90bcc9e947
|
[
"Apache-2.0"
] | null | null | null |
CREATE USER 'dex'@'%' IDENTIFIED BY '${password}';
CREATE DATABASE `dex`;
GRANT ALL PRIVILEGES ON `dex`.* TO 'dex'@'%';
FLUSH PRIVILEGES;
| 20
| 50
| 0.664286
|
7f33711bb26fee1ed478c3321f3a1fbe2b34deb5
| 1,362
|
cs
|
C#
|
Exercice/GoogleCodeJam/2018/FieldTrip.cs
|
yws1988/CSharpAlgo
|
1cf5253014921ccaa3e8ea4f27d09273d4d38ff2
|
[
"MIT"
] | null | null | null |
Exercice/GoogleCodeJam/2018/FieldTrip.cs
|
yws1988/CSharpAlgo
|
1cf5253014921ccaa3e8ea4f27d09273d4d38ff2
|
[
"MIT"
] | null | null | null |
Exercice/GoogleCodeJam/2018/FieldTrip.cs
|
yws1988/CSharpAlgo
|
1cf5253014921ccaa3e8ea4f27d09273d4d38ff2
|
[
"MIT"
] | null | null | null |
using System;
using System.Linq;
using input = System.Console;
namespace CodeJam.Model
{
public class FieldTrip
{
public static int T;
public static int N;
public static int[][] Nums;
public static void Start()
{
#if true
System.IO.StreamReader input = new System.IO.StreamReader(@"test\FieldTrip.txt");
#endif
T = Convert.ToInt32(input.ReadLine());
for (int i = 0; i < T; i++)
{
N = int.Parse(input.ReadLine());
Nums = new int[N][];
for (int j = 0; j < N; j++)
{
Nums[j] = input.ReadLine().Split(' ').Select(int.Parse).ToArray();
}
Console.WriteLine(-~13);
Output(i+1, Solve());
}
Console.Read();
}
public static int Solve()
{
var Xs = Nums.Select(n => n[0]).OrderBy(n => n).ToArray();
var Ys = Nums.Select(n => n[1]).OrderBy(n => n).ToArray();
return (int)Math.Max(Math.Ceiling((Xs[N - 1] - Xs[0])/2.0), Math.Ceiling((Ys[N - 1] - Ys[0]) / 2.0));
}
public static void Output(int caseNum, int result)
{
Console.Write("Case #" + caseNum + ": " + result);
Console.WriteLine();
}
}
}
| 26.705882
| 113
| 0.46696
|
eb43ae6f1651eab7e93e0efd2cb884ed4f76ebbd
| 1,211
|
css
|
CSS
|
examples/ClanLib/AtharonRL/Resources/Engine/GUIThemeAero/lineedit.css
|
ptrefall/propcomp
|
35a751ae0717e5c35621200f64deb373b29341a0
|
[
"MIT"
] | 2
|
2018-10-18T12:06:15.000Z
|
2019-06-13T20:41:31.000Z
|
examples/ClanLib/AtharonRL/Resources/Engine/GUIThemeAero/lineedit.css
|
ptrefall/propcomp
|
35a751ae0717e5c35621200f64deb373b29341a0
|
[
"MIT"
] | null | null | null |
examples/ClanLib/AtharonRL/Resources/Engine/GUIThemeAero/lineedit.css
|
ptrefall/propcomp
|
35a751ae0717e5c35621200f64deb373b29341a0
|
[
"MIT"
] | null | null | null |
lineedit
{
border-image-slice:2 2 2 2 fill;
border-image-width:2px 2px 2px 2px;
border-image-repeat:stretch;
border-top:0px;
border-left:6px;
border-right:16px;
border-bottom:0px;
color:black;
}
lineedit:normal
{
border-image-source:url('res:LineEditNormal');
}
lineedit:hot
{
border-image-source:url('res:LineEditHot');
}
lineedit:disabled
{
border-image-source:url('res:LineEditDisabled');
color:gray;
}
lineedit cursor
{
width:1px;
background-color: black;
blink-time-on:1000;
blink-time-off:1000;
border-image-source:none;
border-top:0px;
border-left:0px;
border-right:0px;
border-bottom:0px;
}
lineedit cursor:blink_on
{
background-color: black;
}
lineedit cursor:blink_off
{
background-color: white;
}
lineedit selection
{
color: white;
expand-top:-2;
expand-bottom:-1;
border-image-source:none;
background-color: #316ac5;
border-top:0px;
border-left:0px;
border-right:0px;
border-bottom:0px;
}
lineedit selection:disabled
{
border-image-source:none;
background-color: #7a96df;
}
lineedit selection:unfocused
{
border-image-source:none;
background-color: #7a96df;
}
| 14.590361
| 51
| 0.679604
|
971afdb701f6276f4b06bdae3fe6826db48d4cee
| 4,397
|
wlua
|
Lua
|
samples/testapp.wlua
|
oberhofer/luawinapi
|
5fa8acf01a6056b32ed45133cee98b0b29c5e07b
|
[
"MIT"
] | 5
|
2015-12-04T17:31:27.000Z
|
2019-09-01T11:56:44.000Z
|
samples/testapp.wlua
|
LuaDist-testing/luawinapi
|
e8bd578481a45bcc70d95d6eb6efa6a098647927
|
[
"MIT"
] | null | null | null |
samples/testapp.wlua
|
LuaDist-testing/luawinapi
|
e8bd578481a45bcc70d95d6eb6efa6a098647927
|
[
"MIT"
] | 2
|
2018-06-22T00:58:34.000Z
|
2020-10-25T15:41:53.000Z
|
--[==[
luawinapi - winapi wrapper for Lua
Copyright (C) 2011 Klaus Oberhofer. See copyright notice in
LICENSE file
Simple test application for luawinapi
--]==]
winapi = require("luawinapi")
-- debugging: define assertion callback for internal window proc
function outputAssert(hwnd, msg, wParam, lParam, expect, ud)
print("wndProc assertion:", hwnd, MSG_CONSTANTS[msg] or msg, wParam, lParam, expect, ud)
end
-- start
print("-----------------GetModuleHandleW")
-- printtable("winapi", winapi)
-- printtable("winapi.WNDCLASSW", winapi.WNDCLASSW.mts.man.__members)
hInstance = winapi.GetModuleHandleW(nil)
clsname = toUCS2Z("Getting Started")
handlers =
{
[WM_PAINT] = function(hwnd, wParam, lParam)
ps = winapi.PAINTSTRUCT:new()
hdc = winapi.BeginPaint(hwnd, ps);
pen = winapi.CreatePen(PS_SOLID, 1, RGB(0xFF,0,0));
oldPen = winapi.SelectObject(hdc, pen);
winapi.SelectObject(hdc, pen);
-- winapi.SelectObject(hdc, winapi.GetStockObject(BLACK_BRUSH))
winapi.MoveToEx(hdc, 0, 0, nil)
winapi.LineTo(hdc, 200, 100)
winapi.MoveToEx(hdc, 0, 100, nil)
winapi.LineTo(hdc, 200, 0)
winapi.MoveToEx(hdc, 100, 100, nil)
winapi.Ellipse(hdc, 50, 50, 0, 100)
winapi.EndPaint(hwnd, ps);
return 0;
end,
[WM_DESTROY] = function(hwnd, wParam, lParam)
winapi.PostQuitMessage(0)
return 0
end
}
function WndProc(hwnd, msg, wParam, lParam)
-- print("WndProc", MSG_CONSTANTS[msg] or msg, wParam, lParam)
local handler = handlers[msg]
if (handler) then
return handler(hwnd, wParam, lParam)
end
-- call default window proc
return nil
end
print("-----------------CreateWndProcThunk")
WndProc_callback = winapi.WndProc.new(nil, WndProc)
wndClass = winapi.WNDCLASSW:new()
-- print("wndClass", wndClass);
-- printtable("wndClass", getmetatable(wndClass).__members)
wndClass.style = CS_HREDRAW + CS_VREDRAW;
wndClass.lpfnWndProc = WndProc_callback.entrypoint
wndClass.cbClsExtra = 0
wndClass.cbWndExtra = 0
wndClass.hInstance = hInstance
wndClass.hIcon = 0 -- winapi.LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = winapi.LoadCursorW(NULL, IDC_ARROW);
wndClass.hbrBackground = winapi.GetStockObject(WHITE_BRUSH);
wndClass.lpszMenuName = 0
wndClass.lpszClassName = clsname
print("-----------------RegisterClassW")
atom = winapi.RegisterClassW(wndClass);
print("-----------------atom", atom)
if (not atom) then
error(WinError())
end
print("---------------CreateWindowExW -------------------")
hWnd = winapi.CreateWindowExW(
0,
clsname, -- window class name
toUCS2Z("Getting Started"), -- window caption
WS_VISIBLE, -- window style
CW_USEDEFAULT, -- initial x position
CW_USEDEFAULT, -- initial y position
CW_USEDEFAULT, -- initial x size
CW_USEDEFAULT, -- initial y size
0, -- parent window handle
0, -- window menu handle
hInstance, -- program instance handle
0); -- creation parameters
print("hwnd", hWnd, hWnd.handle)
--[==[
hEdit = winapi.CreateWindowExW(
0,
toUCS2Z("EDIT"), -- window class name
toUCS2Z("Getting Started"), -- window caption
WS_CHILD + WS_VISIBLE + WS_BORDER,-- window style
20, -- initial x position
200, -- initial y position
100, -- initial x size
100, -- initial y size
hWnd, -- parent window handle
0, -- window menu handle
hInstance, -- program instance handle
0); -- creation parameters
]==]
print("----------- hwnd ", hWnd)
if (0 == hWnd) then
error(WinError())
end
print("ShowWindow")
hWnd:ShowWindow(SW_SHOW)
-- alternative:
-- winapi.ShowWindow(hWnd, SW_SHOW)
print("UpdateWindow")
hWnd:UpdateWindow()
print("winapi.ProcessMessages")
--[==[
msg = winapi.MSG:new()
while (winapi.GetMessageW(msg, NULL, 0, 0)) do
winapi.TranslateMessage(msg);
winapi.DispatchMessageW(msg);
end
return msg.wParam
--]==]
-- this is possible, too
return winapi.ProcessMessages()
| 26.172619
| 90
| 0.604048
|
df25e0f7040f2641a47181a43286864e27916454
| 1,637
|
cs
|
C#
|
src/SimpleExporter/Writer/ReportWriterBase.cs
|
BartoGabriel/SimpleExporter
|
9140626551b5db878793c8923597ccf891fda22d
|
[
"MIT"
] | null | null | null |
src/SimpleExporter/Writer/ReportWriterBase.cs
|
BartoGabriel/SimpleExporter
|
9140626551b5db878793c8923597ccf891fda22d
|
[
"MIT"
] | null | null | null |
src/SimpleExporter/Writer/ReportWriterBase.cs
|
BartoGabriel/SimpleExporter
|
9140626551b5db878793c8923597ccf891fda22d
|
[
"MIT"
] | 2
|
2019-03-12T12:44:14.000Z
|
2020-12-18T08:20:34.000Z
|
using System.Globalization;
using System.IO;
using SimpleExporter.Definition.Elements;
namespace SimpleExporter.Writer
{
public abstract class ReportWriterBase
{
protected CultureInfo CultureInfo { get; set; } = CultureInfo.CurrentCulture;
protected SimpleExporter SimpleExporter { get; set; }
protected Stream Destination { get; set; }
public void WriteReport(SimpleExporter simpleExporter, Stream destination)
{
SimpleExporter = simpleExporter;
Destination = destination;
if (!string.IsNullOrWhiteSpace(simpleExporter.ReportDefinition.CultureName))
CultureInfo = new CultureInfo(simpleExporter.ReportDefinition.CultureName);
WriteReport();
}
protected abstract void WriteReport();
protected TSetting GetSetting<TSetting>() where TSetting : IWriterSetting, new()
{
var name = GetType().Name;
name = char.ToLowerInvariant(name[0]) + name.Substring(1);
return SimpleExporter.ReportDefinition.GetWriterSetting<TSetting>(name);
}
protected string GetRowDataFormatted(object data, Column tableColumn)
{
var internalValue = data.GetType().GetProperty(tableColumn.Field)?.GetValue(data, null);
if (internalValue == null)
return "";
if (string.IsNullOrWhiteSpace(tableColumn.FormatSpecifier)) return internalValue.ToString();
var format = $"{{0:{tableColumn.FormatSpecifier}}}";
return string.Format(CultureInfo, format, internalValue);
}
}
}
| 36.377778
| 104
| 0.6573
|
a35cf0803c835f6963044189b00b3b8dac4adc6b
| 496
|
java
|
Java
|
app/src/main/java/com/asiainfo/uuom/yourhealth/AppContext.java
|
uuom/YourHealth
|
e3f52d31f7a838c6c225f2d7694d292a851135eb
|
[
"MIT"
] | 9
|
2016-11-23T06:40:12.000Z
|
2021-09-07T16:30:31.000Z
|
app/src/main/java/com/asiainfo/uuom/yourhealth/AppContext.java
|
uuom/YourHealth
|
e3f52d31f7a838c6c225f2d7694d292a851135eb
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/asiainfo/uuom/yourhealth/AppContext.java
|
uuom/YourHealth
|
e3f52d31f7a838c6c225f2d7694d292a851135eb
|
[
"MIT"
] | 7
|
2016-06-07T03:41:05.000Z
|
2022-01-22T06:15:06.000Z
|
package com.asiainfo.uuom.yourhealth;
import android.app.Application;
import android.content.Context;
/**
* Created by uuom on 16-1-12.
*/
public class AppContext extends Application {
private static Context appContext;
@Override
public void onCreate() {
super.onCreate();
appContext = getApplicationContext();
appInit();
}
private void appInit() {
}
public static Context getAppContext() {
return appContext;
}
}
| 17.103448
| 45
| 0.641129
|
506d30adc08934f5ad6b6c89bc0db3d7eea3da9d
| 595
|
swift
|
Swift
|
Example/Example/Modules/Login/Coordinator/LoginCoordinator.swift
|
ahmedkhaledss/Coordination
|
2bc5e8c2345266d5a1a9d38df71426f800097d8b
|
[
"MIT"
] | 7
|
2020-01-10T12:30:47.000Z
|
2020-01-13T12:23:23.000Z
|
Example/Example/Modules/Login/Coordinator/LoginCoordinator.swift
|
ahmedkhaledss/Coordination
|
2bc5e8c2345266d5a1a9d38df71426f800097d8b
|
[
"MIT"
] | null | null | null |
Example/Example/Modules/Login/Coordinator/LoginCoordinator.swift
|
ahmedkhaledss/Coordination
|
2bc5e8c2345266d5a1a9d38df71426f800097d8b
|
[
"MIT"
] | null | null | null |
//
// LoginCoordinator.swift
// Example
//
// Created by Ahmed Khaled on 1/9/20.
// Copyright © 2020 Ahmed Khaled. All rights reserved.
//
import UIKit
import Coordination
class LoginCoordinator: Coordinator {
var router: RouterType
var childCoordinators: [Coordinator] = []
var parentCoordinator: ApplicationCoordinator?
let viewcontroller = LoginViewController.instantiate(storyboardName: .login)
init(router: RouterType) {
self.router = router
}
func toPresentable() -> UIViewController {
viewcontroller.coordinator = self
return viewcontroller
}
}
| 21.25
| 78
| 0.72605
|
f34fab1c97ea1335c460791a4e3cdd378923b3c8
| 2,988
|
swift
|
Swift
|
{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/Common/Abstractions/Command.swift
|
VitaliySavchenko/iOS-redux-project-template
|
9258e221fd5910efd15f87bbc0092f1e6f73f170
|
[
"MIT"
] | 1
|
2020-07-30T17:19:41.000Z
|
2020-07-30T17:19:41.000Z
|
{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/Common/Abstractions/Command.swift
|
VitaliySavchenko/iOS-redux-project-template
|
9258e221fd5910efd15f87bbc0092f1e6f73f170
|
[
"MIT"
] | null | null | null |
{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/Common/Abstractions/Command.swift
|
VitaliySavchenko/iOS-redux-project-template
|
9258e221fd5910efd15f87bbc0092f1e6f73f170
|
[
"MIT"
] | null | null | null |
//
// Command.swift
// {{cookiecutter.app_name}}
//
// Copyright © {{cookiecutter.company_name}}. All rights reserved.
//
import Foundation
// swiftlint:disable all
final class Command {
static let nop = Command {}
private let file: StaticString
private let function: StaticString
private let line: Int
private let id: String
private let action: () -> Void
init(
id: String = "unnamed",
file: StaticString = #file,
function: StaticString = #function,
line: Int = #line,
action: @escaping () -> Void
) {
self.id = id
self.action = action
self.function = function
self.file = file
self.line = line
}
func dispatched(on queue: DispatchQueue) -> Command {
return Command {
queue.async {
self.perform()
}
}
}
func perform() {
action()
}
/// Support for Xcode quick look feature.
@objc
func debugQuickLookObject() -> AnyObject? {
return """
type: \(String(describing: type(of: self)))
id: \(id)
file: \(file)
function: \(function)
line: \(line)
""" as NSString
}
}
extension Command: Equatable {
static func == (lhs: Command, rhs: Command) -> Bool {
return true
}
}
extension Command: Codable {
convenience init(from decoder: Decoder) throws {
self.init { }
}
func encode(to encoder: Encoder) throws {}
}
final class CommandWith<T> {
static var nop: CommandWith {
return CommandWith { _ in }
}
let action: (T) -> Void
init(action: @escaping (T) -> Void) {
self.action = action
}
func perform(with value: T) {
action(value)
}
func bind(to value: T) -> Command {
return Command { self.perform(with: value) }
}
func dispatched(on queue: DispatchQueue) -> CommandWith {
return CommandWith { value in
queue.async {
self.perform(with: value)
}
}
}
func then(_ another: CommandWith) -> CommandWith {
return CommandWith { value in
self.perform(with: value)
another.perform(with: value)
}
}
}
extension CommandWith: Equatable {
static func == (lhs: CommandWith<T>, rhs: CommandWith<T>) -> Bool {
return true
}
}
extension CommandWith: Hashable {
public func hash(into hasher: inout Hasher) {
return hasher.combine(ObjectIdentifier(self))
}
}
extension CommandWith: Codable {
convenience init(from decoder: Decoder) throws {
self.init { _ in }
}
func encode(to encoder: Encoder) throws {}
}
extension CommandWith {
func map<U>(transform: @escaping (U) -> T) -> CommandWith<U> {
return CommandWith<U> { u in
self.perform(with: transform(u))
}
}
}
| 22.636364
| 71
| 0.552209
|
a49dd12f1773cf8a516bfdcd0e257e92d9e70c99
| 638
|
php
|
PHP
|
DBAL/SettingsType.php
|
magedan/LexxpavlovSettingsBundle
|
62864331cde1f591a02293f01dc2197faedacee5
|
[
"MIT"
] | 10
|
2017-02-17T09:21:29.000Z
|
2019-07-08T10:10:33.000Z
|
DBAL/SettingsType.php
|
magedan/LexxpavlovSettingsBundle
|
62864331cde1f591a02293f01dc2197faedacee5
|
[
"MIT"
] | 13
|
2016-03-18T17:42:13.000Z
|
2021-09-14T11:11:18.000Z
|
DBAL/SettingsType.php
|
magedan/LexxpavlovSettingsBundle
|
62864331cde1f591a02293f01dc2197faedacee5
|
[
"MIT"
] | 11
|
2016-11-14T13:19:44.000Z
|
2022-01-06T11:11:05.000Z
|
<?php
namespace Lexxpavlov\SettingsBundle\DBAL;
use Fresh\DoctrineEnumBundle\DBAL\Types\AbstractEnumType;
class SettingsType extends AbstractEnumType
{
const Boolean = 'boolean';
const Integer = 'int';
const Float = 'float';
const String = 'string';
const Text = 'text';
const Html = 'html';
protected static $choices = array(
self::Boolean => 'Boolean',
self::Integer => 'Integer',
self::Float => 'Float',
self::String => 'String',
self::Text => 'Text',
self::Html => 'Html',
);
protected $name = 'LexxpavlovSettingsEnumType';
}
| 23.62963
| 57
| 0.594044
|
ca8593772cb87c6766b949b334f49d3c398d33df
| 2,988
|
cs
|
C#
|
BrewLab.Scripts.RecipeGenerator/Program.cs
|
dustmouse/scripts
|
23c687c486c9c348dbe3e7399f63cbba62b8d196
|
[
"MIT"
] | null | null | null |
BrewLab.Scripts.RecipeGenerator/Program.cs
|
dustmouse/scripts
|
23c687c486c9c348dbe3e7399f63cbba62b8d196
|
[
"MIT"
] | null | null | null |
BrewLab.Scripts.RecipeGenerator/Program.cs
|
dustmouse/scripts
|
23c687c486c9c348dbe3e7399f63cbba62b8d196
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace BrewLab.Scripts.RecipeGenerator
{
class Program
{
//Because I'm all about that Baas.
private static readonly string _baseAddress = "http://blabdatadev01.cloudapp.net:3000/api/v1/";
//Default user for now...
private static readonly int _userID = 1;
private static Random _random = new Random();
static void Main(string[] args)
{
var tasks = _generateRecipes(1000).Select(recipe => _postRecipe(recipe));
foreach (var task in tasks)
{
var id = task.Result;
string log = string.Format("Recipe {0} created.", id);
Console.WriteLine(log);
}
Console.ReadKey();
}
private static IEnumerable<Recipe> _generateRecipes(int quantity = 100)
{
Func<bool, Recipe> generateRecipe = null;
generateRecipe = new Func<bool, Recipe>(isVersion =>
{
string name = _generateText(10);
double volume = ((double)_random.Next(20) / 20) * 5;
string units = string.Empty;
if (volume > 2.5)
units = "Gallons";
else
units = "Liters";
string yeastType = _generateText(25);
var recipe = new Recipe
{
Name = name,
UserID = _userID,
Volume = volume,
Units = units,
YeastType = yeastType,
Versions = !isVersion ? Enumerable.Range(0, 10)
.Select(_ => generateRecipe(true)).ToList() : null
};
return recipe;
});
for (int i = 0; i < quantity; i++)
yield return generateRecipe(false);
}
private static async Task<string> _postRecipe(Recipe recipe)
{
using (var client = new HttpClient { BaseAddress = new Uri(_baseAddress)})
{
HttpResponseMessage response = await client.PostAsJsonAsync<Recipe>("recipes/", recipe);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
private static string _generateText(int textLength)
{
//http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c
//Making it more likely to have spaces like some natural text strings.
var pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ";
var text = new string(Enumerable.Repeat(pool, textLength)
.Select(x => x[_random.Next(pool.Length)])
.ToArray());
return text;
}
}
}
| 30.489796
| 108
| 0.527443
|
e08bb45da4f6dc2e0e5b918167a425771817fb07
| 422
|
h
|
C
|
RCocoa/RCCharacterMatrix.h
|
StatTag/RCocoa
|
5a1a32a3f063e8c5f93dc926271778f74238bf66
|
[
"MIT"
] | 1
|
2019-05-01T06:31:59.000Z
|
2019-05-01T06:31:59.000Z
|
RCocoa/RCCharacterMatrix.h
|
StatTag/RCocoa
|
5a1a32a3f063e8c5f93dc926271778f74238bf66
|
[
"MIT"
] | 1
|
2019-09-06T17:57:43.000Z
|
2019-09-11T15:20:52.000Z
|
RCocoa/RCCharacterMatrix.h
|
StatTag/RCocoa
|
5a1a32a3f063e8c5f93dc926271778f74238bf66
|
[
"MIT"
] | null | null | null |
//
// RCCharacterMatrix.h
// RCocoa
//
// Created by Luke Rasmussen on 5/3/17.
// Copyright © 2017 Northwestern University. All rights reserved.
//
#import <Foundation/Foundation.h>
#ifndef RCCharacterMatrix_h
#define RCCharacterMatrix_h
#include "RCMatrix.h"
@interface RCCharacterMatrix : RCMatrix<NSString*>
{
}
-(NSString*) ElementAt: (int)row column:(int)column;
@end
#endif /* RCCharacterMatrix_h */
| 16.230769
| 66
| 0.720379
|
393dfd912b2f5c76a5000a0d65ac1fa850595b61
| 682
|
py
|
Python
|
uber_problems/problem_7.py
|
loftwah/Daily-Coding-Problem
|
0327f0b4f69ef419436846c831110795c7a3c1fe
|
[
"MIT"
] | 129
|
2018-10-14T17:52:29.000Z
|
2022-01-29T15:45:57.000Z
|
uber_problems/problem_7.py
|
loftwah/Daily-Coding-Problem
|
0327f0b4f69ef419436846c831110795c7a3c1fe
|
[
"MIT"
] | 2
|
2019-11-30T23:28:23.000Z
|
2020-01-03T16:30:32.000Z
|
uber_problems/problem_7.py
|
loftwah/Daily-Coding-Problem
|
0327f0b4f69ef419436846c831110795c7a3c1fe
|
[
"MIT"
] | 60
|
2019-02-21T09:18:31.000Z
|
2022-03-25T21:01:04.000Z
|
"""This problem was asked by Uber.
You have N stones in a row, and would like to create from them a pyramid.
This pyramid should be constructed such that the height of each stone
increases by one until reaching the tallest stone, after which the heights
decrease by one. In addition, the start and end stones of the pyramid
should each be one stone high.
You can change the height of any stone by paying a cost of 1 unit to
lower its height by 1, as many times as necessary. Given this information,
determine the lowest cost method to produce this pyramid.
For example, given the stones [1, 1, 3, 3, 2, 1], the optimal solution
is to pay 2 to create [0, 1, 2, 3, 2, 1].
"""
| 45.466667
| 75
| 0.747801
|
2c8ba72610f2a4b34ba30481484a1f376276e9f7
| 1,847
|
py
|
Python
|
aiocloudpayments/endpoints/base.py
|
drforse/aiocloudpayments
|
25b8827250279335d037754dca6978bc79c9b18d
|
[
"MIT"
] | null | null | null |
aiocloudpayments/endpoints/base.py
|
drforse/aiocloudpayments
|
25b8827250279335d037754dca6978bc79c9b18d
|
[
"MIT"
] | null | null | null |
aiocloudpayments/endpoints/base.py
|
drforse/aiocloudpayments
|
25b8827250279335d037754dca6978bc79c9b18d
|
[
"MIT"
] | null | null | null |
import abc
from typing import Optional, Dict, Any, Generic, TypeVar
from pydantic import BaseModel, Field
from pydantic.generics import GenericModel
from pydantic.utils import to_camel
from ..types.transaction import Transaction
from ..types.secure_3d import Secure3D
from ..utils import json
CpType = TypeVar("CpType", bound=Any)
class Request(BaseModel):
endpoint: str
json_str: str = None
x_request_id: str = None
x_signature: str = None
@property
def headers(self) -> Optional[Dict[str, str]]:
result = {}
if self.x_request_id:
result.update({"X-Request-ID": self.x_request_id})
if self.x_signature:
result.update({"X-Signature": self.x_signature})
return result or None
class Config:
json_loads = json.loads
json_dumps = json.dumps
class Response(GenericModel, Generic[CpType]):
success: bool = Field(alias="Success")
message: Optional[str] = Field(alias="Message")
model: Optional[CpType] = Field(None, alias="Model")
def is_error(self):
if self.success is True or isinstance(self.model, Secure3D):
return False
return True
def is_payment_error(self):
return self.success is False and isinstance(self.model, Transaction)
class CpEndpoint(abc.ABC, BaseModel):
x_request_id: str = None
x_signature: str = None
@property
@abc.abstractmethod
def __returning__(self) -> type:
pass
@abc.abstractmethod
def build_request(self) -> Request:
pass
def build_response(self, data: Dict[str, Any]) -> Response[CpType]:
return Response[self.__returning__](**data)
class Config:
json_loads = json.loads
json_dumps = json.dumps
alias_generator = to_camel
allow_population_by_field_name = True
| 26.385714
| 76
| 0.670276
|
2a2b45440329af1d960b931495fc1879dae0e727
| 7,336
|
rs
|
Rust
|
src/ray_scanner.rs
|
MinkowskiMetric/raster
|
d356c6bc623c37ca76bc30c135cb5ff2a5948552
|
[
"MIT"
] | null | null | null |
src/ray_scanner.rs
|
MinkowskiMetric/raster
|
d356c6bc623c37ca76bc30c135cb5ff2a5948552
|
[
"MIT"
] | null | null | null |
src/ray_scanner.rs
|
MinkowskiMetric/raster
|
d356c6bc623c37ca76bc30c135cb5ff2a5948552
|
[
"MIT"
] | null | null | null |
use crate::{
constants,
math::*,
scene::{PreparedScene, Scene},
utils::*,
Color, Intersectable, PartialScatterResult, Ray, RenderStatsAccumulator, RenderStatsCollector,
ScatterResult, TracingStats,
};
use futures::future::join_all;
use std::{
mem::MaybeUninit,
slice::{Chunks, ChunksMut},
};
use std::convert::TryInto;
use std::sync::{Arc, RwLock};
pub struct VectorImage {
width: usize,
data: Box<[cgmath::Vector4<FloatType>]>,
}
pub struct Pixels<'a> {
chunks: Chunks<'a, cgmath::Vector4<FloatType>>,
}
impl<'a> Iterator for Pixels<'a> {
type Item = &'a cgmath::Vector4<FloatType>;
fn next(&mut self) -> Option<Self::Item> {
self.chunks.next().map(|slice| &slice[0])
}
}
pub struct PixelsMut<'a> {
chunks: ChunksMut<'a, cgmath::Vector4<FloatType>>,
}
impl<'a> Iterator for PixelsMut<'a> {
type Item = &'a mut cgmath::Vector4<FloatType>;
fn next(&mut self) -> Option<Self::Item> {
self.chunks.next().map(|slice| &mut slice[0])
}
}
pub struct EnumeratePixelsMut<'a> {
pixels: PixelsMut<'a>,
x: usize,
y: usize,
width: usize,
}
impl<'a> Iterator for EnumeratePixelsMut<'a> {
type Item = (usize, usize, &'a mut cgmath::Vector4<FloatType>);
fn next(&mut self) -> Option<Self::Item> {
if self.x >= self.width {
self.x = 0;
self.y += 1;
}
let (x, y) = (self.x, self.y);
self.x += 1;
self.pixels.next().map(|p| (x, y, p))
}
}
impl VectorImage {
pub fn new(width: usize, height: usize) -> Self {
let data = vec![cgmath::vec4(0.0, 0.0, 0.0, 0.0); width * height];
Self {
width,
data: data.into_boxed_slice(),
}
}
pub fn pixels(&self) -> Pixels {
Pixels {
chunks: self.data.chunks(1),
}
}
pub fn pixels_mut(&mut self) -> PixelsMut {
PixelsMut {
chunks: self.data.chunks_mut(1),
}
}
pub fn enumerate_pixels_mut(&mut self) -> EnumeratePixelsMut {
let width = self.width;
EnumeratePixelsMut {
pixels: self.pixels_mut(),
x: 0,
y: 0,
width,
}
}
}
impl std::ops::Add for VectorImage {
type Output = Self;
fn add(mut self, other: Self) -> Self {
self.pixels_mut()
.zip(other.pixels())
.fold((), |_, (dst, src)| *dst += *src);
self
}
}
pub async fn scan<StatsAccumulator: 'static + RenderStatsAccumulator + Sync + Send>(
scene: Scene,
(image_width, image_height): (usize, usize),
t0: FloatType,
t1: FloatType,
thread_count: usize,
min_passes: usize,
stats: Arc<RwLock<StatsAccumulator>>,
) -> VectorImage {
let thread_count = thread_count.max(1);
let min_passes = min_passes.max(1);
let passes_per_thread = (min_passes + thread_count - 1) / thread_count;
let scene = Arc::new(PreparedScene::make(scene, t0, t1));
let futures = (0..thread_count).into_iter().map(|_| {
let thread_scene = scene.clone();
let thread_stats = stats.clone();
tokio::task::spawn_blocking(move || {
scan_batch(
image_width,
image_height,
passes_per_thread,
&thread_scene,
thread_stats.as_ref(),
)
})
});
let mut thread_results = join_all(futures).await.into_iter();
let result = thread_results.next();
result
.map(|result| {
thread_results.fold(result, |l, r| match (l, r) {
(Ok(l), Ok(r)) => Ok(l + r),
(Err(e), _) => Err(e),
(_, Err(e)) => Err(e),
})
})
.transpose()
.unwrap()
.unwrap()
}
fn scan_batch(
image_width: usize,
image_height: usize,
pass_count: usize,
scene: &PreparedScene,
stats: &RwLock<impl RenderStatsAccumulator>,
) -> VectorImage {
let mut image = VectorImage::new(image_width, image_height);
let (image_width, image_height) = (image_width as FloatType, image_height as FloatType);
let mut pixel_stats = TracingStats::new();
for (x, y, pixel) in image.enumerate_pixels_mut() {
*pixel = (0..pass_count)
.into_iter()
.map(|_s| {
let (s, t) = (
((x as FloatType) + random_in_range(-0.5, 0.5)) / image_width,
((image_height - 1.0 - (y as FloatType)) + random_in_range(-0.5, 0.5))
/ image_height,
);
let ray = scene.camera().make_ray(s, t);
let ret = cgmath::Vector4::from(trace(&ray, scene));
pixel_stats.count_pixel();
if let Ok(mut lock) = stats.try_write() {
let next_stats = std::mem::replace(&mut pixel_stats, TracingStats::new());
lock.add_stats(next_stats.into());
}
ret
})
.fold(cgmath::vec4(0.0, 0.0, 0.0, 0.0), |sum, v| sum + v);
}
image
}
const MAX_DEPTH: usize = 50;
#[derive(Debug, Clone, Copy)]
struct ScatterStackRecord {
partial: PartialScatterResult,
emitted: Color,
}
type FixedSizeAttenuationStack<'a> =
crate::fixed_size_stack::FixedSizeStack<'a, ScatterStackRecord>;
fn collapse_color_stack(mut stack: FixedSizeAttenuationStack<'_>, input_color: Color) -> Color {
let mut color = input_color;
while let Some(scatter_record) = stack.pop() {
let calc_color = Vector4::from(scatter_record.emitted)
+ scatter_record
.partial
.attenuation
.extend(1.0)
.mul_element_wise(Vector4::from(color));
color = calc_color.try_into().unwrap();
}
// We need to ensure that the alpha channel is 1 when we come out of here, because that is used
// later to average the samples.
Vector4::from(color)
.truncate()
.extend(1.0)
.try_into()
.unwrap()
}
pub fn trace(ray: &Ray, scene: &PreparedScene) -> Color {
let mut attenuation_stack_data: [_; MAX_DEPTH] = MaybeUninit::uninit_array();
let mut attenuation_stack = FixedSizeAttenuationStack::new(&mut attenuation_stack_data);
let mut current_ray = *ray;
loop {
if let Some(hit_result) = scene.intersect(¤t_ray, 0.001, constants::INFINITY) {
let (hit_result, material) = hit_result.split();
let (emitted, scatter) = material.base_scatter(¤t_ray, hit_result).split();
if let Some(ScatterResult { partial, scattered }) = scatter {
if !attenuation_stack.try_push(ScatterStackRecord { partial, emitted }) {
// We cannot recurse any further, so stop here and return black
return collapse_color_stack(attenuation_stack, constants::BLACK);
}
current_ray = scattered;
} else {
return collapse_color_stack(attenuation_stack, emitted);
}
} else {
// We did not intersect with any objects, so sample the sky
return collapse_color_stack(attenuation_stack, scene.sky().sample(¤t_ray));
}
}
}
| 28.65625
| 99
| 0.563795
|
15d5ae6b19b2304cfcf69f38aeee434c04f2b5de
| 151
|
rs
|
Rust
|
src/lang/hir/src/lib.rs
|
Trark/slp
|
a74b13e5b2126cbe59888afbad0d31d48d38407e
|
[
"MIT"
] | null | null | null |
src/lang/hir/src/lib.rs
|
Trark/slp
|
a74b13e5b2126cbe59888afbad0d31d48d38407e
|
[
"MIT"
] | 21
|
2015-11-25T21:37:16.000Z
|
2016-01-14T02:58:55.000Z
|
src/lang/hir/src/lib.rs
|
Trark/slp
|
a74b13e5b2126cbe59888afbad0d31d48d38407e
|
[
"MIT"
] | null | null | null |
extern crate slp_shared;
extern crate slp_lang_hst;
mod ir;
mod hir_intrinsics;
pub use ir::*;
pub use hir_intrinsics::*;
pub mod globals_analysis;
| 13.727273
| 26
| 0.768212
|
32821b6c7c2dd900ee972e65f9451e809e51f88f
| 204
|
ps1
|
PowerShell
|
TOOL-Test-IsLocalAdministrator/Test-IsLocalAdministrator.ps1
|
Stephanevg/PowerShell
|
3f7d414284695a24d993e47240b8c004f2a317ec
|
[
"MIT"
] | 2
|
2017-01-06T14:59:44.000Z
|
2021-09-03T01:08:54.000Z
|
TOOL-Test-IsLocalAdministrator/Test-IsLocalAdministrator.ps1
|
Stephanevg/PowerShell
|
3f7d414284695a24d993e47240b8c004f2a317ec
|
[
"MIT"
] | null | null | null |
TOOL-Test-IsLocalAdministrator/Test-IsLocalAdministrator.ps1
|
Stephanevg/PowerShell
|
3f7d414284695a24d993e47240b8c004f2a317ec
|
[
"MIT"
] | null | null | null |
function Test-IsLocalAdministrator
{
return ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
| 51
| 164
| 0.828431
|
e40362ab71c21bcef5e1f27b79f0719f7ff86149
| 1,883
|
cs
|
C#
|
src/Tests/Rsft.Identity3.CacheRedis.Tests/Unit/Serialization/PropertyInfoStoreTests.cs
|
Rolosoft/Rsft.Identity3.CacheRedis
|
b029f7923222f0dcd3c6b14f3d6a6184656a1cbc
|
[
"Apache-2.0"
] | 2
|
2016-10-27T16:24:37.000Z
|
2019-08-15T06:09:21.000Z
|
src/Tests/Rsft.Identity3.CacheRedis.Tests/Unit/Serialization/PropertyInfoStoreTests.cs
|
Rolosoft/Rsft.Identity3.CacheRedis
|
b029f7923222f0dcd3c6b14f3d6a6184656a1cbc
|
[
"Apache-2.0"
] | null | null | null |
src/Tests/Rsft.Identity3.CacheRedis.Tests/Unit/Serialization/PropertyInfoStoreTests.cs
|
Rolosoft/Rsft.Identity3.CacheRedis
|
b029f7923222f0dcd3c6b14f3d6a6184656a1cbc
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2016 Rolosoft Ltd
// 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.
// <copyright file="PropertyInfoStoreTests.cs" company="Rolosoft Ltd">
// Copyright (c) Rolosoft Ltd. All rights reserved.
// </copyright>
namespace Rsft.Identity3.CacheRedis.Tests.Unit.Serialization
{
using System.Diagnostics;
using System.Linq;
using CacheRedis.Logic.Serialization;
using NUnit.Framework;
using TestEntities;
/// <summary>
/// The Property Info Store Tests
/// </summary>
[TestFixture]
public sealed class PropertyInfoStoreTests : TestBase
{
/// <summary>
/// Gets the declared properties when inherited class expect only declared.
/// </summary>
[Test]
[Repeat(2)]
public void GetDeclaredProperties_WhenInheritedClass_ExpectOnlyDeclared()
{
// Arrange
var propertyInfoStore = new PropertyInfoStore();
// Act
var stopwatch = Stopwatch.StartNew();
var declaredProperties = propertyInfoStore.GetDeclaredProperties(typeof(PropertyInfoStoreTestEntity)).ToList();
stopwatch.Stop();
// Assert
this.WriteTimeElapsed(stopwatch);
Assert.That(declaredProperties.Count, Is.EqualTo(1));
Assert.That(declaredProperties.First().Name, Is.EqualTo("NewValue"));
}
}
}
| 36.921569
| 123
| 0.677642
|
d25039d1ff90e1322163a0d3d927ada5ac287336
| 1,111
|
swift
|
Swift
|
Tests/MonkeyTests/compiler/MonkeyCErrorTests.swift
|
YamiDaisuke/rosetta-swift
|
0f6d371090811a43d8e261a55e5883faa87ffc05
|
[
"MIT"
] | 2
|
2021-06-05T04:44:00.000Z
|
2021-06-20T15:55:31.000Z
|
Tests/MonkeyTests/compiler/MonkeyCErrorTests.swift
|
YamiDaisuke/hermes-swift
|
0f6d371090811a43d8e261a55e5883faa87ffc05
|
[
"MIT"
] | 14
|
2021-04-01T15:34:02.000Z
|
2021-06-04T19:26:15.000Z
|
Tests/MonkeyTests/compiler/MonkeyCErrorTests.swift
|
YamiDaisuke/rosetta-swift
|
0f6d371090811a43d8e261a55e5883faa87ffc05
|
[
"MIT"
] | null | null | null |
//
// MonkeyCErrorTests.swift
// MonkeyTests
//
// Created by Franklin Cruz on 07-04-21.
//
import XCTest
@testable import Hermes
@testable import MonkeyLang
class MonkeyCErrorTests: XCTestCase, CompilerTestsHelpers {
func testErrors() throws {
let tests = [
(
"let a = 10;\n notResolved",
"Name \"notResolved\" not resolvable at Line: 2, Column: 1"
),
(
"let a = 10;\n\n a = 100;",
"Cannot assign to value: \"a\" is a constant at Line: 3, Column: 1"
),
(
"let a = 10;\n\nvar a = 100;",
"Cannot redeclare: \"a\" it already exists at Line: 3, Column: 0"
)
]
for test in tests {
do {
_ = try self.compile(test.0)
XCTFail("Compiler must throw an error")
} catch let error as CompilerError {
XCTAssertEqual(test.1, error.description)
} catch {
XCTFail("Unexpected Error \(error)")
}
}
}
}
| 27.097561
| 83
| 0.483348
|
8e6f3be3da9a7d39b219814654cbdcf73e298558
| 1,115
|
js
|
JavaScript
|
database/server/ClanGameLogModel.js
|
Eronisch/GunZ-CMS
|
6142f76338c34bda33c6a91b886ea8bcffae108d
|
[
"Unlicense"
] | 3
|
2016-08-28T11:22:49.000Z
|
2019-05-19T01:07:25.000Z
|
database/server/ClanGameLogModel.js
|
Eronisch/GunZ-CMS
|
6142f76338c34bda33c6a91b886ea8bcffae108d
|
[
"Unlicense"
] | null | null | null |
database/server/ClanGameLogModel.js
|
Eronisch/GunZ-CMS
|
6142f76338c34bda33c6a91b886ea8bcffae108d
|
[
"Unlicense"
] | 3
|
2016-08-28T11:19:59.000Z
|
2020-03-15T02:37:27.000Z
|
var DataContent = require('./../DataContent.js');
var Tedious = require('tedious');
var ClanModel = require('../../database/server/ClanModel.js');
var MapModel = require('../../database/server/MapModel.js');
var ClanGameLog = DataContent.define('ClanGameLog', {
id: {
type: Number,
primaryKey: true,
autoIncrement: true,
field : 'id'
},
WinnerClanId : {
type : Number,
field : 'winnerClid',
},
LoserClanId : {
type : Number,
field : 'loserClid',
},
WinnerClanName: {
type: String,
},
LoserClanName: {
type: String
},
RoundWins : Number,
RoundLosses : Number,
RegDate : Tedious.TYPES.DateTime,
WinnerMembers : String,
LoserMembers : String,
MapId : Number
}, {
freezeTableName: true,
timestamps: false
});
ClanGameLog.belongsTo(ClanModel, { foreignKey: 'WinnerClanId', as : 'WinnerClan' });
ClanGameLog.belongsTo(ClanModel, { foreignKey: 'LoserClanId', as : 'LoserClan' });
ClanGameLog.belongsTo(MapModel, { foreignKey: 'MapId' });
module.exports = ClanGameLog;
| 26.547619
| 84
| 0.616143
|
2cfb21e42761745c3f4e7815b099a7683693c697
| 6,504
|
lua
|
Lua
|
addons/pac3/lua/pac3/editor/client/shortcuts.lua
|
lechu2375/GM-DayZ
|
35beb8cc80bc1673f45be8385b56c654fb066e8d
|
[
"MIT"
] | 4
|
2021-12-01T15:57:30.000Z
|
2022-01-28T11:10:24.000Z
|
addons/pac3/lua/pac3/editor/client/shortcuts.lua
|
lechu2375/GM-DayZ
|
35beb8cc80bc1673f45be8385b56c654fb066e8d
|
[
"MIT"
] | null | null | null |
addons/pac3/lua/pac3/editor/client/shortcuts.lua
|
lechu2375/GM-DayZ
|
35beb8cc80bc1673f45be8385b56c654fb066e8d
|
[
"MIT"
] | 3
|
2021-08-20T15:19:34.000Z
|
2021-12-07T00:34:33.000Z
|
function pace.OnShortcutSave()
if not IsValid(pace.current_part) then return end
local part = pace.current_part:GetRootPart()
surface.PlaySound("buttons/button9.wav")
pace.SaveParts(nil, "part " .. (part:GetName() or "my outfit"), part, true)
end
function pace.OnShortcutWear()
if IsValid(pace.current_part) then return end
local part = pace.current_part:GetRootPart()
surface.PlaySound("buttons/button9.wav")
pace.SendPartToServer(part)
end
local last = 0
function pace.CheckShortcuts()
if gui.IsConsoleVisible() then return end
if not pace.Editor or not pace.Editor:IsValid() then return end
if last > RealTime() or input.IsMouseDown(MOUSE_LEFT) then return end
if input.IsKeyDown(KEY_LALT) and input.IsKeyDown(KEY_E) then
pace.Call("ToggleFocus", true)
last = RealTime() + 0.2
end
if input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_E) then
pace.Call("ToggleFocus")
last = RealTime() + 0.2
end
if input.IsKeyDown(KEY_LALT) and input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_P) then
RunConsoleCommand("pac_restart")
end
-- Only if the editor is in the foreground
if pace.HasFocus() then
if input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_S) then
pace.Call("ShortcutSave")
last = RealTime() + 0.2
end
-- CTRL + (W)ear?
if input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_N) then
pace.Call("ShortcutWear")
last = RealTime() + 0.2
end
if input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_T) then
pace.SetTPose(not pace.GetTPose())
last = RealTime() + 0.2
end
if input.IsKeyDown(KEY_LCONTROL) and input.IsKeyDown(KEY_F) then
pace.properties.search:SetVisible(true)
pace.properties.search:RequestFocus()
pace.properties.search:SetEnabled(true)
pace.property_searching = true
last = RealTime() + 0.2
end
end
end
pac.AddHook("Think", "pace_shortcuts", pace.CheckShortcuts)
do
local hold = false
local last = 0
local function thinkUndo()
-- whooaaa
-- if input.IsControlDown() and input.IsKeyDown(KEY_X) then
-- pace.UndoPosition = math.Round((gui.MouseY() / ScrH()) * #pace.UndoHistory)
-- pace.ApplyUndo()
-- return
-- end
if not input.IsKeyDown(KEY_Z) and not input.IsKeyDown(KEY_Y) then
hold = false
end
if hold then return end
if input.IsControlDown() and ((input.IsKeyDown(KEY_LSHIFT) and input.IsKeyDown(KEY_Z)) or input.IsKeyDown(KEY_Y)) then
pace.Redo()
hold = true
elseif input.IsControlDown() and input.IsKeyDown(KEY_Z) then
pace.Undo()
hold = true
end
end
local hold = false
local function thinkCopy()
if not input.IsKeyDown(KEY_C) then
hold = false
end
if hold or not (input.IsControlDown() and input.IsKeyDown(KEY_C)) then return end
-- copy
hold = true
local part = pace.current_part
if not part or not part:IsValid() then
pace.FlashNotification('No part selected to copy')
return
end
pace.Copy(part)
surface.PlaySound("buttons/button9.wav")
end
local hold = false
local function thinkCut()
if not input.IsKeyDown(KEY_X) then
hold = false
end
if hold or not (input.IsControlDown() and input.IsKeyDown(KEY_X)) then return end
-- copy
hold = true
local part = pace.current_part
if not part or not part:IsValid() then
pace.FlashNotification('No part selected to cut')
return
end
pace.Cut(part)
surface.PlaySound("buttons/button9.wav")
end
local hold = false
local function thinkDelete()
if not input.IsKeyDown(KEY_DELETE) then
hold = false
end
if hold or not input.IsKeyDown(KEY_DELETE) then return end
-- delete
hold = true
local part = pace.current_part
if not part or not part:IsValid() then
pace.FlashNotification('No part to delete')
return
end
pace.RemovePart(part)
surface.PlaySound("buttons/button9.wav")
end
local REVERSE_COLLAPSE_CONTROLS = CreateConVar('pac_reverse_collapse', '1', {FCVAR_ARCHIVE}, 'Reverse Collapse/Expand hotkeys')
local hold = false
local function thinkExpandAll()
if not input.IsKeyDown(KEY_LALT) and not input.IsKeyDown(KEY_RALT) and not input.IsKeyDown(KEY_0) then
hold = false
end
if hold or not input.IsShiftDown() or (not input.IsKeyDown(KEY_LALT) and not input.IsKeyDown(KEY_RALT)) or not input.IsKeyDown(KEY_0) then return end
-- expand all
hold = true
local part = pace.current_part
if not part or not part:IsValid() then
pace.FlashNotification('No part to expand')
return
end
part:CallRecursive('SetEditorExpand', not REVERSE_COLLAPSE_CONTROLS:GetBool())
surface.PlaySound("buttons/button9.wav")
pace.RefreshTree(true)
end
local hold = false
local function thinkCollapseAll()
if not input.IsKeyDown(KEY_LALT) and not input.IsKeyDown(KEY_RALT) and not input.IsKeyDown(KEY_0) then
hold = false
end
if hold or input.IsShiftDown() or (not input.IsKeyDown(KEY_LALT) and not input.IsKeyDown(KEY_RALT)) or not input.IsKeyDown(KEY_0) then return end
-- collapse all
hold = true
local part = pace.current_part
if not part or not part:IsValid() then
pace.FlashNotification('No part to collapse')
return
end
part:CallRecursive('SetEditorExpand', REVERSE_COLLAPSE_CONTROLS:GetBool())
surface.PlaySound("buttons/button9.wav")
pace.RefreshTree(true)
end
local hold = false
local function thinkPaste()
if not input.IsKeyDown(KEY_V) then
hold = false
end
if hold or not (input.IsControlDown() and input.IsKeyDown(KEY_V)) then return end
-- paste
hold = true
local part = pace.Clipboard
if not part then
pace.FlashNotification('No part is stored in clipboard')
return
end
local findParent
if part == pace.current_part then
findParent = part:GetParent()
if not findParent or not findParent:IsValid() then
findParent = part
end
elseif pace.current_part and pace.current_part:IsValid() then
findParent = pace.current_part
else
pace.RecordUndoHistory()
findParent = pace.Call("CreatePart", "group", L"paste data")
pace.RecordUndoHistory()
end
pace.Paste(findParent)
surface.PlaySound("buttons/button9.wav")
end
pac.AddHook("Think", "pace_keyboard_shortcuts", function()
if not pace.IsActive() then return end
if not pace.Focused then return end
if IsValid(vgui.GetKeyboardFocus()) and vgui.GetKeyboardFocus():GetClassName():find('Text') then return end
if gui.IsConsoleVisible() then return end
thinkUndo()
thinkCopy()
thinkPaste()
thinkCut()
thinkDelete()
thinkExpandAll()
thinkCollapseAll()
end)
end
| 24.268657
| 151
| 0.727706
|
c971875f866c661d7a4a6962f9dbd9522a490a66
| 2,500
|
ts
|
TypeScript
|
src/Scan.ts
|
JoshHiles/secret-scanner
|
9006c22cbf378188f0eb22296c63bf2c1f0d29b5
|
[
"MIT"
] | null | null | null |
src/Scan.ts
|
JoshHiles/secret-scanner
|
9006c22cbf378188f0eb22296c63bf2c1f0d29b5
|
[
"MIT"
] | 51
|
2021-10-16T15:00:54.000Z
|
2022-03-25T05:23:39.000Z
|
src/Scan.ts
|
JoshHiles/secret-scanner
|
9006c22cbf378188f0eb22296c63bf2c1f0d29b5
|
[
"MIT"
] | null | null | null |
import { parse } from 'path';
import chalk from 'chalk';
import { StopWatch } from 'stopwatch-node';
import { Duration } from 'luxon';
import Baseline from './types/Baseline';
import ConfigurationHelper from './helpers/Configuration.Helper';
import BaselineHelper from './helpers/Baseline.Helper';
import PluginHelper from './helpers/Plugin.Helper';
import FileHelper from './helpers/File.Helper';
import LoggingHelper from './helpers/Logging.Helper';
import Runner from './Runner';
chalk.level = 3;
export default class Scan {
LoggingHelper: LoggingHelper;
ConfigurationHelper: ConfigurationHelper;
BaselineHelper: BaselineHelper;
PluginHelper: PluginHelper;
FileHelper: FileHelper;
Runner: Runner;
constructor(
loggingHelper: LoggingHelper,
configurationHelper: ConfigurationHelper,
baselineHelper: BaselineHelper,
pluginHelper: PluginHelper,
fileHelper: FileHelper,
runner: Runner,
) {
this.LoggingHelper = loggingHelper;
this.ConfigurationHelper = configurationHelper;
this.BaselineHelper = baselineHelper;
this.PluginHelper = pluginHelper;
this.FileHelper = fileHelper;
this.Runner = runner;
}
async Scan(directory: string): Promise<Baseline> {
this.LoggingHelper.LogBeginScan(directory);
const configuration = this.ConfigurationHelper.LoadConfiguration();
let baseline = this.BaselineHelper.LoadBaseline();
const plugins = this.PluginHelper.LoadPlugins(configuration);
const files = this.FileHelper.GetFiles([directory], configuration);
baseline.results = await this.Runner.Run(files, configuration, plugins);
baseline = this.BaselineHelper.SetGeneratedAt(baseline);
const pluginsNormalised: string[] = [];
plugins.forEach((plugin) => {
pluginsNormalised.push(parse(plugin).name);
});
baseline.plugins = pluginsNormalised;
this.BaselineHelper.SaveBaselineToFile(baseline);
return baseline;
}
}
// const stopwatch = new StopWatch('Scanner');
// stopwatch.start('Get Files');
// stopwatch.stop();
// const totalTime = stopwatch.getTotalTime();
// const timeTaken = Duration.fromMillis(totalTime).toFormat("mm' minutes' ss' seconds' SSS' milliseconds'");
// console.info(`\nTook:`);
// console.info(chalk.blue.bold(`${timeTaken}`));
// if (process.env.DEBUG == '1') {
// console.log();
// stopwatch.prettyPrint();
// }
| 32.467532
| 109
| 0.6896
|
72e1fb25df9e16c3b18f00b0c84f84c71fd05241
| 12,130
|
cs
|
C#
|
HZH_Controls/HZH_Controls/Controls/Roll/UCRollText.cs
|
HappyQuQu/NetWinformControl
|
eaff6160e85cc235558f091b92eaa99120d35e7f
|
[
"Apache-2.0"
] | 1,841
|
2019-08-21T01:35:10.000Z
|
2022-03-31T21:52:12.000Z
|
HZH_Controls/HZH_Controls/Controls/Roll/UCRollText.cs
|
HappyQuQu/NetWinformControl
|
eaff6160e85cc235558f091b92eaa99120d35e7f
|
[
"Apache-2.0"
] | 38
|
2019-08-28T09:44:49.000Z
|
2022-03-31T23:24:32.000Z
|
HZH_Controls/HZH_Controls/Controls/Roll/UCRollText.cs
|
HappyQuQu/NetWinformControl
|
eaff6160e85cc235558f091b92eaa99120d35e7f
|
[
"Apache-2.0"
] | 564
|
2019-08-21T01:33:41.000Z
|
2022-03-31T13:03:19.000Z
|
// ***********************************************************************
// Assembly : HZH_Controls
// Created : 08-31-2019
//
// ***********************************************************************
// <copyright file="UCRollText.cs">
// Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
// </copyright>
//
// Blog: https://www.cnblogs.com/bfyx
// GitHub:https://github.com/kwwwvagaa/NetWinformControl
// gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
//
// If you use this code, please keep this note.
// ***********************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace HZH_Controls.Controls
{
/// <summary>
/// Class UCRollText.
/// Implements the <see cref="System.Windows.Forms.UserControl" />
/// </summary>
/// <seealso cref="System.Windows.Forms.UserControl" />
public class UCRollText : UserControl
{
/// <summary>
/// 获取或设置控件显示的文字的字体。
/// </summary>
/// <value>The font.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
if (!string.IsNullOrEmpty(Text))
{
Graphics g = this.CreateGraphics();
var size = g.MeasureString(Text, this.Font);
rectText = new Rectangle(0, (this.Height - rectText.Height) / 2 + 1, (int)size.Width, (int)size.Height);
rectText.Y = (this.Height - rectText.Height) / 2 + 1;
}
}
}
/// <summary>
/// 获取或设置控件的前景色。
/// </summary>
/// <value>The color of the fore.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
}
}
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>The text.</value>
[Bindable(true)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[EditorBrowsable(EditorBrowsableState.Always)]
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
if (!string.IsNullOrEmpty(value))
{
Graphics g = this.CreateGraphics();
var size = g.MeasureString(value, this.Font);
rectText = new Rectangle(_ISChangeReset ? 0 : rectText.X, (this.Height - rectText.Height) / 2 + 1, (int)size.Width, (int)size.Height);
}
else
{
rectText = Rectangle.Empty;
}
}
}
/// <summary>
/// The roll style
/// </summary>
private RollStyle _RollStyle = RollStyle.LeftToRight;
/// <summary>
/// 文本改变是否重新从边缘运动
/// </summary>
private bool _ISChangeReset = false;
/// <summary>
/// Gets or sets the roll style.
/// </summary>
/// <value>The roll style.</value>
[Description("滚动样式"), Category("自定义")]
public RollStyle RollStyle
{
get { return _RollStyle; }
set
{
_RollStyle = value;
switch (value)
{
case RollStyle.LeftToRight:
m_intdirection = 1;
break;
case RollStyle.RightToLeft:
m_intdirection = -1;
break;
}
}
}
[Description("文本改变是否重新从边缘运动"), Category("自定义")]
public bool ISChangeReset
{
get { return _ISChangeReset; }
set
{
_ISChangeReset = value;
}
}
/// <summary>
/// The move step
/// </summary>
private int _moveStep = 5;
/// <summary>
/// The move sleep time
/// </summary>
private int _moveSleepTime = 100;
/// <summary>
/// Gets or sets the move sleep time.
/// </summary>
/// <value>The move sleep time.</value>
[Description("每次滚动间隔时间,越小速度越快"), Category("自定义")]
public int MoveSleepTime
{
get { return _moveSleepTime; }
set
{
if (value <= 0)
{
return;
}
_moveSleepTime = value;
m_timer.Interval = value;
}
}
/// <summary>
/// The m intdirection
/// </summary>
int m_intdirection = 1;
/// <summary>
/// The rect text
/// </summary>
Rectangle rectText;
/// <summary>
/// The m timer
/// </summary>
Timer m_timer;
/// <summary>
/// Initializes a new instance of the <see cref="UCRollText" /> class.
/// </summary>
public UCRollText()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SizeChanged += UCRollText_SizeChanged;
this.Size = new Size(450, 30);
Text = "滚动文字";
m_timer = new Timer();
m_timer.Interval = 100;
m_timer.Tick += m_timer_Tick;
this.Load += UCRollText_Load;
this.VisibleChanged += UCRollText_VisibleChanged;
this.ForeColor = Color.FromArgb(255, 77, 59);
if (rectText != Rectangle.Empty)
{
rectText.Y = (this.Height - rectText.Height) / 2 + 1;
}
}
/// <summary>
/// Handles the Tick event of the m_timer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void m_timer_Tick(object sender, EventArgs e)
{
if (rectText == Rectangle.Empty)
{
return;
}
if (_RollStyle == HZH_Controls.Controls.RollStyle.BackAndForth && rectText.Width >= this.Width)
{
return;
}
rectText.X = rectText.X + _moveStep * m_intdirection;
if (_RollStyle == HZH_Controls.Controls.RollStyle.BackAndForth)
{
if (rectText.X <= 0)
{
m_intdirection = 1;
}
else if (rectText.Right >= this.Width)
{
m_intdirection = -1;
}
}
else if (_RollStyle == HZH_Controls.Controls.RollStyle.LeftToRight)
{
if (rectText.X > this.Width)
{
rectText.X = -1 * rectText.Width - 1;
}
}
else
{
if (rectText.Right < 0)
{
rectText.X = this.Width + rectText.Width + 1;
}
}
Refresh();
}
/// <summary>
/// Handles the VisibleChanged event of the UCRollText control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void UCRollText_VisibleChanged(object sender, EventArgs e)
{
m_timer.Enabled = this.Visible;
}
/// <summary>
/// Handles the Load event of the UCRollText control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void UCRollText_Load(object sender, EventArgs e)
{
if (_RollStyle == HZH_Controls.Controls.RollStyle.LeftToRight)
{
m_intdirection = 1;
if (rectText != Rectangle.Empty)
{
rectText.X = -1 * rectText.Width - 1;
}
}
else if (_RollStyle == HZH_Controls.Controls.RollStyle.RightToLeft)
{
m_intdirection = -1;
if (rectText != Rectangle.Empty)
{
rectText.X = this.Width + rectText.Width + 1;
}
}
else
{
m_intdirection = 1;
if (rectText != Rectangle.Empty)
{
rectText.X = 0;
}
}
if (rectText != Rectangle.Empty)
{
rectText.Y = (this.Height - rectText.Height) / 2 + 1;
}
}
/// <summary>
/// Handles the SizeChanged event of the UCRollText control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void UCRollText_SizeChanged(object sender, EventArgs e)
{
if (rectText != Rectangle.Empty)
{
rectText.Y = (this.Height - rectText.Height) / 2 + 1;
}
}
/// <summary>
/// 引发 <see cref="E:System.Windows.Forms.Control.Paint" /> 事件。
/// </summary>
/// <param name="e">包含事件数据的 <see cref="T:System.Windows.Forms.PaintEventArgs" />。</param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (rectText != Rectangle.Empty)
{
e.Graphics.SetGDIHigh();
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), rectText.Location);
}
}
}
/// <summary>
/// Enum RollStyle
/// </summary>
public enum RollStyle
{
/// <summary>
/// The left to right
/// </summary>
LeftToRight,
/// <summary>
/// The right to left
/// </summary>
RightToLeft,
/// <summary>
/// The back and forth
/// </summary>
BackAndForth
}
}
| 32.961957
| 215
| 0.487387
|
1bb0488fe38a777e9b69c410886b73c29c1634fb
| 7,994
|
lua
|
Lua
|
rom/programs/turtle/excavate.lua
|
LoganDark/craftos2-rom
|
7fa2e8f86c4442fb2d25acd1f12b40f813160640
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5
|
2021-07-19T23:39:07.000Z
|
2022-02-07T00:06:08.000Z
|
rom/programs/turtle/excavate.lua
|
LoganDark/craftos2-rom
|
7fa2e8f86c4442fb2d25acd1f12b40f813160640
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3
|
2020-12-25T08:51:50.000Z
|
2020-12-30T02:13:27.000Z
|
rom/programs/turtle/excavate.lua
|
LoganDark/craftos2-rom
|
7fa2e8f86c4442fb2d25acd1f12b40f813160640
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 7
|
2019-10-15T00:41:35.000Z
|
2022-02-07T00:04:23.000Z
|
if not turtle then
printError("Requires a Turtle")
return
end
local tArgs = { ... }
if #tArgs ~= 1 then
local programName = arg[0] or fs.getName(shell.getRunningProgram())
print("Usage: " .. programName .. " <diameter>")
return
end
-- Mine in a quarry pattern until we hit something we can't dig
local size = tonumber(tArgs[1])
if size < 1 then
print("Excavate diameter must be positive")
return
end
local depth = 0
local unloaded = 0
local collected = 0
local xPos, zPos = 0, 0
local xDir, zDir = 0, 1
local goTo -- Filled in further down
local refuel -- Filled in further down
local function unload(_bKeepOneFuelStack)
print("Unloading items...")
for n = 1, 16 do
local nCount = turtle.getItemCount(n)
if nCount > 0 then
turtle.select(n)
local bDrop = true
if _bKeepOneFuelStack and turtle.refuel(0) then
bDrop = false
_bKeepOneFuelStack = false
end
if bDrop then
turtle.drop()
unloaded = unloaded + nCount
end
end
end
collected = 0
turtle.select(1)
end
local function returnSupplies()
local x, y, z, xd, zd = xPos, depth, zPos, xDir, zDir
print("Returning to surface...")
goTo(0, 0, 0, 0, -1)
local fuelNeeded = 2 * (x + y + z) + 1
if not refuel(fuelNeeded) then
unload(true)
print("Waiting for fuel")
while not refuel(fuelNeeded) do
os.pullEvent("turtle_inventory")
end
else
unload(true)
end
print("Resuming mining...")
goTo(x, y, z, xd, zd)
end
local function collect()
local bFull = true
local nTotalItems = 0
for n = 1, 16 do
local nCount = turtle.getItemCount(n)
if nCount == 0 then
bFull = false
end
nTotalItems = nTotalItems + nCount
end
if nTotalItems > collected then
collected = nTotalItems
if math.fmod(collected + unloaded, 50) == 0 then
print("Mined " .. collected + unloaded .. " items.")
end
end
if bFull then
print("No empty slots left.")
return false
end
return true
end
function refuel(ammount)
local fuelLevel = turtle.getFuelLevel()
if fuelLevel == "unlimited" then
return true
end
local needed = ammount or xPos + zPos + depth + 2
if turtle.getFuelLevel() < needed then
for n = 1, 16 do
if turtle.getItemCount(n) > 0 then
turtle.select(n)
if turtle.refuel(1) then
while turtle.getItemCount(n) > 0 and turtle.getFuelLevel() < needed do
turtle.refuel(1)
end
if turtle.getFuelLevel() >= needed then
turtle.select(1)
return true
end
end
end
end
turtle.select(1)
return false
end
return true
end
local function tryForwards()
if not refuel() then
print("Not enough Fuel")
returnSupplies()
end
while not turtle.forward() do
if turtle.detect() then
if turtle.dig() then
if not collect() then
returnSupplies()
end
else
return false
end
elseif turtle.attack() then
if not collect() then
returnSupplies()
end
else
sleep(0.5)
end
end
xPos = xPos + xDir
zPos = zPos + zDir
return true
end
local function tryDown()
if not refuel() then
print("Not enough Fuel")
returnSupplies()
end
while not turtle.down() do
if turtle.detectDown() then
if turtle.digDown() then
if not collect() then
returnSupplies()
end
else
return false
end
elseif turtle.attackDown() then
if not collect() then
returnSupplies()
end
else
sleep(0.5)
end
end
depth = depth + 1
if math.fmod(depth, 10) == 0 then
print("Descended " .. depth .. " metres.")
end
return true
end
local function turnLeft()
turtle.turnLeft()
xDir, zDir = -zDir, xDir
end
local function turnRight()
turtle.turnRight()
xDir, zDir = zDir, -xDir
end
function goTo(x, y, z, xd, zd)
while depth > y do
if turtle.up() then
depth = depth - 1
elseif turtle.digUp() or turtle.attackUp() then
collect()
else
sleep(0.5)
end
end
if xPos > x then
while xDir ~= -1 do
turnLeft()
end
while xPos > x do
if turtle.forward() then
xPos = xPos - 1
elseif turtle.dig() or turtle.attack() then
collect()
else
sleep(0.5)
end
end
elseif xPos < x then
while xDir ~= 1 do
turnLeft()
end
while xPos < x do
if turtle.forward() then
xPos = xPos + 1
elseif turtle.dig() or turtle.attack() then
collect()
else
sleep(0.5)
end
end
end
if zPos > z then
while zDir ~= -1 do
turnLeft()
end
while zPos > z do
if turtle.forward() then
zPos = zPos - 1
elseif turtle.dig() or turtle.attack() then
collect()
else
sleep(0.5)
end
end
elseif zPos < z then
while zDir ~= 1 do
turnLeft()
end
while zPos < z do
if turtle.forward() then
zPos = zPos + 1
elseif turtle.dig() or turtle.attack() then
collect()
else
sleep(0.5)
end
end
end
while depth < y do
if turtle.down() then
depth = depth + 1
elseif turtle.digDown() or turtle.attackDown() then
collect()
else
sleep(0.5)
end
end
while zDir ~= zd or xDir ~= xd do
turnLeft()
end
end
if not refuel() then
print("Out of Fuel")
return
end
print("Excavating...")
local reseal = false
turtle.select(1)
if turtle.digDown() then
reseal = true
end
local alternate = 0
local done = false
while not done do
for n = 1, size do
for _ = 1, size - 1 do
if not tryForwards() then
done = true
break
end
end
if done then
break
end
if n < size then
if math.fmod(n + alternate, 2) == 0 then
turnLeft()
if not tryForwards() then
done = true
break
end
turnLeft()
else
turnRight()
if not tryForwards() then
done = true
break
end
turnRight()
end
end
end
if done then
break
end
if size > 1 then
if math.fmod(size, 2) == 0 then
turnRight()
else
if alternate == 0 then
turnLeft()
else
turnRight()
end
alternate = 1 - alternate
end
end
if not tryDown() then
done = true
break
end
end
print("Returning to surface...")
-- Return to where we started
goTo(0, 0, 0, 0, -1)
unload(false)
goTo(0, 0, 0, 0, 1)
-- Seal the hole
if reseal then
turtle.placeDown()
end
print("Mined " .. collected + unloaded .. " items total.")
| 22.329609
| 90
| 0.491869
|
1a8873be93de083b38229d99d7ecff8709e3ba89
| 228
|
py
|
Python
|
todo/celery.py
|
DipeshYogi/MyTodoList_backend
|
0b4103e791857b7e95981bd8c3d580b28b80e9eb
|
[
"MIT"
] | null | null | null |
todo/celery.py
|
DipeshYogi/MyTodoList_backend
|
0b4103e791857b7e95981bd8c3d580b28b80e9eb
|
[
"MIT"
] | 1
|
2021-03-22T19:07:43.000Z
|
2021-03-22T19:07:43.000Z
|
todo/celery.py
|
DipeshYogi/MyTodoList_backend
|
0b4103e791857b7e95981bd8c3d580b28b80e9eb
|
[
"MIT"
] | null | null | null |
# import os
# from celery import Celery
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo.settings")
# app = Celery("todo")
# app.config_from_object("django.conf:settings", namespace="CELERY")
# app.autodiscover_tasks()
| 25.333333
| 68
| 0.75
|
0bf3d8f4320b70ded7ec7aee049879ed23f6d8e2
| 2,232
|
sql
|
SQL
|
SQL/indecsi-view.sql
|
stefan-platon/JustForKids
|
b74ba6b07bf54c1b833ca486f933bb47fac222a3
|
[
"MIT"
] | 1
|
2017-05-29T09:32:20.000Z
|
2017-05-29T09:32:20.000Z
|
SQL/indecsi-view.sql
|
stefan-platon/Proiect-TW
|
b74ba6b07bf54c1b833ca486f933bb47fac222a3
|
[
"MIT"
] | null | null | null |
SQL/indecsi-view.sql
|
stefan-platon/Proiect-TW
|
b74ba6b07bf54c1b833ca486f933bb47fac222a3
|
[
"MIT"
] | null | null | null |
--sterg toti indecsii creati
ALTER TABLE tutor drop CONSTRAINT tutor_unique1;
DROP INDEX tutor_username;
ALTER TABLE player drop CONSTRAINT player_unique1;
DROP INDEX player_username;
ALTER TABLE admins drop CONSTRAINT admins_unique1;
DROP INDEX admin_username;
DROP INDEX games_cauta;
DROP INDEX achievements_cauta;
DROP INDEX player_stats_total;
/
--indecsi pentru select(clauza where)
CREATE INDEX tutor_username ON tutor (username);
ALTER TABLE tutor ADD CONSTRAINT tutor_unique1 UNIQUE ( username ) ;
--select tutor_id from tutor where username = 'Albu.Moalina.t'
CREATE INDEX player_username ON player (username);
ALTER TABLE player ADD CONSTRAINT player_unique1 UNIQUE ( username ) ;
CREATE INDEX admin_username ON admins (username);
ALTER TABLE admins ADD CONSTRAINT admins_unique1 UNIQUE ( username ) ;
/
--indecsi pentru functii
CREATE INDEX games_cauta ON games (LOWER(name));
CREATE INDEX achievements_cauta ON achievements (LOWER(name));
--SELECT g.game_id, g.name, g.difficulty, g.description, g.instructions, g.domain_id from games g join domains d on d.domain_id = g.domain_id where LOWER(g.name) = 'game_1'
/
--indecsi pentru order by
CREATE INDEX player_stats_total ON player_stats (total_score);
--select player_id, total_score from (select player_id, total_score from player_stats order by total_score desc) where rownum <= 10
/
--indecsi pentru comparare si between
CREATE INDEX player_dates_birthday ON player_dates (birthday);
--update player_dates set difficulty = 1 where birthday between TO_DATE('01/01/08','dd/mm/yy') and TO_DATE('31/12/11','dd/mm/yy')
/
--view pt popularea paginii de profil
CREATE MATERIALIZED VIEW player_profile_view
BUILD IMMEDIATE
REFRESH COMPLETE ON COMMIT
AS SELECT pl.username, pl.last_name, pl.first_name, pl.email, pd.birthday, pd.difficulty, pd.total_time, pa.logged_in, pa.logged_out, pl.ROWID as PL_ROWID, pd.ROWID as PD_ROWID, pa.ROWID as PA_ROWID
FROM player pl, player_dates pd, player_activity pa
WHERE pl.player_id = pd.player_id and pa.player_id = pl.player_id;
/
--update player_profile_view set username = '1'
execute DBMS_MVIEW.REFRESH( LIST => 'player_profile_view', METHOD => 'C' );
| 48.521739
| 205
| 0.768817
|
36944c824cdcbccfe7aa863bbc8901849eafab42
| 942
|
swift
|
Swift
|
testdemo/xib/ProgressBarView.swift
|
Changzw/every-case-demo
|
0ba08146fee2904bd2151fcea8041f03b8b86e71
|
[
"Apache-2.0"
] | null | null | null |
testdemo/xib/ProgressBarView.swift
|
Changzw/every-case-demo
|
0ba08146fee2904bd2151fcea8041f03b8b86e71
|
[
"Apache-2.0"
] | null | null | null |
testdemo/xib/ProgressBarView.swift
|
Changzw/every-case-demo
|
0ba08146fee2904bd2151fcea8041f03b8b86e71
|
[
"Apache-2.0"
] | null | null | null |
//
// ProgressBarView.swift
// testdemo
//
// Created by 常仲伟 on 2020/12/20.
// Copyright © 2020 常仲伟. All rights reserved.
//
import UIKit
@IBDesignable
class ProgressBarView: UIView {
override class var layerClass: AnyClass { CAGradientLayer.self }
private var _layer: CAGradientLayer { layer as! CAGradientLayer }
@IBInspectable
var startColor: UIColor = .red {
didSet {
_layer.colors = [startColor, endColor].map{ $0.cgColor }
setNeedsDisplay()
}
}
@IBInspectable
var endColor: UIColor = .green {
didSet {
_layer.colors = [startColor, endColor].map{ $0.cgColor }
setNeedsDisplay()
}
}
@IBInspectable
var startPoint: CGPoint = .zero {
didSet {
_layer.startPoint = startPoint
setNeedsDisplay()
}
}
@IBInspectable
var endPoint: CGPoint = CGPoint(x: 1, y: 0) {
didSet {
_layer.endPoint = endPoint
setNeedsDisplay()
}
}
}
| 19.22449
| 67
| 0.640127
|
4ce0bad6c5dd5960e892ea6985bc11b045b45541
| 1,973
|
py
|
Python
|
keyboard_listener.py
|
aodendaal/ai-stunt-driver
|
fb47dfdd907d73dd97c0df64ef8a5a0b8e894038
|
[
"MIT"
] | null | null | null |
keyboard_listener.py
|
aodendaal/ai-stunt-driver
|
fb47dfdd907d73dd97c0df64ef8a5a0b8e894038
|
[
"MIT"
] | null | null | null |
keyboard_listener.py
|
aodendaal/ai-stunt-driver
|
fb47dfdd907d73dd97c0df64ef8a5a0b8e894038
|
[
"MIT"
] | null | null | null |
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from pynput import keyboard
from pynput.keyboard import Key, Controller
has_started = True
is_listening = False
current_keys = set()
pressed_keys = set()
def on_press(key):
global has_started
global is_listening
current_keys.add(key)
if key == Key.f5:
is_listening = not is_listening
if is_listening:
print('Listening...')
else:
print('Stopped listening.')
if key == Key.f12:
has_started = False
print('App Stopped')
def on_release(key):
current_keys.discard(key)
def setup_keyboard_listening():
listen = keyboard.Listener(on_press=on_press, on_release=on_release)
listen.start()
print('App Started')
def press_keys(keys):
keyboard = Controller()
for key in pressed_keys:
keyboard.release(key)
for key in keys:
pressed_keys.add(key)
keyboard.press(key)
def clear_pressed_keys():
press_keys([]) # clear any pressed keys
def get_current_keys():
result = ''
for key in current_keys:
if hasattr(key, 'char'):
result = result + key.char + '+'
else:
result = result + str(key) + '+'
return result[:-1]
def get_keys_to_press(one_hot):
found = np.argmax(one_hot)
if (found == 0):
return '', 'nothing'
if (found == 1):
return [Key.up, Key.left], 'up+left'
elif (found == 2):
return [Key.up], 'up'
elif (found == 3):
return [Key.up, Key.right], 'up+right'
elif (found == 4):
return [Key.left], 'left'
elif (found == 5):
return [Key.right], 'right'
elif (found == 6):
return [Key.down, Key.left], 'down+left'
elif (found == 7):
return [Key.down], 'down'
elif (found == 8):
return [Key.down, Key.right], 'down+right'
else:
return '', 'FUCK UP!'
| 22.420455
| 82
| 0.597567
|
977790f0380dbd3ed2ce06415d209a7df0674097
| 1,945
|
swift
|
Swift
|
Demo/Demo/ContentView.swift
|
anikaseibezeder/MultiPicker
|
86a5a90e12157d6a69c5ef110194130c711836ae
|
[
"MIT"
] | 1
|
2021-05-15T11:28:42.000Z
|
2021-05-15T11:28:42.000Z
|
Demo/Demo/ContentView.swift
|
anikaseibezeder/MultiPicker
|
86a5a90e12157d6a69c5ef110194130c711836ae
|
[
"MIT"
] | null | null | null |
Demo/Demo/ContentView.swift
|
anikaseibezeder/MultiPicker
|
86a5a90e12157d6a69c5ef110194130c711836ae
|
[
"MIT"
] | null | null | null |
//
// ContentView.swift
// Demo
//
// Created by Anika Seibezeder on 15.05.21.
//
import SwiftUI
import MultiPicker
struct ContentView: View {
@State private var selectedOptionsDefaultStyle = Set<String>()
@State private var selectedOptionsGridStyle = Set<String>()
@State private var allowsMultipleSelectionDefaultStyle = false
@State private var allowsMultipleSelectionGridStyle = false
private let optionsDefaultStyle = ["Option 1", "Option 2"]
private let optionsGridStyle = ["😃", "😄", "😁", "😆", "😅"]
var body: some View {
NavigationView {
Form {
Section(header: Text("Default Multi Picker Style")) {
Toggle("Allows multiple selection", isOn: $allowsMultipleSelectionDefaultStyle)
MultiPicker("Options",
selection: $selectedOptionsDefaultStyle,
options: optionsDefaultStyle) {
$0
}
.multiPickerStyle(DefaultMultiPickerStyle(allowsMultipleSelection: allowsMultipleSelectionDefaultStyle))
}
Section(header: Text("Grid Picker Style")) {
Toggle("Allows multiple selection", isOn: $allowsMultipleSelectionGridStyle)
MultiPicker("Options",
selection: $selectedOptionsGridStyle,
options: optionsGridStyle) {
$0
}
.multiPickerStyle(GridPickerStyle(columns: 5, allowsMultipleSelection: allowsMultipleSelectionGridStyle))
}
}
.navigationTitle("MultiPicker Demo")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 34.732143
| 125
| 0.550129
|
a388757977e254385cf289ca31c1b7321c216e76
| 1,055
|
java
|
Java
|
MATF-Computer-Networks-4R/c06_URL_URLConnection/r02_post/Poster.java
|
Nevena1997/Computer-Networks
|
80ecfed9af0ba815de64d8c9665832f19932b25f
|
[
"MIT"
] | null | null | null |
MATF-Computer-Networks-4R/c06_URL_URLConnection/r02_post/Poster.java
|
Nevena1997/Computer-Networks
|
80ecfed9af0ba815de64d8c9665832f19932b25f
|
[
"MIT"
] | null | null | null |
MATF-Computer-Networks-4R/c06_URL_URLConnection/r02_post/Poster.java
|
Nevena1997/Computer-Networks
|
80ecfed9af0ba815de64d8c9665832f19932b25f
|
[
"MIT"
] | null | null | null |
package r02_post;
// Using QueryBuilder from previous example
import r06_query_builder.QueryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
final class Poster {
private URL url;
private QueryBuilder query;
Poster(URL url) {
if (!url.getProtocol().toLowerCase().startsWith("http"))
throw new IllegalArgumentException("Posting only works for http(s) URLs");
this.url = url;
this.query = new QueryBuilder(this.url.toString());
}
void add(String name, String value) {
this.query.append(name, value);
}
InputStream post() throws IOException {
// Open the connection and prepare it for POST
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream(), StandardCharsets.UTF_8);
out.write(this.query.toString());
out.flush();
out.close();
// Return the response
return uc.getInputStream();
}
}
| 22.934783
| 96
| 0.743128
|
b7537079cfb01614bd2fe684074a4fa7ac1e729b
| 2,590
|
cs
|
C#
|
CoinTime/CoinTime/Input/AmazonFireGameController.cs
|
forcemax/mobile-samples
|
a4ca7e7bf3ceda66107ce5b9049ea52e94afc214
|
[
"Apache-2.0"
] | 1,222
|
2015-01-12T12:11:07.000Z
|
2022-03-31T07:22:32.000Z
|
CoinTime/CoinTime/Input/AmazonFireGameController.cs
|
forcemax/mobile-samples
|
a4ca7e7bf3ceda66107ce5b9049ea52e94afc214
|
[
"Apache-2.0"
] | 61
|
2015-01-19T09:18:54.000Z
|
2021-09-08T10:58:43.000Z
|
CoinTime/CoinTime/Input/AmazonFireGameController.cs
|
forcemax/mobile-samples
|
a4ca7e7bf3ceda66107ce5b9049ea52e94afc214
|
[
"Apache-2.0"
] | 2,758
|
2015-01-01T00:17:56.000Z
|
2022-03-28T15:11:25.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using CoinTimeShared;
using Android.Views;
namespace CoinTimeGame.Input
{
public class AmazonFireGameController : IGameController, IMenuController
{
// The Xamarin component for controllers doesn't seem to work
// with CocosSharp, so we're going to handle the button pushes
// ourselves. The analog stick works well, so we'll still rely on
// the GameController class for analog stick movement
static List<Keycode> toProcess = new List<Keycode>();
static float dPadXToProcess;
static List<Keycode> pressedKeys = new List<Keycode> ();
float dPadX;
float dPadXChange;
float lastAnalogStickX;
float analogStickX;
static float analogStickToProcess;
float IGameController.HorizontalRatio
{
get{ return analogStickX; }
}
bool IGameController.JumpPressed
{
get
{
return pressedKeys.Contains (Keycode.ButtonA);
}
}
bool IGameController.BackPressed
{
get
{
return pressedKeys.Contains (Keycode.Back);
}
}
static bool isConnected;
public bool IsConnected
{
get
{
return isConnected;
}
}
bool IMenuController.SelectPressed
{
get
{
return pressedKeys.Contains (Keycode.ButtonA);
}
}
bool IMenuController.MovedLeft
{
get
{
return
// check the dpad:
(dPadXChange < 0 && dPadX < 0) ||
// and the analog stick:
(lastAnalogStickX > -.5 && analogStickX <= -.5);
}
}
bool IMenuController.MovedRight
{
get
{
return
// check the dpad:
(dPadXChange > 0 && dPadX > 0) ||
// and the analog stick:
(lastAnalogStickX < .5 && analogStickX >= .5);
}
}
public static void SetDPad(float value)
{
if (value != dPadXToProcess)
{
isConnected = true;
dPadXToProcess = value;
}
}
public static void SetLeftAnalogStick(float value)
{
if (value != analogStickToProcess)
{
isConnected = true;
analogStickToProcess = value;
}
}
public static void HandlePush(Keycode code)
{
// This handles all keys, a full implementation
// may only be considered connected if certain keys
// are pressed:
isConnected = true;
lock (toProcess)
{
toProcess.Add (code);
}
}
public void UpdateInputValues()
{
pressedKeys.Clear ();
lock (toProcess)
{
pressedKeys.AddRange (toProcess);
toProcess.Clear ();
}
lastAnalogStickX = analogStickX;
analogStickX = analogStickToProcess;
dPadXChange = dPadXToProcess - dPadX;
dPadX = dPadXToProcess;
}
}
}
| 18.368794
| 73
| 0.660618
|
979446305057c8c231cbd78010348fcf5dd69b4c
| 5,553
|
rb
|
Ruby
|
google-cloud-video_intelligence/samples/video_samples_helper.rb
|
doodzik/google-cloud-ruby
|
a28225ff4637df3bfb264467c02214fcb89d6c23
|
[
"Apache-2.0"
] | 8
|
2021-04-24T02:35:09.000Z
|
2022-01-29T03:05:45.000Z
|
google-cloud-video_intelligence/samples/video_samples_helper.rb
|
doodzik/google-cloud-ruby
|
a28225ff4637df3bfb264467c02214fcb89d6c23
|
[
"Apache-2.0"
] | 1
|
2021-02-24T07:42:47.000Z
|
2021-02-24T07:42:47.000Z
|
google-cloud-video_intelligence/samples/video_samples_helper.rb
|
doodzik/google-cloud-ruby
|
a28225ff4637df3bfb264467c02214fcb89d6c23
|
[
"Apache-2.0"
] | 2
|
2021-06-02T18:47:14.000Z
|
2021-09-18T07:08:17.000Z
|
# Copyright 2020 Google, 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.
def print_labels labels
labels.each do |label|
puts "Label description: #{label.entity.description}"
label.category_entities.each do |category_entity|
puts "Label category description: #{category_entity.description}"
end
label.segments.each do |segment|
start_time = (segment.segment.start_time_offset.seconds +
segment.segment.start_time_offset.nanos / 1e9)
end_time = (segment.segment.end_time_offset.seconds +
segment.segment.end_time_offset.nanos / 1e9)
puts "Segment: #{start_time} to #{end_time}"
puts "Confidence: #{segment.confidence}"
end
end
end
def print_annotations annotation_result
puts "Scenes:"
annotation_result.shot_annotations.each do |shot_annotation|
start_time = (shot_annotation.start_time_offset.seconds +
shot_annotation.start_time_offset.nanos / 1e9)
end_time = (shot_annotation.end_time_offset.seconds +
shot_annotation.end_time_offset.nanos / 1e9)
puts "#{start_time} to #{end_time}"
end
end
def print_explicit_annotation_frames explicit_annotation
explicit_annotation.frames.each do |frame|
frame_time = frame.time_offset.seconds + frame.time_offset.nanos / 1e9
puts "Time: #{frame_time}"
puts "pornography: #{frame.pornography_likelihood}"
end
end
def print_transcriptions transcriptions
transcriptions.each do |transcription|
transcription.alternatives.each do |alternative|
puts "Alternative level information:"
puts "Transcript: #{alternative.transcript}"
puts "Confidence: #{alternative.confidence}"
puts "Word level information:"
alternative.words.each do |word_info|
start_time = (word_info.start_time.seconds +
word_info.start_time.nanos / 1e9)
end_time = (word_info.end_time.seconds +
word_info.end_time.nanos / 1e9)
puts "#{word_info.word}: #{start_time} to #{end_time}"
end
end
end
end
def print_text_annotations text_annotations
text_annotations.each do |text_annotation|
puts "Text: #{text_annotation.text}"
# Print information about the first segment of the text.
text_segment = text_annotation.segments.first
print_segment_times text_segment.segment
puts "Confidence: #{text_segment.confidence}"
# Print information about the first frame of the segment.
frame = text_segment.frames.first
time_offset = (frame.time_offset.seconds +
frame.time_offset.nanos / 1e9)
puts "Time offset for the first frame: #{time_offset}"
puts "Rotated bounding box vertices:"
frame.rotated_bounding_box.vertices.each do |vertex|
puts "\tVertex.x: #{vertex.x}, Vertex.y: #{vertex.y}"
end
end
end
def print_object_annotations object_annotations
object_annotations.each do |object_annotation|
puts "Entity description: #{object_annotation.entity.description}"
puts "Entity id: #{object_annotation.entity.entity_id}" if object_annotation.entity.entity_id
object_segment = object_annotation.segment
print_segment_times object_segment
puts "Confidence: #{object_annotation.confidence}"
# Print information about the first frame of the segment.
frame = object_annotation.frames.first
time_offset = (frame.time_offset.seconds +
frame.time_offset.nanos / 1e9)
puts "Time offset for the first frame: #{time_offset}s"
box = frame.normalized_bounding_box
print_bounding_box_position box
end
end
def print_segment_times segment
start_time_offset = segment.start_time_offset
end_time_offset = segment.end_time_offset
start_time = (start_time_offset.seconds +
start_time_offset.nanos / 1e9)
end_time = (end_time_offset.seconds +
end_time_offset.nanos / 1e9)
puts "Segment start_time: #{start_time}, end_time: #{end_time}"
end
def print_bounding_box_position box
puts "Bounding box position:"
puts "\tleft : #{box.left}"
puts "\ttop : #{box.top}"
puts "\tright : #{box.right}"
puts "\tbottom: #{box.bottom}\n"
end
def print_usage
puts <<~USAGE
Usage: bundle exec ruby video_samples.rb [command] [arguments]
Commands:
analyze_labels <gcs_path> Detects labels given a GCS path.
analyze_labels_local <local_path> Detects labels given file path.
analyze_shots <gcs_path> Detects camera shot changes given a GCS path.
analyze_explicit_content <gcs_path> Detects explicit content given a GCS path.
transcribe_speech <gcs_path> Transcribes speech given a GCS path.
detect_text_gcs <gcs_path> Detects text given a GCS path.
detect_text_local <local_path> Detects text given file path.
track_objects_gcs <gcs_path> Track objects given a GCS path.
track_objects_local <local_path> Track objects given file path.
USAGE
end
| 35.369427
| 97
| 0.709346
|
b35d6bda31e836ac1bc51b7bdb4d7924dffd3c21
| 453
|
py
|
Python
|
python-lab-file/08_multiplymatrix.py
|
zshashz/py1729
|
3281ae2a20c665ebcc0d53840cc95143cbe6861b
|
[
"MIT"
] | 1
|
2021-01-22T09:03:59.000Z
|
2021-01-22T09:03:59.000Z
|
python-lab-file/08_multiplymatrix.py
|
zshashz/py1729
|
3281ae2a20c665ebcc0d53840cc95143cbe6861b
|
[
"MIT"
] | null | null | null |
python-lab-file/08_multiplymatrix.py
|
zshashz/py1729
|
3281ae2a20c665ebcc0d53840cc95143cbe6861b
|
[
"MIT"
] | 2
|
2021-05-04T11:29:38.000Z
|
2021-11-03T13:09:48.000Z
|
# Program 8 : multiply two matrices
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
result = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
| 15.62069
| 36
| 0.507726
|
e23c77889b1d5e423e123d82732c2a2f795da683
| 908
|
py
|
Python
|
deployment/flask_v1/client.py
|
atwork2/pytorch_classification
|
eafd8cfdee53d353f9678c1465e0a05862f58884
|
[
"MIT"
] | 841
|
2020-04-21T01:19:45.000Z
|
2022-03-30T02:50:11.000Z
|
deployment/flask_v1/client.py
|
Curdboycc/torch-template-for-deep-learning
|
da1ebc527d44c8c5a524e757a1d784ba37ec2d5c
|
[
"Apache-2.0"
] | 42
|
2020-04-20T02:42:31.000Z
|
2022-03-30T04:06:49.000Z
|
deployment/flask_v1/client.py
|
Curdboycc/torch-template-for-deep-learning
|
da1ebc527d44c8c5a524e757a1d784ba37ec2d5c
|
[
"Apache-2.0"
] | 235
|
2020-04-24T08:24:01.000Z
|
2022-03-29T06:37:15.000Z
|
# -*- coding:utf-8 -*-
# @time :2020.04.05
# @IDE : pycharm
# @author :lxztju
# @github : https://github.com/lxztju
import requests
import time
# Initialize the keras REST API endpoint URL.
REST_API_URL = 'http://127.0.0.1:5000/predict'
def predict_result(image_path):
# Initialize image path
image = open(image_path, 'rb').read()
payload = {'image': image}
# Submit the request.
r = requests.post(REST_API_URL, files=payload).json()
# Ensure the request was successful.
if r['success']:
# Loop over the predictions and display them.
for (i, result) in enumerate(r['predictions']):
print(result)
# Otherwise, the request failed.
else:
print('Request failed')
if __name__ == '__main__':
t1 = time.time()
img_path = '../test_images/electronic_100.png'
predict_result(img_path)
t2 = time.time()
print(t2-t1)
| 22.146341
| 57
| 0.637665
|
14607552497eec11488b23e0d4eec6d4c327b37e
| 1,052
|
swift
|
Swift
|
SafetySwitch/Switch/CircleShapeLayer.swift
|
flymg/SafetySwitch
|
315a7eaf734adf7ca8a9ea96f26e40cb88d4d2b4
|
[
"MIT"
] | null | null | null |
SafetySwitch/Switch/CircleShapeLayer.swift
|
flymg/SafetySwitch
|
315a7eaf734adf7ca8a9ea96f26e40cb88d4d2b4
|
[
"MIT"
] | null | null | null |
SafetySwitch/Switch/CircleShapeLayer.swift
|
flymg/SafetySwitch
|
315a7eaf734adf7ca8a9ea96f26e40cb88d4d2b4
|
[
"MIT"
] | null | null | null |
//
// created 11.11.20
// lumibit.io
import UIKit
class CircleShapeLayer: CAShapeLayer {
override init(layer: Any) {
self.x = 0
self.y = 0
self.diameter = 0
super.init(layer: layer)
}
override init() {
self.x = 0
self.y = 0
self.diameter = 0
super.init()
}
func layout(x: CGFloat, y: CGFloat, diameter: CGFloat, fillColor: UIColor) {
self.x = x
self.y = y
self.diameter = diameter
self.fillColor = fillColor.cgColor
let circleRect = CGRect(
x: x,
y: y,
width: diameter,
height: diameter)
let circlePath = UIBezierPath(roundedRect: circleRect, cornerRadius: 0.5 * diameter)
self.path = circlePath.cgPath
self.position = CGPoint(x: 0, y: 0)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var x: CGFloat
private var y: CGFloat
var diameter: CGFloat
}
| 21.469388
| 92
| 0.548479
|
a1079afee85172f7091e31498408cb7718a699ba
| 125
|
ts
|
TypeScript
|
dist/word.entity.d.ts
|
xvs32x/nsv-dictionary-nestjs
|
f414183377992757b7b72d5fe647a5ce30abe725
|
[
"MIT"
] | null | null | null |
dist/word.entity.d.ts
|
xvs32x/nsv-dictionary-nestjs
|
f414183377992757b7b72d5fe647a5ce30abe725
|
[
"MIT"
] | null | null | null |
dist/word.entity.d.ts
|
xvs32x/nsv-dictionary-nestjs
|
f414183377992757b7b72d5fe647a5ce30abe725
|
[
"MIT"
] | null | null | null |
export declare class WordEntity {
id?: number;
term: string;
translate: string;
readonly createdAt?: Date;
}
| 17.857143
| 33
| 0.656
|
a4dac7bad98931039df49e8e9b599bd756440602
| 1,378
|
ps1
|
PowerShell
|
Tests/New-DirkConfigExampleItem.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
Tests/New-DirkConfigExampleItem.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
Tests/New-DirkConfigExampleItem.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
if (-not $ENV:BHProjectPath) {
Set-BuildEnvironment -Path $PSScriptRoot\..
}
Remove-Module $ENV:BHProjectName -ErrorAction SilentlyContinue
Import-Module (Join-Path $ENV:BHProjectPath $ENV:BHProjectName) -Force
InModuleScope $ENV:BHProjectName {
$PSVersion = $PSVersionTable.PSVersion.Major
$ProjectRoot = $ENV:BHProjectPath
$Verbose = @{}
if ($ENV:BHBranchName -notlike "master" -or $env:BHCommitMessage -match "!verbose") {
$Verbose.add("Verbose", $True)
}
Describe "New-DirkConfigExampleItem" {
$NewExampleItemParams = @{
RequiredType = 'int'
Prompt = 'This is a prompt'
Example = '999'
Required = $true
}
$NewExampleItem = New-DirkConfigExampleItem @NewExampleItemParams
It "RequiredType should be correct" {
$NewExampleItem.RequiredType | Should -Be $NewExampleItemParams.RequiredType
}
It "Prompt should be correct" {
$NewExampleItem.Prompt | Should -Be $NewExampleItemParams.Prompt
}
It "Example should be correct" {
$NewExampleItem.Example | Should -Be $NewExampleItemParams.Example
}
It "Required should be correct" {
$NewExampleItem.Required | Should -Be $NewExampleItemParams.Required
}
Assert-VerifiableMock
}
}
| 32.046512
| 89
| 0.632801
|
96cc4d1c63474c2e1b94980eccbb63907eb4321e
| 350
|
cs
|
C#
|
Assets/Scripts/Common/SplashScreen/FullScreenVideoDisplayer.cs
|
blacksmokersen/starwheels
|
b765705760c430ce89d51e1d271da8a6a08cf202
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Common/SplashScreen/FullScreenVideoDisplayer.cs
|
blacksmokersen/starwheels
|
b765705760c430ce89d51e1d271da8a6a08cf202
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Common/SplashScreen/FullScreenVideoDisplayer.cs
|
blacksmokersen/starwheels
|
b765705760c430ce89d51e1d271da8a6a08cf202
|
[
"MIT"
] | 1
|
2020-11-26T21:51:44.000Z
|
2020-11-26T21:51:44.000Z
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
namespace Common.UI
{
public class FullScreenVideoDisplayer : MonoBehaviour
{
[Header("Video Settings")]
[SerializeField] private VideoClip _videoClip;
[SerializeField] private VideoPlayer _videoPlayer;
}
}
| 21.875
| 58
| 0.731429
|
f57dfe00b3ab8c3cb53fbc63a63615cfb6cb25a5
| 640
|
sh
|
Shell
|
install-tensorflow.sh
|
Tiryoh/jetson-nano-tools
|
d6cf927b918927cb8017568746a86dcb3b5610e5
|
[
"MIT"
] | null | null | null |
install-tensorflow.sh
|
Tiryoh/jetson-nano-tools
|
d6cf927b918927cb8017568746a86dcb3b5610e5
|
[
"MIT"
] | null | null | null |
install-tensorflow.sh
|
Tiryoh/jetson-nano-tools
|
d6cf927b918927cb8017568746a86dcb3b5610e5
|
[
"MIT"
] | null | null | null |
#!/bin/bash
# Reference Site
# https://docs.nvidia.com/deeplearning/dgx/install-tf-xavier/index.html
sudo apt-get update
# Install HDF5
sudo apt-get -y install libhdf5-serial-dev hdf5-tools
# Install pip
sudo apt-get -y install python3-pip
# Update
# pip3 install -U pip
# Install required packages
sudo apt-get -y install zlib1g-dev zip libjpeg8-dev libhdf5-dev
sudo pip3 install -U numpy grpcio absl-py py-cpuinfo psutil portpicker grpcio six mock requests gast h5py astor termcolor
# Install TensorFlow
pip3 install --extra-index-url https://developer.download.nvidia.com/compute/redist/jp/v42 tensorflow-gpu==1.13.1+nv19.4 --user
| 29.090909
| 127
| 0.776563
|
a15deb0740ab963fca1a9cedc8139c574a70208c
| 1,106
|
ts
|
TypeScript
|
src/modules/baskets/schemas/basket.schema.ts
|
rezabaratvand/shop-panel
|
ae216b4110fb2bafed312f7fe669e71517fa0612
|
[
"MIT"
] | 1
|
2021-11-27T11:59:25.000Z
|
2021-11-27T11:59:25.000Z
|
src/modules/baskets/schemas/basket.schema.ts
|
rezabaratvand/shop-panel
|
ae216b4110fb2bafed312f7fe669e71517fa0612
|
[
"MIT"
] | null | null | null |
src/modules/baskets/schemas/basket.schema.ts
|
rezabaratvand/shop-panel
|
ae216b4110fb2bafed312f7fe669e71517fa0612
|
[
"MIT"
] | null | null | null |
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as mongoose from 'mongoose';
import { Product } from '../../products/schemas/product.schema';
import { Coupon } from '../../coupons/schemas/coupon.schema';
import { User } from '../../users/schemas/user.schema';
import shippingMethods from '../../../constants/shipping-methods.constant';
export type BasketDocument = Basket & Document;
@Schema({ versionKey: false, timestamps: true })
export class Basket {
@Prop({
type: [{ type: mongoose.Types.ObjectId, ref: Product.name }],
required: true,
})
products: Product[];
@Prop({ type: mongoose.Types.ObjectId, ref: Coupon.name })
coupon?: Coupon;
@Prop({ type: Number })
totalPrice: number;
@Prop({ type: Number, default: 0 })
discount?: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name, required: true })
user: User;
@Prop({ type: String, enum: Object.values(shippingMethods), required: true })
shippingMethod: string;
}
export const BasketSchema = SchemaFactory.createForClass(Basket);
| 30.722222
| 81
| 0.690778
|
a43933c6a1126689d7a3cce7341c418179c84588
| 3,184
|
php
|
PHP
|
src/Utilities/Licenses/Ops/CleanDuplicatedSiteActivations.php
|
FernleafSystems/Utilities-EDD
|
d6a4e84865e14be9c18ffd6efb9bc622d7f2c7c7
|
[
"MIT"
] | null | null | null |
src/Utilities/Licenses/Ops/CleanDuplicatedSiteActivations.php
|
FernleafSystems/Utilities-EDD
|
d6a4e84865e14be9c18ffd6efb9bc622d7f2c7c7
|
[
"MIT"
] | null | null | null |
src/Utilities/Licenses/Ops/CleanDuplicatedSiteActivations.php
|
FernleafSystems/Utilities-EDD
|
d6a4e84865e14be9c18ffd6efb9bc622d7f2c7c7
|
[
"MIT"
] | null | null | null |
<?php
namespace FernleafSystems\Integrations\Edd\Utilities\Licenses\Ops;
use FernleafSystems\Integrations\Edd\Consumers;
use FernleafSystems\Integrations\Edd\Utilities\Licenses\Activations\EddActivationVO;
use FernleafSystems\Integrations\Edd\Utilities\Licenses\Activations\Retrieve;
use FernleafSystems\Integrations\Edd\Utilities\Licenses\LicensesIterator;
class CleanDuplicatedSiteActivations {
use Consumers\EddDownloadConsumer;
use Consumers\EddCustomerConsumer;
public function clean() {
$eddSL = edd_software_licensing();
// For each URL, iterate over the activations to determine what state we're in
// i.e. how many activations do we have for the same URL for active licenses, and expired licenses.
foreach ( $this->getActivationsSortedBySite() as $url => $activations ) {
/** @var EddActivationVO[] $activeActs */
$activeActs = [];
/** @var EddActivationVO[] $expiredActs */
$expiredActs = [];
foreach ( $activations as $activ ) {
$activ->lic_expired ? ( $expiredActs[] = $activ ) : ( $activeActs[] = $activ );
}
if ( count( $activeActs ) > 0 ) {
// Since there is an active license with this URL, we remove the URL from all expired licenses.
if ( !empty( $expiredActs ) ) {
foreach ( $expiredActs as $oExpiredAct ) {
$lic = $eddSL->get_license( $oExpiredAct->license_id );
if ( $lic instanceof \EDD_SL_License ) {
error_log( sprintf( 'Unnecessary expired- remove %s from %s', $url, $oExpiredAct->license_id ) );
$lic->remove_site( $url );
}
}
}
/**
* There are multiple licenses with the same URL activated for it.
* We keep the one that will expire last and remove all the rest.
*/
if ( count( $activeActs ) > 1 ) {
// leave only the most recent active
$current = $eddSL->get_license( array_pop( $activeActs )->license_id );
foreach ( $activeActs as $oActiveAct ) {
$lic = $eddSL->get_license( $oActiveAct->license_id );
if ( $lic instanceof \EDD_SL_License && $lic->expiration > 0 ) {
if ( $lic->expiration > $current->expiration ) {
error_log( sprintf( 'Has Active, remove expired- remove %s from %s', $url, $current->ID ) );
$current->remove_site( $url );
$current = $lic;
}
else {
error_log( sprintf( 'Has Active, remove expired- remove %s from %s', $url, $lic->ID ) );
$lic->remove_site( $url );
}
}
}
}
}
}
}
/**
* @return EddActivationVO[][]
*/
private function getActivationsSortedBySite() :array {
$licIT = new LicensesIterator();
$licIT->filterByCustomer( $this->getEddCustomer()->id );
/** @var EddActivationVO[][] $byURLs */
$byURLs = [];
foreach ( $licIT as $lic ) {
if ( !empty( $lic ) ) {
foreach ( ( new Retrieve() )->forLicense( $lic ) as $activation ) {
if ( !isset( $byURLs[ $activation->site_name ] ) ) {
$byURLs[ $activation->site_name ] = [];
}
$byURLs[ $activation->site_name ][] = $activation;
}
}
}
// Keep only the URLs where their activation count is greater 1
return array_filter( $byURLs, fn( $activations ) => count( $activations ) > 1 );
}
}
| 34.236559
| 104
| 0.639761
|
24bfc0a418f87e8ff8f5e1c0e64f7f69d33607ac
| 813
|
php
|
PHP
|
htdocs/magento/vendor/magento/magento-coding-standard/Magento2/Sniffs/PHP/GotoSniff.php
|
Nikhilsb/Xampp-Magento
|
554443597eaf3249724743efe54514d46e3d4884
|
[
"Apache-2.0"
] | null | null | null |
htdocs/magento/vendor/magento/magento-coding-standard/Magento2/Sniffs/PHP/GotoSniff.php
|
Nikhilsb/Xampp-Magento
|
554443597eaf3249724743efe54514d46e3d4884
|
[
"Apache-2.0"
] | null | null | null |
htdocs/magento/vendor/magento/magento-coding-standard/Magento2/Sniffs/PHP/GotoSniff.php
|
Nikhilsb/Xampp-Magento
|
554443597eaf3249724743efe54514d46e3d4884
|
[
"Apache-2.0"
] | null | null | null |
<?php
/**
* Copyright © Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\PHP;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Detects use of GOTO.
*/
class GotoSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $errorMessage = 'Use of goto is discouraged.';
/**
* Warning violation code.
*
* @var string
*/
protected $errorCode = 'FoundGoto';
/**
* @inheritdoc
*/
public function register()
{
return [T_GOTO];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$phpcsFile->addError($this->errorMessage, $stackPtr, $this->errorCode);
}
}
| 17.673913
| 79
| 0.590406
|
48683008210b57161881fd025dfb0cfd0b6b6c91
| 2,126
|
swift
|
Swift
|
Potatso/NotificationHandler.swift
|
yumumu/Potatso-swift5
|
2fc450952cf111290565331ecb5097e5253cd8bd
|
[
"MIT"
] | 101
|
2019-06-23T12:23:56.000Z
|
2022-02-02T02:29:53.000Z
|
Potatso/Potatso/NotificationHandler.swift
|
547/Potatso_SW
|
5f04a52e1fa26216852e4dbc6ce11814686d0ed5
|
[
"MIT"
] | 8
|
2019-06-30T09:15:19.000Z
|
2022-03-31T08:49:03.000Z
|
Potatso/Potatso/NotificationHandler.swift
|
547/Potatso_SW
|
5f04a52e1fa26216852e4dbc6ce11814686d0ed5
|
[
"MIT"
] | 85
|
2019-06-22T09:16:26.000Z
|
2022-03-31T08:47:22.000Z
|
//
// NotificationHandler.swift
// Potatso
//
// Created by LEI on 7/23/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import ICSMainFramework
import CloudKit
class NotificationHandler: NSObject, AppLifeCycleProtocol {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
configPush()
return true
}
func configPush() {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
DDLogInfo("didRegisterForRemoteNotificationsWithDeviceToken: \(deviceToken.hexString())")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let dict = userInfo as? [String: NSObject] {
let ckNotification = CKNotification(fromRemoteNotificationDictionary: dict)
if ckNotification.subscriptionID == potatsoSubscriptionId {
DDLogInfo("received a CKNotification")
SyncManager.shared.sync()
}
}
completionHandler(.noData)
}
}
extension Data {
func hexString() -> String {
// "Array" of all bytes:
let bytes = UnsafeBufferPointer<UInt8>(start: (self as NSData).bytes.bindMemory(to: UInt8.self, capacity: self.count), count:self.count)
// Array of hex strings, one for each byte:
let hexBytes = bytes.map { String(format: "%02hhx", $0) }
// Concatenate all hex strings:
return hexBytes.joined(separator: "")
}
}
| 37.298246
| 198
| 0.704139
|
f7a4a30c0e3b9c6a6cb99df9f2317a892d8bc283
| 4,496
|
rb
|
Ruby
|
spec/kosapi_cli/kosapi_token_loader_spec.rb
|
simactom/kosapi_cli.rb
|
cb19e6dd61a2c47c14124394414bf808638dff75
|
[
"MIT"
] | null | null | null |
spec/kosapi_cli/kosapi_token_loader_spec.rb
|
simactom/kosapi_cli.rb
|
cb19e6dd61a2c47c14124394414bf808638dff75
|
[
"MIT"
] | null | null | null |
spec/kosapi_cli/kosapi_token_loader_spec.rb
|
simactom/kosapi_cli.rb
|
cb19e6dd61a2c47c14124394414bf808638dff75
|
[
"MIT"
] | null | null | null |
RSpec.describe KOSapiCLI::KOSapiTokenLoader do
let(:broken) do
{ 'broken' => { 'env' => 'file' } }
end
let(:valid) do
{ 'config' => { 'client_token' => { 'access_token' => 'fas4f68sef486sef4',
'refresh_token' => '',
'expires_at' => (Time.now.to_i + 1000),
'token_type' => 'bearer',
'scope' => 'cvut:kosapi:read' } } }
end
let(:invalid) do
{ 'config' => { 'client_token' => { 'access_token' => 'fas4f68sef486sef4',
'refresh_token' => '',
'expires_at' => (Time.now.to_i - 1000),
'token_type' => 'bearer',
'scope' => 'cvut:kosapi:read' } } }
end
let(:config) do
KOSapiCLI::Configuration.new(env_file: '/tmp/.kosapi_cli.env')
end
subject(:loader) do
KOSapiCLI::KOSapiTokenLoader.new(config)
end
describe '#restore_token' do
context '.kosapi_cli.env does not file exist' do
it 'should try to read from .env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
loader.restore_token
end
it 'should return nil if env file does not exist' do
expect(loader.restore_token).to be_nil
end
end
context '.kosapi_cli.env does exists but contains not valid data' do
before(:each) { write_yaml_env(config.env_file, broken) }
after(:each) { File.delete(config.env_file) }
it 'should read from .env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
loader.restore_token
end
it 'should return nil if env file is broken' do
expect(loader.restore_token).to be_nil
end
end
context 'valid token in .kosapi_cli.env file' do
before(:each) { write_yaml_env(config.env_file, valid) }
after(:each) { File.delete(config.env_file) }
it 'should read from .env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
loader.restore_token
end
it 'should return hash' do
expect(loader.restore_token).to be_a Hash
end
it 'should contain stored data' do
expect(loader.restore_token).to eq valid['config']['client_token']
end
end
context 'invalid token in .kosapi_cli.env file' do
before(:each) { write_yaml_env(config.env_file, invalid) }
after(:each) { File.delete(config.env_file) }
it 'should read from .env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
loader.restore_token
end
it 'should return nil if token is not valid' do
expect(loader.restore_token).to be_nil
end
end
end
describe '#store_token' do
context '.kosapi_cli.env does not exists' do
it 'should read and write into env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
expect(File).to receive(:open).with(config.env_file, 'w')
loader.store_token(valid['config']['client_token'])
end
it 'should create env file' do
expect(File.file?(config.env_file)).to be false
loader.store_token(valid['config']['client_token'])
expect(File.file?(config.env_file)).to be true
end
it 'should store data that was given' do
loader.store_token(valid['config']['client_token'])
test = {}
File.open(config.env_file, 'r') do |f|
test = YAML.safe_load(f)
end
expect(valid['config']['client_token']).to eq(test['config']['client_token'])
end
end
context '.kosapi_cli.env does already exists' do
before(:each) { write_yaml_env(config.env_file, valid) }
after(:each) { File.delete(config.env_file) }
it 'should read and write into env file' do
expect(File).to receive(:open).with(config.env_file, 'r')
expect(File).to receive(:open).with(config.env_file, 'w')
loader.store_token(valid['config']['client_token'])
end
it 'should store data that was given' do
loader.store_token(valid['config']['client_token'])
test = {}
File.open(config.env_file, 'r') do |f|
test = YAML.safe_load(f)
end
expect(valid['config']['client_token']).to eq(test['config']['client_token'])
end
end
end
end
| 33.552239
| 85
| 0.581628
|
e71c79208914f346d6524cfee5fa6513687d1ad8
| 340
|
php
|
PHP
|
UQTheme/scss/components/previous-next-links/previous_next_links.tpl.php
|
CalvinLowe/HPC-Portal
|
5b7e6aaa63512680b9be612784a5a9848810a414
|
[
"MIT"
] | 2
|
2021-03-05T17:34:57.000Z
|
2022-02-25T01:16:14.000Z
|
UQTheme/scss/components/previous-next-links/previous_next_links.tpl.php
|
CalvinLowe/HPC-Portal
|
5b7e6aaa63512680b9be612784a5a9848810a414
|
[
"MIT"
] | 103
|
2021-01-13T06:29:33.000Z
|
2022-03-24T01:13:14.000Z
|
public/styles/uq/scss/components/previous-next-links/previous_next_links.tpl.php
|
UQ-RCC/ipp
|
b1d3d0cbc6f3cb662f0085d90166b85ba093c806
|
[
"MIT"
] | null | null | null |
<?php
/**
* @file
*/
?>
<div class="previous-next-links">
<div class="row">
<div class="columns medium-6">
<?php
if (isset($prev)) {
print $prev;
}
?>
</div>
<div class="columns medium-6">
<?php
if (isset($next)) {
print $next;
}
?>
</div>
</div>
</div>
| 14.166667
| 34
| 0.426471
|
0bb366080557d20595967b03a363969f4bcd191d
| 3,287
|
swift
|
Swift
|
Sources/BSKAppCore/UIBase/Router/Route/BSKRoute.swift
|
bluesky335/BSKAppCore
|
0d33f8e5912b5fb7ec0d0f0816720a4ec1d9a798
|
[
"MIT"
] | 6
|
2019-08-03T12:10:36.000Z
|
2022-03-08T12:47:51.000Z
|
Sources/BSKAppCore/UIBase/Router/Route/BSKRoute.swift
|
bluesky335/BSKAppCore
|
0d33f8e5912b5fb7ec0d0f0816720a4ec1d9a798
|
[
"MIT"
] | null | null | null |
Sources/BSKAppCore/UIBase/Router/Route/BSKRoute.swift
|
bluesky335/BSKAppCore
|
0d33f8e5912b5fb7ec0d0f0816720a4ec1d9a798
|
[
"MIT"
] | 1
|
2022-02-21T02:02:41.000Z
|
2022-02-21T02:02:41.000Z
|
//
// CLDRoute.swift
//
// Created by BlueSky335 on 2019/4/15.
//
import UIKit
public struct BSKRoute {
static var RouteSchem:String = ""
static var BundleID:String = ""
/// 传递的参数,主要是一些基本数据类型的参数,传递对象类型的参数请在下面的RouteParameters配置
public var queryParameters: [String: QueryValueProtocol]?
/// 需要传递的对象类型的参数
public var routeParameters: [String: Any]?
/// 处理路由的Handler
public let handlerType: RouteHandler.Type
/// 路由路径
public var routePath: String
/// 路由匹配的正则,如果不设置则使用routePath完全匹配
public var routeMatchRegular: String?
/// 路由的优先级
public var priority: Int = 500
/// 生成用于路由的url
public var routeURL: URL {
var urlStr = routePath
if let parameters = self.queryParameters {
urlStr += parameters.bsk.urlQueryString
}
return URL(string: urlStr)!
}
private static let RoutePathHost = "\(RouteSchem)://\(BundleID)/"
public init(routePath: String = #function, routeMatchRegular: String? = nil, handlerType: RouteHandler.Type) {
self.handlerType = handlerType
var absoluteRoutePath = BSKRoute.RoutePathHost
if let path = try? routePath.bsk.replace(match: "(_:)|(:\\))|(\\))", with: "", options: []).bsk
.replace(match: ":_", with: ":", options: []).bsk
.replace(match: ":|\\(", with: "_", options: []) {
absoluteRoutePath += path
} else {
let startIndex = routePath.startIndex
if let endIndex = routePath.firstIndex(of: "(") {
absoluteRoutePath += String(routePath[startIndex..<endIndex])
} else {
absoluteRoutePath += routePath
}
}
self.routePath = absoluteRoutePath
self.routeMatchRegular = routeMatchRegular
}
}
public extension BSKRouter {
@discardableResult
static func open(_ route: BSKRoute, routeParameters: [String: Any]? = nil, animated: Bool = true, targetCallBack: TargerCallBack? = nil, complateCallBack: (() -> Void)? = nil) -> Bool {
var dic = route.routeParameters
if !(dic == nil && routeParameters == nil) { // 二者中有一个不为空时,合并routeParameters,
if dic == nil {
dic = routeParameters
} else {
if let routeDic = routeParameters {
for (key, value) in routeDic {
dic![key] = value
}
}
}
}
if !BSKRouter.share.isRegister(route: route.routePath) {
BSKRouter.share.register(handeler: route.handlerType, routeMatcherRegular: route.routeMatchRegular, for: route)
}
return BSKRouter.share.handel(url: route.routeURL, routeParameters: dic, animated: animated, targetCallBack: targetCallBack, complateCallBack: complateCallBack)
}
private func register(handeler: RouteHandler.Type, routeMatcherRegular: String? = nil, for Route: BSKRoute) {
let matcher = BSKRouteMatcher(routeExpression: routeMatcherRegular ?? Route.routePath)
matcher.priority = Route.priority
register(handeler: handeler, matcher: matcher, for: Route.routePath)
}
}
| 33.20202
| 189
| 0.597201
|
1774c2f6e1cfd94b90010e35c7474cd32b67e963
| 438
|
swift
|
Swift
|
examples/benchmarks/array_filler/Sources/array_filler.swift
|
jpedrosa/sua
|
c7f04f0e4dd7c41f3a9b8c9ea37a2b7f557ccf27
|
[
"Apache-2.0"
] | 49
|
2015-12-30T19:16:24.000Z
|
2019-04-16T05:42:22.000Z
|
examples/benchmarks/array_filler/Sources/array_filler.swift
|
jpedrosa/sua_swift
|
c7f04f0e4dd7c41f3a9b8c9ea37a2b7f557ccf27
|
[
"Apache-2.0"
] | 2
|
2016-01-13T16:09:25.000Z
|
2018-07-17T16:42:01.000Z
|
examples/benchmarks/array_filler/Sources/array_filler.swift
|
jpedrosa/sua_swift
|
c7f04f0e4dd7c41f3a9b8c9ea37a2b7f557ccf27
|
[
"Apache-2.0"
] | 6
|
2016-01-14T02:16:28.000Z
|
2019-05-16T02:46:52.000Z
|
let ITERATIONS = 1000000
func fillArray(_ a: inout [Int]) {
var n = 0
for _ in 0..<ITERATIONS {
a.append(n)
n += 1
if n > 15 {
n = 0
}
}
}
func fillArray2(_ a: inout [Int]) {
var n = 0
for i in 0..<ITERATIONS {
a[i] = n
n += 1
if n > 15 {
n = 0
}
}
}
func countPresence(_ a: [Int], n: Int) -> Int {
var r = 0
for c in a {
if c == n {
r += 1
}
}
return r
}
| 12.514286
| 47
| 0.442922
|
c6a614791b278e999b67693c9a9be6e1817e38df
| 156
|
py
|
Python
|
pfr_api/__init__.py
|
aadamson/pfr-api
|
b5cab2763db71e57e231507e03747fc0922cdba3
|
[
"MIT"
] | 1
|
2021-10-12T01:39:04.000Z
|
2021-10-12T01:39:04.000Z
|
pfr_api/__init__.py
|
aadamson/pfr-api
|
b5cab2763db71e57e231507e03747fc0922cdba3
|
[
"MIT"
] | null | null | null |
pfr_api/__init__.py
|
aadamson/pfr-api
|
b5cab2763db71e57e231507e03747fc0922cdba3
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""Top-level package for pfr_api."""
__author__ = """Alex Adamson"""
__email__ = 'alex.b.adamson@gmail.com'
__version__ = '0.1.0'
| 19.5
| 38
| 0.634615
|
4bfab9bf1787391d55797f7ea1e99ca6415a43bb
| 2,847
|
h
|
C
|
inc/matrix_2d_bl_cpu.h
|
hshi/matrix_lib_hao_0
|
1988119ef9200c7f642966e2f8c1b5d5cc813bf0
|
[
"MIT"
] | null | null | null |
inc/matrix_2d_bl_cpu.h
|
hshi/matrix_lib_hao_0
|
1988119ef9200c7f642966e2f8c1b5d5cc813bf0
|
[
"MIT"
] | null | null | null |
inc/matrix_2d_bl_cpu.h
|
hshi/matrix_lib_hao_0
|
1988119ef9200c7f642966e2f8c1b5d5cc813bf0
|
[
"MIT"
] | null | null | null |
#ifndef MATRIX_HAO_BL_CPU_H
#define MATRIX_HAO_BL_CPU_H
#include<vector>
namespace matrix_hao_lib
{
/*************************************/
/*Matrix Multiply C=alpha*A.B+beta*C */
/*************************************/
void gmm_cpu(const Matrix<float,2>& A, const Matrix<float,2>& B, Matrix<float,2>& C,
char TRANSA='N', char TRANSB='N', float alpha=1, float beta=0);
void gmm_cpu(const Matrix<double,2>& A, const Matrix<double,2>& B, Matrix<double,2>& C,
char TRANSA='N', char TRANSB='N', double alpha=1, double beta=0);
void gmm_cpu(const Matrix<std::complex<float>,2>& A, const Matrix<std::complex<float>,2>& B, Matrix<std::complex<float>,2>& C,
char TRANSA='N', char TRANSB='N', std::complex<float> alpha=1,std::complex<float> beta=0);
void gmm_cpu(const Matrix<std::complex<double>,2>& A, const Matrix<std::complex<double>,2>& B, Matrix<std::complex<double>,2>& C,
char TRANSA='N', char TRANSB='N', std::complex<double> alpha=1, std::complex<double> beta=0);
/*****************************************************/
/*Diagonalize Real symmetric/ Hermitian Matrix********/
/*****************************************************/
void eigen_cpu(Matrix<double,2>& A, Matrix<double,1>& W, char JOBZ='V', char UPLO='U');
void eigen_cpu(Matrix<std::complex<double>,2>& A, Matrix<double,1>& W, char JOBZ='V', char UPLO='U');
/*************************************/
/*Construct LUDecomp with CPU ********/
/*************************************/
LUDecomp< std::complex<double> > LUconstruct_cpu(const Matrix<std::complex<double>,2>& x);
/********************/
/*Inverse of Matrix*/
/********************/
Matrix<std::complex<double>,2> inverse_cpu(const LUDecomp<std::complex<double>>& x);
Matrix<std::complex<double>,2> inverse_cpu(LUDecomp<std::complex<double>>&& x);
/******************************************************/
/*Solve Linear Equation of the matrix A*M=B: M=A^{-1}B*/
/******************************************************/
Matrix<std::complex<double>,2> solve_lineq_cpu(const LUDecomp<std::complex<double>>& x, const Matrix<std::complex<double>,2>& B
,char TRANS='N');
/***********************************************************/
/*QR decompostion of matrix ph, return the determinant of R*/
/***********************************************************/
double QRMatrix_cpu(Matrix<std::complex<double>,2>& ph);
double QRMatrix_cpu(Matrix<std::complex<double>,2>& ph, std::vector<double>& detVec);
/*********************************************/
/*SVD a matrix ph = U D V, return U, D, and V*/
/*********************************************/
void SVDMatrix_cpu(Matrix<std::complex<double>,2>& ph, Matrix<double,1>& D, Matrix<std::complex<double>,2>& V);
}//end namespace matrix_hao_lib
#endif
| 42.492537
| 130
| 0.51563
|
dc3a0287c0ded3ab34c1348f4487c9a5b125e646
| 1,155
|
ts
|
TypeScript
|
packages/api/src/services/v1/user/user.service.ts
|
chase-adams/accelerate-starter
|
b9458abd88f20d91db4272e5d1bacb3cabad49b7
|
[
"MIT"
] | 4
|
2019-02-21T18:34:06.000Z
|
2020-09-05T05:27:39.000Z
|
packages/api/src/services/v1/user/user.service.ts
|
chase-adams/accelerate-starter
|
b9458abd88f20d91db4272e5d1bacb3cabad49b7
|
[
"MIT"
] | 118
|
2019-02-21T04:06:17.000Z
|
2020-03-04T03:39:55.000Z
|
packages/api/src/services/v1/user/user.service.ts
|
chase-adams/accelerate-starter
|
b9458abd88f20d91db4272e5d1bacb3cabad49b7
|
[
"MIT"
] | 2
|
2019-09-05T02:04:36.000Z
|
2019-09-17T09:51:32.000Z
|
// Initializes the `cbsa` service on path `/cbsa`
import { ServiceAddons } from '@feathersjs/feathers';
import { v1UserModel } from '@accelerate-starter/core';
import newPassword from './services/new-password';
import passwordReset from './services/password-reset';
import verify from './services/verify';
import { User } from './user.class';
import { hooks } from './user.hooks';
// Add this service to the service type index
declare module '../../../declarations' {
interface ServiceTypes {
user: User & ServiceAddons<any>; // tslint:disable-line
}
}
const user = (app) => {
const paginate = app.get('paginate');
const options = {
paginate,
Model: v1UserModel
};
// Initialize our service with any options it requires
app.use('/v1/user', new User(options, app));
// Create a password reset and verify endpoint
app.post('/v1/user/password-reset', passwordReset());
app.post('/v1/user/verify', verify(app));
app.post('/v1/user/new-password', newPassword(app));
// Get our initialized service so that we can register hooks
const service = app.service('v1/user');
service.hooks(hooks);
};
export { user };
| 26.860465
| 62
| 0.687446
|
bb5402debc937a19a21351067d93af71f05376f8
| 3,778
|
cs
|
C#
|
WoTUtil/Api/Player.cs
|
negri/WCLUtility
|
adfd7bac587ef6d7390afac362fa2b37eecfcf92
|
[
"MIT"
] | 1
|
2018-06-25T20:18:03.000Z
|
2018-06-25T20:18:03.000Z
|
WoTUtil/Api/Player.cs
|
Versolato/WCLUtility
|
adfd7bac587ef6d7390afac362fa2b37eecfcf92
|
[
"MIT"
] | null | null | null |
WoTUtil/Api/Player.cs
|
Versolato/WCLUtility
|
adfd7bac587ef6d7390afac362fa2b37eecfcf92
|
[
"MIT"
] | 1
|
2018-06-25T20:17:55.000Z
|
2018-06-25T20:17:55.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using Negri.Wot.Tanks;
namespace Negri.Wot.Api
{
/// <summary>
/// A player
/// </summary>
public class Player
{
/// <summary>
/// Player Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// Gamer Tag
/// </summary>
public string GamerTag { get; set; }
/// <summary>
/// The current clan, if any
/// </summary>
public long? CurrentClanId { get; set; }
/// <summary>
/// The current clan tag, if any
/// </summary>
public string CurrentClanTag { get; set; }
/// <summary>
/// Moment data was retrieved
/// </summary>
public DateTime Moment { get; set; } = DateTime.UtcNow;
#region Overall Stats
/// <summary>
/// Tanks of the player
/// </summary>
public TankPlayer[] Tanks { get; internal set; } = new TankPlayer[0];
/// <summary>
/// Total battles
/// </summary>
public long Battles { get; private set; }
/// <summary>
/// Win Rate
/// </summary>
public double WinRate { get; private set; }
/// <summary>
/// Average Tier
/// </summary>
public double AvgTier { get; private set; }
/// <summary>
/// Overall WN8
/// </summary>
public double Wn8 { get; private set; }
#endregion
#region Tier 10 Stats
/// <summary>
/// Tanks of the player
/// </summary>
public TankPlayer[] Tier10Tanks { get; internal set; } = new TankPlayer[0];
/// <summary>
/// Total battles
/// </summary>
public long Tier10Battles { get; private set; }
/// <summary>
/// Win Rate
/// </summary>
public double Tier10WinRate { get; private set; }
/// <summary>
/// Overall WN8
/// </summary>
public double Tier10Wn8 { get; private set; }
/// <summary>
/// Tier 10 direct damage per battle
/// </summary>
public double Tier10DirectDamage { get; private set; }
#endregion
/// <summary>
/// Calculate performance metrics on the player
/// </summary>
/// <param name="wn8ExpectedValues"></param>
public void CalculatePerformance(Wn8ExpectedValues wn8ExpectedValues)
{
if (Tanks.Length == 0)
{
return;
}
// Only tanks that I know about
Tanks = Tanks.Where(t => wn8ExpectedValues.Exists(t.TankId) && t.All.Battles > 0).ToArray();
if (Tanks.Length == 0)
{
return;
}
Battles = Tanks.Sum(t => t.All.Battles);
WinRate = Tanks.Sum(t => t.All.Wins) * 1.0 / Battles;
AvgTier = Tanks.Sum(t => wn8ExpectedValues[t.TankId].Tier * t.All.Battles) * 1.0 / Battles;
Wn8 = wn8ExpectedValues.CalculateWn8(Tanks.ToDictionary(t => t.TankId, t => (TankPlayerWn8Statistics)t.All));
Tier10Tanks = Tanks.Where(t => wn8ExpectedValues[t.TankId].Tier == 10).ToArray();
if (Tier10Tanks.Length == 0)
{
return;
}
Tier10Battles = Tier10Tanks.Sum(t => t.All.Battles);
Tier10WinRate = Tier10Tanks.Sum(t => t.All.Wins) * 1.0 / Tier10Battles;
Tier10Wn8 = wn8ExpectedValues.CalculateWn8(Tier10Tanks.ToDictionary(t => t.TankId, t => (TankPlayerWn8Statistics)t.All));
Tier10DirectDamage = Tier10Tanks.Sum(t => t.All.DamageDealt) * 1.0 / Tier10Battles;
}
}
}
| 28.406015
| 133
| 0.514029
|