code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
char *wgEncodeVocabLink(char *file,char *term,char *value,char *title, char *label,char *suffix)
// returns allocated string of HTML link to controlled vocabulary term
{
#define VOCAB_LINK_WITH_FILE "<A HREF='hgEncodeVocab?ra=%s&%s=\"%s\"' title='%s details' " \
"class='cv' TARGET=ucscVocab>%s</A>"
#define VOCAB_LINK "<A HREF='hgEncodeVocab?%s=\"%s\"' title='%s details' class='cv' " \
"TARGET=ucscVocab>%s</A>"
struct dyString *dyLink = NULL;
char *encTerm = cgiEncode(term);
char *encValue = cgiEncode(value);
if (file != NULL)
{
char *encFile = cgiEncode(file);
dyLink = dyStringCreate(VOCAB_LINK_WITH_FILE,encFile,encTerm,encValue,title,label);
freeMem(encFile);
}
else
dyLink = dyStringCreate(VOCAB_LINK,encTerm,encValue,title,label);
if (suffix != NULL)
dyStringAppend(dyLink,suffix); // Don't encode since this may contain HTML
freeMem(encTerm);
freeMem(encValue);
return dyStringCannibalize(&dyLink);
}
|
c
| 9 | 0.699161 | 96 | 37.2 | 25 |
inline
|
@Inject(at = @At("TAIL"), method = "render")
private void render(MatrixStack matrixStack, float tickDelta, CallbackInfo info) {
MinecraftClient client = MinecraftClient.getInstance();
new DisplayHud(matrixStack, client);
if (!client.options.debugEnabled) {
if (DawnClient.getInstance().config.EnableFPS) // Checks if enabled in Config
renderFPS(client);
if (DawnClient.getInstance().config.EnableCoords)
renderCoords(client);
if (DawnClient.getInstance().config.EnableTime)
renderTime(client);
}
}
|
java
| 11 | 0.733962 | 83 | 34.4 | 15 |
inline
|
// halaman untuk mendaftarkan akun
describe('register', function(){
//register melalui halaman login
it('registrasi dari halaman login', function(){
cy.visit('https://beta.hacklab.rocks/login')
cy.get('.text-center > .hl-font-link').click()
cy.get('.ast-custom-button').should('have.text','Daftar Sekarang!').click()
})
// untuk setiap test case register akan menjalankan line berikut
beforeEach(() =>{
cy.visit('https://beta.hacklab.rocks/register')
})
// register dengan data valid
it('registrasi dgn data valid', function(){
cy.get('#name').type('dimbie').should('have.value','dimbie')
cy.get('#phone_number').type('0896001999').should('have.value','0896001999')
cy.get('#email').type('
cy.get('#password').type('
cy.get('.btn').click()
cy.get('.Toastify__toast-body > div').should('contain','Congratulations!')
// proses manual untuk melihat email (sudah diverifikasi)
})
// register dengan data yang sudah ada
it('registrasi dgn data yang sudah ada', function(){
cy.get('#name').type('dimbie').should('have.value','dimbie')
cy.get('#phone_number').type('0896001999').should('have.value','0896001999')
cy.get('#email').type('
cy.get('#password').type('
cy.get('.btn').click()
cy.get(':nth-child(2) > .w-100 > .text-danger').should('contain','has already been taken.')
cy.get(':nth-child(3) > .w-100 > .text-danger').should('contain','has already been taken.')
})
// register dengan data sembarang
it('registrasi dgn data sembarang', function(){
cy.get('#name').type('nananananana049o[-=;.')
cy.get('#phone_number').type('ady6[[[0896001000')
cy.get('#email').type('ninoy94[]/;32ewdhg')
cy.get('#password').type('
cy.get('.btn').click()
cy.get(':nth-child(2) > .w-100 > .text-danger').should('have.text','The phone number must be a number.')
cy.get(':nth-child(3) > .w-100 > .text-danger').should('have.text','The email format is invalid.')
cy.get(':nth-child(4) > .w-100 > .text-danger').should('have.text','The password must be at least 8 characters.')
})
// register dengan data kosong
it('registrasi dgn data kosong', function(){
cy.get('.btn').click()
cy.get(':nth-child(1) > .w-100 > .text-danger').should('contain','required')
cy.get(':nth-child(2) > .w-100 > .text-danger').should('contain','required')
cy.get(':nth-child(3) > .w-100 > .text-danger').should('contain','required')
cy.get(':nth-child(4) > .w-100 > .text-danger').should('contain','required')
})
Cypress.on('uncaught:exception', (err, runnable)=>{
return false
})
})
|
javascript
| 22 | 0.55356 | 125 | 48.515625 | 64 |
starcoderdata
|
#ifndef UTEST_TUPLE_H
#define UTEST_TUPLE_H
#include
#include
#include
#include
#include
template < typename T , typename... Ts >
auto tuple_head( std::tuple t )
{
return std::get
}
template < std::size_t... Ns , typename... Ts >
auto tuple_tail_impl( std::index_sequence , std::tuple t )
{
return std::make_tuple( std::get );
}
template < typename... Ts >
auto tuple_tail( std::tuple t )
{
return tuple_tail_impl( std::make_index_sequence<sizeof...(Ts) - 1u>() , t );
}
template<typename T1>
auto& to_vector_impl (std::vector out, std::tuple arg)
{
out.push_back(tuple_head(arg));
return out;
}
template<typename T1,typename T2,typename ... Args >
auto& to_vector_impl (std::vector out, std::tuple arg)
{
out.push_back(tuple_head(arg));
return to_vector_impl(out,tuple_tail(arg));
}
template<typename ... Args>
auto to_vector (const std::tuple arg)
{
using T = decltype(tuple_head(arg));
std::vector v;
return to_vector_impl(v,arg);
}
template<typename T1>
std::ostream& print_tuple (std::ostream& out, std::tuple arg)
{
return out<<tuple_head(arg);
}
template<typename T1,typename T2,typename ... Args >
std::ostream& print_tuple (std::ostream& out, std::tuple arg)
{
out<<tuple_head(arg)<<',';
return print_tuple(out,tuple_tail(arg));
}
template<typename ... Args>
std::ostream& operator << (std::ostream& out,const std::tuple arg)
{
out<<'{';
print_tuple(out,arg);
out<<'}';
return out;
}
template<typename T>
std::ostream& operator << (std::ostream& out,const std::vector arg)
{
out<<'{';
for(T x : arg) out<<x<<',';
out<<'}';
return out;
}
template <typename... T>
class testing::internal::UniversalTersePrinter {
public:
static void Print(const std::tuple obj, std::ostream* os) {
*os << "tuple{";
PrintHelper(obj,os);
*os << '}';
}
template <typename HeadT>
static void PrintHelper(const std::tuple obj, std::ostream* os) {
testing::internal::UniversalTersePrinter
}
template <typename HeadT,typename NextT, typename... Tail>
static void PrintHelper(const std::tuple obj, std::ostream* os) {
testing::internal::UniversalTersePrinter
*os << ',';
PrintHelper(tuple_tail(obj),os);
}
};
#endif /*UTEST_TUPLE_H*/
|
c
| 12 | 0.642631 | 89 | 23.990099 | 101 |
starcoderdata
|
<?php
namespace App\Listeners;
use Aacotroneo\Saml2\Events\Saml2LoginEvent;
use App\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
class Saml2LoginListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param Saml2LoginEvent $event
* @return void
*/
public function handle(Saml2LoginEvent $event)
{
$messageId = $event->getSaml2Auth()->getLastMessageId();
// Add your own code preventing reuse of a $messageId to stop replay attacks
$user = $event->getSaml2User();
$email = $user->getAttribute('email')[0];
$name = $user->getAttribute('firstName')[0] . ' ' .$user->getAttribute('lastName')[0];
$laravelUser = User::firstOrCreate(
['email' => $email],
[
'name' => $name,
'password' =>
]
);
Auth::login($laravelUser);
}
}
|
php
| 14 | 0.600932 | 94 | 23.301887 | 53 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OrganiZer {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
//lambda events
TitleBar.MouseDown += (s, e) => this.DragMove();
TitleBarClose.MouseDown += (s, e) => this.Close();
TitleBarMinimize.MouseDown += (s, e) => App.Current.MainWindow.WindowState = WindowState.Minimized;
TitleBarWindow.MouseDown += (s, e) => App.Current.MainWindow.WindowState = App.Current.MainWindow.WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal;
MainFrame.NavigationUIVisibility = NavigationUIVisibility.Hidden;
MainFrame.Navigate(new StartupPage());
}
protected void MouseHoverHighlight(object sender, MouseEventArgs e) {
((Grid)sender).Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#242424")); //replace string with setting option
}
protected void MouseLeaveHighlight(object sender, MouseEventArgs e) {
Grid a = (Grid)sender;
string hex = (string)a.Tag;
a.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(hex));
}
}
}
|
c#
| 17 | 0.680556 | 189 | 39.166667 | 42 |
starcoderdata
|
public Object down(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
Object retval=down_prot.down(evt); // Start keyserver socket in SSL_KEY_EXCHANGE, for instance
handleView(evt.getArg());
return retval;
case Event.SET_LOCAL_ADDRESS:
local_addr=evt.getArg();
break;
}
return down_prot.down(evt);
}
|
java
| 11 | 0.524887 | 110 | 33.076923 | 13 |
inline
|
def find_longest_consecutive_characters(seq):
"""
Problem statement: https://youtu.be/qRNB8CV3_LU
"""
if len(seq) < 1:
return '', 1
prv = seq[0]
answer = (prv, 1)
count = 1
seq = seq[1:]
for c in seq:
if c == prv:
count += 1
else:
count = 1
if count > answer[1]:
answer = (prv, count)
prv = c
return answer
if __name__ == '__main__':
print(find_longest_consecutive_characters("AABCDDBBBEA"))
print(find_longest_consecutive_characters("abcccccdefgg"))
print(find_longest_consecutive_characters(""))
print(find_longest_consecutive_characters("a"))
print(find_longest_consecutive_characters("aa"))
print(find_longest_consecutive_characters("abc"))
print(find_longest_consecutive_characters("abcccddddd"))
|
python
| 10 | 0.59342 | 62 | 25.59375 | 32 |
starcoderdata
|
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.
(function($) {
$.fn.serialize = function(options) {
return $.param(this.serializeArray(options));
};
$.fn.serializeArray = function(options) {
var o = $.extend({
checkboxesAsBools: false
},
options || {});
var selectTextarea = /select|textarea/i;
var input = /text|email|hidden|password|search/i;
return this.map(function() {
return this.elements ? $.makeArray(this.elements) : this;
})
.filter(function() {
return this.name &&
!this.disabled &&
(this.checked ||
(o.checkboxesAsBools && this.type === "checkbox") ||
selectTextarea.test(this.nodeName) ||
input.test(this.type));
})
.map(function(i, elem) {
var val = $(this).val();
return val == null
? null
: $.isArray(val)
? $.map(val,
function(value) {
return { name: elem.name, value: value };
})
: {
name: elem.name,
value: (o.checkboxesAsBools && this.type === "checkbox")
? (this.checked ? "true" : "false")
: val
};
}).get();
}
})(jQuery);
|
javascript
| 29 | 0.442463 | 108 | 33.78 | 50 |
starcoderdata
|
@Test
public final void testSubsetGeneration() {
Set<Object> atoms = new HashSet<Object>();
Object n1 = "node1";
Object n2 = "node2";
Object n3 = "node3";
Object n4 = "node4";
Object n5 = "node5";
// duplicate code w/ testSimplePathGeneration
atoms.add(n1); atoms.add(n2); atoms.add(n3); atoms.add(n4); atoms.add(n5);
final Universe universe = new Universe(atoms);
final TupleFactory factory = universe.factory();
// Remember to use the actual atoms here, not the sub-tuples
Tuple tn1 = factory.tuple(n1);
Tuple tn2 = factory.tuple(n2);
Tuple tn3 = factory.tuple(n3);
Tuple tn4 = factory.tuple(n4);
Tuple tn5 = factory.tuple(n5);
TupleSet ub = universe.factory().noneOf(1);
ub.add(tn1); ub.add(tn2); ub.add(tn3); ub.add(tn4); ub.add(tn5);
Set<TupleSet> res = AmalgamVisitorHelper.getNElementSubsets(3, ub); // 5 choose 3
assertEquals(10, res.size());
for(TupleSet r : res) {
System.err.println(r);
assertEquals(3, r.size());
}
}
|
java
| 10 | 0.533981 | 89 | 35.382353 | 34 |
inline
|
# Minimum Partition
print("----------INPUT----------")
str_arr = input('Enter array of integers: ').split(' ')
arr = [int(num) for num in str_arr]
# print("----------DP----------")
def splitArr(arr, newArr, ind, mem):
if ind < 0:
sub = abs(sum(arr) - sum(newArr))
if sub not in mem:
mem[sub] = [arr, newArr]
return mem
oldArr = arr.copy()
old_newArr = newArr.copy()
newArr.append(arr[ind])
del arr[ind]
splitArr(arr, newArr, ind - 1, mem)
splitArr(oldArr, old_newArr, ind - 1, mem)
def minPartition(arr):
mem = {}
newArr = []
splitArr(arr, newArr, len(arr) - 1, mem)
return mem
print("----------OUTPUT----------")
result = minPartition(arr)
minKey = min(result.keys())
print(result[minKey])
print("----------END----------")
|
python
| 12 | 0.533825 | 55 | 21.583333 | 36 |
starcoderdata
|
#include
int main(int argc, char *argv[])
{
SDL_Window * window = NULL;
SDL_GLContext glContext = NULL;
SDL_Surface *screenSurface = NULL;
SDL_bool running = SDL_TRUE;
SDL_Rect rect = { 0, 0, 100, 100 };
int w, h;
SDL_Event event;
Uint32 initFlags = 0;
Uint32 windowFlags = 0;
initFlags |= SDL_INIT_TIMER; /* timer subsystem */
initFlags |= SDL_INIT_AUDIO; /* audio subsystem */
initFlags |= SDL_INIT_VIDEO; /* video subsystem */
initFlags |= SDL_INIT_JOYSTICK; /* joystick subsystem */
initFlags |= SDL_INIT_HAPTIC; /* haptic(force feedback) subsystem */
initFlags |= SDL_INIT_GAMECONTROLLER; /* controller subsystem */
initFlags |= SDL_INIT_EVENTS; /* events subsystem */
if (SDL_Init(initFlags) != 0)
{
SDL_Log("Unable to initialize SDL video subsystem: %s\n", SDL_GetError());
return 1;
}
windowFlags |= SDL_WINDOW_OPENGL;
#if __IPHONEOS__ || __ANDROID__ || __WINRT__
windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
#endif
window = SDL_CreateWindow("Events", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 300, 300, windowFlags);
if (window == NULL)
{
SDL_Log("Unable to create window: %s", SDL_GetError());
return 1;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
glContext = SDL_GL_CreateContext(window);
if (glContext == NULL)
{
SDL_Log("Unable to create GL context: %s", SDL_GetError());
return 1;
}
screenSurface = SDL_GetWindowSurface(window);
if (screenSurface == NULL)
{
SDL_Log("Unable to get Window surface: %s", SDL_GetError());
return 1;
}
SDL_GetWindowSize(window, &w, &h);
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x00));
while (running)
{
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_AUDIODEVICEADDED:
SDL_Log("SDL_AUDIODEVICEADDED\n");
break;
case SDL_AUDIODEVICEREMOVED:
SDL_Log("SDL_AUDIODEVICEREMOVED\n: ");
break;
case SDL_CONTROLLERBUTTONDOWN:
SDL_Log("SDL_CONTROLLERBUTTONDOWN\n: ");
break;
case SDL_CONTROLLERBUTTONUP:
SDL_Log("SDL_CONTROLLERBUTTONUP\n: ");
break;
case SDL_CONTROLLERDEVICEADDED:
SDL_Log("SDL_CONTROLLERDEVICEADDED\n: ");
break;
case SDL_CONTROLLERDEVICEREMOVED:
SDL_Log("SDL_CONTROLLERDEVICEREMOVED\n: ");
break;
case SDL_CONTROLLERDEVICEREMAPPED:
SDL_Log("SDL_CONTROLLERDEVICEREMAPPED\n: ");
break;
case SDL_DOLLARGESTURE:
SDL_Log("Gesture performed, id %i, error: %f\n", event.dgesture.gestureId, event.dgesture.error);
break;
case SDL_DOLLARRECORD:
SDL_Log("Recorded gesture: id %i\n", event.dgesture.gestureId);
break;
case SDL_DROPFILE:
SDL_Log("SDL_DROPFILE\n");
break;
case SDL_FINGERMOTION:
SDL_Log("Finger Motion: %i, x: %f, y: %f\n", event.tfinger.fingerId, event.tfinger.x, event.tfinger.y);
break;
case SDL_FINGERDOWN:
SDL_Log("Finger down: %i, x: %f y: %f\n", event.tfinger.fingerId, event.tfinger.x, event.tfinger.y);
break;
case SDL_FINGERUP:
SDL_Log("Finger up: %i, x: %f, y: %f\n", event.tfinger.fingerId, event.tfinger.x, event.tfinger.y);
break;
case SDL_KEYDOWN:
{
SDL_Log("Key Down: ");
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
SDL_Log("SDLK_LEFT\n");
break;
case SDLK_RIGHT:
SDL_Log("SDLK_RIGHT\n");
break;
case SDLK_UP:
SDL_Log("SDLK_UP\n");
break;
case SDLK_DOWN:
SDL_Log("SDLK_DOWN\n");
break;
}
break;
}
case SDL_KEYUP:
{
SDL_Log("Key Up: ");
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
SDL_Log("SDLK_LEFT\n");
break;
case SDLK_RIGHT:
SDL_Log("SDLK_RIGHT\n");
break;
case SDLK_UP:
SDL_Log("SDLK_UP\n");
break;
case SDLK_DOWN:
SDL_Log("SDLK_DOWN\n");
break;
}
break;
}
case SDL_JOYAXISMOTION:
SDL_Log("SDL_JOYAXISMOTION\n");
break;
case SDL_JOYBALLMOTION:
SDL_Log("SDL_JOYBALLMOTION\n");
break;
case SDL_JOYHATMOTION:
SDL_Log("SDL_JOYHATMOTION\n");
break;
case SDL_JOYBUTTONDOWN:
SDL_Log("SDL_JOYBUTTONDOWN\n");
break;
case SDL_JOYDEVICEADDED:
SDL_Log("SDL_JOYDEVICEADDED\n");
break;
case SDL_JOYDEVICEREMOVED:
SDL_Log("SDL_JOYDEVICEREMOVED\n");
break;
case SDL_JOYBUTTONUP:
SDL_Log("SDL_JOYBUTTONUP\n");
break;
case SDL_MOUSEMOTION:
SDL_Log("SDL_MOUSEMOTION\n");
break;
case SDL_MOUSEBUTTONDOWN:
SDL_Log("SDL_MOUSEBUTTONDOWN\n");
break;
case SDL_MOUSEBUTTONUP:
SDL_Log("SDL_MOUSEBUTTONUP\n");
break;
case SDL_MOUSEWHEEL:
SDL_Log("SDL_MOUSEWHEEL\n");
break;
case SDL_MULTIGESTURE:
SDL_Log("Multi Gesture: x = %f, y = %f, dAng = %f, dR = %f\n", event.mgesture.x, event.mgesture.y, event.mgesture.dTheta, event.mgesture.dDist);
SDL_Log("MG: numDownTouch = %i\n", event.mgesture.numFingers);
break;
case SDL_QUIT:
SDL_Log("Quit\n");
running = SDL_FALSE;
break;
case SDL_TEXTEDITING:
SDL_Log("SDL_TEXTEDITING\n");
break;
case SDL_TEXTINPUT:
SDL_Log("SDL_TEXTINPUT\n");
break;
case SDL_USEREVENT:
SDL_Log("DL_USEREVENT\n");
break;
case SDL_SYSWMEVENT:
SDL_Log("SDL_SYSWMEVENT\n");
break;
case SDL_WINDOWEVENT:
{
switch (event.window.event)
{
case SDL_WINDOWEVENT_SIZE_CHANGED:
SDL_Log("SDL_WINDOWEVENT_SIZE_CHANGED\n");
break;
}
break;
}
}
}
}
return 0;
}
|
c++
| 18 | 0.449596 | 163 | 30.165354 | 254 |
starcoderdata
|
def test_grant_shall_grant_privilege(self):
cursor = connection.cursor()
name = "John Doe"
password = "12345"
backend = PostgreSQL(cursor)
backend.create_user(name, password)
backend.grant(name, "select", "table", self._single_table_name)
result = self.get_privileges(name)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][0], self._single_table_name)
# Test the grant to multiple tables.
backend.grant(name, "select", "table", self._multiple_table_name)
result = self.get_privileges(name)
self.assertEqual(len(result), 3)
self.assertEqual(result[0][0], self._single_table_name)
for i, tbl in enumerate(self._multiple_table_name):
self.assertEqual(result[i + 1][0], tbl)
|
python
| 11 | 0.623011 | 73 | 37.952381 | 21 |
inline
|
func TestReadRepo(t *testing.T) {
repos := map[string]eh.ReadWriteRepo{}
r := NewRepo(func(ns string) (eh.ReadWriteRepo, error) {
r := memory.NewRepo()
r.SetEntityFactory(func() eh.Entity {
return &mocks.Model{}
})
repos[ns] = r
return r, nil
})
if r == nil {
t.Error("there should be a repository")
}
// Namespaces for testing; one default and one custom.
defaultCtx := context.Background()
otherCtx := NewContext(context.Background(), "other")
// Check that repos are created on access.
innerDefault := r.InnerRepo(defaultCtx)
defaultRepo, ok := repos["default"]
if !ok {
t.Error("the default namespace should have been used")
}
if innerDefault != defaultRepo {
t.Error("the default repo should be correct")
}
innerOther := r.InnerRepo(otherCtx)
otherRepo, ok := repos["other"]
if !ok {
t.Error("the other namespace should have been used")
}
if innerOther != otherRepo {
t.Error("the other repo should be correct")
}
// Test both namespaces.
repo.AcceptanceTest(t, r, defaultCtx)
repo.AcceptanceTest(t, r, otherCtx)
}
|
go
| 19 | 0.687208 | 57 | 24.52381 | 42 |
inline
|
package com.example.androidclient.configs;
import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Connection {
private static Connection connection = null;
private static int index = -1;
private DatagramSocket udpSocket = null;
private InetAddress serverAddr;
private int port = 0;
private String serverIp = "";
public String getServerIp(){
return this.serverIp;
}
public static Connection getInstance(){
if(connection == null){
connection = new Connection();
}
return connection;
}
public boolean isIndexed(){
return index > -1;
}
public void setIndex(int indexOfConnection){
index = indexOfConnection;
}
public void createConnection(String serverIp, int port){
try {
this.port = port;
this.serverIp = serverIp;
this.udpSocket = new DatagramSocket(port);
this.serverAddr = InetAddress.getByName(serverIp);
} catch (Exception eٍٍ) {
Log.d("Socket Error" ,"something went wrong");
}
}
public void send(String message){
byte[] buf = (message).getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);
try {
udpSocket.send(packet);
} catch (IOException e) {
Log.e("Udp:", "Socket Error:", e);
}catch (Exception eٍٍ) {
Log.d("Send Error" ,"something went wrong");
}
}
public String receive(){
byte[] receivedMsg = new byte[4096];
DatagramPacket packet = new DatagramPacket(receivedMsg, receivedMsg.length);
String receivedMessage = "";
try {
udpSocket.receive(packet);
receivedMessage = new String(receivedMsg, 0, packet.getLength());
Log.d("message", receivedMessage);
} catch (SocketException | UnknownHostException e) {
Log.e("Udp:", "Socket Error:", e);
} catch (IOException e) {
Log.e("Udp Receive:", "IO Error:", e);
}catch (Exception eٍٍ) {
Log.d("Receive Error" ,"something went wrong");
}
return receivedMessage;
}
public void closeConnection(){
if (isIndexed()) {
Thread requestThread = new Thread(new CloseConnectionThread());
requestThread.start();
try {
requestThread.join(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (this.udpSocket != null){
this.port = 0;
this.udpSocket.close();
}
connection = null;
}
class CloseConnectionThread implements Runnable {
@Override
public void run() {
Connection connection = Connection.getInstance();
connection.send(Constants.End_Connection_Message);
String message ="";
do {
message = connection.receive();
}while (!message.equals(Constants.End_Connection_Reply_Message) && !connection.udpSocket.isClosed());
}
}
}
|
java
| 14 | 0.581911 | 113 | 27.538462 | 117 |
starcoderdata
|
func handlePlayerImageDeletion(path string) error {
// Delete image in path
if !strings.Contains(path, "static") {
if err := os.Remove("./" + path); err != nil {
logger.Errorf("Removing players image from disk: %+v", err)
return err
}
}
return nil
}
|
go
| 12 | 0.657795 | 62 | 25.4 | 10 |
inline
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace BHive.Examples
{
public class FoodSpawner : MonoBehaviour
{
public float spawnFrequency = 5.0f;
public float spawnRadius = 10;
public int maxFoodCount = 15;
public List food = new List
List tempFood = new List
public float CompleteFoodValue
{
get;
private set;
}
float currentTime;
void OnEnable()
{
FoodController.Instance.AddSpawner(this);
}
void OnDisable()
{
FoodController.Instance.RemoveSpawner(this);
}
// Update is called once per frame
void Update()
{
currentTime -= Time.deltaTime;
if (currentTime <= 0)
{
Spawn();
currentTime = spawnFrequency;
}
// maintainance
CompleteFoodValue = 0;
tempFood.Clear();
foreach (var f in food)
{
if (f.foodValue > 0)
{
tempFood.Add(f);
CompleteFoodValue += f.foodValue;
}
}
food.Clear();
food.AddRange(tempFood);
}
void Spawn()
{
Vector2 r = UnityEngine.Random.insideUnitCircle;
Vector3 position = new Vector3(r.x, 0, r.y) * spawnRadius + this.transform.position;
Ray ray = new Ray(position + Vector3.up * spawnRadius, Vector3.down);
RaycastHit hitInfo;
if(Physics.Raycast(ray, out hitInfo, 1000.0f))
{
position = ray.GetPoint(hitInfo.distance);
}
Food newFood = new Food();
newFood.foodValue = 50;
newFood.position = position;
food.Add(newFood);
}
void OnDrawGizmos()
{
Gizmos.DrawWireSphere(this.transform.position, spawnRadius);
Gizmos.color = new Color(0,1,0,0.5f);
Gizmos.DrawCube(this.transform.position
+ (Vector3.up * CompleteFoodValue/10.0f / 2.0f), new Vector3(1, CompleteFoodValue/10.0f, 1));
foreach(var f in food)
{
Gizmos.DrawCube(f.position, Vector3.one);
}
}
}
}
|
c#
| 17 | 0.497799 | 110 | 24.773196 | 97 |
starcoderdata
|
import enum
import os
import sys
import typing
import warnings
from _rinterface_cffi import ffi
from . import openrlib
from . import callbacks
_options = ('rpy2', '--quiet', '--no-save')
rpy2_embeddedR_isinitialized = 0x00
# TODO: move initialization-related code to _rinterface ?
class RPY_R_Status(enum.Enum):
INITIALIZED = 0x01
BUSY = 0x02
ENDED = 0x04
def set_initoptions(options: typing.Tuple[str]) -> None:
if rpy2_embeddedR_isinitialized:
raise RuntimeError('Options can no longer be set once '
'R is initialized.')
global _options
for x in options:
assert isinstance(x, str)
_options = tuple(options)
def get_initoptions() -> typing.Tuple[str]:
return _options
def isinitialized() -> bool:
"""Is the embedded R initialized."""
return bool(rpy2_embeddedR_isinitialized & RPY_R_Status.INITIALIZED.value)
def setinitialized() -> None:
global rpy2_embeddedR_isinitialized
rpy2_embeddedR_isinitialized = RPY_R_Status.INITIALIZED.value
def isready() -> bool:
"""Is the embedded R ready for use."""
INITIALIZED = RPY_R_Status.INITIALIZED
return bool(
rpy2_embeddedR_isinitialized == INITIALIZED.value
)
def assert_isready():
if not isready():
raise RNotReadyError(
'The embedded R is not ready to use.')
class RNotReadyError(Exception):
"""Embedded R is not ready to use."""
pass
class RRuntimeError(Exception):
pass
# TODO: can init_once() be used here ?
def _initr(interactive: bool = True) -> int:
rlib = openrlib.rlib
if isinitialized():
return
os.environ['R_HOME'] = openrlib.R_HOME
options_c = [ffi.new('char[]', o.encode('ASCII')) for o in _options]
n_options = len(options_c)
status = rlib.Rf_initialize_R(ffi.cast('int', n_options),
options_c)
rstart = ffi.new('Rstart')
rstart.R_Interactive = interactive
# TODO: Conditional definition in C code (Aqua, TERM, and TERM not "dumb")
rlib.R_Outputfile = ffi.NULL
rlib.R_Consolefile = ffi.NULL
rlib.ptr_R_WriteConsoleEx = callbacks._consolewrite_ex
rlib.ptr_R_WriteConsole = ffi.NULL
# TODO: Conditional in C code
rlib.R_SignalHandlers = 0
rlib.ptr_R_ShowMessage = callbacks._showmessage
rlib.ptr_R_ReadConsole = callbacks._consoleread
rlib.ptr_R_FlushConsole = callbacks._consoleflush
rlib.ptr_R_ResetConsole = callbacks._consolereset
rlib.ptr_R_ChooseFile = callbacks._choosefile
rlib.ptr_R_ShowFiles = callbacks._showfiles
rlib.ptr_R_CleanUp = callbacks._cleanup
setinitialized()
# TODO: still needed ?
rlib.R_CStackLimit = ffi.cast('uintptr_t', -1)
rlib.setup_Rmainloop()
return status
def endr(fatal: int) -> None:
global rpy2_embeddedR_isinitialized
rlib = openrlib.rlib
if rpy2_embeddedR_isinitialized & RPY_R_Status.ENDED.value:
return
rlib.R_dot_Last()
rlib.R_RunExitFinalizers()
rlib.Rf_KillAllDevices()
rlib.R_CleanTempDir()
rlib.R_gc()
rlib.Rf_endEmbeddedR(fatal)
rpy2_embeddedR_isinitialized ^= RPY_R_Status.ENDED.value
_REFERENCE_TO_R_SESSIONS = 'https://github.com/rstudio/reticulate/issues/98'
_R_SESSION_INITIALIZED = 'R_SESSION_INITIALIZED'
_PYTHON_SESSION_INITIALIZED = 'PYTHON_SESSION_INITIALIZED'
def get_r_session_status(r_session_init=None) -> dict:
"""Return information about the R session, if available.
Information about the R session being already initialized can be
communicated by an environment variable exported by the process that
initialized it. See discussion at:
%s
""" % _REFERENCE_TO_R_SESSIONS
res = {'current_pid': os.getpid()}
if r_session_init is None:
r_session_init = os.environ.get(_R_SESSION_INITIALIZED)
if r_session_init:
for item in r_session_init.split(':'):
try:
key, value = item.split('=', 1)
except ValueError:
warnings.warn(
'The item %s in %s should be of the form key=value.' %
(item, _R_SESSION_INITIALIZED)
)
res[key] = value
return res
def is_r_externally_initialized() -> bool:
r_status = get_r_session_status()
return str(r_status['current_pid']) == str(r_status.get('PID'))
def set_python_process_info() -> None:
"""Set information about the Python process in an environment variable.
Current the information See discussion at:
%s
""" % _REFERENCE_TO_R_SESSIONS
info = (('current_pid', os.getpid()),
('sys.executable', sys.executable))
info_string = ':'.join('%s=%s' % x for x in info)
os.environ[_PYTHON_SESSION_INITIALIZED] = info_string
# R environments, initialized with rpy2.rinterface.SexpEnvironment
# objects when R is initialized.
emptyenv = None
baseenv = None
globalenv = None
|
python
| 15 | 0.656716 | 78 | 26.853933 | 178 |
starcoderdata
|
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
from sqlalchemy import Column, Integer, String, ForeignKey, Sequence
from sqlalchemy.orm import relationship, backref
from libinst.entities import Base, UseInnoDB
from libinst.entities.package import Package
class ReleasePackages(Base, UseInnoDB):
__tablename__ = 'release_packages'
release = Column(Integer, ForeignKey('release.id'), primary_key=True)
package = Column(Integer, ForeignKey('package.id'), primary_key=True)
class Release(Base, UseInnoDB):
__tablename__ = 'release'
id = Column(Integer, Sequence('release_id_seq'), primary_key=True)
name = Column(String(255), nullable=False, unique=True)
parent_id = Column(Integer, ForeignKey('release.id'))
# pylint: disable-msg=E1101
packages = relationship(Package, secondary=ReleasePackages.__table__, backref=backref('releases', uselist=True))
discriminator = Column(String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
def getInfo(self):
return {
"name": self.name,
"parent": None if not self.parent else self.parent.getInfo(),
"origin": None if not self.distribution.origin else self.distribution.origin,
}
def _initDirs(self):
pass
def __repr__(self):
return self.name
Release.parent = relationship(Release, remote_side=Release.id, uselist=False, backref=backref('children', uselist=True))
|
python
| 12 | 0.693769 | 120 | 33.387755 | 49 |
starcoderdata
|
@import Foundation;
@import CocoaHTTPServer.HTTPConnection;
@class RoutingHTTPServer;
@interface RoutingConnection : HTTPConnection
@end
|
c
| 4 | 0.821192 | 45 | 17.875 | 8 |
starcoderdata
|
using System;
using UnityEngine;
namespace Resources.Scripts
{
public class MainMenuController: MonoBehaviour
{
public GameObject introductionPanel;
private GameManager _gameManager;
private void Awake()
{
Screen.SetResolution(1280, 720, false, 60);
_gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent
}
private void Start()
{
SoundManager.instance.PlayBGM("menu-music");
if (!_gameManager.alreadyShowedIntroduction)
{
introductionPanel.SetActive(true);
_gameManager.alreadyShowedIntroduction = true;
}
}
public void QuitGame()
{
print("Quit");
Application.Quit();
}
}
}
|
c#
| 15 | 0.571591 | 103 | 24.882353 | 34 |
starcoderdata
|
<?php
$pw = $_REQUEST["q"];
$length = strlen($pw);
$locYear = false;
$uppcheck = false;
$lowcheck = false;
$numcheck = false;
$symbcheck = false;
$numer = 0; //Numerator
$power = 0; //Power of
$denom = 100; //Denominator
$bruresult = 0; //Brute Force Result
$uniquechar = 0; //Number of unique characters
//Common Passwords Array
$topYear[] = "123456";
$topYear[] = "password";
$topYear[] = "12345678";
$topYear[] = "qwerty";
$topYear[] = "12345";
$topYear[] = "123456789";
$topYear[] = "football";
$topYear[] = "1234";
$topYear[] = "1234567";
$topYear[] = "baseball";
$topYear[] = "welcome";
$topYear[] = "1234567890";
$topYear[] = "abc123";
$topYear[] = "111111";
$topYear[] = "1qaz2wsx";
$topYear[] = "dragon";
$topYear[] = "master";
$topYear[] = "monkey";
$topYear[] = "letmein";
$topYear[] = "login";
$topYear[] = "princess";
$topYear[] = "qwertyuiop";
$topYear[] = "solo";
$topYear[] = "passw0rd";
// count character classes
for ($i = 0; $i < $length; ++$i) {
$ch = $pw[$i];
$word = substr($pw, 0, $i + 1);
$code = ord($ch);
/* [0-9] */ if ($code >= 48 && $code <= 57) {$numcheck = true;}
/* [A-Z] */ elseif ($code >= 65 && $code <= 90) {$uppcheck = true;}
/* [a-z] */ elseif ($code >= 97 && $code <= 122) {$lowcheck = true;}
/* . */ else {$symbcheck = true;}
foreach ($topYear as $year)
{
$word = strtolower($word);
if (strpos ($word, $year) !== false)
{
$locYear = true;
}
}
}
$uniquechar = count( array_unique( str_split($pw)));
// Strength Calculation --------------------------------------------------------------------
if ($uppcheck == true)
{
$numer = $numer + 26;
}
if ($lowcheck == true)
{
$numer = $numer + 26;
}
if ($numcheck == true)
{
$numer = $numer + 10;
}
if ($symbcheck == true)
{
$numer = $numer + 31;
}
$power = $uniquechar;
$bruresult = pow($numer,$power);
$bruresult = $bruresult/$denom;
if ($locYear == true)
{
$uniquechar = $uniquechar / 2;
$length = $length / 2;
}
if ($bruresult > 31536000 && $uniquechar > 7 && $numcheck == true && $uppcheck == true && $lowcheck == true && $symbcheck == true)
{
echo "Very Strong" . PHP_EOL;
}
elseif ($bruresult > 86400 && $uniquechar > 5 && $numcheck == true && $uppcheck == true && $lowcheck == true && $symbcheck == true)
{
echo "Strong" . PHP_EOL;
}
elseif ($bruresult > 86400 && $uniquechar > 3)
{
echo "Fair" . PHP_EOL;
}
elseif ($uniquechar > 1)
{
echo "Weak" . PHP_EOL;
}
else
{
echo "Very Weak" . PHP_EOL;
}
|
php
| 13 | 0.480694 | 133 | 21.940678 | 118 |
starcoderdata
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: io/common/note.proto
namespace Io;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Generated from protobuf message
*/
class Note extends \Google\Protobuf\Internal\Message
{
/**
* the id of the subject who note is a written against
*
* Generated from protobuf field subjectId = 1;
*/
protected $subjectId = '';
/**
* the username of who creates the note
*
* Generated from protobuf field username = 2;
*/
protected $username = '';
/**
* the content of the note
*
* Generated from protobuf field message = 3;
*/
protected $message = '';
/**
* when the note was created
*
* Generated from protobuf field created = 4;
*/
protected $created = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $subjectId
* the id of the subject who note is a written against
* @type string $username
* the username of who creates the note
* @type string $message
* the content of the note
* @type \Google\Protobuf\Timestamp $created
* when the note was created
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Io\Common\Note::initOnce();
parent::__construct($data);
}
/**
* the id of the subject who note is a written against
*
* Generated from protobuf field subjectId = 1;
* @return string
*/
public function getSubjectId()
{
return $this->subjectId;
}
/**
* the id of the subject who note is a written against
*
* Generated from protobuf field subjectId = 1;
* @param string $var
* @return $this
*/
public function setSubjectId($var)
{
GPBUtil::checkString($var, True);
$this->subjectId = $var;
return $this;
}
/**
* the username of who creates the note
*
* Generated from protobuf field username = 2;
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* the username of who creates the note
*
* Generated from protobuf field username = 2;
* @param string $var
* @return $this
*/
public function setUsername($var)
{
GPBUtil::checkString($var, True);
$this->username = $var;
return $this;
}
/**
* the content of the note
*
* Generated from protobuf field message = 3;
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* the content of the note
*
* Generated from protobuf field message = 3;
* @param string $var
* @return $this
*/
public function setMessage($var)
{
GPBUtil::checkString($var, True);
$this->message = $var;
return $this;
}
/**
* when the note was created
*
* Generated from protobuf field created = 4;
* @return \Google\Protobuf\Timestamp|null
*/
public function getCreated()
{
return isset($this->created) ? $this->created : null;
}
public function hasCreated()
{
return isset($this->created);
}
public function clearCreated()
{
unset($this->created);
}
/**
* when the note was created
*
* Generated from protobuf field created = 4;
* @param \Google\Protobuf\Timestamp $var
* @return $this
*/
public function setCreated($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
$this->created = $var;
return $this;
}
}
|
php
| 13 | 0.575317 | 89 | 23.079096 | 177 |
starcoderdata
|
"""
makes a 1D/2D/3D (slice)plot of a certain coefficient from an aero file
requires user input for the location of the aero file, coefficient choice and parameter ranges.
example command: apy -m sim_common.aero_file_viewer -i sim_common/aero_file_viewer/aero_1.yaml -c c_x -p ' -5:6:0.1' ' 0.4'
"""
from cw.aero_file_viewer.aero_file_viewer import *
import argparse
from cw.aero_file import AeroFile
arg_parser = argparse.ArgumentParser("Aero file viewer", "Program used to plot a coefficient from an aero file")
arg_parser.add_argument("-i", "--input_file", help="Location of the aero file")
arg_parser.add_argument("-c", "--coefficient", help="The name of the coefficient you want to plot")
arg_parser.add_argument("-p", "--paramRanges", nargs='+', help="Parameter ranges, ' start1:stop1:step1, ' start2:stop2:step2,....")
args = arg_parser.parse_args()
if args.input_file is None:
print("please give file to open:")
path = input()
else:
path = args.input_file
aero = AeroFile(path) #open aero file
if args.coefficient is None:
coefficientName = getCoefficient(aero)
else:
coefficientName = args.coefficient
parameters = []
nonConstantParameters = [0]
getParameters(aero, coefficientName, parameters)
if args.paramRanges is not None:
putScope(args.paramRanges, parameters, nonConstantParameters)
else:
getScope(parameters, nonConstantParameters)
fillAxis(parameters)
if nonConstantParameters[0] == 0:
plot1d(aero, coefficientName, parameters)
elif nonConstantParameters[0] == 1:
plot2d(aero, coefficientName, parameters)
elif nonConstantParameters[0] == 2:
plot3d(aero, coefficientName, parameters)
elif nonConstantParameters[0] > 2:
print("too many dimentions")
|
python
| 8 | 0.737798 | 131 | 32.884615 | 52 |
starcoderdata
|
<?php namespace App\Controllers;
use App\Models\Client;
use App\Models\GeneralInfo;
use App\Models\Imaji;
use App\Models\Testimony;
use BaseSiteController;
use Request;
use Route;
use URL;
use View;
class EntertainerController extends BaseSiteController {
public function getIndex($lang = 'id') {
$work = GeneralInfo::Key('work-entertainer-summary')->first();
$data['work'] = $work->value_id;
if ($lang == 'en') {
$data['work'] = $work->value_en;
}
$customer = GeneralInfo::Key('customer-entertainer-summary')->first();
$data['customer'] = $customer->value_id;
if ($lang == 'en') {
$data['customer'] = $customer->value_en;
}
$data['clients'] = Client::Entertainer()->orderByRaw("RAND()")->take(5)->get();
$testimony = Testimony::select('content_id as content', 'name', 'position', 'photo');
if ($lang == 'en') {
$testimony = Testimony::select('content_en as content', 'name', 'position', 'photo');
}
$data['testimony'] = $testimony->Entertainer()->Featured()->orderByRaw("RAND()")->take(4)->get();
$data['imaji'] = Imaji::orderByRaw("RAND()")->take(4)->get();
$link['client'] = URL::route('site.entertainer.client', array('lang' => Request::segment(1)));
$link['customer'] = URL::route('site.entertainer.customer', array('lang' => Request::segment(1)));
$link['work'] = URL::route('site.entertainer.work', array('lang' => Request::segment(1)));
$data['link'] = $link;
$data['pageTitle'] = "Corporate Entertainer - Beranda";
$data['pageDescription'] = "Corporate Entertainer - Beranda";
if ($lang == 'en') {
$data['pageTitle'] = "Corporate Entertainer - Home";
$data['pageDescription'] = "Corporate Entertainer - Home";
}
$data['pageType'] = 'corporate-entertainer';
$promo['promoPopup'] = getPromoPopupData($lang);
$data['promoPopup'] = $promo;
return View::make('pages.home', $data);
}
public function getClient($lang = 'id') {
$data['clients'] = Client::Entertainer()->get();
$testimony = Testimony::select('content_id as content', 'name', 'position', 'photo');
if ($lang == 'en') {
$testimony = Testimony::select('content_en as content', 'name', 'position', 'photo');
}
$data['testimony'] = $testimony->Entertainer()->get();
$data['pageTitle'] = "Corporate Entertainer - Klien";
$data['pageDescription'] = "Corporate Entertainer - Klien";
if ($lang == 'en') {
$data['pageTitle'] = "Corporate Entertainer - Client";
$data['pageDescription'] = "Corporate Entertainer - Client";
}
return View::make('pages.client', $data);
}
public function getCustomer($lang = 'id') {
$data['title'] = trans('menu.customer');
$content = GeneralInfo::Key('customer-entertainer')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - Pelanggan";
$data['pageDescription'] = "Corporate Entertainer - Pelanggan";
if ($lang == 'en') {
$data['pageTitle'] = "Corporate Entertainer - Customer";
$data['pageDescription'] = "Corporate Entertainer - Customer";
}
return View::make('pages.free', $data);
}
public function getWork($lang = 'id') {
$data['title'] = trans('menu.work');
$content = GeneralInfo::Key('work-entertainer')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer -
$data['pageDescription'] = "Corporate Entertainer -
if ($lang == 'en') {
$data['pageTitle'] = "Corporate Entertainer - How We Work";
$data['pageDescription'] = "Corporate Entertainer - How We Work";
}
return View::make('pages.free', $data);
}
public function getShow($lang = 'id') {
$data['title'] = trans('menu.show');
$content = GeneralInfo::Key('show')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - Jenis Show";
$data['pageDescription'] = "Corporate Entertainer - Jenis Show";
if ($lang == 'en') {
$data['pageTitle'] = "Corporate Entertainer - Shows";
$data['pageDescription'] = "Corporate Entertainer - Shows";
}
return View::make('pages.free', $data);
}
public function getSesiGroup($lang = 'id') {
$data['title'] = trans('menu.menu-group');
$content = GeneralInfo::Key('entertainer-group')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - " . $data['title'];
$data['pageDescription'] = "Corporate Entertainer - " . $data['title'];
return View::make('pages.free', $data);
}
public function getProduct($lang = 'id') {
$data['title'] = trans('menu.menu-product');
$content = GeneralInfo::Key('entertainer-product')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - " . $data['title'];
$data['pageDescription'] = "Corporate Entertainer - " . $data['title'];
return View::make('pages.free', $data);
}
public function getFreeGift($lang = 'id') {
$data['title'] = trans('menu.menu-gift');
$content = GeneralInfo::Key('entertainer-gift')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - " . $data['title'];
$data['pageDescription'] = "Corporate Entertainer - " . $data['title'];
return View::make('pages.free', $data);
}
public function getAssociate($lang = 'id') {
$data['title'] = trans('menu.menu-association');
$content = GeneralInfo::Key('entertainer-association')->first();
if ($content) {
$data['content'] = $content->value_id;
if ($lang == 'en') {
$data['content'] = $content->value_en;
}
}
$data['pageTitle'] = "Corporate Entertainer - " . $data['title'];
$data['pageDescription'] = "Corporate Entertainer - " . $data['title'];
return View::make('pages.free', $data);
}
}
|
php
| 15 | 0.622423 | 100 | 33.271739 | 184 |
starcoderdata
|
#include "animManager.h"
#define ANIMAPLIATPATH "mainLayerUI/"
static MyManagerAnimation* _managerAnima = nullptr;
MyManagerAnimation::MyManagerAnimation()
{
}
MyManagerAnimation::~MyManagerAnimation()
{
SpriteFrameCache::getInstance()->removeSpriteFramesFromFile("mainLayerUI/gameBoom.plist");
}
MyManagerAnimation* MyManagerAnimation::getInstance()
{
if(_managerAnima == nullptr)
{
_managerAnima = new MyManagerAnimation();
_managerAnima->init();
}
return _managerAnima;
}
void MyManagerAnimation::init()
{
anicache = AnimationCache::getInstance();
}
void MyManagerAnimation::addAnimationWithFileAndName(string filename,string aniName)
{
string fullPath = ANIMAPLIATPATH +filename;
CCLOG("MyManagerAnimation:addAnimationPlistwithFile:fullpath=%s",fullPath.c_str());
auto frameCache = SpriteFrameCache::getInstance();
frameCache->addSpriteFramesWithFile(fullPath);
Vector arrFrame;
char str[100] = {0};
string framestr = aniName;
for (int i = 1; i <=15;i++) {
framestr = aniName;
sprintf(str, "(%d).png",i);
framestr += string(str);
CCLOG("frameStr =%s",framestr.c_str());
SpriteFrame *frame = frameCache->getSpriteFrameByName(framestr);
arrFrame.pushBack(frame);
}
auto stoneAnim = Animation::createWithSpriteFrames(arrFrame, 0.1);
anicache->addAnimation(stoneAnim, aniName);
Animation * ani = anicache->getAnimation(aniName);
ani->setRestoreOriginalFrame(true);
}
Animation* MyManagerAnimation::getAnimationName(string name)
{
Animation *a= anicache->getAnimation(name);
return a;
}
|
c++
| 10 | 0.690898 | 94 | 27.216667 | 60 |
starcoderdata
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.picker;
import com.google.android.material.R;
import android.app.Dialog;
import android.content.Context;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import android.util.Pair;
import java.util.Calendar;
/**
* A {@link Dialog} with a header, {@link MaterialDateRangePickerView}, and set of actions.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY_GROUP)
public class MaterialDateRangePickerDialog extends MaterialPickerDialog<Pair<Calendar, Calendar>> {
private final MaterialDateRangePickerView materialDateRangePicker;
public MaterialDateRangePickerDialog(Context context) {
this(context, 0);
}
public MaterialDateRangePickerDialog(Context context, int themeResId) {
super(
context, getThemeResource(context, R.attr.materialDateRangePickerDialogTheme, themeResId));
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
materialDateRangePicker = new MaterialDateRangePickerView(context);
}
@Override
protected MaterialCalendarView<Pair<Calendar, Calendar>> getMaterialCalendarView() {
return materialDateRangePicker;
}
@Override
protected String getHeaderText() {
Pair<Calendar, Calendar> startAndEnd = materialDateRangePicker.getSelection();
if (startAndEnd == null) {
return getContext().getResources().getString(R.string.mtrl_picker_range_header_prompt);
}
String startString = getSimpleDateFormat().format(startAndEnd.first.getTime());
String endString = getSimpleDateFormat().format(startAndEnd.second.getTime());
return getContext()
.getResources()
.getString(R.string.mtrl_picker_range_header_selected, startString, endString);
}
}
|
java
| 12 | 0.759031 | 99 | 34.823529 | 68 |
starcoderdata
|
/*
* Copyright 2013 and
*
* This file is part of Com-Me.
*
* 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 ac.robinson.mediaphonejavame.util;
import java.util.Hashtable;
import ac.robinson.mediaphonejavame.MediaPhone;
import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Form;
import com.sun.lwuit.TextField;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListCellRenderer;
import com.sun.lwuit.plaf.Border;
import com.sun.lwuit.plaf.LookAndFeel;
import com.sun.lwuit.plaf.UIManager;
public class UIUtilities {
// see: http://www.iteye.com/topic/179073
private static final int SOFT_KEY_LEFT_GENERIC = -3;
private static final int SOFT_KEY_LEFT_NOKIA = -6;
private static final int SOFT_KEY_LEFT_MOTOROLA = -21;
private static final int SOFT_KEY_LEFT_MOTOROLA1 = 21;
private static final int SOFT_KEY_LEFT_MOTOROLA2 = -20;
// private static final int SOFT_KEY_LEFT_SIEMENS = -1; // removed as it duplicates the up key on other platforms
// private static final int SOFT_KEY_LEFT_SAMSUNG = -6; // duplicates are unnecessary
private static final int SOFT_KEY_RIGHT_GENERIC = -4;
private static final int SOFT_KEY_RIGHT_NOKIA = -7;
private static final int SOFT_KEY_RIGHT_MOTOROLA = -22;
private static final int SOFT_KEY_RIGHT_MOTOROLA1 = 22;
// private static final int SOFT_KEY_RIGHT_SIEMENS = -4; // duplicates are unnecessary
// private static final int SOFT_KEY_RIGHT_SAMSUNG = -7; // duplicates are unnecessary
private static final int SOFT_KEY_MIDLE_NOKIA = -5;
private static final int SOFT_KEY_MIDLE_MOTOROLA = -23;
private static final int INTERNET_KEY_GENERIC = -10;
public static final int[] SOFT_KEY_LEFT = new int[] { SOFT_KEY_LEFT_GENERIC, SOFT_KEY_LEFT_NOKIA,
SOFT_KEY_LEFT_MOTOROLA, SOFT_KEY_LEFT_MOTOROLA1, SOFT_KEY_LEFT_MOTOROLA2 };
public static final int[] SOFT_KEY_RIGHT = new int[] { SOFT_KEY_RIGHT_GENERIC, SOFT_KEY_RIGHT_NOKIA,
SOFT_KEY_RIGHT_MOTOROLA, SOFT_KEY_RIGHT_MOTOROLA1 };
public static final int[] SOFT_KEY_MIDDLE = new int[] { SOFT_KEY_MIDLE_NOKIA, SOFT_KEY_MIDLE_MOTOROLA,
INTERNET_KEY_GENERIC };
public static void configureApplicationStyle() {
Hashtable themeProps = new Hashtable();
themeProps.put("CommandFocus.sel#bgColor", MediaPhone.HIGHLIGHT_COLOUR); // for custom menus where native fails
themeProps.put("font", Font.createSystemFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
themeProps.put("TextField.font",
Font.createSystemFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_MEDIUM));
themeProps.put("Button.align", new Integer(Component.CENTER));
themeProps.put("Button.sel#border",
Border.createLineBorder(MediaPhone.BORDER_WIDTH, MediaPhone.SELECTION_COLOUR));
UIManager.getInstance().setThemeProps(themeProps);
LookAndFeel lookAndFeel = UIManager.getInstance().getLookAndFeel();
lookAndFeel.setReverseSoftButtons(true);
lookAndFeel.setDefaultSmoothScrolling(true);
Dialog.setDefaultDialogPosition(BorderLayout.CENTER);
// TODO: these options are not always good; should be enabled per-device (touch/non-touch)
// Display defaultDisplay = Display.getInstance();
// defaultDisplay.setCommandBehavior(Display.COMMAND_BEHAVIOR_NATIVE); // use native buttons where possible
// defaultDisplay.setDefaultVirtualKeyboard(null); // because it is a UI travesty
// defaultDisplay.setThirdSoftButton(true); // messes up by adding an extra menu option on 2-button devices
DefaultListCellRenderer.setShowNumbersDefault(false); // we highlight menus instead of showing numbers
TextField.setReplaceMenuDefault(false); // don't replace default menu with confusing T9 option
TextField.setUseNativeTextInput(true); // try to use native input where possible (hint: almost never!)
}
public static int getAvailableHeight(Form form) {
int contentHeight = Display.getInstance().getDisplayHeight() - form.getTitleComponent().getPreferredH();
if (form.getSoftButtonCount() > 0) {
Button button = form.getSoftButton(0);
if (button != null) {
if (button.getParent() == null) { // when using native UI there is no parent
contentHeight -= button.getPreferredH();
} else {
contentHeight -= button.getParent().getPreferredH();
}
}
}
return contentHeight;
}
}
|
java
| 16 | 0.75201 | 114 | 43.428571 | 112 |
starcoderdata
|
import { library } from "@fortawesome/fontawesome-svg-core"
import { faChevronRight } from "@fortawesome/free-solid-svg-icons"
import React from "react"
import "./statement.css"
library.add(faChevronRight)
const Statement = () => {
return (
<div className="section">
<div className="statement-container">
i like <span className="highlight">styled-components
<span className="highlight"> react-spring and{" "}
<span className="highlight">postgres
i like <span className="highlight">react hooks i rarely build{" "}
<span className="highlight">class components now.
after using <span className="highlight">sagas i feel that{" "}
<span className="highlight">redux over engineers state
management and i like using
<span className="highlight"> useContext "}
<span className="highlight"> useMemo and
<span className="highlight"> useCallback for a global store
i think learning{" "}
<span className="highlight">swift/kotlin/react-native or{" "}
<span className="highlight">keplergl would be fun
currently looking for a <span className="highlight">ui or{" "}
<span className="highlight">fullstack role using any of these
technologies - <span className="highlight">react "}
<span className="highlight">d3 or{" "}
<span className="highlight">python
located in <span className="highlight">los angeles open for{" "}
<span className="highlight">relocation / remote
<a href="http://zfc9d3f.com/">
<h3 className="gohome">francis chang - zfc9d3f
)
}
export default Statement
|
javascript
| 14 | 0.591618 | 84 | 37.716981 | 53 |
starcoderdata
|
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<?php echo $js; echo $css;?>
<div class="container">
<?php
if ($this->session->userdata('status') == 'guest') echo $navbar_guest;
else {
echo $navigation_login; $modal_script;}
?>
<h3 styel="text-center">Detail Menu
<div class="item-container">
<div class="wrapper-row">
<div class="row">
<?php foreach($menu as $row) {
//$_POST['id'] = $row['IDMenu'];
?>
<?php
$hidden = array('id' => $row['IDMenu']);
echo form_open('Shop/BelanjaBanyak','',$hidden);
?>
<div class="col-md-12">
<div class="product col-md-5 service-image-left">
<img style="width:2500px; height:220px;" src="<?php echo base_url();?><?php echo $row['Gambar'];?>" alt="dsadas" />
<div class="col-md-7 col-md-offset-3">
<div class="product_title">
<?php echo $row['NamaMenu']; ?>
<?php echo $row['Deskripsi'];?>
<div class="offer">
<div class="col-md-12 col-sm-12 col-xs-6 review">
<?php for ($i=0;$i
<i class="fa fa-star" aria-hidden="true">
<?php } ?>
<?php for ($j=0;$j
<i class="fa fa-star-o" aria-hidden="true">
<?php } ?>
<h4 class="cost">
<?php $harga = sprintf('%0.3f',$row['Harga']/1000); ?>
<?php echo 'Rp. '.$harga.',00';?>
<div class="form-group">
<label for="jumlah_tamu" class="col-md-7 control-label">
<div class="col-md-4">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="quantity-left-minus btn btn-primary btn-number" data-type="minus" data-field="">
<span class="fa fa-minus">
<input type="text" id="quantity" name="qty" class="form-control input-number text-center" value="1" min="1" max="100">
<span class="input-group-btn">
<button type="button" class="quantity-right-plus btn btn-primary btn-number" data-type="plus" data-field="">
<span class="fa fa-plus">
<div class="btn-group cart">
<button type="submit" class="btn btn-success">
<span class="fa fa-shopping-cart"> Pesan
<div class="btn-group wishlist">
<a href=<?php echo base_url( "Shop")?>>
<button type="button" class="btn btn-danger">
<span class="fa fa-arrow-left"> Kembali
<?php echo form_close();?>
<?php echo $popularitem; ?>
<?php } ?>
<?php echo $footer; echo $button_script; ?>
|
php
| 11 | 0.341512 | 154 | 43.734513 | 113 |
starcoderdata
|
#ifndef DEBUG20_CALL
#define DEBUG20_CALL
namespace d20 {
struct system_error;
template<typename func, typename... Args>
constexpr void sys_call(const func& function, Args ...args) {
if (func(args...) != 0) {
throw system_error();
}
}
#if defined(_WIN32)
template<typename func, typename... Args>
constexpr void winapi_call(const func& function, Args ...args) {
if (func(args...) != 0) {
throw windows_error();
}
}
#endif
}
#endif//DEBUG20_CALL
|
c++
| 14 | 0.573013 | 68 | 20.68 | 25 |
starcoderdata
|
<?php
namespace JRpc\Json\Server;
use Zend\Stdlib\ArrayObject;
class ResponseSet extends ArrayObject
{
public function __toString()
{
return '['.implode(',', $this->getArrayCopy()).']';
}
}
|
php
| 13 | 0.633803 | 59 | 15.384615 | 13 |
starcoderdata
|
<?php
namespace PwdMgr\Bundle\AdminBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Class DefaultController
*
* @package PwdMgr\Bundle\AdminBundle\Controller
* @author
* @PreAuthorize("hasRole('ROLE_USER')")
*
* @Route("/")
*/
class DefaultController extends Controller
{
/**
* @Route("/")
* @Method("GET")
* @Secure(roles="ROLE_USER")
* @Template()
* @return array()
*/
public function indexAction()
{
return array('name' => 'fff');
}
/**
* @Route("/403")
* @Method("GET")
*
* @return RedirectResponse
*/
public function accessDeniedAction()
{
$this->flashError('Security - 403 FORBIDDEN');
return $this->redirect('/');
}
}
|
php
| 10 | 0.657116 | 62 | 22.021277 | 47 |
starcoderdata
|
/*
ID: magicgh
PROG: MaoLaoDaNumber
LANG: C++
*/
#include
#include
#include
#include
#include
#include
#define N 70000
using namespace std;
bool PrimeNum[N];
bool PrimeCheck(int n)
{
int i;
if(n==0||n==1)return 1;
for(i=2;i<=sqrt(n);i++)if(n%i==0)return 1;
return 0;
}
void Prime()
{
int i,j;
PrimeNum[0]=PrimeNum[1]=1;
PrimeNum[2]=0;
for(i=2;i<sqrt(N);i++)
{
if(PrimeNum[i]==0)for(j=i*i;j<N;j+=i)PrimeNum[j]=1;
}
}
int main(){
int list[1005],p=0,n,i;
memset(PrimeNum,0,sizeof(PrimeNum));
Prime();
while(cin>>n)
{
p=i=0;
memset(list,0,sizeof(list));
while(1)
{
i++;
if(PrimeNum[i]==1)continue;
if(i>n)break;
if(n%i==0){n/=i;list[++p]=i;i=0;}
}
if(p==0)cout<<n<<endl;
else
{
for(i=1;i<p;i++)cout<<list[i]<<'*';
cout<<list[p]<<endl;
}
}
return 0;
}
|
c++
| 14 | 0.608247 | 56 | 14.607143 | 56 |
starcoderdata
|
var app = require('express')();
const https = require('https');
var bodyParser = require('body-parser')
const request = require('request-promise');
const fs = require('fs');
const privateKey = fs.readFileSync('/etc/letsencrypt/live/buytambola.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/buytambola.com/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/buytambola.com/chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(8080, function() {
console.log('Socket server is running 8080.');
});
var io = require('socket.io')(httpsServer);
app.use(bodyParser.json());
app.post('/callNumber', function(req, res) {
var content = req.body;
//console.log('message received from php: ' + content.call_number + " " + content.prize_claims);
//to-do: forward the message to the connected nodes.
// setTimeout(startTime, content.duration);
io.sockets.in("Users").emit("numbercall", content);
if (content.status == "ACTIVE") {
setTimeout(startTime, content.duration);
}
res.status(200).end();
});
app.post('/ticketSale', function(req, res) {
var content = req.body;
console.log("Tick" + content);
io.sockets.in("Users").emit("ticketsold", content);
res.status(200).end();
})
app.post('/gametimechange', function(req, res) {
var content = req.body;
console.log("Tick" + content);
io.sockets.in("Agents").emit("gametimechange", content);
io.sockets.in("Admins").emit("gametimechange", content);
res.status(200).end();
})
app.post('/bookingstatuschange', function(req, res) {
var content = req.body;
console.log("Tick" + content);
io.sockets.in("Agents").emit("bookingstatuschange", content);
io.sockets.in("Admins").emit("bookingstatuschange", content);
res.status(200).end();
})
io.on('connection', function(socket) {
console.log("Connected");
// var redisClient = redis.createClient();
// redisClient.subscribe('message');
// redisClient.on('message', function(channel, message) {
// console.log("New Message", channel, message);
// })
var handshakeData = socket.request;
if (handshakeData._query['type'] == "user") {
socket.join("Users");
} else if (handshakeData._query['type'] == "agent") {
socket.join("Agents");
} else if (handshakeData._query['type'] == "admin") {
socket.join("Admins");
}
// redisClient.on("error", function(err) {
// console.log("Error " + err);
// });
})
function startTime() {
console.log("Test succ");
// app.post("http://127.0.0.1:8000/api/createTickets", function(err, response) {
// console.log("AA");
// });
request(options).then(function(response) {
console.log("In func");
// res.status(200).json(response);
})
.catch(function(err) {
console.log(err);
})
}
const options = {
method: 'GET',
uri: 'http://172.16.58.3/api/createTickets',
body: "",
json: true,
headers: {
'Content-Type': 'application/json'
// 'Authorization': '
}
}
|
javascript
| 13 | 0.626214 | 100 | 28.4375 | 112 |
starcoderdata
|
2/Assets/GameAssets/Scripts/GUI/TitleScreen/TitleScreenSelections.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EclipticTwo.Core;
namespace EclipticTwo.Title
{
public class TitleScreenSelections : MonoBehaviour
{
[SerializeField] private IInputReader _input;
private int _selection;
public List Options = new List
private bool _canChangeSelection;
public delegate void SelectionChangeHandler();
public event SelectionChangeHandler SelectionChanged;
private void Awake()
{
_input = GetComponent
}
private void Start()
{
Options.Sort(delegate (ISelection x, ISelection y)
{
if (x.GetTransform().position.y < y.GetTransform().position.y) return 1;
else return -1;
});
}
private void Update()
{
if (_input == null) return;
ConfirmSelection();
BrowseSelections();
}
private void ConfirmSelection()
{
if (_input.GetAction())
{
Options[_selection].Selected();
}
}
private void BrowseSelections()
{
if (Mathf.Abs(_input.GetThrust()) < float.Epsilon)
{
_canChangeSelection = true;
return;
}
if (_canChangeSelection)
{
SelectionChanged?.Invoke();
_selection += (int)Mathf.Sign(_input.GetThrust());
_canChangeSelection = false;
EnsureSelection();
}
}
private void EnsureSelection()
{
if(_selection >= Options.Count)
{
_selection = 0;
return;
}
if(_selection < 0)
{
_selection = Options.Count - 1;
}
}
public int GetSelectionNumber()
{
return _selection;
}
}
}
|
c#
| 19 | 0.509504 | 88 | 25.641975 | 81 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace SuperAgent
{
public class Agent
{
#region static member
// default agent
public static Agent defaultAgent = new Agent() {
// chrome that I'm using
AgentName = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"
};
#endregion
#region class member
public Agent(string agentName = "",CookieContainer cookies = null)
{
if(string.IsNullOrEmpty(agentName))
{
this.AgentName = "SuperAgent.NET";
}
else
{
this.AgentName = agentName;
}
if(cookies == null)
{
this.Cookies = new CookieContainer();
}
else
{
this.Cookies = cookies;
}
}
// user-agent
public string AgentName;
// cookie-jar
public CookieContainer Cookies;
public Request Get(string url)
{
return new Request(this,"GET",url);
}
public Request Post(string url)
{
return new Request(this,"POST",url);
}
#endregion
}
}
|
c#
| 13 | 0.507163 | 135 | 21.516129 | 62 |
starcoderdata
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include
#include
#include
#include "descedit.hxx"
#include "dp_gui.hrc"
using dp_gui::DescriptionEdit;
// DescriptionEdit -------------------------------------------------------
DescriptionEdit::DescriptionEdit( Window* pParent, const ResId& rResId ) :
ExtMultiLineEdit( pParent, rResId ),
m_bIsVerticalScrollBarHidden( true )
{
Init();
}
// -----------------------------------------------------------------------
void DescriptionEdit::Init()
{
Clear();
// no tabstop
SetStyle( ( GetStyle() & ~WB_TABSTOP ) | WB_NOTABSTOP );
// read-only
SetReadOnly();
// no cursor
EnableCursor( sal_False );
}
// -----------------------------------------------------------------------
void DescriptionEdit::UpdateScrollBar()
{
if ( m_bIsVerticalScrollBarHidden )
{
ScrollBar* pVScrBar = GetVScrollBar();
if ( pVScrBar && pVScrBar->GetVisibleSize() < pVScrBar->GetRangeMax() )
{
pVScrBar->Show();
m_bIsVerticalScrollBarHidden = false;
}
}
}
// -----------------------------------------------------------------------
void DescriptionEdit::Clear()
{
SetText( String() );
m_bIsVerticalScrollBarHidden = true;
ScrollBar* pVScrBar = GetVScrollBar();
if ( pVScrBar )
pVScrBar->Hide();
}
// -----------------------------------------------------------------------
void DescriptionEdit::SetDescription( const String& rDescription )
{
SetText( rDescription );
UpdateScrollBar();
}
|
c++
| 11 | 0.560335 | 79 | 26.364583 | 96 |
starcoderdata
|
#pragma once
#include "MatrixLib/utils/Math.h"
#include "MatrixLib/utils/VectorMath.h"
#include "MatrixLib/utils/Promotion.h"
#include "MatrixLib/matrix_structures/MatrixStructuresInclude.h"
#include "MatrixLib/pose_structures/PoseStructuresInclude.h"
#include "MatrixLib/utils/SoAConversions.h"
#include "MatrixLib/utils/SoloSupport.h"
|
c
| 3 | 0.818991 | 64 | 41.125 | 8 |
starcoderdata
|
package ir.mbfakouri.artificialintelligence.Main_Page;
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import java.util.LinkedHashMap;
/**
* Created by
*/
public class getPercent {
private Activity activity;
private Context Global_Context;
private LinkedHashMap<Double, Integer> list = new LinkedHashMap<>();
public getPercent(Context context) {
Global_Context = context;
}
public getPercent(Activity activity) {
this.activity = activity;
Global_Context = activity;
}
//---------> int_Number_Target if equal 1 equal width if 2 equal height
public int percent(int model, double percent) {
boolean negative_number = false;
if (percent < 0) {
negative_number = true;
percent = Math.abs(percent);
}
Double dbl_Merge = Double.parseDouble(model + "" + percent);
if (list.get(dbl_Merge) != null) {
return list.get(dbl_Merge);
}
//------------>get with and height
//DisplayMetrics displayMetrics = new DisplayMetrics();
//((Activity)Global_Context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
DisplayMetrics displayMetrics = Global_Context.getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (model == 1) {
model = width;
} else if (model == 2) {
model = height;
} else {
return 0;
}
list.put(dbl_Merge, (int) ((double) (model / 100.0f) * percent));
if (negative_number) {
return -((int) ((double) (model / 100.0f) * percent));
} else {
return (int) ((double) (model / 100.0f) * percent);
}
}
public void setPaddingWithPercent(int id_view, double Left_Percent, double Top_Percent, double Right_Percent, double Bottom_Percent) {
View view=(View) activity.findViewById(id_view);
view.setPadding(percent(1, Left_Percent), percent(2, Top_Percent), percent(1, Right_Percent), percent(2, Bottom_Percent));
}
public void setMarginWithPercent(int id_view, double Left_Percent, double Top_Percent, double Right_Percent, double Bottom_Percent) {
View view=(View) activity.findViewById(id_view);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
params.setMargins(percent(1, Left_Percent), percent(2, Top_Percent), percent(1, Right_Percent), percent(2, Bottom_Percent));
view.setLayoutParams(params);
}
}
|
java
| 16 | 0.63899 | 138 | 34.506494 | 77 |
starcoderdata
|
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyparser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
const expressValidator = require('express-validator')
require('dotenv').config()
// import routes
const authRoutes = require('./app/routes/auth')
const userRoutes = require('./app/routes/user')
const categoryRoutes = require('./app/routes/category')
const productRoutes = require('./app/routes/product')
const braintreeRoutes = require('./app/routes/braintree')
const orderRoutes = require('./app/routes/order')
// app
const app = express()
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('DB Connected'))
mongoose.connection.on('error', (err) => {
console.log(`DB connection error: ${err.message}`)
})
//middleware
app.use(morgan('dev'))
app.use(bodyparser.json())
app.use(cookieParser())
app.use(expressValidator())
app.use(cors())
// routes
app.use('/api/v1/', authRoutes)
app.use('/api/v1/', userRoutes)
app.use('/api/v1/', categoryRoutes)
app.use('/api/v1/', productRoutes)
app.use('/api/v1/', braintreeRoutes)
app.use('/api/v1/', orderRoutes)
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Server started on port: ${port}`)
})
|
javascript
| 8 | 0.708333 | 57 | 27.32 | 50 |
starcoderdata
|
import dash
import dash_core_components as dcc
import dash_html_components as html
from dashWebAppColors import BLE_WebAppColors
from BLE_Graph import BLE_Graph
class BLE_AppLayout:
def __init__(self):
self.style = BLE_WebAppColors()
self.init_graph = BLE_Graph('example')
self.layout = html.Div([
html.H1(
['Ble App']
),
BLE_Graph(id='example', datasets=[
{'x': [1, 2, 3, 4, 5], 'y': [9, 6, 2, 1, 5], 'type': 'line', 'name': 'Boats'},
{'x': [1, 2, 3, 4, 5], 'y': [8, 7, 2, 7, 3], 'type': 'bar', 'name': 'Cars'},
], layout = {
'title': 'Basic Dash Example'
}).graph
])
def getLayout(self):
return self.layout
|
python
| 18 | 0.48995 | 94 | 28.518519 | 27 |
starcoderdata
|
package com.nirima.belvedere.cli;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.spi.SubCommand;
import org.kohsuke.args4j.spi.SubCommandHandler;
import org.kohsuke.args4j.spi.SubCommands;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import static org.kohsuke.args4j.OptionHandlerFilter.ALL;
public class Cli {
public static void main(String[] args) throws IOException {
new Cli().doMain(args);
}
@Argument(required=true,index=0,metaVar="action",usage="subcommands, e.g., {search|modify|delete}",handler= SubCommandHandler.class)
@SubCommands({
@SubCommand(name="convert",impl=ConvertCommand.class),
@SubCommand(name="reverse",impl=ReverseCommand.class),
@SubCommand(name="validate",impl=ValidateCommand.class),
})
protected Command action;
public void doMain(String[] args) throws IOException {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// you can parse additional arguments if you want.
// parser.parseArgument("more","args");
// after parsing arguments, you should check
// if enough arguments are given.
// if( arguments.isEmpty() )
// throw new CmdLineException(parser,"No argument is given");
// Convert it
//DSLExec dsl = new DSLExec(getClass().getResource("test.api"));
action.execute();
} catch( CmdLineException e ) {
// if there's a problem in the command line,
// you'll get this exception. this will report
// an error message.
System.err.println(e.getMessage());
System.err.println("java belvedere [options...] arguments...");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
// print option sample. This is useful some time
System.err.println(" Example: java belvedere"+parser.printExample(ALL));
return;
}
}
public void convert() throws MalformedURLException {
}
public void reverse() throws JsonProcessingException, MalformedURLException {
}
}
|
java
| 14 | 0.645965 | 136 | 29.829268 | 82 |
starcoderdata
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AppTour {
public class OpeningTutorial : MonoBehaviour {
//Set content in editor
public GameObject openingTutorialContent;
void Awake () {
openingTutorialContent.SetActive(false);
}
//Set open and close to buttons
public void OpenTutorial() {
openingTutorialContent.SetActive(true);
}
public void CloseTutorial()
{
openingTutorialContent.SetActive(false);
}
}
}
|
c#
| 12 | 0.685512 | 49 | 20 | 27 |
starcoderdata
|
from screws.freeze.base import FrozenOnly
class _3dCSCG_SpaceAllocator(FrozenOnly):
""""""
@classmethod
def ___space_name___(cls):
return {'polynomials': "_3dCSCG_PolynomialSpace"}
@classmethod
def ___space_path___(cls):
base_path = '.'.join(str(cls).split(' ')[1][1:-2].split('.')[:-2]) + '.'
return {'polynomials': base_path + "polynomials"}
|
python
| 20 | 0.602381 | 80 | 25.3125 | 16 |
starcoderdata
|
//===--- BuiltinOptions.h - The LLVM Compiler Driver ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Declarations of all global command-line option variables.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H
#define LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H
#include "llvm/Support/CommandLine.h"
#include
namespace SaveTempsEnum { enum Values { Cwd, Obj, Unset }; }
extern llvm::cl::list InputFilenames;
extern llvm::cl::opt OutputFilename;
extern llvm::cl::opt TempDirname;
extern llvm::cl::list Languages;
extern llvm::cl::opt DryRun;
extern llvm::cl::opt Time;
extern llvm::cl::opt VerboseMode;
extern llvm::cl::opt CheckGraph;
extern llvm::cl::opt ViewGraph;
extern llvm::cl::opt WriteGraph;
extern llvm::cl::opt SaveTemps;
#endif // LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H
|
c
| 7 | 0.627817 | 80 | 34.75 | 36 |
starcoderdata
|
__________________________________________________________________________________________________
sample 76 ms submission
static const auto _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}();
class Solution {
public:
int numMatchingSubseq(string S, vector words) {
int N = words.size();
int current_index[N] = {0};
queue next[26];
for(int i = 0; i < N; i++)
next[words[i][0] - 'a'].push(i);
for(const auto& character : S)
{
int temp = next[character - 'a'].size();
for(int i = 0; i < temp; i++)
{
int word_index = next[character - 'a'].front();
next[character - 'a'].pop();
current_index[word_index]++;
if(current_index[word_index] < words[word_index].length())
next[words[word_index][current_index[word_index]] - 'a'].push(word_index);
}
}
int matching_subsequences = 0;
for(int i = 0; i < N; i++)
if(current_index[i] == words[i].length())
matching_subsequences++;
return matching_subsequences;
}
};
__________________________________________________________________________________________________
sample 23860 kb submission
class Solution {
bool isSub(string const & s, string & word) {
if (word.length() > s.length())
return false;
int i = 0, j = 0;
while (i < word.length()) {
if (j >= s.length())
return false;
if (word[i] == s[j])
++i;
++j;
}
return true;
}
public:
int numMatchingSubseq(string S, vector words) {
int result = 0;
for (auto & word : words) {
if (isSub(S, word)) {
//cout << "it is " << word << endl;
++result;
}
}
return result;
}
};
__________________________________________________________________________________________________
|
c++
| 20 | 0.397267 | 98 | 31.646154 | 65 |
starcoderdata
|
package org.jenkinsci.plugins.workflow.graph;
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.Stack;
/**
* Visits a graph of flow nodes and iterates nodes in them.
* @author
*/
// TODO guarantee DFS order (is it not already in DFS order?)
public class FlowGraphWalker implements Iterable {
// queue of nodes to visit.
// it's a stack and not queue to visit nodes in DFS
Stack q = new Stack<>();
Set visited = new HashSet<>();
public FlowGraphWalker(FlowExecution exec) {
q.addAll(exec.getCurrentHeads());
}
public FlowGraphWalker() {
}
public void addHead(FlowNode head) {
q.add(head);
}
public void addHeads(List heads) {
ListIterator itr = heads.listIterator(heads.size());
while (itr.hasPrevious())
q.add(itr.previous());
}
/**
* Each time this method is called, it returns a new node until all the nodes are visited,
* in which case this method returns null.
* @deprecated This class is {@link Iterable} now. Use {@link #iterator()} instead.
*/
@Deprecated
public FlowNode next() {
while (!q.isEmpty()) {
FlowNode n = q.pop();
if (!visited.add(n))
continue;
addHeads(n.getParents());
return n;
}
return null;
}
/**
* Unlike {@link Iterable#iterator()}, this may be iterated only once.
*/
@Override
public Iterator iterator() {
return new FlowGraphWalkerIterator();
}
private class FlowGraphWalkerIterator implements Iterator {
private FlowNode next;
private int expectedCount;
public FlowGraphWalkerIterator() {
expectedCount = q.size();
next = getNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public FlowNode next() {
FlowNode temp = next;
next = getNext();
return temp;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private FlowNode getNext() {
checkForComodification();
while (!q.isEmpty()) {
FlowNode n = q.pop();
if (!visited.add(n)) {
continue;
}
List parents = n.getParents();
addHeads(parents);
expectedCount = q.size();
return n;
}
return null;
}
private void checkForComodification() {
if (q.size() != expectedCount) {
throw new ConcurrentModificationException();
}
}
}
}
|
java
| 14 | 0.568804 | 94 | 25.29661 | 118 |
starcoderdata
|
fn test_log_replay_response() {
let mut deserializer = Deserializer::new(vec![
0x00, 0x25, /* Subcommand::Pinweaver */
0x01, /* Protocol version */
0x20, 0x00, /* Data length (little endian) */
0x00, 0x00, 0x00, 0x00, /* Result code */
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, /* Root hash (in header) */
/* Unimported leaf data */
0x01, 0x00, /* minor */
0x00, 0x00, /* major */
0x04, 0x00, /* pub_len */
0x08, 0x00, /* sec_len */
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, /* HMAC (32 bytes) */
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, /* IV (16 bytes) */
0x01, 0x01, 0x01, 0x01, /* pub_data (4 bytes) */
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, /* cipher_text (8 bytes) */
]);
let response =
PinweaverResponse::<PinweaverLogReplayResponse>::deserialize(&mut deserializer)
.expect("deserialize ok");
assert_eq!(response.result_code, 0);
assert_eq!(response.root, [0x01; 32]);
let leaf_data = response.data.expect("parsed log replay response").unimported_leaf_data;
assert_eq!(leaf_data.minor, 0x01);
assert_eq!(leaf_data.major, 0x00);
assert_eq!(leaf_data.pub_len, 0x04);
assert_eq!(leaf_data.sec_len, 0x08);
assert_eq!(leaf_data.hmac, [0xaa; 32]);
assert_eq!(leaf_data.iv, [0xcc; 16]);
assert_eq!(leaf_data.payload, vec![0x1; 12]);
}
|
rust
| 10 | 0.545038 | 96 | 49.410256 | 39 |
inline
|
int Channel::write(buffer& inBuffer)
{
int rc = 0;
auto outputPtr = inBuffer.data();
auto bufferSize = inBuffer.size();
auto spuriousWakeup = false;
ssize_t writeDataLen = 0;
timeval varTimeout = timeout;
fd_set writeSet;
FD_ZERO(&writeSet);
FD_SET(sockfd, &writeSet);
do
{
spuriousWakeup = false;
rc = select((sockfd + 1), nullptr, &writeSet, NULL, &varTimeout);
if (rc > 0)
{
if (FD_ISSET(sockfd, &writeSet))
{
address.addrSize =
static_cast<socklen_t>(sizeof(address.inAddr));
do
{
writeDataLen =
sendto(sockfd, // File Descriptor
outputPtr, // Message
bufferSize, // Length
MSG_NOSIGNAL, // Flags
&address.sockAddr, // Destination Address
address.addrSize); // Address Length
if (writeDataLen < 0)
{
rc = -errno;
std::cerr
<< "Channel::Write: Write failed with errno:" << rc
<< "\n";
}
else if (static_cast<size_t>(writeDataLen) < bufferSize)
{
rc = -1;
std::cerr << "Channel::Write: Complete data not written"
" to the socket\n";
}
} while ((writeDataLen < 0) && (-(rc) == EINTR));
}
else
{
// Spurious wake up
std::cerr << "Spurious wake up on select (writeset)\n";
spuriousWakeup = true;
}
}
else
{
if (rc == 0)
{
// Timed out
rc = -1;
std::cerr << "We timed out on select call (writeset)\n";
}
else
{
// Error
rc = -errno;
std::cerr << "select call (writeset) had an error : " << rc
<< "\n";
}
}
} while (spuriousWakeup);
return rc;
}
|
c++
| 20 | 0.371928 | 80 | 30.194805 | 77 |
inline
|
package main
import(
"fmt"
"bufio"
"os"
)
func main(){
f, err := os.Open("day3_input.txt")
if err != nil{
panic(err)
}
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanRunes)
var cmds []string
for scanner.Scan(){
x := scanner.Text()
if x == ">" || x == "<" || x == "^" || x == "v"{
cmds = append(cmds, x)
}
}
var houses = make(map[string]int)
robo := false
currentX := 0
currentY := 0
RcurrentX := 0
RcurrentY := 0
idx:= fmt.Sprintf("%d x%d", currentX, currentY)
houses[idx] = houses[idx] + 1
for _ , cmd := range cmds{
if robo{
switch{
case cmd == "<":
RcurrentX = RcurrentX - 1
case cmd == ">":
RcurrentX = RcurrentX + 1
case cmd == "^":
RcurrentY = RcurrentY + 1
case cmd == "v":
RcurrentY = RcurrentY - 1
}
idx := fmt.Sprintf("%d x %d", RcurrentX, RcurrentY)
houses[idx] = houses[idx] + 1
robo = false
} else {
switch{
case cmd == "<":
currentX = currentX - 1
case cmd == ">":
currentX = currentX + 1
case cmd == "^":
currentY = currentY + 1
case cmd == "v":
currentY = currentY - 1
}
idx := fmt.Sprintf("%d x %d", currentX, currentY)
houses[idx] = houses[idx] + 1
robo = true
}
}
var visited int
for _ , el := range houses{
if el > 0{
visited = visited + 1
}
}
fmt.Println(visited)
}
|
go
| 12 | 0.302479 | 75 | 30.428571 | 77 |
starcoderdata
|
/*
* Copyright (c) 2021, All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.abst.sfm.d3;
import boofcv.abst.sfm.AccessPointTracks3D;
import boofcv.abst.tracker.PointTrack;
import boofcv.alg.geo.DistanceFromModelMultiView;
import boofcv.alg.sfm.StereoSparse3D;
import boofcv.alg.sfm.d3.VisOdomMonoDepthPnP;
import boofcv.struct.calib.StereoParameters;
import boofcv.struct.geo.Point2D3D;
import boofcv.struct.image.ImageGray;
import boofcv.struct.image.ImageType;
import georegression.struct.point.Point2D_F64;
import georegression.struct.point.Point3D_F64;
import georegression.struct.point.Point4D_F64;
import georegression.struct.se.Se3_F64;
import org.jetbrains.annotations.Nullable;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Wrapper around {@link VisOdomMonoDepthPnP} for {@link StereoVisualOdometry}.
*
* @author
*/
// TODO WARNING! active list has been modified by dropping and adding tracks
// this is probably true of other SFM algorithms
public class WrapVisOdomMonoStereoDepthPnP<T extends ImageGray
implements StereoVisualOdometry AccessPointTracks3D {
// low level algorithm
VisOdomMonoDepthPnP alg;
StereoSparse3D stereo;
DistanceFromModelMultiView<Se3_F64, Point2D3D> distance;
Class imageType;
boolean success;
List active = new ArrayList<>();
public WrapVisOdomMonoStereoDepthPnP( VisOdomMonoDepthPnP alg,
StereoSparse3D stereo,
DistanceFromModelMultiView<Se3_F64, Point2D3D> distance,
Class imageType ) {
this.alg = alg;
this.stereo = stereo;
this.distance = distance;
this.imageType = imageType;
}
@Override
public boolean getTrackWorld3D( int index, Point3D_F64 world ) {
Point4D_F64 p = alg.getVisibleTracks().get(index).worldLoc;
world.setTo(p.x/p.w, p.y/p.w, p.z/p.w);
return true;
}
@Override
public int getTotalTracks() {
return alg.getVisibleTracks().size();
}
@Override
public long getTrackId( int index ) {
return alg.getVisibleTracks().get(index).id;
}
@Override
public void getTrackPixel( int index, Point2D_F64 pixel ) {
// If this throws a null pointer exception then that means there's a bug. The only way a visible track
// could have a null trackerTrack is if the trackerTrack was dropped. In that case it's no longer visible
PointTrack track = Objects.requireNonNull(alg.getVisibleTracks().get(index).visualTrack);
pixel.setTo(track.pixel);
}
@Override
public List getAllTracks( @Nullable List storage ) {
throw new RuntimeException("Not supported any more");
}
@Override
public boolean isTrackInlier( int index ) {
return alg.getInlierTracks().contains(alg.getVisibleTracks().get(index));
}
@Override
public boolean isTrackNew( int index ) {
VisOdomMonoDepthPnP.Track track = alg.getVisibleTracks().get(index);
return Objects.requireNonNull(track.visualTrack).spawnFrameID == alg.getFrameID();
}
@Override
public void setCalibration( StereoParameters parameters ) {
stereo.setCalibration(parameters);
alg.setCamera(parameters.left);
distance.setIntrinsic(0, parameters.left);
}
@Override
public boolean process( T leftImage, T rightImage ) {
stereo.setImages(leftImage, rightImage);
success = alg.process(leftImage);
active.clear();
alg.getTracker().getActiveTracks(active);
return success;
}
@Override
public ImageType getImageType() {
return ImageType.single(imageType);
}
@Override
public void reset() {
alg.reset();
}
@Override
public boolean isFault() {
return !success;
}
@Override
public Se3_F64 getCameraToWorld() {
return alg.getCurrentToWorld();
}
@Override
public long getFrameID() {
return alg.getFrameID();
}
public VisOdomMonoDepthPnP getAlgorithm() {
return alg;
}
@Override
public void setVerbose( @Nullable PrintStream out, @Nullable Set configuration ) {
alg.setVerbose(out, configuration);
}
}
|
java
| 13 | 0.747248 | 107 | 27.25 | 164 |
starcoderdata
|
//
// UIImage+OpenCV.h
//
// Copyright (c) 2015 Bracing Effect, LLC. See LICENSE for details.
//
#import
#include "opencv2/opencv.hpp"
@interface UIImage (OpenCV)
- (cv::Mat)mat;
- (cv::Mat)matGray;
/**
* Must call cvReleaseImage(iplImage) and free(iplImage) on returned (IplImage *).
*/
- (IplImage *)iplImageWithNumberOfChannels:(int)channels;
//- (NSArray *)textBoundingBoxes;
- (CGAffineTransform)transformForOrientationDrawnTransposed:(BOOL *)drawTransposed;
//- (UIImage *)binarization;
// Returns a UIImage by copying the IplImage's bitmap data.
+ (UIImage *)imageFromIplImage:(IplImage *)iplImage;
+ (UIImage *)imageFromIplImage:(IplImage *)iplImage orientation:(UIImageOrientation)orientation;
+ (UIImage *)imageFromMat:(cv::Mat)mat;
@end
|
c
| 10 | 0.729798 | 96 | 23.75 | 32 |
starcoderdata
|
package io.home.ui.controller.runprofile;
import io.home.model.Profile;
import io.home.ui.share.SwingHelper;
import io.home.ui.share.Resource;
import jiconfont.icons.google_material_design_icons.GoogleMaterialDesignIcons;
import jiconfont.swing.IconFontSwing;
import javax.swing.*;
import javax.swing.text.Document;
import java.awt.event.ActionEvent;
public class RunProfileAction extends AbstractAction {
private Document fileDocument;
private Document argumentsDocument;
private Document environmentDocument;
private Document workingPathDocument;
public RunProfileAction() {
putValue(SMALL_ICON, IconFontSwing.buildIcon(GoogleMaterialDesignIcons.PLAY_ARROW, Resource.ICON_SIZE));
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
Profile profile = new Profile();
String file = SwingHelper.getText(fileDocument);
String arguments = SwingHelper.getText(argumentsDocument);
String environment = SwingHelper.getText(environmentDocument);
String workingPath = SwingHelper.getText(workingPathDocument);
System.out.println(file);
System.out.println(arguments);
System.out.println(environment);
System.out.println(workingPath);
}
public void setFileDocument(Document fileDocument) {
this.fileDocument = fileDocument;
}
public void setArgumentsDocument(Document argumentsDocument) {
this.argumentsDocument = argumentsDocument;
}
public void setEnvironmentDocument(Document environmentDocument) {
this.environmentDocument = environmentDocument;
}
public void setWorkingPathDocument(Document workingPathDocument) {
this.workingPathDocument = workingPathDocument;
}
}
|
java
| 11 | 0.749008 | 112 | 32.942308 | 52 |
starcoderdata
|
<?php
/**
* Shows more on how a week can be used
*/
function getmicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$start = getmicrotime();
if (!@include 'Calendar/Calendar.php') {
define('CALENDAR_ROOT', '../../');
}
require_once CALENDAR_ROOT.'Week.php';
if (!isset($_GET['y'])) $_GET['y'] = date('Y');
if (!isset($_GET['m'])) $_GET['m'] = date('m');
if (!isset($_GET['d'])) $_GET['d'] = 1;
// Build the month
$Week = new Calendar_Week($_GET['y'], $_GET['m'], $_GET['d']);
/*
$Validator = $Week->getValidator();
if (!$Validator->isValidWeek()) {
die ('Please enter a valid week!');
}
*/
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Paging Weeks
Weeks
<?php echo $Week->thisWeek().' '.date('F Y',$Week->thisMonth(true)); ?>
<?php
$Week->build();
while ($Day = $Week->fetch()) {
echo ' F',$Day->thisDay(true))."
}
$days = $Week->fetchAll();
$prevWeek = $Week->prevWeek('array');
$prevWeekLink = $_SERVER['PHP_SELF'].
'?y='.$prevWeek['year'].
'&m='.$prevWeek['month'].
'&d='.$prevWeek['day'];
$nextWeek = $Week->nextWeek('array');
$nextWeekLink = $_SERVER['PHP_SELF'].
'?y='.$nextWeek['year'].
'&m='.$nextWeek['month'].
'&d='.$nextWeek['day'];
?>
href="<?php echo $prevWeekLink; ?>"> | <a href="<?php echo $nextWeekLink; ?>">>>
|
php
| 12 | 0.527103 | 100 | 26.220339 | 59 |
starcoderdata
|
def create_cost(request, id):
"""Create cost of plan"""
# if user is logged in
if request.user.is_authenticated:
# get single_cost by id
single_plan = Plan.objects.get(id=id)
# if its users plan
if single_plan in request.user.plan.all():
if request.method == 'POST':
# take create cost form
form = CreateNewCost(request.POST)
# form validation
if form.is_valid():
cn = form.cleaned_data["cost_name"]
c = form.cleaned_data["cost"]
nm = form.cleaned_data["number_of_members"]
cinf = form.cleaned_data["cost_info"]
pd = form.cleaned_data["payment_date"]
t = Cost(plan_of_cost=single_plan, cost_name=cn, cost=c, number_of_members=nm,
payment_date=pd, cost_info=cinf)
# save form data
t.save()
return HttpResponseRedirect(f'/single_plan/{id}')
else:
# render create cost form
form = CreateNewCost()
context = {'form': form, 'single_plan': single_plan}
return render(request, 'account/create_cost.html', context)
else:
return HttpResponseRedirect('/login')
|
python
| 16 | 0.508065 | 98 | 43.032258 | 31 |
inline
|
/*
* Copyright 2013 - 2019 The Original Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elasticsoftware.elasticactors.cluster.tasks.app;
import org.elasticsoftware.elasticactors.ActorRef;
import org.elasticsoftware.elasticactors.ElasticActor;
import org.elasticsoftware.elasticactors.MessageDeliveryException;
import org.elasticsoftware.elasticactors.MethodActor;
import org.elasticsoftware.elasticactors.cluster.InternalActorSystem;
import org.elasticsoftware.elasticactors.cluster.logging.LoggingSettings;
import org.elasticsoftware.elasticactors.cluster.logging.MessageLogger;
import org.elasticsoftware.elasticactors.cluster.metrics.MetricsSettings;
import org.elasticsoftware.elasticactors.cluster.tasks.ActorLifecycleTask;
import org.elasticsoftware.elasticactors.messaging.InternalMessage;
import org.elasticsoftware.elasticactors.messaging.MessageHandlerEventListener;
import org.elasticsoftware.elasticactors.messaging.reactivestreams.NextMessage;
import org.elasticsoftware.elasticactors.serialization.Message;
import org.elasticsoftware.elasticactors.serialization.MessageSerializer;
import org.elasticsoftware.elasticactors.serialization.MessageToStringConverter;
import org.elasticsoftware.elasticactors.state.ActorStateUpdateProcessor;
import org.elasticsoftware.elasticactors.state.MessageSubscriber;
import org.elasticsoftware.elasticactors.state.PersistentActor;
import org.elasticsoftware.elasticactors.state.PersistentActorRepository;
import org.elasticsoftware.elasticactors.util.concurrent.MessageHandlingThreadBoundRunnable;
import org.elasticsoftware.elasticactors.util.ByteBufferUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Set;
import static org.elasticsoftware.elasticactors.tracing.TracingUtils.shorten;
import static org.elasticsoftware.elasticactors.util.SerializationTools.deserializeMessage;
/**
* Task that is responsible for internalMessage deserialization, error handling and state updates
*
* @author
*/
final class HandleMessageTask
extends ActorLifecycleTask
implements MessageHandlingThreadBoundRunnable {
private static final Logger logger = LoggerFactory.getLogger(HandleMessageTask.class);
HandleMessageTask(
InternalActorSystem actorSystem,
ElasticActor receiver,
ActorRef receiverRef,
InternalMessage internalMessage,
PersistentActor persistentActor,
PersistentActorRepository persistentActorRepository,
ActorStateUpdateProcessor actorStateUpdateProcessor,
MessageHandlerEventListener messageHandlerEventListener,
MetricsSettings metricsSettings,
LoggingSettings loggingSettings)
{
super(
actorStateUpdateProcessor,
persistentActorRepository,
persistentActor,
actorSystem,
receiver,
receiverRef,
messageHandlerEventListener,
internalMessage,
metricsSettings,
loggingSettings
);
}
@Override
protected boolean doInActorContext(InternalActorSystem actorSystem,
ElasticActor receiver,
ActorRef receiverRef,
InternalMessage internalMessage) {
try {
Object message = deserializeMessage(actorSystem, internalMessage);
logMessageContents(message);
try {
if (receiver instanceof MethodActor) {
((MethodActor) receiver).onReceive(
internalMessage.getSender(),
message,
() -> getStringBody(message)
);
} else {
receiver.onReceive(internalMessage.getSender(), message);
}
// reactive streams
notifySubscribers(internalMessage);
return shouldUpdateState(receiver, message);
} catch(MessageDeliveryException e) {
// see if it is a recoverable exception
if(!e.isRecoverable()) {
logger.error("Unrecoverable MessageDeliveryException while handling message for actor [{}]", receiverRef, e);
}
// message cannot be sent but state should be updated as the received message did most likely change
// the state
return shouldUpdateState(receiver, message);
} catch (Exception e) {
logException(message, receiverRef, internalMessage, e);
return false;
}
} catch (Exception e) {
logger.error(
"Exception while Deserializing Message class [{}] in ActorSystem [{}]",
internalMessage.getPayloadClass(),
actorSystem.getName(),
e);
return false;
}
}
private void logException(
Object message,
ActorRef receiverRef,
InternalMessage internalMessage,
Exception e) {
if (logger.isErrorEnabled()) {
Message messageAnnotation = message.getClass().getAnnotation(Message.class);
if (messageAnnotation != null && messageAnnotation.logBodyOnError()) {
logger.error(
"Exception while handling message of type [{}]. "
+ "Actor [{}]. "
+ "Sender [{}]. "
+ "Message payload [{}].",
shorten(message.getClass()),
receiverRef,
internalMessage.getSender(),
getStringBody(message),
e
);
} else {
logger.error(
"Exception while handling message of type [{}]. "
+ "Actor [{}]. "
+ "Sender [{}].",
shorten(message.getClass()),
receiverRef,
internalMessage.getSender(),
e
);
}
}
}
private String getStringBody(Object message) {
MessageToStringConverter messageToStringConverter =
MessageLogger.getMessageToStringConverter(actorSystem, message.getClass());
return MessageLogger.convertToString(
message,
actorSystem,
internalMessage,
messageToStringConverter
);
}
private void notifySubscribers(InternalMessage internalMessage) {
if(persistentActor.getMessageSubscribers() != null) {
try {
// todo consider using ActorRefGroup here
if(persistentActor.getMessageSubscribers().containsKey(internalMessage.getPayloadClass())) {
// copy the bytes from the incoming message, discarding possible changes made in onReceive
NextMessage nextMessage = new NextMessage(internalMessage.getPayloadClass(), getMessageBytes(internalMessage));
((Set persistentActor.getMessageSubscribers().get(internalMessage.getPayloadClass()))
.stream().filter(messageSubscriber -> messageSubscriber.getAndDecrement() > 0)
.forEach(messageSubscriber -> messageSubscriber.getSubscriberRef().tell(nextMessage, receiverRef));
}
} catch(Exception e) {
logger.error("Unexpected exception while forwarding message to Subscribers", e);
}
}
}
private byte[] getMessageBytes(InternalMessage internalMessage) throws IOException {
if(internalMessage.hasSerializedPayload()) {
ByteBuffer messagePayload = internalMessage.getPayload();
return ByteBufferUtils.toByteArrayAndReset(messagePayload);
} else {
// transient message, need to serialize the bytes
Object message = internalMessage.getPayload(null);
ByteBuffer messageBytes = ((MessageSerializer
return ByteBufferUtils.toByteArray(messageBytes);
}
}
@Override
protected boolean shouldLogMessageInformation() {
return true;
}
@Override
public Class<? extends ElasticActor> getActorType() {
return receiver.getClass();
}
@Override
public Class getMessageClass() {
return unwrapMessageClass(internalMessage);
}
@Override
public InternalMessage getInternalMessage() {
return internalMessage;
}
}
|
java
| 21 | 0.643986 | 132 | 41.171171 | 222 |
starcoderdata
|
/**
* @file reNaraMetaData.c
*
*/
#include "reNaraMetaData.h"
#include "apiHeaderAll.h"
/**
* \fn msiExtractNaraMetadata (ruleExecInfo_t *rei)
*
* \brief This microservice extracts NARA style metadata from a local configuration file.
*
* \module core
*
* \since pre-2.1
*
* \author DICE
* \date 2007
*
* \usage See clients/icommands/test/rules3.0/
*
* \param[in,out] rei - The RuleExecInfo structure that is automatically
* handled by the rule engine. The user does not include rei as a
* parameter in the rule invocation.
*
* \DolVarDependence none
* \DolVarModified none
* \iCatAttrDependence none
* \iCatAttrModified none
* \sideeffect none
*
* \return integer
* \retval 0 on success
* \pre none
* \post none
* \sa none
**/
int
msiExtractNaraMetadata (ruleExecInfo_t *rei)
{
FILE *fp;
char str[500];
char *substring;
int counter;
int flag;
char attr[100];
char value[500];
modAVUMetadataInp_t modAVUMetadataInp;
int status;
/* specify the location of the metadata file here */
char metafile[MAX_NAME_LEN];
snprintf (metafile, MAX_NAME_LEN, "%-s/reConfigs/%-s", getConfigDir(),
NARA_META_DATA_FILE);
if((fp=fopen(metafile, "r")) == NULL) {
rodsLog (LOG_ERROR,
"msiExtractNaraMetadata: Cannot open the metadata file %s.", metafile);
return (UNIX_FILE_OPEN_ERR);
}
memset (&modAVUMetadataInp, 0, sizeof (modAVUMetadataInp));
modAVUMetadataInp.arg0 = "add";
while(!feof(fp)){
counter = 0;
flag = 0;
if(fgets(str, 500, fp)){
substring = strtok (str,"|");
while (substring != NULL){
if(flag == 0 && strcmp(substring,rei->doi->objPath) == 0){
flag = 2;
}
if(counter == 1){
strcpy( attr, substring );
}
if(flag == 2 && counter == 2){
strcpy( value, substring );
/*Call the function to insert metadata here.*/
modAVUMetadataInp.arg1 = "-d";
modAVUMetadataInp.arg2 = rei->doi->objPath;
modAVUMetadataInp.arg3 = attr;
modAVUMetadataInp.arg4 = value;
modAVUMetadataInp.arg5 = "";
status = rsModAVUMetadata (rei->rsComm, &modAVUMetadataInp);
rodsLog (LOG_DEBUG, "msiExtractNaraMetadata: %s:%s",attr, value);
}
substring = strtok (NULL, "|");
counter++;
}
}
}
fclose(fp);
return(0);
}
|
c
| 17 | 0.619243 | 90 | 23.565657 | 99 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using NrsLib.ClassFileGenerator.Core.Meta.Def.Methods;
using NrsLib.ClassFileGenerator.Core.Meta.Words;
namespace NrsLib.ClassFileGenerator.Core.Meta.Def {
public class ConstructorDefinition {
private readonly List arguments = new List
private readonly List body = new List
private readonly List callArguments = new List
internal AccessLevel AccessLevel { get; private set; } = AccessLevel.Private;
internal string[] Body => body.ToArray();
internal bool CallBase { get; private set; }
internal bool CallThis { get; private set; }
public ConstructorDefinition AddArgument(string name, string type)
{
arguments.Add(new VariantDefinition(name, type));
return this;
}
public ConstructorDefinition SetAccessLevel(AccessLevel level)
{
AccessLevel = level;
return this;
}
public ConstructorDefinition AddBody(params string[] texts) {
body.AddRange(texts);
return this;
}
public ConstructorDefinition SetCallBase(params string[] args)
{
if (CallThis)
{
throw new InvalidOperationException("This constructor is setting up call this().");
}
CallBase = true;
callArguments.AddRange(args);
return this;
}
public ConstructorDefinition SetCallThis(params string[] args)
{
if (CallBase)
{
throw new InvalidOperationException("This constructor is setting up call base().");
}
CallThis = true;
callArguments.AddRange(args);
return this;
}
internal string ArgumentsText(IArgumentFormatter fomatter) {
return string.Join(", ", arguments.Select(fomatter.Format));
}
internal string CallArgumentsText()
{
return string.Join(", ", callArguments);
}
}
}
|
c#
| 15 | 0.581938 | 99 | 30.428571 | 70 |
starcoderdata
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* dtoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okryzhan +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/16 13:59:51 by okryzhan #+# #+# */
/* Updated: 2018/11/16 13:59:52 by okryzhan ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *itostr(uintmax_t n, int after)
{
char *s;
int i;
MALCH((s = ft_strnew(after)));
i = 0;
while (n)
{
s[i++] = n % 10 + '0';
n /= 10;
}
while (i < after)
{
s[i] = '0';
i++;
}
ft_strrev(s);
return (s);
}
char *pf_dtoa(long double n, int after)
{
char *is;
char *fs;
char *tmp;
intmax_t ipart;
long double fpart;
ipart = (intmax_t)n;
fpart = n - (intmax_t)n;
MALCH((is = ft_itoa_base(n, 10)));
if (n < 0 && ipart == 0)
{
MALCH((tmp = ft_strjoin("-", is)));
free(is);
is = tmp;
}
if (after != 0)
{
ft_strcat(is, ".");
fpart = fpart * ft_power(10, after);
fpart = fpart < 0 ? -fpart : fpart;
fs = itostr((uintmax_t)fpart, after);
ft_strcat(is, fs);
free(fs);
}
return (is);
}
|
c
| 13 | 0.295981 | 80 | 25.063492 | 63 |
starcoderdata
|
<?php
/**
* Created by PhpStorm.
* User: haiye_000
* Date: 11-Nov-16
* Time: 6:11 PM
*/
namespace frontend\controllers;
use Yii;
use mdm\admin\components\AccessControl;
use yii\base\Controller;
use yii\filters\VerbFilter;
class OrthancController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['index','create','update','view'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied
],
],
];
}
public function actionIndex() {
// curl http://localhost:8042/patients
$patient_info = "";
$studies = "";
$study = array();
$curl = new Curl();
$patients_id = json_decode($curl->curl("http://localhost:8042/patients","GET"));
if (isset($patients_id) && $patients_id != null) {
for($i = 0; $i < sizeof($patients_id); $i++){
$patient_info[$i] = json_decode($curl->curl("http://localhost:8042/patients/$patients_id[$i]","GET"));
// var_dump($patient_info[$i]);
}
// die();
$studies_id = json_decode($curl->curl("http://localhost:8042/studies/", "GET"));
for ($i=0; $i< sizeof($studies_id);$i++){
$study[$i] = json_decode($curl->curl("http://localhost:8042/studies/$studies_id[$i]", "GET"));
}
}
return $this->render('index', [
'patients_id' => $patients_id,
'patient_info' => $patient_info,
'study' => $study
]);
}
public function actionStudy() {
$id = $_GET['id'];
$curl = new Curl();
$study = json_decode($curl->curl("http://localhost:8042/studies/$id", "GET"));
// var_dump($study);
return $this->render('study',[
'study'=> $study
]);
}
public function actionSeries () {
$id = $_GET['id'];
$curl = new Curl();
$series = json_decode($curl->curl("http://localhost:8042/series/$id", "GET"));
return $this->render('series',[
'series'=> $series
]);
}
public function actionInstances () {
$id = $_GET['id'];
$curl = new Curl();
$instances = json_decode($curl->curl("http://localhost:8042/instances/$id", "GET"));
return $this->render('instances',[
'instances'=> $instances
]);
}
public function actionDelete(){
// curl -X DELETE http://localhost:8042/patients/dc65762c-f476e8b9-898834f4-2f8a5014-2599bc94
$url = $_GET['url'];
$curl = new Curl();
$curl->curl($url,"DELETE");
Yii::$app->response->redirect(['orthanc/index']);
}
public function actionUpload() {
// curl -X POST -H "Expect:" http://localhost:8042/instances --data-binary @ffc.dcm
if (isset($_POST['upload']))
{
$url = "http://localhost:8042/instances"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], "E:/tmp". DIRECTORY_SEPARATOR . $filename)) {
$filedata = "E:/tmp". DIRECTORY_SEPARATOR . $filename;
$output = shell_exec('curl -X POST http://localhost:8042/instances --data-binary @'.$filedata);
}
}
// echo "?";
Yii::$app->response->redirect(['orthanc/index']);
}
public function actionUp() {
shell_exec('curl -X POST -H "Expect:" http://localhost:8042/instances --data-binary @ffc.dcm');
}
}
|
php
| 20 | 0.499617 | 118 | 30.36 | 125 |
starcoderdata
|
package com.rizky.ca.cmp.common;
public enum CertRequestStatus {
Submitted,
Rejected,
Approved
}
|
java
| 4 | 0.75974 | 43 | 18.25 | 8 |
starcoderdata
|
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
ll n;
cin>>n;
unordered_map<ll,ll> umap;
// freq[]=;
for(int i=0;i<n;i++)
{
ll x;
cin>>x;
umap[x]++;
}
int count=0;
for(auto &x:umap){
int tmp=x.second-x.first;
count+=tmp>=0?tmp:x.second;
}
cout<<abs(count);
}
|
c++
| 9 | 0.461735 | 35 | 15.333333 | 24 |
codenet
|
from math import inf
from pyutils import *
def parse(lines):
heights = {}
for y, line in enumerate(lines):
for x, char in enumerate(line):
heights[(x, y)] = int(char)
return heights
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def neighbors(loc, heights):
for direction in directions:
neighbor = tuple(x+dx for x, dx in zip(loc, direction))
if neighbor in heights:
yield neighbor
def lows(heights):
return [loc for loc, height in heights.items() if all(height < heights[neighbor] for neighbor in neighbors(loc, heights))]
def basin_from(low, heights):
q, basin = [(low, -inf)], set()
while q:
loc, prev = q.pop()
if loc in basin or heights[loc] == 9:
continue
if heights[loc] > prev:
basin.add(loc)
q.extend([(neighbor, heights[loc])
for neighbor in neighbors(loc, heights)])
heights[loc] = 9
return tuple(sorted(basin))
@expect({'test': 15})
def solve1(heights):
return sum(1+heights[loc] for loc in lows(heights))
@expect({'test': 1134})
def solve2(heights):
answer = 1
for basin in sorted([basin_from(low, heights) for low in lows(heights)], key=len, reverse=True)[:3]:
answer *= len(basin)
return answer
|
python
| 14 | 0.569209 | 126 | 24.735849 | 53 |
starcoderdata
|
a='abcd@12#ef$k'
i=0
l=[]
s=[]
while i<len(a):
if a[i].isalnum():
l.append(a[i])
else:
s.append(a[i])
i+=1
print(l)
print(s)
i=0
k=len(a)
m=0
while i<len(a):
if a[i].isalnum():
print(l[k],end='')
k-=1
else:
print(s[m],end='')
m+=1
i+=1
|
python
| 11 | 0.39577 | 26 | 12.391304 | 23 |
starcoderdata
|
/**
* Copyright (c) Open Carbon, 2020
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* components/Endpoints.js
*
* Endpoints page describing how to access core JSON data stored on site
*/
import React, { Component } from 'react';
import { withStyles } from '@material-ui/styles';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import { globalstyle } from '../styles/globalstyle';
class Endpoints extends Component {
render() {
return (
<Container maxWidth="sm">
<Box my={4}>
<Typography variant="h2" gutterBottom>
Endpoints
<Box bgcolor="primary.light" p={1.5} mt={6}>
<Typography variant="h6">
<a href="/organisations" style={{textDecoration: 'none'}}>/organisations
<Box mt={2}>
<Typography variant="body1">
Provides list of all published organisations, including their id, name, parent organisation and OSM (Open Street Map) link, if available.
Detailed information about an organisation's emissions is not provided.
<Box bgcolor="primary.light" p={1.5} mt={6}>
<Typography variant="h6">
<a href="/organisations?name=" style={{textDecoration: 'none'}}>/organisations?name=[name]
<Box mt={2}>
<Typography variant="body1" gutterBottom>
Searches all published organisations by name and returns list of organisations whose name contains including their id, name, parent organisation and OSM (Open Street Map) link, if available.
Detailed information about an organisation's emissions is not provided.
<Typography variant="body1" gutterBottom>
Special characters such as punctuation should be encoded when making API call. For example, for
<Box mt={1}>
<Typography variant="body1">
<a href="/organisations?name=H%26M" style={{textDecoration: 'none'}}>/organisations?name=H%26M
<Box bgcolor="primary.light" p={1.5} mt={6}>
<Typography variant="h6">
<a href="/organisations/[id]" style={{textDecoration: 'none'}}>/organisations/[id]
<Box mt={2}>
<Typography variant="body1" gutterBottom>
Provides detailed information about an organisation and its carbon emissions.
The structure of the data follows <a href="/standards" style={{textDecoration: 'none', fontWeight: 'bold'}}>this specification
<Typography variant="body1" gutterBottom>
is organisation's unique identifier, a lowercase string created by removing all non-alphanumeric characters from
organisation's name when record is initially created.
);
}
}
export default withStyles(globalstyle)(Endpoints);
|
javascript
| 17 | 0.54564 | 236 | 43.568182 | 88 |
starcoderdata
|
with open('palindrome.txt') as fin:
word = next(fin)
# pal[i][j] = True if subsequence between i and j is palindrome
# = s[i] == s[j] and pal[i + 1][j - 1] (stop when i > j)
n = len(word)
pal = [[False for _ in range(n)] for _ in range(n)]
for i in range(n):
pal[i][i] = True
|
python
| 8 | 0.558923 | 66 | 26 | 11 |
starcoderdata
|
using System;
namespace STRSOhioAnnualReporting
{
public enum StrsPadding
{
Left,
Right,
Default,
Fail
}
}
|
c#
| 6 | 0.669528 | 80 | 18.416667 | 12 |
starcoderdata
|
void generate_r1cs_witness(const ethsnarks::FieldT &floatValue)
{
f.fill_with_bits_of_field_element(pb, floatValue);
// Decodes the mantissa
for (unsigned int i = 0; i < floatEncoding.numBitsMantissa; i++)
{
unsigned j = floatEncoding.numBitsMantissa - 1 - i;
pb.val(values[i]) = (i == 0) ? pb.val(f[j]) : (pb.val(values[i - 1]) * 2 + pb.val(f[j]));
}
// Decodes the exponent and shifts the mantissa
for (unsigned int i = floatEncoding.numBitsMantissa; i < f.size(); i++)
{
// Decode the exponent
unsigned int j = i - floatEncoding.numBitsMantissa;
pb.val(baseMultipliers[j]) = (j == 0) ? floatEncoding.exponentBase : pb.val(baseMultipliers[j - 1]) * pb.val(baseMultipliers[j - 1]);
multipliers[j].generate_r1cs_witness();
// Shift the value with the partial exponent
pb.val(values[i]) = pb.val(values[i - 1]) * pb.val(multipliers[j].result());
}
}
|
c
| 15 | 0.533998 | 149 | 47 | 23 |
inline
|
var exec = require('cordova/exec');
var PLUGIN_NAME = 'GenieSDK';
var preferences = {
getString: function (key, success) {
exec(success, null, PLUGIN_NAME, this.action(), ["getString", key]);
},
getStringWithoutPrefix: function (key, success) {
exec(success, null, PLUGIN_NAME, this.action(), ["getStringWithoutPrefix", key]);
},
putString: function (key, value, success) {
exec(success, null, PLUGIN_NAME, this.action(), ["putString", key, value]);
},
action: function () {
return "preferences";
}
};
module.exports = preferences;
|
javascript
| 12 | 0.666129 | 85 | 21.962963 | 27 |
starcoderdata
|
int main(int argc, char **argv) {
CGI_varlist *varlist;
//const char *name;
CGI_value *value;
printf("%s%c%c\n",
"Content-Type:text/html;charset=iso-8859-1", 13, 10);
if ((varlist = CGI_get_all(0)) == 0) {
printf("<p>No CGI data received</p>\r\n");
exit(1);
}
/* output all values of all variables and cookies */
value = CGI_lookup_all(varlist, "operation");
if (strcmp(value[0], "Delete") == 0) {
value = CGI_lookup_all(varlist, "selected");
delete(value);
}
else if (strcmp(value[0], "Add") == 0)
{
printf("<META HTTP-EQUIV=refresh CONTENT=\"1;URL=%s\">\n", ADD_URL);
}
else if (strcmp(value[0], "Edit") == 0) {
value = CGI_lookup_all(varlist, "selected");
edit(value);
}
CGI_free_varlist(varlist);
return 0;
}
|
c
| 14 | 0.513393 | 76 | 26.0625 | 32 |
inline
|
import re
__all__ = [
'Survey', 'Recipient', 'Collector', 'EmailMessage'
]
class Survey(dict):
def __init__(self, survey_title, template_id=None, from_survey_id=None):
params = {
'survey_title': survey_title
}
if template_id:
params['template_id'] = template_id
if from_survey_id:
params['from_survey_id'] = from_survey_id
assert not template_id, \
"template_id and form_survey_id cannot be specified together"
super(Survey, self).__init__(params)
class Recipient(dict):
def __init__(self, email, first_name=None, last_name=None, custom_id=None):
params = {
'email': email
}
if first_name:
params['first_name'] = first_name
if last_name:
params['last_name'] = last_name
if custom_id:
params['custom_id'] = custom_id
super(Recipient, self).__init__(params)
class Collector(dict):
def __init__(self, type, name=None, recipients=None, send=None):
params = {
'type': type
}
if name:
params['name'] = name
if recipients:
params['recipients'] = recipients
if send is not None:
params['send'] = send
super(Collector, self).__init__(params)
class EmailMessage(dict):
survey_link = "[SurveyLink]"
remove_link = "[RemoveLink]"
re_survey_link = re.compile(re.escape(survey_link))
re_remove_link = re.compile(re.escape(remove_link))
def __init__(self, reply_email, subject, body_text=None):
params = {
'reply_email': reply_email,
'subject': subject
}
if body_text:
assert self.re_survey_link.search(body_text), \
"%s has to be inside the 'body_text'" % self.survey_link
assert self.re_remove_link.search(body_text), \
"%s has to be inside the 'body_text'" % self.remove_link
params['body_text'] = body_text
super(EmailMessage, self).__init__(params)
|
python
| 11 | 0.544512 | 79 | 29.328571 | 70 |
starcoderdata
|
package com.dragontalker.java1;
/**
* 自定义函数式接口
*/
@FunctionalInterface
public interface MyInterface {
void method1();
}
|
java
| 4 | 0.775424 | 107 | 20.454545 | 11 |
starcoderdata
|
// https://codeforces.com/problemset/problem/1618/C
#define _USE_MATH_DEFINES
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#pragma warning(disable : 4996)
#pragma comment(linker, "/STACK:16777216")
#define pb push_back
#define en '\n'
#define forn(i, n) for (int i = 0; i < n; i++)
#define for0(i, n) for (int i = 0; i < n; i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define vec vector
#define veci vector
#define pii pair<int, int>
#define pll pair<ll, ll>
#define szof(x) int(x.size())
#define sqr(x) ((x) * (x))
#define debug(x) cerr << #x << " = " << x << '\n'
using namespace std;
const int INF = 1000000000 + 1e8;
const ll LINF = 2000000000000000000;
template <typename T>
void print(vector a) {
for (int i = 0; i < a.size(); i++) cout << a[i] << ' ';
}
template <typename T>
void input(vector a) {
for (int i = 0; i < a.size(); i++) cin >> a[i];
}
void solve() {
int n;
cin >> n;
vec a(n);
input(a);
ull gcd = a[0];
for (int i = 0; i < n; i += 2) gcd = __gcd(gcd, a[i]);
if (gcd != 1) {
bool u = false;
for (int i = 1; i < n && !u; i += 2) {
if (a[i] % gcd == 0) u = true;
}
if (!u) {
cout << gcd << en;
return;
}
}
gcd = a[1];
for (int i = 1; i < n; i += 2) gcd = __gcd(gcd, a[i]);
if (gcd != 1) {
bool u = false;
for (int i = 0; i < n && !u; i += 2) {
if (a[i] % gcd == 0) u = true;
}
if (!u) {
cout << gcd << en;
return;
}
}
cout << 0 << en;
}
int main() {
srand(time(0));
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int tst = 1;
cin >> tst;
while (tst--) solve();
}
|
c++
| 13 | 0.542169 | 59 | 19.586777 | 121 |
starcoderdata
|
@Override
public void onClick(View v) {
// Setup and show date picker dialog listener
Calendar now = Calendar.getInstance(); // instantiate calender to get current time
DatePickerDialog dpd = DatePickerDialog.newInstance(
MealsRecordActivity.this,
now.get(Calendar.YEAR), // Initial year selection
now.get(Calendar.MONTH), // Initial month selection
now.get(Calendar.DAY_OF_MONTH) // Inital day selection
);
// set accent color
dpd.setAccentColor(getResources().getColor(R.color.colorPrimaryLight));
// show date picker dialog
dpd.show(getSupportFragmentManager(), "Datepickerdialog");
}
|
java
| 10 | 0.552632 | 99 | 54.8 | 15 |
inline
|
<?php
namespace LapayGroup\FivePostSdk;
use LapayGroup\FivePostSdk\Entity\Order;
trait TariffsTrait {
private $return_percent = 0.50; // Тариф за возврат невыкупленных отправлений и обработку и возврат отмененных отправлений
private $valuated_amount_percent = 0.005; // Сбор за объявленную ценность
private $cash_percent = 0.0192; // Вознаграждение за прием наложенного платежа наличными
private $card_percent = 0.0264; // Вознаграждение за прием платежа с использованием банковских карт
private $zone_tariffs = [
'1' => [
'basic_price' => 129,
'overload_kg_price' => 18
],
'2' => [
'basic_price' => 138,
'overload_kg_price' => 18
],
'3' => [
'basic_price' => 148,
'overload_kg_price' => 18
],
'4' => [
'basic_price' => 160,
'overload_kg_price' => 36
],
'5' => [
'basic_price' => 205,
'overload_kg_price' => 36
],
'6' => [
'basic_price' => 180,
'overload_kg_price' => 36
],
'7' => [
'basic_price' => 225,
'overload_kg_price' => 36
],
'8' => [
'basic_price' => 217,
'overload_kg_price' => 54
],
'9' => [
'basic_price' => 259,
'overload_kg_price' => 54
],
'10' => [
'basic_price' => 268,
'overload_kg_price' => 54
],
'11' => [
'basic_price' => 264,
'overload_kg_price' => 54
],
'12' => [
'basic_price' => 308,
'overload_kg_price' => 54
],
'13' => [
'basic_price' => 342,
'overload_kg_price' => 72
]
];
/**
* Расчет стоимости доставки
*
* @param string $zone - Тарифная зона
* @param int $weight - Вес заказа в граммах
* @param float $amount - Стоимость заказа
* @param string $payment_type - Тип оплаты (оплачен, картой или наличными)
* @param bool $returned - Возврат в случае невыкупа
* @return float - Стоимость доставки
*/
public function calculationTariff($zone = '1', $weight = 100, $amount = 0, $payment_type = Order::P_TYPE_PREPAYMENT, $returned = false)
{
if (empty($zone))
throw new \InvalidArgumentException('Не передана тарифная зона');
if (empty($weight))
throw new \InvalidArgumentException('Не передан вес заказа');
if (empty($this->zone_tariffs[$zone]))
throw new \InvalidArgumentException('Тарифная зона не найдена');
if (!empty($amount) && $payment_type == Order::P_TYPE_PREPAYMENT)
throw new \InvalidArgumentException('Передан не корректный тип оплаты');
$weight /= 1000;
if ($weight > 3) {
$tariff = $this->zone_tariffs[$zone]['basic_price'] + (($weight - 3) * $this->zone_tariffs[$zone]['overload_kg_price']);
} else {
$tariff = $this->zone_tariffs[$zone]['basic_price'];
}
if ($returned)
$tariff += $tariff * $this->return_percent;
if ($amount > 0) {
$tariff += $amount * $this->valuated_amount_percent;
}
if ($payment_type == Order::P_TYPE_CASHLESS)
$tariff += $amount * $this->card_percent;
if ($payment_type == Order::P_TYPE_CASH)
$tariff += $amount * $this->cash_percent;
return round($tariff, 2);
}
/**
* @return int
*/
public function getReturnPercent()
{
return $this->return_percent;
}
/**
* @param int $return_percent
*/
public function setReturnPercent($return_percent)
{
$this->return_percent = $return_percent;
}
/**
* @return float
*/
public function getValuatedAmountPercent()
{
return $this->valuated_amount_percent;
}
/**
* @param float $valuated_amount_percent
*/
public function setValuatedAmountPercent($valuated_amount_percent)
{
$this->valuated_amount_percent = $valuated_amount_percent;
}
/**
* @return float
*/
public function getCashPercent()
{
return $this->cash_percent;
}
/**
* @param float $cash_percent
*/
public function setCashPercent($cash_percent)
{
$this->cash_percent = $cash_percent;
}
/**
* @return float
*/
public function getCardPercent()
{
return $this->card_percent;
}
/**
* @param float $card_percent
*/
public function setCardPercent($card_percent)
{
$this->card_percent = $card_percent;
}
/**
* @return array
*/
public function getZoneTariffs()
{
return $this->zone_tariffs;
}
/**
* @param array $zone_tariffs
*/
public function setZoneTariffs($zone_tariffs)
{
$this->zone_tariffs = $zone_tariffs;
}
}
|
php
| 16 | 0.51363 | 139 | 25.28866 | 194 |
starcoderdata
|
# coding=utf-8
import matplotlib.pyplot as plt
import wordcloud
import jieba
import os
font_file = os.path.join(os.path.dirname("./"), "ZDroidSansFallbackFull.ttf") # 中文字体文件路径
mask_image = plt.imread("./Zstar.jpg") # 背景图片
stopwords = set(wordcloud.STOPWORDS) # 设置屏蔽词
stopwords.add("不见") # 添加屏蔽词
# contents = "这是一个Python脚本。" \
# "这是一个关于词云的Python脚本测试。" \
# "使用matplotlib库绘制图形、jieba库进行中文分词、wordcloud生成词云。"
# words_cut = jieba.cut(contents, cut_all=True)
file_path = open('./ZQiangJinJiu.txt').read() # 注意txt文件的编码字符集
words_cut = jieba.cut(file_path, cut_all=True) # 分词
words_join = " ".join(words_cut) # 分词结果以空格隔开
word_cloud = wordcloud.WordCloud(background_color='white', # 背景颜色,默认为黑色
mask=mask_image, # 背景图片
stopwords=stopwords, # 屏蔽词
font_path=font_file, # 字体文件
max_words=300, # 最多显示的词数,默认为200
width=800, # 宽度
height=800, # 高度
margin=10, # 边缘
scale=1.1, # 缩放系数,默认为1
max_font_size=60, # 字体最大值
min_font_size=18, # 字体最小值
random_state=30 # 随机配色的数量
)
word_cloud.generate(words_join) # 生成词云
plt.imshow(word_cloud) # 绘制图片
plt.axis("off") # 去除坐标轴(不显示X轴和Y轴)
plt.show() # 显示图片
# ### 词云生成库wordcloud
# HomePage: https://github.com/amueller/word_cloud
# 默认中文乱码,需要引入中文字体,在WordCloud构造函数的参数font_path可以指定中文字体文件;
# 也可使用系统自带的支持中文的字体文件,例如window系统下“C:\Windows\Fonts”中ttf格式的字体文件
#
# ### 中文分词库jieba
# HomePage: https://github.com/fxsjy/jieba
|
python
| 8 | 0.538587 | 89 | 37.170213 | 47 |
starcoderdata
|
<?php
/**
* This file is part of the Bono CMS
*
* Copyright (c) No Global State Lab
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*/
namespace Shop\Controller\Admin;
use Cms\Controller\Admin\AbstractController;
use Krystal\Stdlib\VirtualEntity;
use Krystal\Form\Gadget\LastCategoryKeeper;
use Shop\Collection\SpecificationItemTypeCollection;
final class SpecificationItem extends AbstractController
{
/**
* Renders grid
*
* @param int $categoryId Optional category ID filter
* @return string
*/
public function indexAction($categoryId)
{
$categoryId = $this->getCategoryId($categoryId);
// Append breadcrumb
$this->view->getBreadcrumbBag()->addOne('Shop', 'Shop:Admin:Browser@indexAction')
->addOne('Specifications');
return $this->view->render('specification/index', array(
'categories' => $this->getModuleService('specificationCategoryService')->fetchAll(),
'categoryId' => $categoryId,
'items' => $this->getModuleService('specificationItemService')->fetchAll($categoryId)
));
}
/**
* Returns current category ID
*
* @param mixed $value Current raw category ID
* @return mixed
*/
private function getCategoryId($value)
{
// Last category ID keeper
$keeper = new LastCategoryKeeper($this->sessionBag, 'last_shop_item_category_id');
// If not provided, then try to get previous one if available. If not, then fallback to last category
if (!$value) {
if ($keeper->hasLastCategoryId()) {
$value = $keeper->getLastCategoryId();
} else {
$value = $this->getModuleService('specificationCategoryService')->getLastId();
$keeper->persistLastCategoryId($value);
}
} else {
// Category ID is provided, so save it
$keeper->persistLastCategoryId($value);
}
return $value;
}
/**
* Renders a form
*
* @param \Krystal\Stdlib\VirtualEntity|array $item
* @param string $title Page title
* @return string
*/
private function createForm($item, $title)
{
$new = is_object($item);
$typeCollection = new SpecificationItemTypeCollection();
// Append breadcrumb
$this->view->getBreadcrumbBag()->addOne('Shop', 'Shop:Admin:Browser@indexAction')
->addOne('Specifications', $this->createUrl('Shop:Admin:SpecificationItem@indexAction', array(null)))
->addOne($title);
return $this->view->render('specification/item.form', array(
'item' => $item,
'new' => $new,
'categories' => $this->getModuleService('specificationCategoryService')->fetchList(),
'types' => $typeCollection->getAll()
));
}
/**
* Renders add form
*
* @return string
*/
public function addAction()
{
return $this->createForm(new VirtualEntity(), 'Add new item');
}
/**
* Renders edit form
*
* @param int $id Item ID
* @return string
*/
public function editAction($id)
{
$item = $this->getModuleService('specificationItemService')->fetchById($id, true);
if ($item !== false) {
$name = $this->getCurrentProperty($item, 'name');
return $this->createForm($item, $this->translator->translate('Edit the item "%s"', $name));
} else {
return false;
}
}
/**
* Deletes an item
*
* @param int $id Category ID
* @return mixed
*/
public function deleteAction($id)
{
$this->getModuleService('specificationItemService')->deleteById($id);
$this->flashBag->set('success', 'Selected element has been removed successfully');
return 1;
}
/**
* Saves item
*
* @return mixed
*/
public function saveAction()
{
$data = $this->request->getPost();
$new = !$data['item']['id'];
$specificationItemService = $this->getModuleService('specificationItemService');
if ($specificationItemService->save($data)) {
$this->flashBag->set('success', !$new ? 'The element has been updated successfully' : 'The element has been created successfully');
}
if ($new) {
return $specificationItemService->getLastId();
} else {
return 1;
}
}
}
|
php
| 17 | 0.575738 | 143 | 28.41875 | 160 |
starcoderdata
|
package page3.q255;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s = new Scanner(System.in).nextLine();
System.out.println(getDigitalRoot(s));
}
private static int getDigitalRoot(String s) {
int n = getDigitSum(s);
return (n < 10) ? n : getDigitalRoot(String.valueOf(n));
}
private static int getDigitSum(String s) {
int sum = 0;
for(char c : s.toCharArray()) sum += c - '0';
return sum;
}
}
|
java
| 11 | 0.645418 | 60 | 21.818182 | 22 |
starcoderdata
|
package utils
import (
"sync"
ggio "github.com/gogo/protobuf/io"
"github.com/gogo/protobuf/proto"
)
func NewSafeWriter(w ggio.WriteCloser) *safeWriter {
return &safeWriter{w: w}
}
type safeWriter struct {
w ggio.WriteCloser
m sync.Mutex
}
func (sw *safeWriter) WriteMsg(msg proto.Message) error {
sw.m.Lock()
defer sw.m.Unlock()
return sw.w.WriteMsg(msg)
}
func (sw *safeWriter) Close() error {
sw.m.Lock()
defer sw.m.Unlock()
return sw.w.Close()
}
|
go
| 10 | 0.702355 | 57 | 15.103448 | 29 |
starcoderdata
|
Perlin::Noise::Noise(
unsigned short width, // Number of collums
unsigned short height, // Number of rows
double frequency, // Frequency of noise features
unsigned int octaves, // Number of octaves (halving frequency)
double persistence, // Compounding weight of octaves
unsigned int seed // Seed for perlin noise engine
){
generate(width, height, frequency, octaves, persistence, seed);
}
|
c++
| 6 | 0.729927 | 64 | 40.2 | 10 |
inline
|
package org.jf.dexlib2.immutable.value;
import org.jf.dexlib2.base.value.BaseBooleanEncodedValue;
import org.jf.dexlib2.iface.value.BooleanEncodedValue;
public class ImmutableBooleanEncodedValue extends BaseBooleanEncodedValue implements ImmutableEncodedValue {
public static final ImmutableBooleanEncodedValue TRUE_VALUE = new ImmutableBooleanEncodedValue(true);
public static final ImmutableBooleanEncodedValue FALSE_VALUE = new ImmutableBooleanEncodedValue(false);
protected final boolean value;
private ImmutableBooleanEncodedValue(boolean value) {
this.value = value;
}
public static ImmutableBooleanEncodedValue forBoolean(boolean value) {
return value ? TRUE_VALUE : FALSE_VALUE;
}
public static ImmutableBooleanEncodedValue of(BooleanEncodedValue booleanEncodedValue) {
return forBoolean(booleanEncodedValue.getValue());
}
@Override
public boolean getValue() {
return value;
}
}
|
java
| 10 | 0.770492 | 108 | 31.533333 | 30 |
starcoderdata
|
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import SignupTitle from './signupTitle';
test('test the title', () => {
const className = jest.fn();
const { getByText } = render(<SignupTitle className={className} />);
expect(getByText('Sign up to Annotate the web')).toHaveTextContent(
'Sign up to Annotate the web',
);
});
|
javascript
| 14 | 0.691566 | 70 | 33.583333 | 12 |
starcoderdata
|
package com.zavod.launch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServerContext {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerContext.class);
private final Map Object> instanceMap = new HashMap<>();
private final List instanceList = new ArrayList<>();
private final Set initialized = new HashSet<>();
public void register(Class type, T instance) {
instanceMap.put(type, instance);
instanceList.add(instance);
}
public T getInstance(Class type) {
//noinspection unchecked
return (T) instanceMap.get(type);
}
void initialize() throws Exception {
for (Object instance : instanceList) {
if (instance instanceof Initializable) {
Initializable initializable = (Initializable) instance;
LOGGER.info("Initializing {}...", getName(initializable));
initializable.initialize(this);
initialized.add(initializable);
}
}
LOGGER.info("Initialized.");
}
void shutdown() {
List instancesReversed = new ArrayList<>(instanceList);
Collections.reverse(instancesReversed);
for (Object instance : instancesReversed) {
if (instance instanceof Shutdownable) {
Shutdownable shutdownable = (Shutdownable) instance;
if (initialized.contains(shutdownable)) {
LOGGER.info("Shutting down {}...", getName(shutdownable));
shutdownable.shutdown();
}
}
}
LOGGER.info("Stopped.");
}
private String getName(Object instance) {
return instance.getClass().getSimpleName();
}
}
|
java
| 16 | 0.689197 | 84 | 28.590164 | 61 |
starcoderdata
|
'use strict'
var config = require('config')
var path = require('path')
var vfs = require('vinyl-fs')
var plumber = require('gulp-plumber')
var gulpif = require('gulp-if')
var sourcemaps = require('gulp-sourcemaps')
var sass = require('gulp-sass')
var postcss = require('gulp-postcss')
var autoprefixer = require('autoprefixer')
var tap = require('gulp-tap')
var logger = require('../logger')()
// Where the entry point for our stylesheet lives.
var STYLE_SOURCE = '/assets/css/styles.scss'
var plugins = [
autoprefixer({ browsers: ['last 2 versions', 'IE >= 11'] })
]
var compiledStyles
// Precompile
// Express app handles gzip compression, don't do it here.
vfs.src(path.join(process.cwd(), STYLE_SOURCE))
.pipe(plumber({ errorHandler: logger.error }))
.pipe(gulpif(config.env !== 'production', sourcemaps.init()))
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(postcss(plugins))
.pipe(gulpif(config.env !== 'production', sourcemaps.write()))
.pipe(tap(function (file) {
compiledStyles = file.contents
}))
module.exports = function (req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next()
}
if (req.fresh) {
res.status(304).send()
} else {
// Note: Express will handle the ETag.
res.set({
'Content-Type': 'text/css',
'Cache-Control': 'public, max-age=31536000'
})
res.status(200).send(compiledStyles)
}
}
|
javascript
| 12 | 0.662517 | 64 | 26.807692 | 52 |
starcoderdata
|
var test = require('tape'),
onError = require('..')
test('on-error().otherwiseWithError', function plan (t) {
var h = function errHandler () {}
t.equal(typeof onError(h).otherwiseWithError, 'function', 'should be a function')
t.throws(onError(h).otherwiseWithError, 'requires a callback')
t.end()
})
test('on-error().otherwiseWithError when passed an error', function plan (t) {
t.plan(4)
var errorCalls = [],
otherCalls = []
function errHandler () {
var args = Array.prototype.slice.call(arguments, 0)
errorCalls.push(args)
}
function otherHandler () {
var args = Array.prototype.slice.call(arguments, 0)
otherCalls.push(args)
}
var anError = new Error('error 1'),
handler = onError(errHandler).otherwiseWithError(otherHandler)
t.notOk(handler(anError), 'should return undefined')
t.equal(errorCalls.length, 1, 'should invoke error handler')
t.equal(otherCalls.length, 0, 'should not invoke otherwise handler')
t.equal(errorCalls[0][0], anError, 'should pass error to handler')
})
test('on-error().otherwiseWithError when passed no error', function plan (t) {
t.plan(4)
var errorCalls = [],
otherCalls = []
function errHandler () {
var args = Array.prototype.slice.call(arguments, 0)
errorCalls.push(args)
}
function otherHandler () {
var args = Array.prototype.slice.call(arguments, 0)
otherCalls.push(args)
return true
}
var handler = onError(errHandler).otherwiseWithError(otherHandler)
t.equal(handler(null, 5, 10), true, 'should return true')
t.equal(errorCalls.length, 0, 'should not invoke error handler')
t.equal(otherCalls.length, 1, 'should invoke otherwise handler')
t.deepEqual(otherCalls[0], [null, 5, 10], 'should pass all args to otherwise handler')
})
|
javascript
| 14 | 0.656582 | 90 | 33.888889 | 54 |
starcoderdata
|
def main():
# alustukset
sense = SenseHat()
sense.clear()
# koitetaan hakea viite conffiin. Defaulttina 'config.json'
try:
conffile = sys.argv[1]
except IndexError:
conffile = 'config.json'
try:
# Luetaan conffit. Api avain ja sääpaikka oltava tiedostossa.
with open(conffile,'r') as f:
conf = json.load(f)
except Exception as e:
sys.exit(e.args)
try:
# Luodaan uusi hakija käyttäen conffia:
hakija = Hakija(conf['FMIapiKey'],conf['Location'])
# Toistetaan ikuisesti
while True:
# satunnainen tekstin väritys
vari = (randint(0,255),randint(0,255),randint(0,255))
# tekstin nopeus
nopeus = 0.1
# Tarkistetaan tarviiko uusi kelitieto hakea fmi:ltä
if hakija.paivitettava():
hakija.hae_kelidata()
# Luetaan datafilu
hakija.lue_kelidata()
# pyydetään uusin teksti tila hakijalta:
teksti = hakija.nayta()
# lisätään vielä sisäilman paine mittaus:
teksti += " {}".format(int(sense.get_pressure()))
teksti += "hPa"
print("teksti : "+ teksti)
# näyetään ledeillä
sense.show_message(teksti, nopeus, text_colour=vari)
sense.clear()
except KeyboardInterrupt:
sense.clear()
|
python
| 15 | 0.56383 | 69 | 34.275 | 40 |
inline
|
def create_shadow_classifier_from_training_set(
self, num_elements_per_classes: Dict[int, int]
) -> list:
"""
Creates and trains shadow classifiers from shadow training sets with specific ratio (= for one subattack).
Calls create_shadow_training_sets and train_shadow_classifiers.
:param num_elements_per_classes: number of elements per class
:return: list of shadow classifiers, accuracies for the classifiers
"""
# create training sets
shadow_training_sets = self.create_shadow_training_sets(
num_elements_per_classes
)
# create classifiers with trained models based on given data set
shadow_classifiers = self.train_shadow_classifiers(
shadow_training_sets, num_elements_per_classes
)
return shadow_classifiers
|
python
| 8 | 0.665497 | 114 | 41.8 | 20 |
inline
|
package org.raml.ramltopojo.extensions.jaxb;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import org.raml.ramltopojo.EventType;
import org.raml.ramltopojo.extensions.ObjectPluginContext;
import org.raml.ramltopojo.extensions.ObjectTypeHandlerPlugin;
import org.raml.v2.api.model.v10.datamodel.ArrayTypeDeclaration;
import org.raml.v2.api.model.v10.datamodel.ObjectTypeDeclaration;
import org.raml.v2.api.model.v10.datamodel.TypeDeclaration;
import javax.xml.bind.annotation.*;
/**
* Created. There, you have it.
*/
public class JaxbObjectExtension extends ObjectTypeHandlerPlugin.Helper {
@Override
public TypeSpec.Builder classCreated(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) {
String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default";
String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name();
if (eventType == EventType.IMPLEMENTATION) {
builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class)
.addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build());
AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class)
.addMember("namespace", "$S", namespace)
.addMember("name", "$S", name);
builder.addAnnotation(annotation.build());
} else {
builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class)
.addMember("namespace", "$S", namespace)
.addMember("name", "$S", name).build());
}
return builder;
}
@Override
public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType) {
String namespace = property.xml() != null && property.xml().namespace() != null ? property.xml().namespace() : "##default";
String name = property.xml() != null && property.xml().name() != null ? property.xml().name() : property.name();
if (eventType == EventType.IMPLEMENTATION) {
if (property.xml() != null && property.xml().wrapped() != null && property.xml().wrapped() && isArray(property)) {
fieldSpec.addAnnotation(
AnnotationSpec.builder(XmlElementWrapper.class).addMember("name", "$S", name).build()
);
TypeName elementTypeName = objectPluginContext.dependentType(((ArrayTypeDeclaration)property).items()).getJavaName(EventType.IMPLEMENTATION);
if (property.xml().attribute() != null && property.xml().attribute()) {
fieldSpec.addAnnotation(
AnnotationSpec.builder(XmlAttribute.class)
.addMember("name", "$S", elementTypeName)
.addMember("namespace", "$S", namespace)
.build());
} else {
fieldSpec.addAnnotation(
AnnotationSpec.builder(XmlElement.class)
.addMember("name", "$S", elementTypeName)
.addMember("namespace", "$S", namespace)
.build());
}
} else {
if (property.xml() != null && property.xml().attribute()) {
fieldSpec.addAnnotation(
AnnotationSpec.builder(XmlAttribute.class)
.addMember("name", "$S", name)
.addMember("namespace", "$S", namespace)
.build());
} else {
fieldSpec.addAnnotation(
AnnotationSpec.builder(XmlElement.class)
.addMember("name", "$S", name)
.addMember("namespace", "$S", namespace)
.build());
}
}
}
return fieldSpec;
}
private boolean isArray(TypeDeclaration property) {
return property instanceof ArrayTypeDeclaration;
}
}
|
java
| 20 | 0.573574 | 158 | 44.94 | 100 |
starcoderdata
|
package com.nexeo.kata.bank_account.app.conf;
import com.google.inject.AbstractModule;
import com.nexeo.kata.bank_account.repo.AccountsRepository;
import com.nexeo.kata.bank_account.repo.StatementsRepository;
import com.nexeo.kata.bank_account.repo.TransactionsRepository;
import com.nexeo.kata.bank_account.repo.impl.in_memory.AccountsRepositoryInMemory;
import com.nexeo.kata.bank_account.repo.impl.in_memory.StatementsRepositoryInMemory;
import com.nexeo.kata.bank_account.repo.impl.in_memory.TransactionsRepositoryInMemory;
import com.nexeo.kata.bank_account.service.AccountsService;
public class MainModule extends AbstractModule {
@Override
protected void configure() {
bind(AccountsRepository.class).to(AccountsRepositoryInMemory.class).asEagerSingleton();
bind(StatementsRepository.class).to(StatementsRepositoryInMemory.class).asEagerSingleton();
bind(TransactionsRepository.class).to(TransactionsRepositoryInMemory.class).asEagerSingleton();
bind(AccountsService.class);
}
}
|
java
| 11 | 0.83498 | 97 | 45 | 22 |
starcoderdata
|
'use strict';
d3c_module.controller('generalCalcTabCtrl', function ($scope, $log) {
$scope.test = 'jo';
});
|
javascript
| 5 | 0.609023 | 69 | 18.142857 | 7 |
starcoderdata
|
package com.liangxiaoqiao.leetcode.day.medium;
/*
* English
* id: 1003
* title: Check If Word Is Valid After Substitutions
* href: https://leetcode.com/problems/check-if-word-is-valid-after-substitutions
* desc:
*
* 中文
* 序号: 1003
* 标题: 检查替换后的词是否有效
* 链接: https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions
* 描述:
*
* acceptance: 53.7%
* difficulty: Medium
* private: False
*/
//TODO init
|
java
| 4 | 0.721915 | 103 | 21.625 | 24 |
starcoderdata
|
package cmd
import (
"github.com/spf13/cobra"
)
// KoolRestart holds data and logic necessary for
// restarting containers controller by kool.
type KoolRestart struct {
DefaultKoolService
start KoolService
stop KoolService
}
// Execute implements the logic for restarting
func (r *KoolRestart) Execute(args []string) (err error) {
if err = r.stop.Execute(nil); err != nil {
return
}
err = r.start.Execute(nil)
return
}
// NewRestartCommand initializes new kool start command
func NewRestartCommand(restart *KoolRestart) *cobra.Command {
return &cobra.Command{
Use: "restart",
Short: "Restart containers - the same as stop followed by start.",
Run: func(cmd *cobra.Command, args []string) {
restart.SetWriter(cmd.OutOrStdout())
restart.start.SetWriter(cmd.OutOrStdout())
restart.stop.SetWriter(cmd.OutOrStdout())
if err := restart.Execute(nil); err != nil {
restart.Error(err)
restart.Exit(1)
}
},
DisableFlagsInUseLine: true,
}
}
func init() {
rootCmd.AddCommand(NewRestartCommand(&KoolRestart{
*newDefaultKoolService(),
NewKoolStart(),
NewKoolStop(),
}))
}
|
go
| 17 | 0.713904 | 68 | 21 | 51 |
starcoderdata
|
#include "DynamicGameObject.h"
#include "../Core/Renderer.h"
#include "../Core/Input.h"
#include "../Scene/Scene.h"
#include
DynamicGameObject::DynamicGameObject()
{
texture = std::make_shared
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = texture->GetWidth();
srcRect.h = texture->GetHeight();
scale = 0;
body = std::make_shared / 2);
dstRect.x = (int)body->position.x;
dstRect.y = (int)body->position.y;
dstRect.w = scale;
dstRect.h = scale;
}
DynamicGameObject::DynamicGameObject(const char* filepath)
{
texture = std::make_shared
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = texture->GetWidth();
srcRect.h = texture->GetHeight();
scale = 64;
body = std::make_shared / 2);
dstRect.x = (int)body->position.x;
dstRect.y = (int)body->position.y;
dstRect.w = scale;
dstRect.h = scale;
}
DynamicGameObject::DynamicGameObject(const char* filepath, float _scale)
{
texture = std::make_shared
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = texture->GetWidth();
srcRect.h = texture->GetHeight();
scale = _scale;
body = std::make_shared / 2);
dstRect.x = (int)body->position.x;
dstRect.y = (int)body->position.y;
dstRect.w = scale;
dstRect.h = scale;
}
void DynamicGameObject::Update(float deltaTime)
{
Vector2 startMousePos = { 0, 0 };
SDL_Point mousePoint = { Input::Get()->GetMousePosition().x, Input::Get()->GetMousePosition().y };
if (SDL_PointInRect(&mousePoint, &dstRect) && Input::Get()->isMouseDown(SDL_BUTTON_LEFT))
{
selected = true;
body->velocity = {0, 0};
}
if (Input::Get()->isMouseUp(SDL_BUTTON_LEFT) && selected)
{
body->velocity = (body->position - camera->ScreenToWorld(Input::Get()->GetMousePosition())) * 5;
selected = false;
}
}
void DynamicGameObject::Draw(std::shared_ptr cam)
{
dstRect.x = (body->position.x - body->halfExtent - cam->offset.x) * cam->scale.x;
dstRect.y = (body->position.y - body->halfExtent - cam->offset.y) * cam->scale.y;
dstRect.w = scale * cam->scale.x;
dstRect.h = scale * cam->scale.y;
if (dstRect.y > 480 - dstRect.h)
dstRect.y = 480 - dstRect.h;
std::cout << dstRect.y << std::endl;
Renderer::Get()->Render(texture->GetTexture(), srcRect, dstRect, body->angle * (180 / 3.14), SDL_FLIP_NONE);
SDL_SetRenderDrawColor(Renderer::Get()->GetRenderer(), 255, 255, 255, SDL_ALPHA_OPAQUE);
/*for (int i = 0; i < body->pointsInBodyTransformed.size(); i++)
{
SDL_RenderDrawLine(Renderer::Get()->GetRenderer(), (body->pointsInBodyTransformed[i].x - cam->offset.x) * cam->scale.x,
(body->pointsInBodyTransformed[i].y - cam->offset.y) * cam->scale.y,
(body->pointsInBodyTransformed[(i + 1) % body->pointsInBodyTransformed.size()].x - cam->offset.x) * cam->scale.x,
(body->pointsInBodyTransformed[(i + 1) % body->pointsInBodyTransformed.size()].y - cam->offset.y) * cam->scale.y);
}*/
if (selected)
{
Vector2 mousePos = { 0, 0 };
mousePos = cam->ScreenToWorld(Input::Get()->GetMousePosition());
SDL_RenderDrawLine(Renderer::Get()->GetRenderer(), (body->position.x - cam->offset.x) * cam->scale.x, (body->position.y - cam->offset.y) * cam->scale.y,
(mousePos.x - cam->offset.x) * cam->scale.x, (mousePos.y - cam->offset.y) * cam->scale.y);
}
SDL_SetRenderDrawColor(Renderer::Get()->GetRenderer(), 0, 0, 0, SDL_ALPHA_OPAQUE);
}
|
c++
| 16 | 0.664793 | 154 | 30.009174 | 109 |
starcoderdata
|
#!/usr/bin/env python3
import sys
import contextlib
import tempfile
import subprocess
from ruamel import yaml
path, old_file, _, _, new_file, _, _ = \
sys.argv[1:]
def diff(path, old, new):
subprocess.run(["diff", '-u',
'--label=a/{}'.format(path),
'--label=b/{}'.format(path),
old, new])
with contextlib.ExitStack() as stack:
try:
old_data = yaml.load(stack.enter_context(open(old_file, 'r')), Loader=yaml.Loader)
new_data = yaml.load(stack.enter_context(open(new_file, 'r')), Loader=yaml.Loader)
except yaml.YAMLError:
diff(path, old_file, new_file)
else:
old_formatted = stack.enter_context(tempfile.NamedTemporaryFile(mode='w'))
new_formatted = stack.enter_context(tempfile.NamedTemporaryFile(mode='w'))
yaml.dump(old_data, old_formatted, default_flow_style=False)
yaml.dump(new_data, new_formatted, default_flow_style=False)
diff(path, old_formatted.name, new_formatted.name)
|
python
| 14 | 0.62585 | 90 | 34.482759 | 29 |
starcoderdata
|
import crossfilter from "crossfilter2"
export const ON_LOAD = "@@crossfilter/LOAD"
export const load = (data, filters) => {
const cf = crossfilter(data)
const dimensions = filters.map(filter => {
const { field, dimensionIsArray = false } = filter
// default is identify function for field
const dimensionFunction = filter.dimensionFunction || (d => d[field])
const dimension = cf.dimension(dimensionFunction, !!dimensionIsArray)
dimension.config = filter
return dimension
})
return {
type: ON_LOAD,
payload: {
crossfilter: cf,
dimensions
}
}
}
export const SET_FILTER = "@@crossfilter/SET_FILTER"
export const setFilter = (filter, filterValues) => ({
type: SET_FILTER,
payload: {
filter,
filterValues
}
})
export const RESET = "@@crossfilter/RESET"
export const reset = () => ({
type: RESET
})
export const CLEAR = "@@crossfilter/CLEAR"
export const clear = () => ({
type: CLEAR
})
|
javascript
| 15 | 0.624888 | 77 | 24.386364 | 44 |
starcoderdata
|
/**
* @licence MIT
* @author
*/
var allSettled = require('promise-ext-settled');
/**
* Image preloader
*
* @class ImagePreloader
* @constructor
*
* @param {(String|HTMLImageElement)=} fallbackImage
* @param {function({status:boolean, value:HTMLImageElement})=} onProgress
*/
var ImagePreloader = function(fallbackImage, onProgress) {
/**
* @type {?function({status: boolean, value: HTMLImageElement})}
*/
this.onProgress = typeof onProgress === 'function' ? onProgress : null;
/**
* @type {?String|HTMLImageElement}
*/
this.fallbackImage = typeof fallbackImage === 'string' || fallbackImage instanceof HTMLImageElement ? fallbackImage : null;
};
/**
* Do simple image preloading.
*
* @param {!(String|HTMLImageElement)} imageSource
*
* @return {Promise} will be resolved/rejected with HTMLImageElement
*/
ImagePreloader.simplePreload = function(imageSource) {
return new Promise(function(resolve, reject) {
var img;
if (imageSource instanceof HTMLImageElement) {
img = imageSource;
if (!img.complete) {
img.onload = resolve.bind(null, img);
img.onerror = img.onabort = reject.bind(null, img);
} else if (img.naturalHeight) {
resolve(img);
} else {
reject(img);
}
} else if (typeof imageSource === 'string') {
img = new Image();
img.onload = resolve.bind(null, img);
img.onerror = img.onabort = reject.bind(null, img);
img.src = imageSource;
}
});
};
/**
* Preload image.
*
* If fallbackImage-property is defined and correct, then src-attribute for the broken images will replaced by fallbackImage
* As well, origin image url will be placed to 'data-fail-src' attribute.
*
* If onProgress-method is defined, then this method will be calling for every image loading (fulfilled of rejected).
*
* @param {...(String|HTMLImageElement|Array args
*
* @return {Promise} will be resolved with Array<{status:boolean, value:HTMLImageElement}>
*
* status-property - is the status of image loading
* status-property will be true if:
* - original image loading is ok
* - or original image loading is fail but fallback-image loading is ok
* status-property will be false if:
* - original image loading is fail
* - or original image loading is fail and fallback-image loading is fail
*
* value-property - is the image that was loaded
*/
ImagePreloader.prototype.preload = function(args) {
var that = this,
imagesToLoad = Array.prototype.concat.apply([], Array.prototype.slice.call(arguments));
imagesToLoad = imagesToLoad.map(function(imageSource) {
return ImagePreloader.simplePreload(imageSource).catch(function(brokenImage) {
if (that.fallbackImage) {
return ImagePreloader.simplePreload(that.fallbackImage)
.then(function(fallbackImage) {
brokenImage.setAttribute('data-fail-src', brokenImage.src);
brokenImage.src = fallbackImage.src;
return brokenImage;
}, function() {
return Promise.reject(brokenImage);
});
}
return Promise.reject(brokenImage);
});
});
return allSettled(imagesToLoad, that.onProgress);
};
module.exports = ImagePreloader;
|
javascript
| 27 | 0.625803 | 127 | 32.46729 | 107 |
starcoderdata
|
/**
* Created by eugene.levenetc on 03/12/2016.
*/
const assert = require('assert');
const sinon = require('sinon');
const utils = require('../src/utils/utils');
const OrderedMap = require('../src/utils/ordered-map');
describe('Utils', function () {
before(function () {
});
it('checkNull should throw NPE on empty filed', function () {
assert.throws(function () {
utils.checkNull({}, 'field');
});
});
it('checkNull should throw NPE on null object', function () {
assert.throws(function () {
utils.checkNull(null, 'field');
});
});
it('checkNull should not throw NPE', function () {
assert.doesNotThrow(function () {
utils.checkNull({field: 42}, 'field');
});
});
it('First letter should be capital', function () {
assert.equal(utils.capitalize('hello'), 'Hello');
});
it('Object should be defined', function () {
assert.equal(utils.isDefined({}), true);
assert.equal(utils.isDefined(''), true);
});
it('Object should not be defined', function () {
assert.equal(utils.isDefined(null), false);
assert.equal(utils.isDefined(undefined), false);
});
it('Clone array', function () {
const array = [{x: '0'}, {y: '1'}];
assert.deepEqual(utils.cloneArray(array), array);
});
it('Is number', function () {
assert.equal(utils.isNumber(10), true);
assert.equal(utils.isNumber(1), true);
assert.equal(utils.isNumber(0), true);
assert.equal(utils.isNumber(-1), true);
assert.equal(utils.isNumber(50000), true);
assert.equal(utils.isNumber('b'), false);
assert.equal(utils.isNumber(), false);
});
it('Is string', function () {
assert.equal(utils.isString(), false);
assert.equal(utils.isString(null), false);
assert.equal(utils.isString(undefined), false);
assert.equal(utils.isString(1), false);
assert.equal(utils.isString(1.0), false);
assert.equal(utils.isString(true), false);
assert.equal(utils.isString(false), false);
assert.equal(utils.isString(''), true);
assert.equal(utils.isString(""), true);
assert.equal(utils.isString("A"), true);
});
it('Is string contains string', function () {
assert.equal(utils.contains('xv:z', null), false);
assert.equal(utils.contains('xv:z', undefined), false);
assert.equal(utils.contains(null, undefined), false);
assert.equal(utils.contains('xv:z', 'v:true'), false);
assert.equal(utils.contains('xv:truez', 'v:true'), true);
});
it('OrderedMap: Iterate', function () {
let orderedMap = new OrderedMap();
let keysArray = [];
let valuesArray = [];
orderedMap.put('a', 0);
orderedMap.put('b', 1);
orderedMap.put('c', 2);
orderedMap.iterate(function (key, value) {
keysArray.push(key);
valuesArray.push(value);
});
assert.deepEqual(keysArray, ['a', 'b', 'c']);
assert.deepEqual(valuesArray, [0, 1, 2]);
});
it('OrderedMap: get', function () {
let orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('b', 1);
assert.equal(orderedMap.get('b'), 1);
assert.equal(orderedMap.get('x'), null);
});
it('OrderedMap: indexOfValue', function () {
let orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('b', 1);
assert.equal(orderedMap.indexOfValue(0), 0);
assert.equal(orderedMap.indexOfValue(10), -1);
});
it('OrderedMap: indexOfKey', function () {
let orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('b', 1);
assert.equal(orderedMap.indexOfKey('b'), 1);
assert.equal(orderedMap.indexOfKey('x'), -1);
});
it('OrderedMap: remove', function () {
let orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('b', 1);
orderedMap.put('c', 2);
orderedMap.remove('b');
assert.equal(orderedMap.get('b'), null);
assert.equal(orderedMap.indexOfKey('b'), -1);
assert.equal(orderedMap.size(), 2);
});
it('OrderedMap: size', function () {
const orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('b', 1);
assert.equal(orderedMap.size(), 2);
});
it('OrderedMap: check duplicates', function () {
const orderedMap = new OrderedMap();
orderedMap.put('a', 0);
orderedMap.put('a', 1);
assert.equal(orderedMap.get('a'), 1);
assert.equal(orderedMap.size(), 1);
});
it('Is prop defined', function () {
assert.equal(utils.isPropDefined({a: 10}, 'a'), true);
assert.equal(utils.isPropDefined({a: '10'}, 'a'), true);
assert.equal(utils.isPropDefined({'a': 'b', 'z': 10, 'x': null}, 'a'), true);
assert.equal(utils.isPropDefined({a: null}, 'a'), false);
assert.equal(utils.isPropDefined({a: undefined}, 'a'), false);
assert.equal(utils.isPropDefined({}, 'a'), false);
});
it('Is device valid', function () {
assert.equal(utils.isDeviceValid({
deviceId: 1,
pushToken: 1,
manufacturer: 1,
model: 1,
osVersion: 1,
platform: 1,
screenSize: 1
}), true);
});
});
|
javascript
| 21 | 0.558231 | 85 | 29.409836 | 183 |
starcoderdata
|
// Concord
//
// Copyright (c) 2019 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the sub-component's license, as noted in the LICENSE
// file.
#pragma once
#include "SerializableActiveWindow.hpp"
#include "SerializableActiveWindow.cpp"
#include "messages/PrePrepareMsg.hpp"
#include "messages/SignedShareMsgs.hpp"
#include "messages/FullCommitProofMsg.hpp"
#include "messages/CheckpointMsg.hpp"
#include
namespace bftEngine {
namespace impl {
enum SeqNumDataParameters {
SEQ_NUM_FIRST_PARAM = 1,
PRE_PREPARE_MSG = SEQ_NUM_FIRST_PARAM,
FULL_COMMIT_PROOF_MSG = 2,
PRE_PREPARE_FULL_MSG = 3,
COMMIT_FULL_MSG = 4,
FORCE_COMPLETED = 5,
SLOW_STARTED = 6,
SEQ_NUM_LAST_PARAM = SLOW_STARTED
};
class SeqNumData {
static constexpr size_t EMPTY_MESSAGE_FLAG_SIZE = sizeof(bool);
public:
SeqNumData(PrePrepareMsg *prePrepare,
FullCommitProofMsg *fullCommitProof,
PrepareFullMsg *prepareFull,
CommitFullMsg *commitFull,
bool forceComplete,
bool slowStart)
: prePrepareMsg_(prePrepare),
fullCommitProofMsg_(fullCommitProof),
prepareFullMsg_(prepareFull),
commitFullMsg_(commitFull),
forceCompleted_(forceComplete),
slowStarted_(slowStart) {}
SeqNumData() = default;
bool equals(const SeqNumData &other) const;
void reset();
size_t serializePrePrepareMsg(char *&buf) const;
size_t serializeFullCommitProofMsg(char *&buf) const;
size_t serializePrepareFullMsg(char *&buf) const;
size_t serializeCommitFullMsg(char *&buf) const;
size_t serializeForceCompleted(char *&buf) const;
size_t serializeSlowStarted(char *&buf) const;
void serialize(char *buf, uint32_t bufLen, size_t &actualSize) const;
bool isPrePrepareMsgSet() const { return (prePrepareMsg_ != nullptr); }
bool isFullCommitProofMsgSet() const { return (fullCommitProofMsg_ != nullptr); }
bool isPrepareFullMsgSet() const { return (prepareFullMsg_ != nullptr); }
bool isCommitFullMsgSet() const { return (commitFullMsg_ != nullptr); }
PrePrepareMsg *getPrePrepareMsg() const { return prePrepareMsg_; }
FullCommitProofMsg *getFullCommitProofMsg() const { return fullCommitProofMsg_; }
PrepareFullMsg *getPrepareFullMsg() const { return prepareFullMsg_; }
CommitFullMsg *getCommitFullMsg() const { return commitFullMsg_; }
bool getSlowStarted() const { return slowStarted_; }
bool getForceCompleted() const { return forceCompleted_; }
void setPrePrepareMsg(MessageBase *msg) { prePrepareMsg_ = (PrePrepareMsg *)msg; }
void setFullCommitProofMsg(MessageBase *msg) { fullCommitProofMsg_ = (FullCommitProofMsg *)msg; }
void setPrepareFullMsg(MessageBase *msg) { prepareFullMsg_ = (PrepareFullMsg *)msg; }
void setCommitFullMsg(MessageBase *msg) { commitFullMsg_ = (CommitFullMsg *)msg; }
void setSlowStarted(const bool &slowStarted) { slowStarted_ = slowStarted; }
void setForceCompleted(const bool &forceCompleted) { forceCompleted_ = forceCompleted; }
static size_t serializeMsg(char *&buf, MessageBase *msg);
static size_t serializeOneByte(char *&buf, const uint8_t &oneByte);
static MessageBase *deserializeMsg(char *&buf, uint32_t bufLen, size_t &actualMsgSize);
static uint8_t deserializeOneByte(char *&buf);
static SeqNumData deserialize(char *buf, uint32_t bufLen, uint32_t &actualSize);
static uint32_t maxSize();
template <typename MessageT>
static uint32_t maxMessageSize() {
return maxMessageSizeInLocalBuffer + EMPTY_MESSAGE_FLAG_SIZE;
}
static constexpr uint16_t getNumOfParams() { return SEQ_NUM_LAST_PARAM; }
private:
static bool compareMessages(MessageBase *msg, MessageBase *otherMsg);
private:
PrePrepareMsg *prePrepareMsg_ = nullptr;
FullCommitProofMsg *fullCommitProofMsg_ = nullptr;
PrepareFullMsg *prepareFullMsg_ = nullptr;
CommitFullMsg *commitFullMsg_ = nullptr;
bool forceCompleted_ = false;
bool slowStarted_ = false;
};
enum CheckDataParameters {
CHECK_DATA_FIRST_PARAM = 1,
CHECKPOINT_MSG = CHECK_DATA_FIRST_PARAM,
COMPLETED_MARK = 2,
CHECK_DATA_LAST_PARAM = COMPLETED_MARK
};
class CheckData {
public:
CheckData(CheckpointMsg *checkpoint, bool completed) : checkpointMsg_(checkpoint), completedMark_(completed) {}
CheckData() = default;
bool equals(const CheckData &other) const;
void reset();
size_t serializeCheckpointMsg(char *&buf) const;
size_t serializeCompletedMark(char *&buf) const;
void serialize(char *buf, uint32_t bufLen, size_t &actualSize) const;
bool isCheckpointMsgSet() const { return (checkpointMsg_ != nullptr); }
CheckpointMsg *getCheckpointMsg() const { return checkpointMsg_; }
bool getCompletedMark() const { return completedMark_; }
void deleteCheckpointMsg() { delete checkpointMsg_; }
void setCheckpointMsg(MessageBase *msg) { checkpointMsg_ = (CheckpointMsg *)msg; }
void setCompletedMark(const bool &completedMark) { completedMark_ = completedMark; }
static size_t serializeCheckpointMsg(char *&buf, CheckpointMsg *msg);
static size_t serializeCompletedMark(char *&buf, const uint8_t &completedMark);
static CheckpointMsg *deserializeCheckpointMsg(char *&buf, uint32_t bufLen, size_t &actualMsgSize);
static uint8_t deserializeCompletedMark(char *&buf);
static CheckData deserialize(char *buf, uint32_t bufLen, uint32_t &actualSize);
static uint32_t maxSize();
static uint32_t maxCheckpointMsgSize();
static constexpr uint16_t getNumOfParams() { return CHECK_DATA_LAST_PARAM; }
private:
CheckpointMsg *checkpointMsg_ = nullptr;
bool completedMark_ = false;
};
typedef SerializableActiveWindow<kWorkWindowSize, 1, SeqNumData> SeqNumWindow;
typedef SerializableActiveWindow<kWorkWindowSize + checkpointWindowSize, checkpointWindowSize, CheckData> CheckWindow;
typedef std::shared_ptr SharedPtrSeqNumWindow;
typedef std::shared_ptr SharedPtrCheckWindow;
} // namespace impl
} // namespace bftEngine
|
c++
| 16 | 0.745319 | 118 | 37.426829 | 164 |
starcoderdata
|
package core
import (
"fmt"
"os"
)
type ConfigEnvFailed struct {
Name string
Err error
}
func (c *ConfigEnvFailed) Error() string {
return fmt.Sprintf("error: failed to evaluate env %q \n %q ", c.Name, c.Err)
}
type Node struct {
Path string
Imports []string
Children []*Node
Visiting bool
Visited bool
}
type NodeLink struct {
A Node
B Node
}
type FoundCyclicDependency struct {
Cycles []NodeLink
}
func (c *FoundCyclicDependency) Error() string {
var msg string
msg = "Found direct or indirect circular dependency between:\n"
for i := range c.Cycles {
msg += fmt.Sprintf(" %s\n %s\n", c.Cycles[i].A.Path, c.Cycles[i].B.Path)
}
return msg
}
type FailedToOpenFile struct {
Name string
}
func (f *FailedToOpenFile) Error() string {
return fmt.Sprintf("error: failed to open %q", f.Name)
}
type FailedToParsePath struct {
Name string
}
func (f *FailedToParsePath) Error() string {
return fmt.Sprintf("error: failed to parse path %q", f.Name)
}
type FailedToParseFile struct {
Name string
Msg error
}
func (f *FailedToParseFile) Error() string {
return fmt.Sprintf("error: failed to parse %q \n%s", f.Name, f.Msg)
}
type PathDoesNotExist struct {
Path string
}
func (p *PathDoesNotExist) Error() string {
return fmt.Sprintf("fatal: path %q does not exist", p.Path)
}
type ProjectNotFound struct {
Name string
}
func (c *ProjectNotFound) Error() string {
return fmt.Sprintf("fatal: could not find project %q", c.Name)
}
type TaskNotFound struct {
Name string
}
func (c *TaskNotFound) Error() string {
return fmt.Sprintf("fatal: could not find task %q", c.Name)
}
type ThemeNotFound struct {
Name string
}
func (c *ThemeNotFound) Error() string {
return fmt.Sprintf("fatal: could not find theme %q", c.Name)
}
type SpecNotFound struct {
Name string
}
func (c *SpecNotFound) Error() string {
return fmt.Sprintf("fatal: could not find spec %q", c.Name)
}
type TargetNotFound struct {
Name string
}
func (c *TargetNotFound) Error() string {
return fmt.Sprintf("fatal: could not find target %q", c.Name)
}
type ConfigNotFound struct {
Names []string
}
func (f *ConfigNotFound) Error() string {
return fmt.Sprintf("fatal: could not find any configuration file %v in current directory or any of the parent directories", f.Names)
}
func CheckIfError(err error) {
if err == nil {
return
}
fmt.Printf("%s\n", err)
os.Exit(1)
}
|
go
| 13 | 0.69975 | 133 | 17.166667 | 132 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.