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 |
---|---|---|---|---|---|---|---|
package compiletime;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
/**
* @author
* 20/06/2017
*/
public class Collections {
private static List getProtectedTurtles() {
return java.util.Collections.unmodifiableList(getTurtles());
}
private static List getTurtles() {
return new ArrayList<>(asList("Leo", "Don", "Raf", "Mike"));
}
private static void infiltrate(List src) {
src.add("Shredder");
}
public static void main(String[] args) {
infiltrate(getTurtles());
infiltrate(getProtectedTurtles());
}
} | java | 11 | 0.681885 | 64 | 20.21875 | 32 | starcoderdata |
<?php
namespace Surcouf\PhpArchive;
use Surcouf\PhpArchive\User\Session;
if (!defined('CORE2'))
exit;
interface IUser {
public function createNewSession($keepSession) : bool;
public function getFirstname() : string;
public function getId() : int;
public function getInitials() : string;
public function getLastname() : string;
public function getLastActivityTime() : ?\DateTime;
public function getMail() : string;
public function getName() : string;
public function getSession() : ?Session;
public function getUsername() : string;
public function loadFiles(int $folder, $tenant = null) : array;
public function loadFolders(int $parent, $tenant = null) : array;
public function verify($password) : bool;
public function verifySession(string $session_token, string $session_password) : bool;
} | php | 9 | 0.732227 | 88 | 29.142857 | 28 | starcoderdata |
#!/usr/bin/env python
# Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved
"""
This script will do PostgreSQL database migrations, when they are needed.
"""
from __future__ import absolute_import
from djangoinit import *
from django import db
from django.db import transaction, IntegrityError, DatabaseError
import sys
from django.core import management
from south.exceptions import NoMigrations
def fix_south_issues(log):
# Torrent Server Version 2.2 is hereby declared as db schema version 0001
# This legacy migration script is still used to get to initial 2.2 schema
# We must fake inject existing db structures, or South will try to do it too
# Note initial non-fake attempt for initial installs.
log.write("Fixing common south issues with and tastypie\n")
# tastypie started using migrations in 0.9.11
# So we may have the initial tables already
try:
management.call_command('migrate', 'tastypie', verbosity=0, ignore_ghosts=True)
except DatabaseError as e:
if "already exists" in str(e):
management.call_command('migrate', 'tastypie', '0001', fake=True)
else:
raise
except NoMigrations:
log.write("ERROR: tastypie should have been upgraded to 0.9.11 before now...\n")
return
def has_south_init():
try:
cursor = db.connection.cursor()
cursor.execute("""SELECT * FROM south_migrationhistory WHERE app_name='rundb' AND migration='0001_initial' LIMIT 1""")
found_init = (cursor.rowcount == 1)
cursor.close()
return found_init
except (IntegrityError, DatabaseError):
try:
transaction.rollback() # restore django db to usable state
except transaction.TransactionManagementError:
pass
return False
if __name__ == '__main__':
if has_south_init():
# south handles this from now on.
# Ensure south is sane and let it handle the rest.
fix_south_issues(sys.stdout) | python | 12 | 0.679283 | 126 | 31.918033 | 61 | starcoderdata |
import wx, wx.html
from searchquery import *
from makeindex import *
import os
answer = ''
corrector = ''
suggestvalue = ''
class HtmlWindow(wx.html.HtmlWindow):
def __init__(self, parent, id, size=(400,600)):
wx.html.HtmlWindow.__init__(self, parent, id, size=size)
if "gtk2" in wx.PlatformInfo:
self.SetStandardFonts()
def OnLinkClicked(self, link):
wx.LaunchDefaultBrowser(link.GetHref())
class SearchBox(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "search answer",
style = wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.THICK_FRAME | wx.RESIZE_BORDER | wx.TAB_TRAVERSAL)
hwin = HtmlWindow(self, -1)
global answer
hwin.SetPage(answer)
irep = hwin.GetInternalRepresentation()
hwin.SetSize((irep.GetWidth()+25, irep.GetHeight()+10))
self.SetClientSize(hwin.GetSize())
self.CentreOnParent(wx.BOTH)
self.SetFocus()
class myframe(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, "My Simple GUI App.")
self.Move((300,100))
self.panel = wx.Panel(self, style=wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE)
self.text = wx.TextCtrl(self.panel, -1, pos = (10,10), size=(300,-1))
self.text1 = wx.TextCtrl(self.panel, -1, pos=(10,40), size = (100, -1))
self.text1.Enable(False)
self.buttonsearch = wx.Button(self.panel, label = 'search', pos=(310, 10), size=(55, -1))
self.radio4 = wx.RadioButton(self.panel, -1, "TF-IDF", pos=(10, 110), style=wx.RB_GROUP)
self.radio5 = wx.RadioButton(self.panel, -1, "BM25F", pos=(110, 110))
self.radio6 = wx.RadioButton(self.panel, -1, "Frequency", pos=(210, 110))
self.radio7 = wx.RadioButton(self.panel, -1, "OR", pos=(10, 140), style=wx.RB_GROUP)
self.radio8 = wx.RadioButton(self.panel, -1, "AND", pos=(110,140))
self.checkbox1 = wx.CheckBox(self.panel, -1, "pdf", pos=(10,80))
self.checkbox2 = wx.CheckBox(self.panel, -1, "doc", pos=(60,80))
self.checkbox3 = wx.CheckBox(self.panel, -1, "txt", pos=(110,80))
self.checkbox4 = wx.CheckBox(self.panel, -1, "other", pos=(160,80))
self.radio9 = wx.RadioButton(self.panel, -1, "Nothing", pos = (10,170), style=wx.RB_GROUP)
self.radio10 = wx.RadioButton(self.panel, -1, "MajorClust", pos = (110, 170))
self.text_dir = wx.TextCtrl(self.panel, -1, pos= (10, 240), size = (300,-1))
self.buttonindex = wx.Button(self.panel, label = "index", pos=(310,240), size = (55,-1))
self.radio1 = wx.RadioButton(self.panel, -1, "Standard", pos=(10, 270), style=wx.RB_GROUP)
self.radio2 = wx.RadioButton(self.panel, -1, "Stemming", pos=(110, 270))
self.radio3 = wx.RadioButton(self.panel, -1, "4-gram", pos=(210, 270))
self.static_box = wx.StaticText(self.panel, -1, "Create file index, please enter your dir name:", pos = (10, 210))
self.static_line = wx.StaticLine(self.panel, pos=(0,200),size=(400,5),style=wx.LI_HORIZONTAL)
self.static_line1 = wx.StaticLine(self.panel, pos=(0,70),size=(400,5),style=wx.LI_HORIZONTAL)
self.static_text1 = wx.StaticText(self.panel,-1, label=':suggest',pos=(310,43))
self.static_text2 = wx.StaticText(self.panel,-1, label=':scores',pos=(310,110))
self.static_text3 = wx.StaticText(self.panel,-1, label=':and/or?',pos=(310,140))
self.static_text4 = wx.StaticText(self.panel,-1, label=':file type',pos=(310,80))
self.static_text5 = wx.StaticText(self.panel, -1, label=':index type',pos=(310,270))
self.static_text6 = wx.StaticText(self.panel, -1, label=':clustering', pos=(310,170))
self.static_text7 = wx.StaticText(self.panel, -1, label='Did you mean :', pos=(10, 45))
self.buttonhide = wx.Button(self.panel, pos=(370,10), size=(20,-1))
self.isShown = False
self.buttonhide.SetLabel(u'+')
self.suggestbotton = wx.Button(self.panel, -1, pos = (110,40), size=(150,-1),style=wx.NO_BORDER)
###
self.text1.Hide()
self.text_dir.Hide()
self.radio4.Hide()
self.radio5.Hide()
self.radio6.Hide()
self.radio7.Hide()
self.radio8.Hide()
self.checkbox1.Hide()
self.checkbox2.Hide()
self.checkbox3.Hide()
self.checkbox4.Hide()
self.buttonindex.Hide()
self.radio1.Hide()
self.radio2.Hide()
self.radio3.Hide()
self.radio9.Hide()
self.radio10.Hide()
self.suggestbotton.Hide()
self.static_text1.Hide()
self.static_text2.Hide()
self.static_text3.Hide()
self.static_text4.Hide()
self.static_box.Hide()
self.static_text5.Hide()
self.static_text6.Hide()
self.static_text7.Hide()
self.static_line.Hide()
self.static_line1.Hide()
self.SetClientSize((400,50))
###
self.Bind(wx.EVT_BUTTON, self.search, self.buttonsearch)
self.Bind(wx.EVT_BUTTON, self.index, self.buttonindex)
self.Bind(wx.EVT_BUTTON, self.touch, self.buttonhide)
def touch(self, event):
if self.isShown:
self.buttonhide.SetLabel(u'+')
self.text1.Hide()
self.text_dir.Hide()
self.radio4.Hide()
self.radio5.Hide()
self.radio6.Hide()
self.radio7.Hide()
self.radio8.Hide()
self.checkbox1.Hide()
self.checkbox2.Hide()
self.checkbox3.Hide()
self.checkbox4.Hide()
self.buttonindex.Hide()
self.radio1.Hide()
self.radio2.Hide()
self.radio3.Hide()
self.radio9.Hide()
self.radio10.Hide()
self.suggestbotton.Hide()
self.static_text1.Hide()
self.static_text2.Hide()
self.static_text3.Hide()
self.static_text4.Hide()
self.static_text7.Hide()
self.static_box.Hide()
self.static_text5.Hide()
self.static_text6.Hide()
self.static_line.Hide()
self.static_line1.Hide()
self.isShown = False
self.SetClientSize((400,50))
else:
self.text1.Hide()
self.text_dir.Show()
self.radio4.Show()
self.radio5.Show()
self.radio6.Show()
self.radio7.Show()
self.radio8.Show()
self.checkbox1.Show()
self.checkbox2.Show()
self.checkbox3.Show()
self.checkbox4.Show()
self.buttonindex.Show()
self.radio1.Show()
self.radio2.Show()
self.radio3.Show()
self.radio9.Show()
self.radio10.Show()
self.suggestbotton.Show()
self.static_text1.Show()
self.static_text2.Show()
self.static_text3.Show()
self.static_text4.Show()
self.static_box.Show()
self.static_text5.Show()
self.static_text6.Show()
self.static_text7.Show()
self.static_line.Show()
self.static_line1.Show()
self.buttonhide.SetLabel(u'*')
dirname = os.environ['HOME']
self.text_dir.SetValue(dirname + '/Desktop')
self.isShown = True
self.SetClientSize((400,305))
def search(self, event):
l = self.text.GetValue()
self.text1.Clear()
self.do_search(l)
def searchsuggest(self, event):
l = self.text1.GetValue()
self.text1.Clear()
self.do_search(l)
def do_search(self, l):
global answer,corrector, suggestvalue
answer = ''
corrector = ''
suggestvalue = ''
if self.radio6.GetValue():
score_method = 'Frequency'
elif self.radio5.GetValue():
score_method = 'BM25F'
else:
score_method = 'TF_IDF'
if self.radio8.GetValue():
and_or = 'AND'
else:
and_or = 'OR'
if self.radio9.GetValue():
clustering_not = 'no'
else:
clustering_not = 'majorclust'
filetypelist = []
if self.checkbox1.GetValue():
filetypelist.append('pdf')
if self.checkbox2.GetValue():
filetypelist.append('doc')
if self.checkbox3.GetValue():
filetypelist.append('txt')
if self.checkbox4.GetValue():
filetypelist.append('@_@')
if not check_all_stop_words(l):
box = wx.MessageDialog(None, 'STOP WORDS! NO information! please re-type!', 'stop words', wx.OK)
if box.ShowModal() == wx.ID_OK:
box.Destroy()
self.text.Clear()
else:
a, b = searchfile(l, score_method, and_or, filetypelist, clustering_not)
answer += a
corrector += b
if len(corrector) > 0:
self.text1.write('Did you mean: ')
self.suggestbotton.SetLabel(corrector)
suggestvalue = corrector
if len(suggestvalue) > 0:
self.text1.SetValue(corrector)
self.Bind(wx.EVT_BUTTON, self.searchsuggest, self.suggestbotton)
dlg = SearchBox()
dlg.Show()
def index(self, event):
l = self.text_dir.GetValue()
if self.radio3.GetValue():
analyser = '4-gram'
elif self.radio2.GetValue():
analyser = 'Stemming'
else:
analyser = 'Standard'
xxx = make_index(l, analyser)
if xxx:
box1 = wx.MessageDialog(None, 'Finish making index!', 'finish', wx.OK)
if box1.ShowModal() == wx.ID_OK:
box1.Destroy()
if not xxx:
box2 = wx.MessageDialog(None, 'The dir does not exist!', 'wrong', wx.OK)
if box2.ShowModal() == wx.ID_OK:
box2.Destroy()
if __name__=='__main__':
app = wx.PySimpleApp()
frame = myframe(None, -1)
frame.Show()
app.MainLoop() | python | 16 | 0.556381 | 122 | 35.913357 | 277 | starcoderdata |
using System.Threading.Tasks;
using TelegramNotifyBot.WebApi.Model;
namespace TelegramNotifyBot.WebApi.Services.Abstractions
{
public interface IMessagesService
{
Task Publish(MessageDto message);
}
} | c# | 8 | 0.753191 | 56 | 20.363636 | 11 | starcoderdata |
//
// logo.c
// DoritOS
//
// Created by on 22/12/2017.
// Copyright © 2017 All rights reserved.
//
#include
void print_logo(void);
void print_logo(void) {
sys_print("\n ` \n", 94);
sys_print(" `` - \n", 93);
sys_print(" ``` \n", 93);
sys_print(" `.` \n", 93);
sys_print(" .:/.` \n", 93);
sys_print(" `-sNho:.` \n", 93);
sys_print(" -ymydhs/-`` \n", 93);
sys_print(" -s/--:+oo+:.` \n", 93);
sys_print(" -+- `.-::/:-.` \n", 93);
sys_print(" -:` ``.---..` \n", 93);
sys_print(" `-- `..-.`` \n", 93);
sys_print(" ` `-` ````` `` \n", 93);
sys_print(" ``` ``.........``` `` ``. ``` ``` ``.-:::-```` ``.:/+++++/-`` \n", 93);
sys_print(" ``` `:MMMMMMMMMNho.`` `````` `+o/.`./s+-`` `.+dMMMMMMNh:```sNMMMMMMMd`` \n", 93);
sys_print(" ``` `:MMMdhhhhmMMMNs.` .+:s:::-.`` ``-///:oyoo.:yMMMo/-`dMMmo++oyMMM+`oMMMNmmmmd.` \n", 93);
sys_print(" ``` `:MMNo.````-oMMMy``:hMMMMMMMd+.``.sNMMMMy/mMN:mMMMMMMs:MMN- `sMMm`sMMMNs:```` \n", 93);
sys_print(" ``` `:MMNo. .sMMN./MMNyooosmMMd..sMMNo++:oMMN:/yMMNs/:/MMN. ````oMMm`.dMMMMMNy/`` \n", 93);
sys_print(" ``` `:MMNo. `sMMN.dMMs`````.MMN/`dMMN.` .oMMN:.oMMN:../MMN. `-odo:sd```/hNMMMMMm-` \n", 93);
sys_print(" ``` `:MMNo. `yMMN`mMMs. . `.NMN+`dMMN.` `oMMN:.oMMN:``/MMh:-oys:/dMm````..:oNMMMy`` \n", 93);
sys_print(" ``` `:MMNo````./yMMNs`dMMy.``-`:MMN/`dMMN.` `oMMN:.oMMM+`../:/++:-..yMMd`./ossssmMMNs` \n", 93);
sys_print(" ``` `:MMMNNNNNMMMMm+``:mMMNh/-:dMNs`.dMMN.` `oMMN:./MMMd/.-:/:-/hNhmMMm:.:MMMMMMMMNd.` \n", 93);
sys_print(" ``` `:NNNNNNNNmho:`` `.+ymNm:::y:```+ooo`` `:ooo-``:o/-:::-.`+mNNNmy+.``yhhhhyyyo/.-` \n", 93);
sys_print(" `` ````````````` `` ````--.:.` `-:::-.` ````````` `````````````.` \n", 93);
sys_print(" ``` ``--` `-::::-.` \n", 93);
sys_print(" ` .::` `-/+/:-.` \n", 93);
sys_print(" `-/:. `./ss+:-.` \n", 93);
sys_print(" .:o-` `.:sdy+:-` \n", 93);
sys_print(" `-ss-.:smNh+:-` DoritOS \n", 93);
sys_print(" ./mydMNy/:.` \n", 93);
sys_print(" `-yMNy/-.` \n", 93);
sys_print(" .:o-.` \n", 93);
sys_print(" ..` - - 94);
} | c | 7 | 0.234964 | 118 | 80.75 | 48 | starcoderdata |
from typing import Tuple
from ..utils import TreeNode
def transformIntoSortedList(node: TreeNode) -> Tuple[TreeNode, TreeNode]:
"""Transform binary search tree rooted at the specified 'node' into a
linked list. Return the head and tail of the linked list."""
if node.left is not None:
# Transform left child into linked list, and connect the *tail*
# of that linked list to the current node.
head, leftTail = transformIntoSortedList(node.left)
node.left = None
leftTail.right = node
else:
head = node
if node.right is not None:
# Transform right child into linked list, and connect the current
# node to the *head* of that linked list.
mid, tail = transformIntoSortedList(node.right)
node.right = mid
else:
tail = node
return head, tail
def increasingBST(root: TreeNode) -> TreeNode:
"""Return linked list representation of the specified 'root' BST."""
head, _ = transformIntoSortedList(root)
return head | python | 10 | 0.665706 | 73 | 31.53125 | 32 | starcoderdata |
import _objectSpread from "@babel/runtime/helpers/objectSpread";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React from 'react';
import { useTranslation } from './useTranslation';
import { getDisplayName } from './utils';
export function withTranslation(ns) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return function Extend(WrappedComponent) {
function I18nextWithTranslation(props, ref) {
var _useTranslation = useTranslation(ns, props),
_useTranslation2 = _slicedToArray(_useTranslation, 3),
t = _useTranslation2[0],
i18n = _useTranslation2[1],
ready = _useTranslation2[2];
var passDownProps = _objectSpread({}, props, {
t: t,
i18n: i18n,
tReady: ready
});
if (options.withRef && ref) {
passDownProps.ref = ref;
}
return React.createElement(WrappedComponent, passDownProps);
}
I18nextWithTranslation.displayName = "withI18nextTranslation(".concat(getDisplayName(WrappedComponent), ")");
I18nextWithTranslation.WrappedComponent = WrappedComponent;
return options.withRef ? React.forwardRef(I18nextWithTranslation) : I18nextWithTranslation;
};
} | javascript | 14 | 0.693646 | 113 | 37.911765 | 34 | starcoderdata |
module.exports = {
locales: {
'/de/': {
description: 'Ihre Quelle für die Base32- und Base32Check1-Algorithmen',
lang: 'de',
},
'/': {
description: 'Your source for the Base32 and Base32Check1 algorithms',
lang: 'en-US',
},
},
themeConfig: {
docsBranch: 'develop',
docsDir: 'docs',
editLinks: true,
editLinkText: 'Help us improve this page!',
locales: {
'/de/': {
editLinkText: 'Helfen Sie uns, diese Seite zu verbessern!',
label: 'Deutsch',
selectText: 'Sprachen',
sidebar: [
'/de/introduction',
'/de/samples',
['/de/java', 'Java-Leitfaden'],
['/de/scala', 'Scala-Leitfaden'],
]
},
'/': {
label: 'English',
},
},
repo: 'bitmarck-service/base32check',
sidebar: [
'/introduction',
'/samples',
['/java', 'Java Guide'],
['/scala', 'Scala Guide'],
]
},
title: 'Base32Check',
head: [
['link', { rel: "icon", type: "image/png", sizes: "192x192", href: "/assets/favicons/192.png"}],
['link', { rel: "icon", type: "image/png", sizes: "64x64", href: "/assets/favicons/64.png"}],
['link', { rel: "icon", type: "image/png", sizes: "32x32", href: "/assets/favicons/32.png"}],
['link', { rel: "icon", type: "image/png", sizes: "16x16", href: "/assets/favicons/16.png"}],
['link', { rel: "apple-touch-icon", sizes: "180x180", href: "/assets/favicons/180.png"}],
],
} | javascript | 14 | 0.454441 | 104 | 34.612245 | 49 | starcoderdata |
import React from 'react';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';
const addChannelMutation = gql`
mutation($file: Upload!) {
singleUpload(file: $file) {
username
}
}
`;
const AddChannel = () => {
return (
<Mutation mutation={addChannelMutation}>
{( singleUpload, { data }) => (
<div className="messageInput">
<input type="file" required onChange={ evt => {
singleUpload({variables: {file: evt.target.files[0]}})
}} />
)}
);
};
export default AddChannel; | javascript | 27 | 0.57309 | 66 | 20.5 | 28 | starcoderdata |
// Leetcode - 1007 - Minimum Domino rotations for equal row
int numSwaps(int target, vector A, vector B)
{
int swapCount = 0;
for (int i = 0; i < A.size(); i++)
{
if (A[i] != target && B[i] != target)
return INT_MAX;
else if (A[i] != target)
{
swapCount++;
}
}
return swapCount;
}
int minDominoRotations(vector &tops, vector &bottoms)
{
int minSwaps = min(numSwaps(tops[0], tops, bottoms), numSwaps(bottoms[0], tops, bottoms));
minSwaps = min(minSwaps, numSwaps(tops[0], bottoms, tops));
minSwaps = min(minSwaps, numSwaps(bottoms[0], bottoms, tops));
return minSwaps == INT_MAX ? -1 : minSwaps;
} | c++ | 12 | 0.583099 | 94 | 28.625 | 24 | starcoderdata |
package com.zhanghuagui.uninstallapp.db;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class WhiteItem {
@Id(autoincrement = true)
private Long mId;
@Property
private String mPackageName;
@Generated(hash = 303993317)
public WhiteItem(Long mId, String mPackageName) {
this.mId = mId;
this.mPackageName = mPackageName;
}
@Generated(hash = 1454278319)
public WhiteItem() {
}
public Long getId() {
return this.mId;
}
public void setId(Long mId) {
this.mId = mId;
}
public String getPackageName() {
return this.mPackageName;
}
public void setPackageName(String mPackageName) {
this.mPackageName = mPackageName;
}
public Long getMId() {
return this.mId;
}
public void setMId(Long mId) {
this.mId = mId;
}
public String getMPackageName() {
return this.mPackageName;
}
public void setMPackageName(String mPackageName) {
this.mPackageName = mPackageName;
}
} | java | 8 | 0.655172 | 54 | 20 | 58 | starcoderdata |
<?php
namespace App\Http\Controllers;
use App\Follow;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class FollowController extends Controller
{
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create($id)
{
$follow = new Follow();
$follow->user_id = Auth::user()->id;
$follow->other_user_id = $id; // žmogus kurį pafollowina
$follow->save();
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Follow $Follow
* @return \Illuminate\Http\Response
*/
public function destroy($follow)
{
$data = Follow::all()
->where('user_id', Auth::user()->id)
->where('other_user_id', $follow)
->first();
$data->delete();
return redirect()->back();
}
} | php | 15 | 0.628445 | 60 | 20.595238 | 42 | starcoderdata |
def test_pyfolder_deletes_elements(self):
"""
PyFolder accepts delete of elements
:return:
"""
pyfolder = PyFolder(self.test_folders)
pyfolder["prueba"] = b"hola"
pyfolder["test/example.txt"] = "jeje"
with self.assertRaises(Exception):
del pyfolder["."]
del pyfolder["prueba"]
del pyfolder["test/example.txt"]
del pyfolder["test"]
pyfolder = PyFolder(self.test_folders, allow_remove_folders_with_content=True)
with self.assertRaises(Exception):
del pyfolder["."]
del pyfolder["test"]
del pyfolder["test/example.txt"]
pyfolder = PyFolder(self.test_folders, allow_override=True)
with self.assertRaises(OSError):
del pyfolder["test"]
del pyfolder["."]
pyfolder2 = PyFolder(os.path.join(self.test_folders, "example"), allow_override=True)
self.assertTrue(os.path.exists(os.path.join(self.test_folders, "example")))
del pyfolder["example"]
self.assertFalse(os.path.exists(os.path.join(self.test_folders, "example")))
self.assertTrue(os.path.exists(os.path.join(self.test_folders, "prueba")))
del pyfolder["prueba"]
self.assertFalse(os.path.exists(os.path.join(self.test_folders, "prueba")))
pyfolder = PyFolder(self.test_folders, allow_override=True, allow_remove_folders_with_content=True)
self.assertTrue(os.path.exists(os.path.join(self.test_folders, "test")))
del pyfolder["test"]
self.assertFalse(os.path.exists(os.path.join(self.test_folders, "test")))
self.assertTrue(os.path.exists(self.test_folders))
del pyfolder["."]
self.assertFalse(os.path.exists(self.test_folders)) | python | 11 | 0.623542 | 107 | 37.340426 | 47 | inline |
#ifndef MYDELAY_H
#define MYDELAY_H
#include "updatethread.h"
class MyDelay : public UpdateThread
{
public:
MyDelay(int sec);
private:
int sec;
protected:
void run();
};
#endif // MYDELAY_H | c | 9 | 0.685345 | 35 | 11.210526 | 19 | starcoderdata |
import Immutable from 'immutable'
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import Block from './Block'
import ImageAsset from '../assets/ImageAsset'
import { ArrowIcon } from '../assets/Icons'
import { css } from '../../styles/jss'
import * as s from '../../styles/jso'
const busyWrapperStyle = css(
s.absolute,
s.flex,
s.itemsCenter,
s.justifyCenter,
{ backgroundColor: 'rgba(0, 0, 0, 0.5)', top: 0, right: -40, bottom: 0, left: -40 },
)
const arrowStyle = css(
s.relative,
s.colorA,
s.bgcWhite,
{
padding: 4,
borderRadius: '50%',
transform: 'rotate(-90deg)',
},
)
const Busy = () =>
(<div className={busyWrapperStyle}>
<div className={arrowStyle}>
<ArrowIcon isAnimated />
export default class ImageBlock extends Component {
static propTypes = {
blob: PropTypes.string,
data: PropTypes.object,
isUploading: PropTypes.bool,
}
static defaultProps = {
blob: null,
data: Immutable.Map(),
isUploading: false,
}
onLoadSuccess = () => {
const { data } = this.props
URL.revokeObjectURL(data.get('src'))
}
render() {
const { blob, data, isUploading } = this.props
return (
<Block {...this.props}>
<div className={classNames('editable image', { isUploading })}>
{isUploading && <Busy /> }
<ImageAsset
alt={data.get('alt')}
onLoadSuccess={this.onLoadSuccess}
src={blob || data.get('url')}
/>
)
}
} | javascript | 17 | 0.599751 | 86 | 21.277778 | 72 | starcoderdata |
# -*- coding: utf-8 -*-
# @Time : 2019/3/15 0015 18:55
# @Author : __Yanfeng
# @Site :
# @File : sitemap.py
# @Software: PyCharm
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from blog.models import Post
class PostSiteMap(Sitemap):
changefreq = 'always'
priority = 1.0
protocol = 'https'
def items(self):
return Post.objects.filter(status=Post.STATUS_NORMAL)
def lastmod(self, obj):
return obj.created_time
def location(self, obj):
return reverse('postDetail', args=(obj.pk,)) | python | 11 | 0.658615 | 61 | 22.884615 | 26 | starcoderdata |
func ToParts(p string) []string {
p = path.Clean(p)
if p == "/" {
return []string{}
}
if len(p) > 0 {
// Prefix ./ if relative
if p[0] != '/' && p[0] != '.' {
p = "./" + p
}
}
ps := strings.Split(p, "/")
if ps[0] == "" {
// Start at root
ps = ps[1:]
}
return ps
} | go | 11 | 0.431034 | 33 | 12.857143 | 21 | inline |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Response;
class TransaksiController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = DB::table('data_transaksi')->join('transaksis','transaksis.id_transaksi','=','data_transaksi.id_transaksi')->get();
return view('admin.transaksi.index',['data'=>$data]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$barang = DB::table('barangs')->get();
return view('admin.transaksi.create',['barang'=>$barang]);
}
public function getharga(Request $request){
$barang = $request->input('barang');
$barangs = DB::table('barangs')->where('id_barang',$barang)->first();
//print_r($barangs);
return Response::json($barangs);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$qty = $request->qty;
$barang = $request->barang;
$costumer = $request->costumer;
$total = $request->total;
$arr = array('c' => $costumer,'t'=>$total );
$sum = array_sum($total);
print_r($sum);
$transaksi = DB::table('transaksis')->insertGetID([
'costumer'=>$request->costumer,
'total_bayar'=>$sum,
'tgl_transaksi'=>date('Y-m-d'),
]);
for ($i=0; $i <count($qty) ; $i++) {
DB::table('data_transaksi')->insert([
'id_barang'=>$barang[$i],
'id_transaksi'=>$transaksi,
'qty'=>$qty[$i],
'total'=>$total[$i],
]);
}
return redirect('admin/transaksi')->with('message', '<div class="alert alert-success">Transaksi Berhasil Ditambahkan
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$transaksi = DB::table('transaksis')->where('id_transaksi',$id)->first();
$data = DB::table('data_transaksi')->where('data_transaksi.id_transaksi',$id)->join('barangs','barangs.id_barang','=','data_transaksi.id_barang')->get();
return view('admin.transaksi.detail',['transaksi'=>$transaksi,'data'=>$data]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
DB::table('data_transaksi')->where('id_transaksi',$id)->delete();
DB::table('transaksis')->where('id_transaksi',$id)->delete();
$cek = DB::table('data_transaksi')->where('id_transaksi',$id)->get();
$cek2 = DB::table('transaksis')->where('id_transaksi',$id)->first();
if (count($cek) == 0 && count($cek2) == 0) {
# code...
return redirect('admin/transaksi')->with('message', '<div class="alert alert-success">Data Transaksi Berhasil di Hapus
}
}
public function prints($id){
$transaksi = DB::table('transaksis')->where('id_transaksi',$id)->first();
$data = DB::table('data_transaksi')->where('data_transaksi.id_transaksi',$id)->join('barangs','barangs.id_barang','=','data_transaksi.id_barang')->get();
return view('admin.transaksi.print',['transaksi'=>$transaksi,'data'=>$data]);
}
} | php | 16 | 0.562638 | 159 | 29.669173 | 133 | starcoderdata |
# ifndef CPPAD_CORE_ATOMIC_THREE_REV_DEPEND_HPP
# define CPPAD_CORE_ATOMIC_THREE_REV_DEPEND_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
$begin atomic_three_rev_depend$$
$spell
afun
enum
cpp
taylor.hpp
$$
$section Atomic Function Reverse Dependency Calculation$$
$head Syntax$$
$icode%ok% = %afun%.rev_depend(
%parameter_x%, %type_x%, %depend_x%, %depend_y%
)%$$
$subhead Prototype$$
$srcthisfile%0%// BEGIN_PROTOTYPE%// END_PROTOTYPE%1
%$$
$head Dependency Analysis$$
This calculation is sometimes referred to as a reverse dependency analysis.
$head Implementation$$
This function must be defined if
$cref/afun/atomic_three_ctor/atomic_user/afun/$$ is
used to define an $cref ADFun$$ object $icode f$$,
and $cref/f.optimize()/optimize/$$ is used.
$head Base$$
See $cref/Base/atomic_three_afun/Base/$$.
$head parameter_x$$
See $cref/parameter_x/atomic_three/parameter_x/$$.
$head type_x$$
See $cref/type_x/atomic_three/type_x/$$.
$head depend_x$$
This vector has size equal to the number of arguments for this atomic function;
i.e. $icode%n%=%ax%.size()%$$.
The input values of the elements of $icode depend_x$$
are not specified (must not matter).
Upon return, for $latex j = 0 , \ldots , n-1$$,
$icode%depend_x%[%j%]%$$ is true if the values of interest depend
on the value of $cref/ax[j]/atomic_three_afun/ax/$$ in the corresponding
$icode%afun%(%ax%, %ay%)%$$ call.
Note that parameters and variables,
that the values of interest do not depend on,
may get removed by $cref/optimization/optimize/$$.
The corresponding values in $cref/parameter_x/atomic_three/parameter_x/$$,
and $cref/taylor_x/atomic_three_forward/taylor_x/$$
(after optimization has removed them) are not specified.
$head depend_y$$
This vector has size equal to the number of results for this atomic function;
i.e. $icode%m%=%ay%.size()%$$.
For $latex i = 0 , \ldots , m-1$$,
$icode%depend_y%[%i%]%$$ is true if the values of interest depend
on the value of $cref/ay[i]/atomic_three_afun/ay/$$ in the corresponding
$icode%afun%(%ax%, %ay%)%$$ call.
$head ok$$
If this calculation succeeded, $icode ok$$ is true.
Otherwise, it is false.
$childtable%
example/atomic_three/rev_depend.cpp
%$$
$head Example$$
The following is an example of a atomic function $code rev_depend$$ definition:
$cref atomic_three_rev_depend.cpp$$.
$end
-----------------------------------------------------------------------------
*/
namespace CppAD { // BEGIN_CPPAD_NAMESPACE
/*!
\file atomic/three_rev_depend.hpp
Third generation atomic type computation.
*/
/*!
Link from atomic_three to reverse dependency calculation
\param parameter_x [in]
is the value of the parameters in the corresponding function call
afun(ax, ay).
\param type_x [in]
is the value for each of the components of x.
\param depend_x [out]
specifies which components of x affect values of interest.
\param depend_y [in]
specifies which components of y affect values of interest.
*/
// BEGIN_PROTOTYPE
template <class Base>
bool atomic_three
const vector parameter_x ,
const vector type_x ,
vector depend_x ,
const vector depend_y )
// END_PROTOTYPE
{ return false; }
} // END_CPPAD_NAMESPACE
# endif | c++ | 12 | 0.666841 | 79 | 29.325397 | 126 | starcoderdata |
def ui_get_font(self, key):
'''Returns font configuration tuple'''
Log.debug('Requested font "{}"'.format(key))
font_family = self.CORE.font_family
height, is_bold = self.CORE.fonts[key]
if is_bold: return (font_family, height, 'bold')
else: return (font_family, height) | python | 9 | 0.610063 | 56 | 44.571429 | 7 | inline |
import {createElement, Component} from 'rax';
import View from 'rax-view';
import {isWeex} from 'universal-env';
const WIDTH = 750;
class TabBarContents extends Component {
state = {};
componentWillMount() {
this.hasBeenSelected = false;
if (this.props.selected) {
this.hasBeenSelected = true;
}
}
render() {
if (this.props.selected) {
this.hasBeenSelected = true;
}
let style = {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
width: WIDTH
};
if (!this.props.selected) {
style.left = 0 - WIDTH;
style.overflow = 'hidden';
} else {
style.left = 0;
}
return (
this.hasBeenSelected ?
<View style={[this.props.style, style]}>
{this.props.children}
: <View style={[this.props.style, style]} />
);
}
}
export default TabBarContents; | javascript | 10 | 0.579003 | 60 | 19.085106 | 47 | starcoderdata |
function (error, data) {
if (error) {
callback(error, data);
return;
}
// Modify the config data
data = modifyFunction(data);
self.update_job(jobName, data, customParams, callback);
} | javascript | 9 | 0.525896 | 63 | 21.909091 | 11 | inline |
<?php declare(strict_types=1);
use Clue\React\Buzz\Browser;
use React\EventLoop\LoopInterface;
use React\Socket\ConnectorInterface;
use function DI\factory;
return [
Browser::class => factory(function (
ConnectorInterface $connector,
LoopInterface $loop
) {
return new Browser(
$loop,
$connector
);
}),
]; | php | 14 | 0.629353 | 40 | 20.157895 | 19 | starcoderdata |
package hack.veteran_app.sdk.backend.factories;
import hack.veteran_app.sdk.backend.DomainResolver;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class RetrofitService {
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(DomainResolver.getRESTUrl())
.addConverterFactory(JacksonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static S createService(Class serviceClass) {
return retrofit.create(serviceClass);
}
} | java | 10 | 0.809231 | 102 | 33.210526 | 19 | starcoderdata |
#include <bits/stdc++.h>
#define LL long long
#define PI pair<int,int>
#define PL pair<LL,LL>
#define st first
#define nd second
#define all(x) x.begin(),x.end()
using namespace std;
const int MX = 1e5+5;
int a[MX];
int n;
int main(){
cin >> n;
for(int i=0 ; i<n ; ++i)
cin >> a[i];
int ans = 0;
for(int i=0 ; i<n-1 ; ++i){
int len = 0;
while(a[i] >= a[i+1] && i < n-1){
len++;
i++;
}
ans = max(len,ans);
}
cout << ans << "\n";
} | c++ | 12 | 0.470135 | 41 | 17.571429 | 28 | codenet |
const toggleMenu = document.querySelector('.toggle');
const icon = document.querySelector('.icon-menu');
const body = document.getElementById('landing-body');
let isOpen = false;
const toggleCourseModules = (e) => {
isOpen = !isOpen;
const nav = e.target.parentElement.previousElementSibling;
nav.classList.toggle('open');
body.classList.toggle('overflow');
console.log(isOpen);
if(isOpen){
icon.classList.remove('fa-bars');
icon.classList.add('fa-times');
}else{
icon.classList.remove('fa-times');
icon.classList.add('fa-bars');
}
}
toggleMenu.addEventListener('click', toggleCourseModules); | javascript | 12 | 0.676783 | 62 | 30.380952 | 21 | starcoderdata |
/*
* Copyright 2020, Brightspot.
*
* 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 gyro.aws.apigatewayv2;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import gyro.aws.AwsResource;
import gyro.aws.Copyable;
import gyro.core.GyroUI;
import gyro.core.Type;
import gyro.core.resource.Id;
import gyro.core.resource.Output;
import gyro.core.resource.Resource;
import gyro.core.resource.Updatable;
import gyro.core.scope.State;
import gyro.core.validation.Required;
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
import software.amazon.awssdk.services.apigatewayv2.model.ApiMapping;
import software.amazon.awssdk.services.apigatewayv2.model.CreateApiMappingResponse;
import software.amazon.awssdk.services.apigatewayv2.model.DomainName;
import software.amazon.awssdk.services.apigatewayv2.model.GetApiMappingsResponse;
/**
* Create an api mapping.
*
* Example
* -------
*
* .. code-block:: gyro
*
* aws::api-mapping example-mapping
* api: $(aws::api-gateway example-api)
* domain-name: "vpn.ops-test.psdops.com"
* stage: $(aws::api-gateway-stage example-stage)
* api-mapping-key: "example-key"
* end
*/
@Type("api-mapping")
public class ApiMappingResource extends AwsResource implements Copyable {
private ApiResource api;
private String apiMappingKey;
private DomainNameResource domainName;
private StageResource stage;
// Output
private String id;
/**
* The API which should be mapped.
*/
@Required
public ApiResource getApi() {
return api;
}
public void setApi(ApiResource api) {
this.api = api;
}
/**
* The key of the mapping.
*/
@Updatable
public String getApiMappingKey() {
return apiMappingKey;
}
public void setApiMappingKey(String apiMappingKey) {
this.apiMappingKey = apiMappingKey;
}
/**
* The domain name to which the API should be mapped.
*/
@Updatable
public DomainNameResource getDomainName() {
return domainName;
}
public void setDomainName(DomainNameResource domainName) {
this.domainName = domainName;
}
/**
* The stage of the API.
*/
@Updatable
public StageResource getStage() {
return stage;
}
public void setStage(StageResource stage) {
this.stage = stage;
}
/**
* The ID of the api mapping.
*/
@Output
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public void copyFrom(ApiMapping model) {
setApi(findById(ApiResource.class, model.apiId()));
setApiMappingKey(model.apiMappingKey());
setStage(findById(StageResource.class, model.stage()));
setId(model.apiMappingId());
ApiGatewayV2Client client = createClient(ApiGatewayV2Client.class);
List domainNames = client.getDomainNames().items().stream().map(DomainName::domainName)
.collect(Collectors.toList());
domainNames.stream().filter(d -> {
GetApiMappingsResponse apiMappings = client.getApiMappings(r -> r.domainName(d));
return apiMappings.hasItems() &&
apiMappings.items()
.stream()
.filter(i -> i.apiMappingId().equals(getId()))
.findFirst()
.orElse(null) != null;
}).findFirst().ifPresent(domainName -> setDomainName(findById(DomainNameResource.class, domainName)));
}
@Override
public boolean refresh() {
ApiGatewayV2Client client = createClient(ApiGatewayV2Client.class);
ApiMapping mapping = getApiMapping(client);
if (mapping == null) {
return false;
}
copyFrom(mapping);
return true;
}
@Override
public void create(GyroUI ui, State state) throws Exception {
ApiGatewayV2Client client = createClient(ApiGatewayV2Client.class);
CreateApiMappingResponse apiMapping = client.createApiMapping(r -> r.apiId(getApi().getId())
.apiMappingKey(getApiMappingKey())
.domainName(getDomainName().getName())
.stage(getStage().getName()));
setId(apiMapping.apiMappingId());
}
@Override
public void update(GyroUI ui, State state, Resource current, Set changedFieldNames) throws Exception {
ApiGatewayV2Client client = createClient(ApiGatewayV2Client.class);
client.updateApiMapping(r -> r.apiId(getApi().getId())
.apiMappingId(getId())
.apiMappingKey(getApiMappingKey())
.domainName(getDomainName().getName())
.stage(getStage().getName()));
}
@Override
public void delete(GyroUI ui, State state) throws Exception {
ApiGatewayV2Client client = createClient(ApiGatewayV2Client.class);
client.deleteApiMapping(r -> r.apiMappingId(getId()).domainName(getDomainName().getName()));
}
private ApiMapping getApiMapping(ApiGatewayV2Client client) {
ApiMapping apiMapping = null;
GetApiMappingsResponse mappings = client.getApiMappings(r -> r.domainName(getDomainName().getName()));
if (mappings.hasItems()) {
apiMapping = mappings.items()
.stream()
.filter(i -> i.apiMappingId().equals(getId()))
.findFirst()
.orElse(null);
}
return apiMapping;
}
} | java | 24 | 0.650835 | 114 | 28.215311 | 209 | starcoderdata |
BOOST_AUTO_TEST_CASE(TestExpiredQuery)
{
Listener<int, TestEntry> lsnr;
ContinuousQueryHandle<int, TestEntry> handle;
{
// Query scope.
ContinuousQuery<int, TestEntry> qry(MakeReference(lsnr));
handle = cache.QueryContinuous(qry);
}
// Query is destroyed here.
CheckEvents(cache, lsnr);
} | c++ | 11 | 0.652941 | 65 | 20.3125 | 16 | inline |
package api.support.fakes;
import static api.support.APITestContext.getTenantId;
import static api.support.fakes.Storage.getStorage;
import static api.support.http.InterfaceUrls.holdingsStorageUrl;
import static org.apache.commons.lang3.ObjectUtils.firstNonNull;
import static org.folio.circulation.domain.representations.ItemProperties.EFFECTIVE_LOCATION_ID;
import static org.folio.circulation.domain.representations.ItemProperties.HOLDINGS_RECORD_ID;
import static org.folio.circulation.domain.representations.ItemProperties.PERMANENT_LOCATION_ID;
import static org.folio.circulation.domain.representations.ItemProperties.TEMPORARY_LOCATION_ID;
import static org.folio.circulation.support.json.JsonPropertyWriter.write;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.folio.circulation.domain.representations.ItemProperties;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import io.vertx.core.json.JsonObject;
public final class StorageRecordPreProcessors {
// Holdings record property name, item property name, effective property name
private static final List<Triple<String, String, String>> CALL_NUMBER_PROPERTIES = Arrays.asList(
new ImmutableTriple<>("callNumber", "itemLevelCallNumber", "callNumber"),
new ImmutableTriple<>("callNumberPrefix", "itemLevelCallNumberPrefix", "prefix"),
new ImmutableTriple<>("callNumberSuffix", "itemLevelCallNumberSuffix", "suffix")
);
// RMB uses ISO-8601 compatible date time format by default.
private static final String RMB_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS+0000";
private StorageRecordPreProcessors() {
throw new UnsupportedOperationException("Do not instantiate");
}
public static JsonObject setEffectiveLocationIdForItem(
@SuppressWarnings("unused") JsonObject oldItem, JsonObject newItem) {
final String holdingsRecordId = newItem.getString("holdingsRecordId");
final JsonObject holding = getHoldingById(holdingsRecordId);
newItem.put(EFFECTIVE_LOCATION_ID, firstNonNull(
newItem.getString(TEMPORARY_LOCATION_ID),
newItem.getString(PERMANENT_LOCATION_ID),
holding.getString(TEMPORARY_LOCATION_ID),
holding.getString(PERMANENT_LOCATION_ID)));
return newItem;
}
public static JsonObject setItemStatusDateForItem(JsonObject oldItem, JsonObject newItem) {
if (Objects.nonNull(oldItem)) {
JsonObject oldItemStatus = oldItem.getJsonObject(ItemProperties.STATUS_PROPERTY);
JsonObject newItemStatus = newItem.getJsonObject(ItemProperties.STATUS_PROPERTY);
if (ObjectUtils.allNotNull(oldItemStatus, newItemStatus)) {
if (!Objects.equals(oldItemStatus.getString("name"),
newItemStatus.getString("name"))) {
write(newItemStatus, "date",
DateTime.now(DateTimeZone.UTC).toString(RMB_DATETIME_PATTERN)
);
}
}
}
return newItem;
}
public static JsonObject setEffectiveCallNumberComponents(
@SuppressWarnings("unused") JsonObject oldItem, JsonObject newItem) {
final JsonObject effectiveCallNumberComponents = new JsonObject();
final String holdingsId = newItem.getString(HOLDINGS_RECORD_ID);
final JsonObject holding = getHoldingById(holdingsId);
CALL_NUMBER_PROPERTIES.forEach(properties -> {
String itemPropertyName = properties.getMiddle();
String holdingsPropertyName = properties.getLeft();
String effectivePropertyName = properties.getRight();
final String propertyValue = StringUtils.firstNonBlank(
newItem.getString(itemPropertyName),
holding.getString(holdingsPropertyName)
);
if (StringUtils.isNotBlank(propertyValue)) {
effectiveCallNumberComponents.put(effectivePropertyName, propertyValue);
}
});
newItem.put("effectiveCallNumberComponents", effectiveCallNumberComponents);
return newItem;
}
private static JsonObject getHoldingById(String id) {
return getStorage()
.getTenantResources(holdingsStorageUrl("").getPath(), getTenantId())
.get(id);
}
} | java | 18 | 0.765585 | 99 | 40.182692 | 104 | starcoderdata |
static void hexdump_print(
byte data, /* Item to print */
byte mode /* ASCII or hex mode */
)
{
switch (mode)
{
case DEBUG_ASCII:
data = (' ' <= data && data <= '~') ? data : '.';
fprintf(stdout, "%c", data);
break;
case DEBUG_HEX:
fprintf(stdout, "%02x ", data);
break;
default:
break;
}
} | c | 13 | 0.469169 | 57 | 19.777778 | 18 | inline |
//
// UIButton+NSFExt.h
// NSFKitObjC
//
// Created by shlexingyu on 2018/12/21.
//
#import
NS_ASSUME_NONNULL_BEGIN
@interface NSFUIButtonBuilder : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) UIColor *titleColor;
@property (nonatomic, copy) UIColor *titleShadowColor;
@property (nonatomic, copy) NSAttributedString *attributedTitle;
@property (nonatomic, copy) UIImage *image;
@property (nonatomic, copy) UIImage *backgroundImage;
@end
@interface UIButton (NSFExt)
+ (instancetype)nsf_customButton NS_SWIFT_NAME(custom());
/**
image 和 title 垂直居中显示,title 在 image 下方
@param spacing 间距
*/
- (void)nsf_centerImageAndTitleVertincallyWithSpace:(CGFloat)spacing NS_SWIFT_NAME(centerImageAndTitleVertincally(withSpace:));
/**
image 和 title 水平居中显示,image 在 title 左侧
@param spacing 间距
*/
- (void)nsf_centerImageAndTitleHorizontallyWithSpace:(CGFloat)spacing NS_SWIFT_NAME(centerImageAndTitleHorizontally(withSpace:));
- (void)nsf_setState:(UIControlState)state
withUIConfiguration:(void(NS_NOESCAPE ^)(NSFUIButtonBuilder *button))configuration NS_SWIFT_NAME(set(state:withUIConfiguration:));
@end
NS_ASSUME_NONNULL_END | c | 8 | 0.772152 | 130 | 24.76087 | 46 | starcoderdata |
package it.polimi.ingsw.GC_04.server.timer;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TimerJson{
private static int start=0;//timeout from json in milliseconds
private static int input=0;
private static int action=0;
@JsonCreator
public TimerJson(@JsonProperty("start") int start,@JsonProperty("input") int input,@JsonProperty("action") int action){
TimerJson.start=start;
TimerJson.input=input;
TimerJson.action=action;
}
public TimerJson(){//for json
}
public static int getStartTimer(){
return TimerJson.start;
}
public static int getInputTimer(){
return TimerJson.input;
}
public static int getActionTimer(){
return TimerJson.action;
}
} | java | 10 | 0.749347 | 120 | 20.885714 | 35 | starcoderdata |
#include "common.h"
#include "tickerScheduler.h"
#include
// Ref: http://www.schatenseite.de/en/2016/04/22/esp8266-witty-cloud-module/
static const uint8_t button_Pin = 4; // pin connected to Witty Cloud Module button
static const byte button_Led = 13; // BLUE_LED (in RGB, not led_builtin)
static void checkButton()
{
static int lastButtonState = HIGH;
const int buttonState = digitalRead(button_Pin);
if (buttonState == lastButtonState)
return;
lastButtonState = buttonState;
digitalWrite(button_Led, !buttonState);
#ifdef DEBUG
Serial.printf("Button %s\n", buttonState == HIGH ? "released" : "pressed");
#endif // #ifdef DEBUG
if (buttonState == HIGH)
{ // when button is released...
updateTemperatureSensorCachedValue();
sendOperState();
sendLightSensor();
sendTemperatureSensor();
}
}
void initButton(TickerScheduler &ts)
{
pinMode(button_Pin, INPUT);
pinMode(button_Led, OUTPUT);
digitalWrite(button_Led, LOW);
ts.sched(checkButton, 333);
} | c++ | 9 | 0.675141 | 82 | 24.902439 | 41 | starcoderdata |
def analyse_selections(api_key, endpoint, project_id, result_id, path, doi,
project_short_name, throttle, **kwargs):
"""Analyse In the Spotlight selection results."""
e = enki.Enki(api_key, endpoint, project_short_name, all=1)
result = enki.pbclient.find_results(project_id, id=result_id, limit=1,
all=1)[0]
df = helpers.get_task_run_df(e, result.task_id)
# Flatten annotations into a single list
anno_list = df['info'].tolist()
anno_list = list(itertools.chain.from_iterable(anno_list))
defaults = {'annotations': []}
result.info = helpers.init_result_info(doi, path, defaults)
clusters = []
comments = []
# Cluster similar regions
for anno in anno_list:
if anno['motivation'] == 'commenting':
comments.append(anno)
continue
elif anno['motivation'] == 'tagging':
r1 = get_rect_from_selection(anno)
matched = False
for cluster in clusters:
r2 = get_rect_from_selection(cluster)
overlap_ratio = get_overlap_ratio(r1, r2)
if overlap_ratio > MERGE_RATIO:
matched = True
r3 = merge_rects(r1, r2)
update_selector(cluster, r3)
if not matched:
update_selector(anno, r1) # still update to round rect params
clusters.append(anno)
else: # pragma: no cover
raise ValueError('Unhandled motivation')
result.info['annotations'] = clusters + comments
enki.pbclient.update_result(result)
time.sleep(throttle) | python | 16 | 0.573731 | 78 | 37.976744 | 43 | inline |
<?php
/**
* PromotionController.php
*
* @since 19/08/16
* @author gseidel
*/
namespace Enhavo\Bundle\ShopBundle\Controller;
use Enhavo\Bundle\ShopBundle\Model\OrderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sylius\Component\Cart\Provider\CartProviderInterface;
use Sylius\Component\Cart\Model\CartInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Sylius\Component\Cart\Event\CartEvent;
use Symfony\Component\EventDispatcher\GenericEvent;
use Sylius\Component\Resource\Event\FlashEvent;
use Sylius\Component\Order\SyliusCartEvents;
class PromotionController extends AbstractController
{
public function redeemCouponAction(Request $request)
{
$order = $this->getCurrentCart();
$form = $this->createForm('enhavo_shop_order_promotion_coupon', $order);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$event = new CartEvent($order);
$eventDispatcher = $this->getEventDispatcher();
$eventDispatcher->dispatch(SyliusCartEvents::CART_CHANGE, new GenericEvent($order));
$eventDispatcher->dispatch(SyliusCartEvents::CART_SAVE_INITIALIZE, $event);
$eventDispatcher->dispatch(SyliusCartEvents::CART_SAVE_COMPLETED, new FlashEvent());
$this->getManager()->flush();
}
if($request->isXmlHttpRequest()) {
/** @var OrderInterface $order */
return new JsonResponse([
'order' => $order,
'coupon' => $order->getPromotionCoupon() ? $order->getPromotionCoupon()->getCode() : null
]);
}
$redirectUrl = $request->get('redirectUrl');
if($redirectUrl) {
return $this->redirect($redirectUrl);
}
return $this->render('EnhavoShopBundle:Theme:Promotion/coupon.html.twig', [
'form' => $form->createView()
]);
}
public function cancelCouponAction(Request $request)
{
/** @var OrderInterface $order */
$order = $this->getCurrentCart();
$order->setPromotionCoupon(null);
$event = new CartEvent($order);
$eventDispatcher = $this->getEventDispatcher();
$eventDispatcher->dispatch(SyliusCartEvents::CART_CHANGE, new GenericEvent($order));
$eventDispatcher->dispatch(SyliusCartEvents::CART_SAVE_INITIALIZE, $event);
$eventDispatcher->dispatch(SyliusCartEvents::CART_SAVE_COMPLETED, new FlashEvent());
$this->getManager()->flush();
if($request->isXmlHttpRequest()) {
return new JsonResponse([
'order' => $order,
'coupon' => $order->getPromotionCoupon() ? $order->getPromotionCoupon()->getCode() : null
]);
}
$redirectUrl = $request->get('redirectUrl');
if($redirectUrl) {
return $this->redirect($redirectUrl);
}
return $this->render('EnhavoShopBundle:Theme:Promotion/coupon.html.twig');
}
/**
* @return CartProviderInterface
*/
protected function getCartProvider()
{
return $this->get('sylius.cart_provider');
}
/**
* @return CartInterface
*/
protected function getCurrentCart()
{
return $this->getCartProvider()->getCart();
}
/**
* @return \Doctrine\ORM\EntityManager
*/
protected function getManager()
{
return $this->get('doctrine.orm.entity_manager');
}
/**
* @return EventDispatcherInterface
*/
public function getEventDispatcher()
{
return $this->get('event_dispatcher');
}
} | php | 17 | 0.640999 | 116 | 32.188034 | 117 | starcoderdata |
#include
#include
#include
#include
#include
using namespace std;
#define LIMIT 100000
int sum[LIMIT+1];
int ambical_sum[LIMIT+1];
bool flg[LIMIT+1];
int factor_sum(int no){
if(no <= 1)
return 0;
int sum = 1;
int bound = (int)sqrt(no);
if(bound*bound == no)
sum+= bound;
for(int i = 2; i < bound; i++){
if( no % i == 0){
sum += i + no /i;
}
}
return sum;
}
void build_sum(){
int f_sum = 0;
for(int i = 0; i <= LIMIT; i++){
f_sum = factor_sum(i);
if(i != f_sum && i == factor_sum(f_sum)){
flg[i] = true;
if(f_sum <= LIMIT)
flg[f_sum] = true;
}
else
flg[i] = false;
}
int curr = 0;
for(int i = 0; i <= LIMIT; i++){
ambical_sum[i] = curr;
if(flg[i] == true)
curr += i;
}
return;
}
int main() {
build_sum();
int t,n;
cin >> t;
while(t--){
cin >> n;
cout << ambical_sum[n] << endl;
}
return 0;
} | c++ | 12 | 0.440273 | 49 | 18.578947 | 57 | starcoderdata |
def draw(self,t):
'''Show a block of text to the user for a given duration on a blank screen'''
if not self.isRunning :
self.isRunning=True # mark that we're running
self.t0=getTimeStamp()
if self.clearScreen:
self.window.clear()
self.instructLabel.draw() | python | 9 | 0.597523 | 85 | 39.5 | 8 | inline |
import os
import sys
class Lock:
""" Try to prevent multiple instances of the program running at once """
def __init__(self):
self.lockfile = None
if os.name == 'posix':
fcntl = __import__('fcntl')
try:
self.lockfile = open('lockfile', 'w')
self.lockfile.write(str(os.getpid()) + "\n")
self.lockfile.flush()
except Exception as e:
sys.stderr.write(
"ERROR: was harvester runnning under a different user previously? (could not write to lockfile)\n")
raise SystemExit
try:
os.chmod('lockfile', 0o664)
except Exception as e:
pass
try:
fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (OSError, IOError):
sys.stderr.write("ERROR: is harvester already running? (could not lock lockfile)\n")
raise SystemExit
def unlock(self):
if os.name == 'posix':
fcntl = __import__('fcntl')
fcntl.flock(self.lockfile, fcntl.LOCK_UN)
self.lockfile.close()
os.unlink('lockfile') | python | 17 | 0.518489 | 119 | 30.897436 | 39 | starcoderdata |
@Deprecated
public Map<String, Object> getItem( String item ){ // Does not play well with aliases
Map<String, Object> result = new HashMap<String, Object>();
ResultSet rs;
PreparedStatement prep;
try {
prep = connection.prepareStatement("SELECT * FROM item WHERE id = ?;");
prep.setLong(1, getid( item ));
rs = prep.executeQuery();
int colCount = rs.getMetaData().getColumnCount();
while( rs.next() ) {
for( int i = 0; i <= colCount; i++ ) {
result.put( rs.getMetaData().getColumnName( i ), rs.getObject( i ) );
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
} | java | 15 | 0.634646 | 86 | 27.909091 | 22 | inline |
void SurrogateHeatDriver::write_step(int timestep, int iteration)
{
if (!has_coupling_data())
return;
// if called, but viz isn't requested for the situation,
// exit early - no output
if ((iteration < 0 && "final" != viz_iterations_) ||
(iteration >= 0 && "all" != viz_iterations_)) {
return;
}
// otherwise construct an appropriate filename and write the data
std::stringstream filename;
filename << viz_basename_;
if (iteration >= 0 && timestep >= 0) {
filename << "_t" << timestep << "_i" << iteration;
}
filename << ".vtk";
SurrogateVtkWriter vtk_writer(*this, vtk_radial_res_, viz_regions_, viz_data_);
comm_.message("Writing VTK file: " + filename.str());
vtk_writer.write(filename.str());
return;
} | c++ | 11 | 0.634565 | 81 | 28.192308 | 26 | inline |
# Author: allannozomu
# Runtime: 44 ms
# Memory: 13.4 MB
class Solution:
solution =
size = 0
def parenthese(self, s, left, right):
if len(s) == (self.size << 1):
self.solution.append(s)
return
if left:
self.parenthese(s + '(', left - 1, right)
if left < right:
self.parenthese(s + ')', left, right - 1)
def generateParenthesis(self, n: int) -> List[str]:
self.solution =
self.size = n
self.parenthese('', n, n)
return self.solution | python | 12 | 0.545156 | 55 | 25.521739 | 23 | starcoderdata |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('global_model');
if (!$this->_is_logged_in('admin_id')) {
_redirect('admin');
}
}
public function index($load_view,$data = []){
$data['data'] = $data;
$this->load->view('admin/common/header');
$this->load->view('admin/company/'.$load_view,$data);
$this->load->view('admin/common/footer');
}
public function privacy_policy(){
if($data=$this->input->post()){
$result = $this->global_model->update('privacy_policy',[],$data);
if ($result) {
$this->_class('alert_class',"green");
$this->_class('alert',"Privacy Policy Updated Successfully");
}else{
$this->_class('alert_class',"red");
$this->_class('alert',"Unable to Update!");
}
_redirect_pre();
}else{
$data=$this->global_model->get_all('privacy_policy');
$data=$data[0];
$this->index('privacy_policy',$data);
}
}
public function terms_condition(){
if($data=$this->input->post()){
$result = $this->global_model->update('terms_condition',[],$data);
if ($result) {
$this->_class('alert_class',"green");
$this->_class('alert',"Terms & Conditions Updated Successfully");
}else{
$this->_class('alert_class',"red");
$this->_class('alert',"Unable to Update!");
}
_redirect_pre();
}else{
$data=$this->global_model->get_all('terms_condition');
$data=$data[0];
$this->index('terms_condition',$data);
}
}
public function about(){
if($data=$this->input->post()){
$result = $this->global_model->update('about_us',[],$data);
if ($result) {
$this->_class('alert_class',"green");
$this->_class('alert',"Updated Successfully");
}else{
$this->_class('alert_class',"red");
$this->_class('alert',"Unable to Update!");
}
_redirect_pre();
}else{
$data=$this->global_model->get_all('about_us');
$data=$data[0];
$this->index('about',$data);
}
}
} | php | 15 | 0.490441 | 81 | 32.298701 | 77 | starcoderdata |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/svg/SVGElementProxy.h"
#include "core/dom/IdTargetObserver.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGResourceClient.h"
#include "platform/loader/fetch/FetchInitiatorTypeNames.h"
#include "platform/loader/fetch/FetchParameters.h"
#include "platform/loader/fetch/ResourceFetcher.h"
#include "platform/loader/fetch/ResourceLoaderOptions.h"
namespace blink {
class SVGElementProxy::IdObserver : public IdTargetObserver {
public:
IdObserver(TreeScope& tree_scope, SVGElementProxy& proxy)
: IdTargetObserver(tree_scope.GetIdTargetObserverRegistry(), proxy.Id()),
tree_scope_(&tree_scope) {}
void AddClient(SVGResourceClient* client) { clients_.insert(client); }
bool RemoveClient(SVGResourceClient* client) {
return clients_.erase(client);
}
bool HasClients() const { return !clients_.IsEmpty(); }
TreeScope* GetTreeScope() const { return tree_scope_; }
void TransferClients(IdObserver& observer) {
for (const auto& client : clients_)
observer.clients_.insert(client.key, client.value);
clients_.clear();
}
DEFINE_INLINE_VIRTUAL_TRACE() {
visitor->Trace(clients_);
visitor->Trace(tree_scope_);
IdTargetObserver::Trace(visitor);
}
void ContentChanged() {
DCHECK(Lifecycle().GetState() <= DocumentLifecycle::kCompositingClean ||
Lifecycle().GetState() >= DocumentLifecycle::kPaintClean);
HeapVector clients;
CopyToVector(clients_, clients);
for (SVGResourceClient* client : clients)
client->ResourceContentChanged();
}
private:
const DocumentLifecycle& Lifecycle() const {
return tree_scope_->GetDocument().Lifecycle();
}
void IdTargetChanged() override {
DCHECK(Lifecycle().StateAllowsTreeMutations());
HeapVector clients;
CopyToVector(clients_, clients);
for (SVGResourceClient* client : clients)
client->ResourceElementChanged();
}
HeapHashCountedSet clients_;
Member tree_scope_;
};
SVGElementProxy::SVGElementProxy(const AtomicString& id)
: id_(id), is_local_(true) {}
SVGElementProxy::SVGElementProxy(const String& url, const AtomicString& id)
: id_(id), url_(url), is_local_(false) {}
SVGElementProxy::~SVGElementProxy() {}
void SVGElementProxy::AddClient(SVGResourceClient* client) {
// An empty id will never be a valid element reference.
if (id_.IsEmpty())
return;
if (!is_local_) {
if (document_)
document_->AddClient(client);
return;
}
TreeScope* client_scope = client->GetTreeScope();
if (!client_scope)
return;
// Ensure sure we have an observer registered for this tree scope.
auto& scope_observer =
observers_.insert(client_scope, nullptr).stored_value->value;
if (!scope_observer)
scope_observer = new IdObserver(*client_scope, *this);
auto& observer = clients_.insert(client, nullptr).stored_value->value;
if (!observer)
observer = scope_observer;
DCHECK(observer && scope_observer);
// If the client moved to a different scope, we need to unregister the old
// observer and transfer any clients from it before replacing it. Thus any
// clients that remain to be removed will be transferred to the new observer,
// and hence removed from it instead.
if (observer != scope_observer) {
observer->Unregister();
observer->TransferClients(*scope_observer);
observer = scope_observer;
}
observer->AddClient(client);
}
void SVGElementProxy::RemoveClient(SVGResourceClient* client) {
// An empty id will never be a valid element reference.
if (id_.IsEmpty())
return;
if (!is_local_) {
if (document_)
document_->RemoveClient(client);
return;
}
auto entry = clients_.find(client);
if (entry == clients_.end())
return;
IdObserver* observer = entry->value;
DCHECK(observer);
// If the client is not the last client in the scope, then no further action
// needs to be taken.
if (!observer->RemoveClient(client))
return;
// Unregister and drop the scope association, then drop the client.
if (!observer->HasClients()) {
observer->Unregister();
observers_.erase(observer->GetTreeScope());
}
clients_.erase(entry);
}
void SVGElementProxy::Resolve(Document& document) {
if (is_local_ || id_.IsEmpty() || url_.IsEmpty())
return;
ResourceLoaderOptions options;
options.initiator_info.name = FetchInitiatorTypeNames::css;
FetchParameters params(ResourceRequest(url_), options);
document_ = DocumentResource::FetchSVGDocument(params, document.Fetcher());
url_ = String();
}
TreeScope* SVGElementProxy::TreeScopeForLookup(TreeScope& tree_scope) const {
if (is_local_)
return &tree_scope;
if (!document_)
return nullptr;
return document_->GetDocument();
}
SVGElement* SVGElementProxy::FindElement(TreeScope& tree_scope) {
// An empty id will never be a valid element reference.
if (id_.IsEmpty())
return nullptr;
TreeScope* lookup_scope = TreeScopeForLookup(tree_scope);
if (!lookup_scope)
return nullptr;
if (Element* target_element = lookup_scope->getElementById(id_)) {
SVGElementProxySet* proxy_set =
target_element->IsSVGElement()
? ToSVGElement(target_element)->ElementProxySet()
: nullptr;
if (proxy_set) {
proxy_set->Add(*this);
return ToSVGElement(target_element);
}
}
return nullptr;
}
void SVGElementProxy::ContentChanged(TreeScope& tree_scope) {
if (auto* observer = observers_.at(&tree_scope))
observer->ContentChanged();
}
DEFINE_TRACE(SVGElementProxy) {
visitor->Trace(clients_);
visitor->Trace(observers_);
visitor->Trace(document_);
}
void SVGElementProxySet::Add(SVGElementProxy& element_proxy) {
element_proxies_.insert(&element_proxy);
}
bool SVGElementProxySet::IsEmpty() const {
return element_proxies_.IsEmpty();
}
void SVGElementProxySet::NotifyContentChanged(TreeScope& tree_scope) {
for (SVGElementProxy* proxy : element_proxies_)
proxy->ContentChanged(tree_scope);
}
DEFINE_TRACE(SVGElementProxySet) {
visitor->Trace(element_proxies_);
}
} // namespace blink | c++ | 16 | 0.707911 | 79 | 30.287129 | 202 | starcoderdata |
@Override /* PetStore */
@RestMethod(
name=GET,
path="/pet",
summary="All pets in the store",
swagger=@MethodSwagger(
tags="pet",
parameters={
Queryable.SWAGGER_PARAMS // Documents searching.
}
),
converters={Queryable.class} // Searching support.
)
@BeanConfig(
bpx="Pet: tags,photo" // In this view, don't serialize tags/photos properties.
)
public Collection<Pet> getPets() throws NotAcceptable {
return store.getPets();
} | java | 11 | 0.648649 | 81 | 23.421053 | 19 | inline |
<?php return array(
// The alias Underscore will be mapped to
'alias' => 'Underscore',
// Various aliases for methods, you can specify your own
'aliases' => array(
'contains' => 'find',
'getLast' => 'last',
'select' => 'filter',
'sortBy' => 'sort',
),
); | php | 7 | 0.504673 | 60 | 21.928571 | 14 | starcoderdata |
<?php
namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Event;
use DB;
class AllTeamController extends Controller
{
public function index(){
$eventfoot = Event::latest()->paginate(3);
$playerfoot = DB::table('player')
->select('player.*','users.*','game.nama_game','team.nama_team')
->leftjoin('users','users.id','=','player.id')
->leftjoin('game','game.id_game','=','player.id_game')
->leftjoin('team','team.id_team','=','player.id_team')
->where('users.is_active','1')
->latest('player.created_at')
->paginate(3);
$datateam = DB::table('team')
->select('team.*','game.id_game','game.nama_game','coach.id_coach','users.*',DB::raw('count(player.id_player) as total_player'),)
->join('game','game.id_game','=','team.id_game')
->join('coach','coach.id_coach','=','team.id_coach')
->join('users','users.id','=','coach.id')
->leftjoin('player','player.id_team','=','team.id_team')
->groupBy('team.id_team')
->get();
$tour = DB::table('event')
->select('event.*','game.nama_game')
->leftjoin('game','game.id_game','=','event.id_game')
->latest('event.created_at')->paginate(1);
return view('frontend.team-all', compact('eventfoot','playerfoot','datateam','tour'));
}
public function show($id_team){
$eventfoot = Event::latest()->paginate(3);
$playerfoot = DB::table('player')
->select('player.*','users.*','game.nama_game','team.nama_team')
->leftjoin('users','users.id','=','player.id')
->leftjoin('game','game.id_game','=','player.id_game')
->leftjoin('team','team.id_team','=','player.id_team')
->where('users.is_active','1')
->latest('player.created_at')
->paginate(3);
$datacoach = DB::table('team')
->select('team.*','coach.*','users.*')
->join('coach','coach.id_coach','=','team.id_coach')
->join('users','users.id','=','coach.id')
->where('users.is_active',1)
->where('team.id_team',$id_team)
->get();
// dd($datacoach);
$dataplayer = DB::table('team')
->select('team.*','users.*','player.*',DB::raw('count(player.id_player) as total_player'),)
->join('player','player.id_team','=','team.id_team')
->join('users','users.id','=','player.id')
->where('users.is_active',1)
->where('player.id_team',$id_team)
->get();
$player = DB::table('team')
->select('team.*','users.*','player.*')
->join('player','player.id_team','=','team.id_team')
->join('users','users.id','=','player.id')
->where('users.is_active',1)
->where('player.id_team',$id_team)
->get();
// dd($player);
return view('frontend.team-detail',compact('eventfoot','playerfoot','datacoach','dataplayer','player'));
}
} | php | 20 | 0.423802 | 157 | 52.753425 | 73 | starcoderdata |
# -*- coding: utf-8 -*-
"""
This example benchmarks the performances of a ray tracer with the 2D and 3D
Eikonal solvers on a stratified medium.
Author:
License: MIT
"""
import numpy as np
import time
from raytracer.raytracer import Ray3D
try:
from fteikpy import Eikonal, lay2vel, lay2tt
except ImportError:
import sys
sys.path.append("../")
from fteikpy import Eikonal, lay2vel, lay2tt
if __name__ == "__main__":
# Parameters
sources = np.loadtxt("shots.txt")
receivers = np.loadtxt("stations.txt")
dz, dx, dy = 2.5, 2.5, 2.5
nz, nx, ny = 400, 280, 4
n_threads = 8
# Make a layered velocity model
lay = 1500. + 250. * np.arange(10)
zint = 100. + 100. * np.arange(10)
vel2d = lay2vel(np.hstack((lay[:,None], zint[:,None])), dz, (nz, nx))
vel3d = np.tile(vel2d[:,:,None], ny)
# Ray tracer
start_time = time.time()
ray = Ray3D()
tcalc_ray = ray.lay2tt(sources[:,[1,2,0]], receivers[:,[1,2,0]], lay, zint)
print("Ray tracer: %.3f seconds" % (time.time() - start_time))
# Eikonal 2D
start_time = time.time()
tcalc_eik2d = lay2tt(vel2d, (dz, dx), sources, receivers, n_sweep = 2, n_threads = n_threads)
print("\nEikonal 2D: %.3f seconds" % (time.time() - start_time))
print("Mean residual (2D): ", (tcalc_eik2d - tcalc_ray).mean())
# Eikonal 3D
start_time = time.time()
eik3d = Eikonal(vel3d, (dz, dx, dy), n_sweep = 2)
tt = eik3d.solve(sources, n_threads = n_threads)
tcalc_eik3d = np.array([ [ grid.get(z, x, y, check = False) for z, x, y in receivers ]
for grid in tt ]).transpose()
print("\nEikonal 3D: %.3f seconds" % (time.time() - start_time))
print("Mean residual (3D): ", (tcalc_eik3d - tcalc_ray).mean()) | python | 14 | 0.595721 | 97 | 31.571429 | 56 | starcoderdata |
module.exports = {
mockMap: new Map(),
mock: function (realFunction, fakeFunction) {
this.mockMap.set(fakeFunction, realFunction);
return fakeFunction;
},
unmock: function (fakeFunction) {
const realFunction = this.mockMap.get(fakeFunction);
this.mockMap.delete(fakeFunction);
return realFunction;
}
}; | javascript | 11 | 0.645503 | 60 | 28.076923 | 13 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Genus.Migrator.Migrations.Design
{
public class IndentedStringBuilder
{
private readonly StringBuilder _builder = new StringBuilder();
private int _indent = 0;
private const char indentChar = ' ';
private const int indentSize = 4;
private string NewLine => Environment.NewLine + new string(indentChar, indentSize * _indent);
public IndentedStringBuilder Append(object value, bool ignoreIndent=false)
{
var strVal = value.ToString();
if(!ignoreIndent)
strVal.Replace(Environment.NewLine, this.NewLine);
_builder.Append(value);
return this;
}
public IndentedStringBuilder AppendNewLine(object value)
{
return AppendLine("").Append(value);
}
public IndentedStringBuilder AppendLine(object value)
{
Append(value);
_builder.Append(this.NewLine);
return this;
}
public void Clear() => _builder.Clear();
public IndentedStringBuilder Indent()
{
_indent++;
return this;
}
public IndentedStringBuilder DeIndent()
{
if (_indent > 0)
_indent--;
return this;
}
public Indenter Indenter() => new Indenter(this);
public override string ToString() => _builder.ToString();
}
public class Indenter : IDisposable
{
private readonly IndentedStringBuilder _builder;
public Indenter(IndentedStringBuilder builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
_builder = builder;
builder.Indent();
}
public void Dispose() => _builder.DeIndent();
}
} | c# | 15 | 0.581513 | 101 | 26.732394 | 71 | starcoderdata |
#ifdef ZIMG_X86
#include "common/ccdep.h"
#include
#include "common/align.h"
#include "f16c_x86.h"
#include "common/x86/sse2_util.h"
#include "common/x86/avx_util.h"
namespace zimg {
namespace depth {
void f16c_half_to_float_ivb(const void *src, void *dst, unsigned left, unsigned right)
{
const uint16_t *src_p = static_cast<const uint16_t *>(src);
float *dst_p = static_cast<float *>(dst);
unsigned vec_left = ceil_n(left, 8);
unsigned vec_right = floor_n(right, 8);
if (left != vec_left) {
__m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_left - 8)));
mm256_store_idxhi_ps(dst_p + vec_left - 8, x, left % 8);
}
for (unsigned j = vec_left; j < vec_right; j += 8) {
__m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + j)));
_mm256_store_ps(dst_p + j, x);
}
if (right != vec_right) {
__m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_right)));
mm256_store_idxlo_ps(dst_p + vec_right, x, right % 8);
}
}
void f16c_float_to_half_ivb(const void *src, void *dst, unsigned left, unsigned right)
{
const float *src_p = static_cast<const float *>(src);
uint16_t *dst_p = static_cast<uint16_t *>(dst);
unsigned vec_left = ceil_n(left, 8);
unsigned vec_right = floor_n(right, 8);
if (left != vec_left) {
__m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_left - 8), 0);
mm_store_idxhi_epi16((__m128i *)(dst_p + vec_left - 8), x, left % 8);
}
for (unsigned j = vec_left; j < vec_right; j += 8) {
__m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + j), 0);
_mm_store_si128((__m128i *)(dst_p + j), x);
}
if (right != vec_right) {
__m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_right), 0);
mm_store_idxlo_epi16((__m128i *)(dst_p + vec_right), x, right % 8);
}
}
} // namespace depth
} // namespace zimg
#endif // ZIMG_X86 | c++ | 20 | 0.615633 | 86 | 27.106061 | 66 | starcoderdata |
int main() {
int num;
printf("Cuantos elementos desea Introducir: ");
scanf("%d", &num);
// Se declara un arreglo del número de elementos que se introdujo
int Elementos[num];
/**
* Ciclo que permite leer la información del arreglo desde teclado
*/
for (int i=0; i<num; i++){
printf("Introduzca el elemento %d: ", (i+1));
scanf("%d", &Elementos[i]);
}
int par = 0, impar =0;
/**
* Ciclo que permite contar cuantos elementos son pares y cuantos son impares.
*/
for (int i=0; i<num; i++){
if (Elementos[i]%2==0){
par++;
} else {
impar++;
}
}
printf("De los elementos que se introdujeron %d son pares y %d impares\n", par, impar);
/**
* Ciclo que permite imprimir cuales de los elementos son pares
*/
for (int i=0; i<num; i++){
if (Elementos[i]%2==0){
printf("%d ", Elementos[i]);
}
}
return 0;
} | c | 11 | 0.514881 | 92 | 24.225 | 40 | inline |
/**
* Created by MomoLuaNative.
* Copyright (c) 2019, Momo Group. All rights reserved.
*
* This source code is licensed under the MIT.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
package com.immomo.mls.fun.ud.anim.interpolator;
import android.view.animation.Interpolator;
/**
* Created by wang.yang on 2020-04-16
*/
public class SpringInterpolator implements Interpolator {
private final float damping;
private final float mass;
private final float stiffness;
public SpringInterpolator() {
this(1, 100, 10);
}
public SpringInterpolator(float mass, float stiffness, float damping) {
this.mass = mass;
this.stiffness = stiffness;
this.damping = damping;
}
@Override
public float getInterpolation(float input) {
float beta = damping / (2 * mass);
float omega0 = (float) Math.sqrt(stiffness / mass);
float omega1 = (float) Math.sqrt((omega0 * omega0) - (beta * beta));
float omega2 = (float) Math.sqrt((beta * beta) - (omega0 * omega0));
float x0 = -1;
float v0 = 0;
float envelope = (float) Math.exp(-beta * input);
if (beta < omega0) {
return -x0 + envelope * (x0 * ((float) Math.cos(omega1 * input)) + ((beta * x0 + v0) / omega1) * ((float) Math.sin(omega1 * input)));
} else if (beta == omega0) {
return -x0 + envelope * (x0 + (beta * x0 + v0) * input);
} else {
return -x0 + envelope * (x0 * ((float) Math.cos(omega2 * input)) + ((beta * x0 + v0) / omega2) * ((float) Math.sin(omega2 * input)));
}
}
} | java | 19 | 0.610307 | 145 | 34.979167 | 48 | starcoderdata |
package org.motechproject.csd.domain;
import org.motechproject.csd.constants.CSDConstants;
import org.motechproject.mds.annotations.Access;
import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;
import org.motechproject.mds.annotations.UIDisplayable;
import org.motechproject.mds.util.SecurityMode;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* The text content of this element may optionally be used to provide translations to the local language of a coded value.
*
* class for codedtype complex type.
*
* following schema fragment specifies the expected content contained within this class.
*
*
* <complexType name="codedtype">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="code" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="codingScheme" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* </extension>
* </simpleContent>
* </complexType>
*
*
*
*/
@Entity
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
@Access(value = SecurityMode.PERMISSIONS, members = {CSDConstants.MANAGE_CSD})
public class CodedType extends AbstractID {
/* The value of Coded Type eg */
@UIDisplayable(position = 0)
@Field(tooltip = "The human readable value for that code (i.e. \"Community Health Worker\").")
private String value = "";
/* Attribute @code */
@UIDisplayable(position = 1)
@Field(required = true, tooltip = "The code provided by the coding organization (i.e. \"3253\").")
private String code;
/* Attribute @codingScheme*/
@UIDisplayable(position = 2)
@Field(required = true, tooltip = "The coding scheme used to identify this code (i.e. \"ISCO-08\").")
private String codingScheme;
public CodedType() {
}
public CodedType(String code, String codingScheme) {
this.code = code;
this.codingScheme = codingScheme;
}
public CodedType(String value, String code, String codingScheme) {
this.value = value;
this.code = code;
this.codingScheme = codingScheme;
}
public String getValue() {
return value;
}
@XmlValue
public void setValue(String value) {
this.value = value;
}
public String getCode() {
return code;
}
@XmlAttribute(required = true)
public void setCode(String code) {
this.code = code;
}
public String getCodingScheme() {
return codingScheme;
}
@XmlAttribute(required = true)
public void setCodingScheme(String codingScheme) {
this.codingScheme = codingScheme;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CodedType codedType = (CodedType) o;
if (!code.equals(codedType.code)) {
return false;
}
if (!codingScheme.equals(codedType.codingScheme)) {
return false;
}
if (value != null ? !value.equals(codedType.value) : codedType.value != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = value != null ? value.hashCode() : 0;
result = 31 * result + code.hashCode();
result = 31 * result + codingScheme.hashCode();
return result;
}
@Override
public String toString() {
if (value != null && !value.isEmpty()) {
return value;
}
return code;
}
} | java | 12 | 0.641681 | 122 | 27.824818 | 137 | starcoderdata |
const rosebot = require("./rosebot");
const prompt = require('prompt-sync')({sigint: true});
function main() {
console.log('--------------------------------------------------')
console.log('Testing the SERVO classes of a robot')
console.log('--------------------------------------------------')
robot = new rosebot.RoseBot();
// Allow the I2C module an opportunity to finish initialization.
setTimeout(() => {
run_servo_test();
}, 50);
}
function run_servo_test() {
console.log("Type in a servo number. Options:")
console.log("11 --> Camera Tilt");
console.log("12 --> Arm Joint 1");
console.log("13 --> Arm Joint 2");
console.log("14 --> Arm Joint 3");
console.log("15 --> Gripper");
let servoNumber = parseInt(prompt("Servo number (11 to 15) or (0 to exit): "));
if (servoNumber == 0) {
return;
}
let pulseWidth = parseInt(prompt('Pulse width (500 to 2500): '));
if (pulseWidth == 0) {
return;
}
// prompt('Press the ENTER key when ready for the robot to start moving.');
if (servoNumber == 11) {
robot.cameraServo.setPulseWidth(pulseWidth);
} else if (servoNumber == 12) {
robot.armServos.setPulseWidth(1, pulseWidth);
} else if (servoNumber == 13) {
robot.armServos.setPulseWidth(2, pulseWidth);
} else if (servoNumber == 14) {
robot.armServos.setPulseWidth(3, pulseWidth);
} else if (servoNumber == 15) {
robot.gripperServo.setPulseWidth(pulseWidth);
}
// Allow the I2C an opportunity to run.
setTimeout(() => {
run_servo_test();
}, 50);
}
main(); | javascript | 18 | 0.603394 | 81 | 30.215686 | 51 | starcoderdata |
@Test
public void testAutoRemoveWhenSetToTrue() throws Exception {
requireDockerApiVersionAtLeast("1.25", "AutoRemove");
// Container should be removed after it is stopped (new since API v.1.25)
// Pull image
sut.pull(BUSYBOX_LATEST);
final ContainerConfig config = ContainerConfig.builder()
.image(BUSYBOX_LATEST)
.hostConfig(HostConfig.builder()
.autoRemove(true) // Default is false
.build())
.build();
final ContainerCreation container = sut.createContainer(config, randomName());
final ContainerInfo info = sut.inspectContainer(container.id());
assertThat(info.hostConfig().autoRemove(), is(true));
sut.startContainer(container.id());
sut.stopContainer(container.id(), 5);
await().until(containerIsRunning(sut, container.id()), is(false));
// A ContainerNotFoundException should be thrown since the container is removed when it stops
exception.expect(ContainerNotFoundException.class);
sut.inspectContainer(container.id());
} | java | 12 | 0.684161 | 97 | 38.555556 | 27 | inline |
package org.firstinspires.ftc.teamcode.freightfrenzy2021.opmodes.autonroutines;
import java.util.ArrayList;
public abstract class EbotsAutonRoutine {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instance Attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
protected ArrayList itinerary = new ArrayList<>();
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Getters & Setters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
public ArrayList getRoutineItinerary() {
return itinerary;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instance Methods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
} | java | 8 | 0.428788 | 79 | 25.4 | 25 | starcoderdata |
def find_modules_with_subcommands():
# Get the modules that were named precisely
modules = CLI_MODULES
# Obtain the modules we infer from the list of packages
packages = PACKAGES_WITH_CLI
package_modules = map(lambda m: m + '.cli', packages)
# Combine those two into one generator of CLI modules
return itertools.chain(modules, package_modules) | python | 10 | 0.716578 | 59 | 36.5 | 10 | inline |
package cz.ilasek.namedentities.disambiguation;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import cz.ilasek.namedentities.index.dao.sql.EntityMentionsDao;
import cz.ilasek.namedentities.index.models.Entity;
import cz.ilasek.namedentities.models.DisambiguatedEntity;
public class SpotlightDisambiguation {
private static final String CONTEXT_FIELD = "context";
private static final String ENTITY_URI_FIELD = "entity_uri";
private static final String ENTITY_ID_FIELD = "entity_id";
private final EntityMentionsDao entityMetionsDao;
private StandardAnalyzer analyzer;
private Directory index;
public SpotlightDisambiguation(EntityMentionsDao entityMetionsDao) {
this.entityMetionsDao = entityMetionsDao;
analyzer = new StandardAnalyzer(Version.LUCENE_35);
}
public List disambiguateEntity(String entityName, String context, int limit) {
List candidates = entityMetionsDao.findCandidates(entityName);
try {
createNewIndex();
IndexWriter w = getIndexWriter();
// System.out.println("============================");
// System.out.println("Candidates for " + entityName);
// System.out.println("============================");
for (Entity candidate : candidates) {
// System.out.println(candidate.getUri());
StringBuilder sb = new StringBuilder();
List paragraphs = entityMetionsDao.getEntityMentionParagraphs(candidate.getId(), 100);
for (String paragraph : paragraphs) {
sb.append(" ");
sb.append(paragraph);
}
addDoc(w, candidate.getId(), candidate.getUri(), sb.toString());
}
w.close();
try {
return findBestMatches(entityName, context, limit);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private Directory createNewIndex() {
index = new RAMDirectory();
return index;
}
private IndexWriter getIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException {
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
return new IndexWriter(index, config);
}
private IndexSearcher getIndexSearcher() throws CorruptIndexException, IOException {
IndexReader reader = IndexReader.open(index);
return new IndexSearcher(reader);
}
private List findBestMatches(String entityName, String context, int limit) throws ParseException, CorruptIndexException, IOException {
List disambiguations = new LinkedList
Query q = new QueryParser(Version.LUCENE_35, CONTEXT_FIELD, analyzer).
parse(context);
TopScoreDocCollector collector = TopScoreDocCollector.create(limit, true);
IndexSearcher searcher = getIndexSearcher();
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
for (int i = 0; (i < hits.length) && (i < limit); i++) {
int bestId = hits[i].doc;
Document d = searcher.doc(bestId);
DisambiguatedEntity entity = new DisambiguatedEntity();
entity.setEntityId(new Long(d.get(ENTITY_ID_FIELD)));
entity.setUri(d.get(ENTITY_URI_FIELD));
entity.setName(entityName);
entity.setStringScore(hits[i].score);
disambiguations.add(entity);
searcher.close();
}
return disambiguations;
}
private static void addDoc(IndexWriter w, long entityId, String entityUri, String context) throws CorruptIndexException, IOException {
Document doc = new Document();
doc.add(new Field(ENTITY_ID_FIELD, "" + entityId, Field.Store.YES, Field.Index.NO));
doc.add(new Field(ENTITY_URI_FIELD, entityUri, Field.Store.YES, Field.Index.NO));
doc.add(new Field(CONTEXT_FIELD, context, Field.Store.YES, Field.Index.ANALYZED));
w.addDocument(doc);
}
} | java | 15 | 0.651671 | 159 | 40.058394 | 137 | starcoderdata |
"use strict";
var _ = require('lodash');
module.exports = function(action, options) {
if (_.isFunction(action.uses)) {
return action;
}
throw new Error('Non-function actions are not supported in the default action handler. Overwrite "actionHandler" to support your case.');
}; | javascript | 8 | 0.676282 | 141 | 25 | 12 | starcoderdata |
<?php namespace App\Repositories\website\blogger;
interface BloggerContract
{
} | php | 3 | 0.79646 | 49 | 11.666667 | 9 | starcoderdata |
#!/usr/bin/env node
"use strict";
const generate = require("./generate.js");
const program = require("commander");
program
.usage("-i image directory")
.option("-i, --input "image directory", String);
program
.usage("-o output file path")
.option("-o, --output "output file path", String, "./images.xlsx");
program.parse(process.argv);
generate(program.input, program.output); | javascript | 3 | 0.669048 | 78 | 22.333333 | 18 | starcoderdata |
using System;
using System.Collections.Generic;
namespace Base.Runtime
{
[Serializable]
public class ComponentInfo
{
public string name;
public string path;
public Dictionary<string, PropertyInfo> properties;
}
[Serializable]
public class PropertyInfo
{
public string name;
public string type;
public bool isArray;
public bool editable;
}
} | c# | 9 | 0.652361 | 59 | 19.304348 | 23 | starcoderdata |
(function () {
'use strict';
var testCase = require('nodeunit').testCase;
var http = require('http');
var Q = require('q');
function sendRequest(method, host, port, path, jsonBody) {
var deferred = Q.defer();
var body = (typeof jsonBody === "string" ? jsonBody : JSON.stringify(jsonBody || ""));
var options = {
method: method,
host: host,
path: path,
port: port
};
var req = http.request(options);
req.once('response', function (response) {
var data = '';
if (response.statusCode === 400 || response.statusCode === 404) {
deferred.reject(response.statusCode);
}
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
deferred.resolve({
statusCode: response.statusCode,
body: data
});
});
});
req.once('error', function (error) {
deferred.reject(error);
});
req.write(body);
req.end();
return deferred.promise;
}
exports.mock_server_started = {
'mock server should have started': testCase({
'should allows expectation to be setup': function (test) {
test.expect(2);
sendRequest("PUT", "localhost", 1080, "/expectation", {
'httpRequest': {
'path': '/somePath'
},
'httpResponse': {
'statusCode': 202,
'body': JSON.stringify({ name: 'first_body' })
}
})
.then(function (response) {
test.equal(response.statusCode, 201, "allows expectation to be setup");
}, function () {
test.ok(false, "failed to setup expectation");
})
.then(function () {
sendRequest("GET", "localhost", 1080, "/somePath")
.then(function (response) {
test.equal(response.statusCode, 202, "expectation matched sucessfully");
}, function () {
test.ok(false, "failed to match expectation");
})
.then(function () {
// end
test.done();
});
});
}
})
};
})(); | javascript | 30 | 0.417685 | 104 | 31.348837 | 86 | starcoderdata |
<?php
namespace App\Models;
use App\Http\Resources\ReportResource;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Report extends Model
{
use HasFactory;
protected $fillable = [ 'title','description','status','user_id','agency_id'];
// RELATIONSHIP ON THE OTHER TABLE
public function agency () {
return $this->belongsTo(Agency::class);
}
// ACTIONS
public function list () {
return ReportResource::collection(Report::all());
}
} | php | 11 | 0.68547 | 82 | 19.172414 | 29 | starcoderdata |
def test__keypath(self):
expected = {
'foo': {
'bar': 'hello',
# the only change from input is the second entry here
'baz': [1, 'hello', '990', '89.9'],
},
'nested': [
{
'test': '90',
'other_test': None,
},
{
'test': 400,
'other_test': 4.7e9,
},
],
}
actual = dbt.utils.deep_map(self.special_keypath, self.input_value)
self.assertEqual(actual, expected)
actual = dbt.utils.deep_map(self.special_keypath, expected)
self.assertEqual(actual, expected) | python | 11 | 0.402985 | 75 | 31.086957 | 23 | inline |
package org.daboodb.daboo.shared.compression;
import com.google.common.primitives.Bytes;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4FastDecompressor;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Abstract superclass for LZ4-based compression algorithms. Subclasses implement LZ4 with the compression rate set
* to some point in the allowable range:
*
* The "Fast" version provides minimal compression.
* The "High Compression" version provides the best compression, with the slowest performance.
* The Moderate version splits the difference for both speed and compression ratio.
*
* Implementation note:
* LZ4 requires that the size of the original message be known at decompression time, so it can allocate an
* appropriately sized byte array for the results. To support this, we append the uncompressed length (an integer)
* as four bytes to the end of the compressed data when compression, and pull those four bytes off the end to convert
* back to an int for use when decompressing.
*/
public abstract class LZ4AbstractCompressor implements CompressorDeCompressor {
private final LZ4Compressor compressor;
private final LZ4FastDecompressor decompressor;
LZ4AbstractCompressor(LZ4Compressor compressor, LZ4FastDecompressor decompressor) {
this.compressor = compressor;
this.decompressor = decompressor;
}
public LZ4Compressor getCompressor() {
return compressor;
}
private LZ4FastDecompressor getDecompressor() {
return decompressor;
}
@Override
public byte[] compress(byte[] uncompressedBytes) {
byte[] compressed = compressor.compress(uncompressedBytes);
// see implementation note in class comment regarding storing the uncompressed length
byte[] lengthBytes = ByteBuffer.allocate(4).putInt(uncompressedBytes.length).array();
return Bytes.concat(compressed, lengthBytes);
}
@Override
public byte[] decompress(byte[] compressedBytes) {
// see implementation note in class comment regarding storing the uncompressed length
int decompressedLength =
bytesToInt(Arrays.copyOfRange(compressedBytes, compressedBytes.length - 4, compressedBytes.length));
byte[] actualCompressedBytes = Arrays.copyOf(compressedBytes, compressedBytes.length - 4);
// put the decompressed bytes here
byte[] destination = new byte[decompressedLength];
getDecompressor().decompress(actualCompressedBytes, 0, destination, 0, decompressedLength);
return destination;
}
/**
* Returns an int equivalent derived from the given byte array
* @param arr An array of bytes representing a single integer in standard Java Big-Endian format
*/
private int bytesToInt(byte[] arr) {
ByteBuffer bb = ByteBuffer.wrap(arr);
return bb.getInt();
}
} | java | 13 | 0.766193 | 117 | 36.986842 | 76 | starcoderdata |
var testContext = require.context('../src', true, /\.spec\.(ts|tsx)$/);
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
var modules = requireAll(testContext); | javascript | 7 | 0.751773 | 76 | 34.25 | 8 | starcoderdata |
import tensorflow as tf
import numpy as np
# Create some layer wrappers for simplicity
def conv2d(x, W, b, strides=1, padding = "VALID", name=None):
# Conv2D wrapper, with bias and relu activation
with tf.name_scope(name):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding = padding, name = name)
x = tf.nn.bias_add(x, b)
x = tf.nn.relu(x)
return x
def maxpool2d(x, k=2, padding = "VALID", name = None):
# MaxPool2D wrapper
with tf.name_scope(name):
x = tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding= padding)
return x
def batch_normalization(x, is_training=True, scale=True, updates_collections=None, name = None):
with tf.name_scope(name):
x = tf.contrib.layers.batch_norm(x, is_training=is_training, scale=scale, updates_collections=updates_collections)
return x
def weight_variable(shape, stddev = 0.02, name = None):
initial = tf.truncated_normal(shape, stddev = stddev)
#initial = tf.contrib.layers.xavier_initializer(uniform=False)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer = initial)
def bias_variable(shape, name = None):
initial = tf.constant(0.0, shape = shape)
#initial = tf.contrib.layers.xavier_initializer(uniform=False)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer = initial)
def gaussian(size, sigma = 1.0):
x, y = np.mgrid[-size:size + 1, -size: size + 1]
g = np.exp(-(x**2+y**2)/float(sigma))
return g / g.sum()
def smooth(layer, name = None):
kernel = gaussian(2)
kernel = tf.cast(tf.reshape(kernel, [5, 5, 1, 1]), tf.float32)
return tf.nn.conv2d(layer, kernel, [1, 1, 1, 1], padding='VALID', name = name) | python | 12 | 0.623849 | 123 | 36.372549 | 51 | starcoderdata |
from opentracing.ext import tags
from ..utils import get_logger
logger = get_logger(__name__)
class RequestHandler:
def __init__(self, tracer, context=None, ignore_active_span=True):
self.tracer = tracer
self.context = context
self.ignore_active_span = ignore_active_span
def before_request(self, request, request_context):
logger.info("Before request %s", request)
# If we should ignore the active Span, use any passed SpanContext
# as the parent. Else, use the active one.
if self.ignore_active_span:
span = self.tracer.start_span(
"send", child_of=self.context, ignore_active_span=True
)
else:
span = self.tracer.start_span("send")
span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
request_context["span"] = span
def after_request(self, request, request_context):
# pylint: disable=no-self-use
logger.info("After request %s", request)
span = request_context.get("span")
if span is not None:
span.finish() | python | 13 | 0.617806 | 73 | 29.888889 | 36 | starcoderdata |
package io.honeycomb.beeline.spring.e2e;
import io.honeycomb.libhoney.eventdata.ResolvedEvent;
import io.honeycomb.libhoney.responses.ResponseObservable;
import io.honeycomb.libhoney.transport.Transport;
import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.get;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.springframework.http.HttpStatus.OK;
@SuppressWarnings({"unchecked", "SpringJavaInjectionPointsAutowiringInspection"})
@RunWith(SpringRunner.class)
@ActiveProfiles("path-pattern-test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PathPatternTest {
private ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(ResolvedEvent.class);
// replace the transport from the BeelineAutoconfig with mock, so we can capture and inspect events to be sent to honeycomb
@MockBean
private Transport transport;
@LocalServerPort
private int port;
private void setTransportStubs() {
when(transport.submit(any(ResolvedEvent.class))).thenReturn(true);
when(transport.getResponseObservable()).thenReturn(mock(ResponseObservable.class));
}
@Before
public void setup() {
setTransportStubs();
RestAssured.port = port;
}
@Test
public void GIVEN_pathIsOnAllowlist_EXPECT_requestToProduceSpans() {
// WHEN hitting an instrumented web service with a trace header
get("/allowlist/basic-get").then().statusCode(OK.value()).body(is("hello"));
final Map<String, Object> eventFields = captureNoOfEvents(1).get(0).getFields();
assertThat(eventFields).containsEntry("response.status_code", 200);
assertThat(eventFields).containsEntry("endpoint", "allowlist");
}
@Test
public void GIVEN_pathIsOnDenylist_EXPECT_requestToNotProduceAnySpans() {
get("/denylist/basic-get").then().statusCode(OK.value()).body(is("olleh"));
verify(transport, after(200).never()).submit(any(ResolvedEvent.class));
}
@Test
public void GIVEN_allowlistedRndpointForwardsToDenylistedEndpoints_EXPECT_denylistToNotApplyToForwarding() {
get("/allowlist/forward-to-denylist").then().statusCode(OK.value()).body(is("olleh"));
final List eventFields = captureNoOfEvents(2);
final ResolvedEvent forwardEvent = eventFields.get(0);
final ResolvedEvent requestEvent = eventFields.get(1);
assertThat(forwardEvent.getFields()).containsEntry("endpoint", "denylist");
assertThat(requestEvent.getFields()).containsEntry("endpoint", "forward");
}
private List captureNoOfEvents(final int times) {
verify(transport, timeout(1000).times(times)).submit(eventCaptor.capture());
return eventCaptor.getAllValues();
}
} | java | 14 | 0.754164 | 127 | 39.022989 | 87 | starcoderdata |
"""
Vertex
======
"""
import numpy as np
class Vertex:
"""
An abstract base class for :class:`.TopologyGraph` vertices.
Notes
-----
You might notice that some of the public methods of this abstract
base class are implemented. This is purely for convenience when
implementing subclasses. The implemented public methods are
simply default implementations, which can be safely ignored or
overridden, when implementing subclasses. Any private methods are
implementation details of these default implementations.
"""
def __init__(self, id, position):
"""
Initialize a :class:`.Vertex`.
Parameters
----------
id : :class:`int`
The id of the vertex.
position : :class:`tuple` of :class:`float`
The position of the vertex.
"""
self._id = id
self._position = np.array(position, dtype=np.float64)
def get_id(self):
"""
Get the id.
Returns
-------
:class:`int`
The id.
"""
return self._id
def _with_scale(self, scale):
"""
Modify the vertex.
"""
self._position *= scale
return self
def with_scale(self, scale):
"""
Get a clone with a scaled position.
Parameters
----------
scale : :class:`float` or :class:`tuple` of :class:`float`
The value by which the position of the :class:`Vertex` is
scaled. Can be a single number if all axes are scaled by
the same amount or a :class:`tuple` of three numbers if
each axis is scaled by a different value.
Returns
-------
:class:`.Vertex`
The clone. Has the same type as the original vertex.
"""
return self.clone()._with_scale(scale)
def clone(self):
"""
Return a clone.
Returns
-------
:class:`.Vertex`
The clone.
"""
clone = self.__class__.__new__(self.__class__)
Vertex.__init__(clone, self._id, self._position)
return clone
def get_position(self):
"""
Get the position.
Returns
-------
:class:`numpy.ndarray`
The position of the :class:`Vertex`.
"""
return np.array(self._position)
def _with_position(self, position):
"""
Modify the vertex.
"""
self._position = np.array(position, dtype=np.float64)
return self
def with_position(self, position):
"""
Get a clone at a certain position.
Parameters
----------
position : :class:`numpy.ndarray`
The desired position of the clone.
Returns
-------
:class:`.Vertex`
The clone. Has the same type as the original vertex.
"""
return self.clone()._with_position(position)
def get_cell(self):
"""
Get the cell of the lattice in which the vertex is found.
Returns
-------
:class:`numpy.ndarray`
The cell of the lattice in which the vertex is found.
"""
return np.array([0, 0, 0])
def place_building_block(self, building_block, edges):
"""
Place `building_block` on the :class:`.Vertex`.
Parameters
----------
building_block : :class:`.BuildingBlock`
The building block molecule which is to be placed on the
vertex.
edges : :class:`tuple` of :class:`.Edge`
The edges to which the vertex is attached.
Returns
-------
:class:`numpy.nadarray`
The position matrix of `building_block` after being
placed.
"""
raise NotImplementedError()
def map_functional_groups_to_edges(self, building_block, edges):
"""
Map functional groups to edges.
Each functional group in `building_block` needs to be assigned
to an edge in `edges`.
Parameters
----------
building_block : :class:`.BuildingBlock`
The building block which is needs to have functional
groups assigned to edges.
edges : :class:`tuple` of :class:`.Edge`
The edges to which the vertex is attached.
Returns
-------
:class:`dict`
A mapping from the id of a functional group in
`building_block` to the id of the edge in `edges` it
is assigned to.
"""
raise NotImplementedError()
def __str__(self):
position = self._position.tolist()
return f'Vertex(id={self._id}, position={position})'
def __repr__(self):
return str(self) | python | 11 | 0.533004 | 70 | 22.267943 | 209 | starcoderdata |
package guard_test
import (
"fmt"
"time"
"github.com/kezhuw/guard"
)
func ExampleGuard() {
var guard guard.Guard
l0 := guard.NewLocker()
l1 := guard.NewLocker()
go func() {
time.Sleep(time.Millisecond * 500)
l0.Lock()
fmt.Println("l0 locked.")
l0.Unlock()
}()
l1.Lock()
fmt.Println("l1 locked.")
l1.Unlock()
// Output:
// l0 locked.
// l1 locked.
}
func ExampleRWGuard() {
var guard guard.RWGuard
r0 := guard.NewReader()
r1 := guard.NewReader()
w0 := guard.NewWriter()
r0.Lock()
done := make(chan struct{})
go func() {
time.Sleep(time.Millisecond * 500)
r1.Lock()
fmt.Println("r1 locked.")
r1.Unlock()
}()
go func() {
w0.Lock()
fmt.Println("w0 locked.")
w0.Unlock()
close(done)
}()
fmt.Println("r0 locked.")
r0.Unlock()
<-done
// Output:
// r0 locked.
// r1 locked.
// w0 locked.
} | go | 12 | 0.613555 | 36 | 14.574074 | 54 | starcoderdata |
// ////////////////////////////////////////////////////////
// # Title
// Sub-string divisibility
//
// # URL
// https://projecteuler.net/problem=43
// http://euler.stephan-brumme.com/43/
//
// # Problem
// The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order,
// but it also has a rather interesting sub-string divisibility property.
//
// Let `d_1` be the 1st digit, `d_2` be the 2nd digit, and so on. In this way, we note the following:
//
// `d_2 d_3 d_4 = 406` is divisible by 2
// `d_3 d_4 d_5 = 063` is divisible by 3
// `d_4 d_5 d_6 = 635` is divisible by 5
// `d_5 d_6 d_7 = 357` is divisible by 7
// `d_6 d_7 d_8 = 572` is divisible by 11
// `d_7 d_8 d_9 = 728` is divisible by 13
// `d_8 d_9 d_10 = 289` is divisible by 17
//
// Find the sum of all 0 to 9 pandigital numbers with this property.
//
// # Solved by
//
// February 2017
//
// # Algorithm
// Once more, ''std::next_permutation'' turns out to be a rather handy feature:
// I generate all permutations of ''pan = "0123456789"'' and check all its substrings with length 3 for divisibility with the first prime numbers.
//
// ''str2num'' converts an ASCII string to a number, ignoring leading zeros: ''str2num("012") = 12''
//
// We need only the first 7 prime numbers - that's why I opted against a full prime sieve and just declared a precomputed array ''primes''.
//
// # Note
// Ten digits can exceed 32 bits, therefore you'll find ''unsigned long long'' instead of ''unsigned int'' in a few places.
//
// There are many optimization possible: when applying the rules of divisibility by 3, 5, ... then
// we could easily exclude the majority of permutations. Nevertheless, the non-optimized code runs fast enough.
//
// # Hackerrank
// The number of digits can vary. All I do is adjusting ''pan'': anything else remains the same.
// Hackerrank accepts pandigital numbers that start with a zero.
#include
#include
#include
// convert a string to a number
unsigned long long str2num(const std::string& x)
{
// process string from left to right
unsigned long long result = 0;
for (auto c : x)
{
// shift digits
result *= 10;
// add new digit on the right-hand side
result += c - '0'; // was ASCII
}
return result;
}
int main()
{
// available digits
std::string pan = "0123456789"; // unlike other problems, zero is allowed this time
// remove a few digits if test case requires this
unsigned int maxDigit;
std::cin >> maxDigit;
pan.erase(maxDigit + 1);
// all divisors
const unsigned int primes[] = { 2,3,5,7,11,13,17 };
// result
unsigned long long sum = 0;
// look at all permutations
do
{
// let's assume it's a great number ;-)
bool ok = true;
// check each 3-digit substring for divisibility
for (unsigned int i = 0; i + 2 < maxDigit; i++)
{
// check pan[1..3] against primes[0],
// check pan[2..4] against primes[1],
// check pan[3..5] against primes[2] ...
std::string check = pan.substr(i + 1, 3);
if (str2num(check) % primes[i] != 0)
{
// nope ...
ok = false;
break;
}
}
// passed all tests, it's great indeed !
if (ok)
sum += str2num(pan);
} while (std::next_permutation(pan.begin(), pan.end()));
std::cout << sum << std::endl;
return 0;
} | c++ | 13 | 0.633972 | 146 | 30.504505 | 111 | starcoderdata |
/*
Various assorted routines the program's toolbox is comprised of.
*/
#pragma once
#include
#include
#include
namespace utility
{
struct ScopedAction
{
ScopedAction(std::function action) : m_action(action)
{
}
~ScopedAction()
{
m_action();
}
private:
std::function m_action;
};
struct Counter
{
Counter() : m_countRejected(0), m_countFiltered(0) {}
virtual ~Counter() {}
auto getRejectedCount() { return m_countRejected; }
auto filteredCount() { return m_countFiltered; }
protected:
unsigned m_countRejected;
unsigned m_countFiltered;
};
template <typename T>
[[noreturn]] void throw_exception(const char* msg)
{
char buf[256] = "CsvProcessor - ";
unsigned len = strlen(buf);
strncat(buf, msg, sizeof(buf) - (len + 1));
throw T(buf);
}
std::string constructPath(const std::string& strPath);
std::string getConfigFilePath(const std::string& strExtension = ".cfg");
const wchar_t* getGmtDate();
const inline std::wregex g_regexIndex{L"^[A-Z]{2}(_[A-Z0-9]{1,3})?(_[A-Za-z0-9\\u0080-\\uDB7F]{1,12})?$"};
} // namespace utility | c | 14 | 0.640099 | 108 | 21.537037 | 54 | starcoderdata |
package com.xedus.tutorials.api.models.callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public interface OnDataReceived{
void onDataSuccess(Response response);
void onDataFailed(Request request, IOException e);
void onNoData();
} | java | 4 | 0.798995 | 91 | 29.692308 | 13 | starcoderdata |
using System;
namespace Ember.Services.Holidays
{
public class EmberDayCalculator
{
public DateTime GetAdventEmbertideStart(int year)
{
// Wednesday after Gaudete Sunday.
// Gaudete Sunday = 3rd Sunday of Advent
// Advent begins on the closest Sunday to St. Andrew’s Day(November 30).
var stAndrewsDay = new DateTime(year, 11, 30);
var firstSundayOfAdvent = GetClosestSunday(stAndrewsDay);
var thirdSundayOfAdvent = firstSundayOfAdvent.AddDays(14);
return thirdSundayOfAdvent.AddDays(3);
}
public DateTime GetLentenEmbertideStart(int year)
{
// Wednesday after Quadragesima Sunday
// Quadragesima = 1st Sunday of Lent
// Lent = 6 Sundays before Easter
// Easter = Sunday after the first full moon after March 21
var easterSunday = new EasterCalculator().Get(year);
var quadragesima = easterSunday.AddDays(-42);
return quadragesima.AddDays(3);
}
public DateTime GetWhitEmbertideStart(int year)
{
// Wednesday after Pentecost Sunday
// Pentecost = 50th day(inclusive) from Easter
// Easter = Sunday after the first full moon after March 21
var easterSunday = new EasterCalculator().Get(year);
var whitSunday = easterSunday.AddDays(49);
return whitSunday.AddDays(3);
}
public DateTime GetMichaelmasEmbertideStart(int year)
{
// Wednesday after the Exaltation of the Holy Cross (Sept 14)
var holyCross = new DateTime(year, 9, 14);
return GetNextWednesday(holyCross);
}
private DateTime GetClosestSunday(DateTime date)
{
return date.DayOfWeek switch
{
DayOfWeek.Sunday => date,
DayOfWeek.Monday => date.AddDays(-1),
DayOfWeek.Tuesday => date.AddDays(-2),
DayOfWeek.Wednesday => date.AddDays(-3),
DayOfWeek.Thursday => date.AddDays(3),
DayOfWeek.Friday => date.AddDays(2),
DayOfWeek.Saturday => date.AddDays(1),
_ => throw new NotImplementedException(),
};
}
private DateTime GetNextWednesday(DateTime date)
{
return date.DayOfWeek switch
{
DayOfWeek.Sunday => date.AddDays(3),
DayOfWeek.Monday => date.AddDays(2),
DayOfWeek.Tuesday => date.AddDays(1),
DayOfWeek.Wednesday => date.AddDays(7),
DayOfWeek.Thursday => date.AddDays(6),
DayOfWeek.Friday => date.AddDays(5),
DayOfWeek.Saturday => date.AddDays(4),
_ => throw new NotImplementedException(),
};
}
}
} | c# | 15 | 0.567466 | 84 | 37.421053 | 76 | starcoderdata |
#!/usr/bin/python
import argparse
import logging
import urllib3
from ssrfmap.core.config import SsrfmapConfig
from ssrfmap.core.ssrf import SSRF
def display_banner():
print(" _____ _________________ ")
print("/ ___/ ___| ___ \ ___| ")
print("\ `--.\ `--.| |_/ / |_ _ __ ___ __ _ _ __ ")
print(" `--. \`--. \ /| _| '_ ` _ \ / _` | '_ \ ")
print("/\__/ /\__/ / |\ \| | | | | | | | (_| | |_) |")
print("\____/\____/\_| \_\_| |_| |_| |_|\__,_| .__/ ")
print(" | | ")
print(" |_| ")
def parse_args():
example_text = """Examples:
ssrfmap -r demo/request2.txt -p url -m portscan
ssrfmap -r demo/request.txt -p url -m redis
ssrfmap -r demo/request.txt -p url -m portscan --ssl --uagent "SSRFmapAgent"
ssrfmap -r demo/request.txt -p url -m redis --lhost=127.0.0.1 --lport=4242 -l 4242
ssrfmap -r demo/request.txt -p url -m readfiles --rfiles
"""
parser = argparse.ArgumentParser(
epilog=example_text, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("-r", action="store", dest="reqfile", help="SSRF Request file")
parser.add_argument(
"-p", action="store", dest="param", help="SSRF Parameter to target"
)
parser.add_argument(
"-m", action="store", dest="modules", help="SSRF Modules to enable"
)
parser.add_argument(
"-l",
action="store",
dest="handler",
help="Start an handler for a reverse shell",
nargs="?",
const="1",
)
parser.add_argument(
"-v",
action="store",
dest="verbose",
help="Enable verbosity",
nargs="?",
const=True,
)
parser.add_argument(
"--lhost", action="store", dest="lhost", help="LHOST reverse shell"
)
parser.add_argument(
"--lport", action="store", dest="lport", help="LPORT reverse shell"
)
parser.add_argument(
"--rfiles",
action="store",
dest="targetfiles",
help="Files to read with readfiles module",
nargs="?",
const=True,
)
parser.add_argument(
"--uagent", action="store", dest="useragent", help="User Agent to use"
)
parser.add_argument(
"--ssl",
action="store",
dest="ssl",
help="Use HTTPS without verification",
nargs="?",
const=True,
)
parser.add_argument(
"--level",
action="store",
dest="level",
help="Level of test to perform (1-5, default: 1)",
nargs="?",
const=1,
default=1,
type=int,
)
results = parser.parse_args()
if results.reqfile == None:
parser.print_help()
exit()
return results
def ssrfmap():
# disable ssl warning for self signed certificate
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# enable custom logging
logging.basicConfig(level=logging.INFO, format="[%(levelname)s]:%(message)s")
logging.addLevelName(
logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING)
)
logging.addLevelName(
logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR)
)
display_banner()
# SSRFmap
args = parse_args()
config = SsrfmapConfig(
reqfile=args.reqfile,
param=args.param,
modules=args.modules.split(","),
handler=args.handler,
verbose=args.verbose,
lhost=args.lhost,
lport=args.lport,
targetfiles=args.targetfiles.split(",") if args.targetfiles else None,
useragent=args.useragent,
ssl=args.ssl,
level=args.level,
)
ssrf = SSRF(config) | python | 12 | 0.532657 | 88 | 28.790698 | 129 | starcoderdata |
public void testIsValid() throws Exception {
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload"));
assertFalse(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist"));
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32"));
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32"));
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"));
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"));
assertFalse(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.nonexist"));
assertTrue(
FieldMaskUtil.isValid(NestedTestAllTypes.class, FieldMaskUtil.fromString("payload")));
assertFalse(
FieldMaskUtil.isValid(NestedTestAllTypes.class, FieldMaskUtil.fromString("nonexist")));
assertFalse(
FieldMaskUtil.isValid(
NestedTestAllTypes.class, FieldMaskUtil.fromString("payload,nonexist")));
assertTrue(FieldMaskUtil.isValid(NestedTestAllTypes.getDescriptor(), "payload"));
assertFalse(FieldMaskUtil.isValid(NestedTestAllTypes.getDescriptor(), "nonexist"));
assertTrue(
FieldMaskUtil.isValid(
NestedTestAllTypes.getDescriptor(), FieldMaskUtil.fromString("payload")));
assertFalse(
FieldMaskUtil.isValid(
NestedTestAllTypes.getDescriptor(), FieldMaskUtil.fromString("nonexist")));
assertTrue(
FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message.bb"));
// Repeated fields cannot have sub-paths.
assertFalse(
FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message.bb"));
// Non-message fields cannot have sub-paths.
assertFalse(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32.bb"));
} | java | 11 | 0.754098 | 99 | 53.057143 | 35 | inline |
private static string GetLocation(string data)
{
var lines = data.Split('\n').Select(l=>l.Trim()).Where(l=>l.Length>0);
foreach(string line in lines)
{
if(line.StartsWith("HTTP/1.") || line.StartsWith("NOTIFY *"))
continue;
int colonIndex = line.IndexOf(':');
if(colonIndex<0)
continue;
string name = line[..colonIndex];
string val = line.Length >= name.Length ? line[(colonIndex + 1)..].Trim() : null;
if(name.ToLowerInvariant() == "location")
{
if(val.IndexOf('/', 7) == -1)// finds the first slash after http://
{
throw new Exception("Unsupported Gateway");
}
return val;
}
}
throw new Exception("Unsupported Gateway");
} | c# | 19 | 0.597765 | 85 | 24.607143 | 28 | inline |
package xo
var games []Game
var tokens = []string{"X", "O"}
func makeField() string{
return "***\n***\n***\n"
}
func makeFieldMove(field string, token string, x int, y int) string{
out := []rune(field)
i := x + 4 * y
out[i] = []rune(token)[0]
return string(out)
}
func validPos(x int, y int) bool{
return x >= 0 && x < 3 && y >= 0 && y < 3
}
func validMove(field string, x int, y int) bool{
if ! validPos(x,y){
return false
}
i := x + 4 * y
return field[i] == '*'
}
func detectWinner(field string) string {
rfield := []rune(field)
//vertical
for x:= 0; x < 3; x++ {
last := rfield[x]
sum := 0
for y:= 0; y < 3; y++ {
i := x + 4 * y
if rfield[i] == last {
sum++
}
}
if(sum == 3 && last != '*'){
return string(last)
}
}
//horizontal
for y:= 0; y < 3; y++ {
last := rfield[y*4]
sum := 0
for x:= 0; x < 3; x++ {
i := x + 4 * y
if rfield[i] == last {
sum++
}
}
if(sum == 3 && last != '*'){
return string(last)
}
}
//diagonal \
last := rfield[0]
sum := 0
for x:= 0; x < 3; x++ {
y := x
i := x + 4 * y
if rfield[i] == last {
sum++
}
}
if(sum == 3 && last != '*'){
return string(last)
}
//diagonal /
last = rfield[0 + 4 * 2]
sum = 0
for x:= 0; x < 3; x++ {
y := 2-x
i := x + 4 * y
if rfield[i] == last {
sum++
}
}
if(sum == 3 && last != '*'){
return string(last)
}
return "none"
} | go | 11 | 0.462435 | 68 | 14.815217 | 92 | starcoderdata |
namespace Jellyfin.Plugin.Reports.Api.Common
{
public enum HeaderActivitiesMetadata
{
None,
Name,
Overview,
ShortOverview,
Type,
Date,
UserPrimaryImageTag,
Severity,
Item,
User
}
} | c# | 6 | 0.543071 | 44 | 15.6875 | 16 | starcoderdata |
s = input()
t = input()
def check(a, b):
if len(a) != len(b):
return 0
else:
ans = 0
for i in range(len(a)):
if a[i] == b[i]:
ans += 1
return ans
ans = 0
for i in range(len(s)):
x = check(s[i:i + len(t)], t)
if ans < x:
ans = x
print(len(t) - ans) | python | 12 | 0.40597 | 33 | 15.8 | 20 | codenet |
UI Widgets/Scripts/Tabs/TabButton.cs
namespace UIWidgets
{
using UnityEngine.UI;
///
/// Tab button.
///
public class TabButton : Button
{
}
} | c# | 9 | 0.714286 | 95 | 18.333333 | 12 | starcoderdata |
package org.usfirst.frc.team1746.robot;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class GearIntake {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// Class setup
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ElectricalConstants eConstants = new ElectricalConstants();
private Controls m_controls;
public GearIntake(Controls controls){
m_controls = controls;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// GearIntake init
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Solenoid flapsOut;
Solenoid flapsIn;
Solenoid hopperFlapsOut;
Solenoid hopperFlapsIn;
Solenoid LEDLeft;
Solenoid LEDRight;
DigitalInput beambreak;
boolean lastBB;
boolean nowBB;
public void init(){
flapsOut = new Solenoid(eConstants.GEAR_FLAPS_OUT);
flapsIn = new Solenoid(eConstants.GEAR_FLAPS_IN);
LEDLeft = new Solenoid(eConstants.GEAR_LED_LEFT);
LEDRight = new Solenoid(eConstants.GEAR_LED_RIGHT);
hopperFlapsOut = new Solenoid(eConstants.GEAR_HOPPER_FLAPS_OUT);
hopperFlapsIn = new Solenoid(eConstants.GEAR_HOPPER_FLAPS_IN);
beambreak = new DigitalInput(eConstants.DIFFUSE_GEAR);
flapsIn();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// GearIntake SmartDashboard
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void initSmartDashboard(){
}
public void updateSmartDashboard(){
SmartDashboard.putBoolean("Gear Sensor", gearSensor());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// GearIntake functions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean gearSensor(){
return beambreak.get();
}
public void flapsOut(){
flapsIn.set(false);
flapsOut.set(true);
}
public void flapsIn(){
flapsOut.set(false);
flapsIn.set(true);
}
public void hopperFlapsOut(){
hopperFlapsIn.set(false);
hopperFlapsOut.set(true);
}
public void hopperFlapsIn(){
hopperFlapsOut.set(false);
hopperFlapsIn.set(true);
}
public void hopperFlapsOff(){
hopperFlapsOut.set(false);
hopperFlapsIn.set(false);
}
public void LEDsOn(){
LEDLeft.set(true);
LEDRight.set(true);
}
public void LEDsOff(){
LEDLeft.set(false);
LEDRight.set(false);
}
//beambreak.get()
//!beambreak.get()
//m_controls.operator_gearFlapsOut() || m_controls.driver_gearFlapsOut()
//m_controls.operator_gearFlapsIn() || m_controls.driver_gearFlapsIn)
//false = in
//true = out
boolean prevBeam = false;
boolean prevControlOut = false;
boolean prevControlIn = false;
int loops = 0;
public void leds(){
if(!beambreak.get()){
LEDsOn();
}
if(beambreak.get()){
LEDsOff();
}
}
public void smartFlaps(){
// Controls: Flaps In
if((m_controls.driver_gearFlapsIn() || m_controls.operator_gearFlapsIn()) && !prevControlIn){ //controllers says go in
flapsIn();
prevControlIn = true;
}
if(!(m_controls.driver_gearFlapsIn() || m_controls.operator_gearFlapsIn()) && prevControlIn){ //controllers says go in
prevControlIn = false;
}
// Controls: Flaps Out
if((m_controls.driver_gearFlapsOut() || m_controls.operator_gearFlapsOut()) && !prevControlOut){
flapsOut();
prevControlOut = true;
}
if(!(m_controls.driver_gearFlapsOut() || m_controls.operator_gearFlapsOut()) && prevControlOut){
prevControlOut = false;
}
// Sensor
if(!beambreak.get() && !prevBeam){ // gear detected
flapsIn();
LEDsOn();
prevBeam = true;
}
if(beambreak.get() && prevBeam){ // gear no longer detected
flapsOut();
LEDsOff();
prevBeam = false;
}
}
// Not Used
public void checkControls(){
if(m_controls.operator_gearHopperOut()){
hopperFlapsOut();
}
if(m_controls.operator_gearHopperIn()){
hopperFlapsIn();
}
}
} | java | 13 | 0.501905 | 160 | 27.981595 | 163 | starcoderdata |
/*-
*
* Hedera Mirror Node
*
* Copyright (C) 2019 - 2022 Hedera Hashgraph, LLC
*
* 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 domain
import (
"github.com/hashgraph/hedera-mirror-node/hedera-mirror-rosetta/app/interfaces"
"github.com/hashgraph/hedera-mirror-node/hedera-mirror-rosetta/app/persistence/domain"
"github.com/thanhpk/randstr"
)
type TransactionBuilder struct {
dbClient interfaces.DbClient
transaction domain.Transaction
}
func (b *TransactionBuilder) ConsensusTimestamp(timestamp int64) *TransactionBuilder {
b.transaction.ConsensusTimestamp = timestamp
return b
}
func (b *TransactionBuilder) EntityId(encodedId int64) *TransactionBuilder {
entityId := domain.MustDecodeEntityId(encodedId)
b.transaction.EntityId = &entityId
return b
}
func (b *TransactionBuilder) Result(result int16) *TransactionBuilder {
b.transaction.Result = result
return b
}
func (b *TransactionBuilder) Type(txnType int16) *TransactionBuilder {
b.transaction.Type = txnType
return b
}
func (b *TransactionBuilder) Persist() domain.Transaction {
b.dbClient.GetDb().Create(&b.transaction)
return b.transaction
}
func NewTransactionBuilder(dbClient interfaces.DbClient, payer, validStartNs int64) *TransactionBuilder {
transaction := domain.Transaction{
ConsensusTimestamp: validStartNs + 1,
PayerAccountId: domain.MustDecodeEntityId(payer),
Result: 22,
TransactionHash: randstr.Bytes(8),
Type: domain.TransactionTypeCryptoTransfer,
ValidDurationSeconds: 120,
ValidStartNs: validStartNs,
}
return &TransactionBuilder{dbClient: dbClient, transaction: transaction}
} | go | 11 | 0.750114 | 105 | 29.774648 | 71 | starcoderdata |
#include "Int64.h"
typedef struct Int64Private
{
Object object;
long value;
void (*Set)(long);
} Int64Private;
/* Public */
long Int64_Get(Int64 * const);
Int64 *Int64_Parse(struct string *, Int64 * const);
struct string *Int64_ToString(Int64 * const);
bool Int64_ReferenceEquality(void *, Int64 * const);
bool Int64_Equals(Int64 *, Int64 * const);
/* Ctor */
void *Int64_Int640(Int64 *);
void *Int64_Int641(long, Int64 *);
/* Private */
static void Int64Private_Set(long, Int64Private * const);
long Int64_Get(Int64 * const this)
{
return this->Int64Private->value;
}
Int64 *Int64_Parse(String *str, Int64 * const this)
{
Int64 *ret = Int64_Int641(0, this);
ret->Int64Private->value = atoi(str->Get());
return ret;
}
/*
Char *Int16_ToChar(Int16 *this)
{
Char *ret = new Char((char)this->value + '0');
return ret;
} */
String *Int64_ToString(Int64 * const this)
{
String *ret;
char *aux = GC_MALLOC(255);
(void)sprintf(aux, "%ld", this->Int64Private->value);
//return (ret = new String(aux));
return 0;
}
bool Int64_ReferenceEquality(void *object, Int64 * const this)
{
if(object == (void *)this)
return true;
else
return false;
}
bool Int64_Equals(Int64 *check, Int64 * const this)
{
return (check->Int64Private->value == this->Int64Private->value) ? true : false;
}
/* Ctor */
optimize(0) void *Int64_Int640(Int64 *this)
{
/* Encapsulate */
void *__this;
void *__save_fp = (void *)this->Int640;
callprotect(&this->object);
__this = Object_create(sizeof(*this), 9);
memcpy(this, __this, sizeof(*this));
FUNCTION(Int64, Get, 0);
FUNCTION(Int64, Parse, 1);
FUNCTION(Int64, ToString, 0);
FUNCTION(Int64, ReferenceEquality, 1);
FUNCTION(Int64, Equals, 1);
FUNCTION(Int64, Int641, 1);
this->Int640 = __save_fp;
this->Int64Private = Object_create(sizeof(Int64Private), 1);
FUNCTIONP(Int64, Set, 1);
Object_prepare(&this->Int64Private->object);
this->Int64Private->Set(0);
Object_prepare(&this->object);
return 0;
}
optimize(0) void *Int64_Int641(long value, Int64 *this)
{
/* Encapsulate */
void *__this;
void *__save_fp = (void *)this->Int641;
callprotect(&this->object);
__this = Object_create(sizeof(*this), 9);
memcpy(this, __this, sizeof(*this));
FUNCTION(Int64, Get, 0);
FUNCTION(Int64, Parse, 1);
FUNCTION(Int64, ToString, 0);
FUNCTION(Int64, ReferenceEquality, 1);
FUNCTION(Int64, Equals, 1);
FUNCTION(Int64, Int640, 1);
this->Int641 = __save_fp;
this->Int64Private = Object_create(sizeof(Int64Private), 1);
FUNCTIONP(Int64, Set, 1);
Object_prepare(&this->Int64Private->object);
this->Int64Private->Set(value);
Object_prepare(&this->object);
return 0;
}
/* Private method */
static void Int64Private_Set(long value, Int64Private * const this)
{
this->value = value;
return;
} | c | 10 | 0.648052 | 81 | 22.610169 | 118 | starcoderdata |
int nk_mcuflash_erase(uint32_t address, uint32_t byte_count)
{
int rtn = 0;
// As long as we're not done..
while (byte_count) {
// Try to use largest erase that works..
if ((address & (NK_MCUFLASH_ERASE_SIZE - 1)) == 0 && byte_count >= NK_MCUFLASH_ERASE_SIZE) {
rtn = flash_erase(&FLASH_0, address, NK_MCUFLASH_ERASE_SIZE / NK_MCUFLASH_PAGE_SIZE);
if (rtn) break;
address += NK_MCUFLASH_ERASE_SIZE;
byte_count -= NK_MCUFLASH_ERASE_SIZE;
} else {
// None work? Fail..
break;
}
}
if (rtn) {
nk_printf("ERROR: flash_erase returned %d\n", rtn);
} else if (byte_count) {
nk_printf("ERROR: Invalid erase size\n");
rtn = -1;
}
return rtn;
} | c | 13 | 0.62426 | 94 | 24.074074 | 27 | inline |
private void doExchange(TradeList partnerList)
{
boolean success = false;
// check weight and slots
if ((!getOwner().getInventory().validateWeight(partnerList.calcItemsWeight())) || !(partnerList.getOwner().getInventory().validateWeight(calcItemsWeight())))
{
partnerList.getOwner().sendPacket(new SystemMessage(SystemMessageId.WEIGHT_LIMIT_EXCEEDED));
getOwner().sendPacket(new SystemMessage(SystemMessageId.WEIGHT_LIMIT_EXCEEDED));
}
else if ((!getOwner().getInventory().validateCapacity(partnerList.countItemsSlots(getOwner()))) || (!partnerList.getOwner().getInventory().validateCapacity(countItemsSlots(partnerList.getOwner()))))
{
partnerList.getOwner().sendPacket(new SystemMessage(SystemMessageId.SLOTS_FULL));
getOwner().sendPacket(new SystemMessage(SystemMessageId.SLOTS_FULL));
}
else
{
// Prepare inventory update packet
InventoryUpdate ownerIU = Config.FORCE_INVENTORY_UPDATE ? null : new InventoryUpdate();
InventoryUpdate partnerIU = Config.FORCE_INVENTORY_UPDATE ? null : new InventoryUpdate();
// Transfer items
partnerList.TransferItems(getOwner(), partnerIU, ownerIU);
TransferItems(partnerList.getOwner(), ownerIU, partnerIU);
// Send inventory update packet
if (ownerIU != null)
_owner.sendPacket(ownerIU);
else
_owner.sendPacket(new ItemList(_owner, false));
if (partnerIU != null)
_partner.sendPacket(partnerIU);
else
_partner.sendPacket(new ItemList(_partner, false));
// Update current load as well
StatusUpdate playerSU = new StatusUpdate(_owner);
playerSU.addAttribute(StatusUpdate.CUR_LOAD, _owner.getCurrentLoad());
_owner.sendPacket(playerSU);
playerSU = new StatusUpdate(_partner);
playerSU.addAttribute(StatusUpdate.CUR_LOAD, _partner.getCurrentLoad());
_partner.sendPacket(playerSU);
success = true;
}
// Finish the trade
partnerList.getOwner().onTradeFinish(success);
getOwner().onTradeFinish(success);
} | java | 15 | 0.734312 | 200 | 38.54 | 50 | inline |
# coding:utf-8
'''
Created on 2018/1/4
@author: sunyihuan
'''
import math
import numpy as np
import time
import scipy.io as scio
import matplotlib.pyplot as plt
from assignment1.data_utils import load_CIFAR10
from assignment1.classifiers.linear_svm import svm_loss_naive, svm_loss_vectorized
from assignment1.classifiers import LinearSVM
from assignment1.gradient_check import grad_check_sparse
cifar10_dir = '../datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# data = scio.loadmat('../res/cifar10')
# X_train, y_train, X_test, y_test = data['trX'], data['trY'], data['teX'], data['teY']
# generate a random SVM weight matrix of small numbers
W = np.random.randn(3073, 10) * 0.0001
# Split the data into train, val, and test sets. In addition we will
# create a small development set as a subset of the training data;
# we can use this for development so our code runs faster.
num_training = 49000
num_validation = 1000
num_test = 1000
num_dev = 500
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_val = np.reshape(X_val, (X_val.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))
mean_image = np.mean(X_train, axis=0)
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
X_dev -= mean_image
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])
X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))])
X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])
X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))])
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.000005)
print('loss: %f' % (loss,))
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.0)
# Numerically compute the gradient along several randomly chosen dimensions, and
# compare them with your analytically computed gradient. The numbers should match
# almost exactly along all dimensions.
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 0.0)[0]
grad_numerical = grad_check_sparse(f, W, grad)
# do the gradient check once again with regularization turned on
# you didn't forget the regularization gradient did you?
loss, grad = svm_loss_naive(W, X_dev, y_dev, 5e1)
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 5e1)[0]
grad_numerical = grad_check_sparse(f, W, grad)
tic = time.time()
loss_naive, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Naive loss: %e computed in %fs' % (loss_naive, toc - tic))
tic = time.time()
loss_vectorized, _ = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic))
# The losses should match but your vectorized implementation should be much faster.
print('difference: %f' % (loss_naive - loss_vectorized))
tic = time.time()
_, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Naive loss and gradient: computed in %fs' % (toc - tic))
tic = time.time()
_, grad_vectorized = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Vectorized loss and gradient: computed in %fs' % (toc - tic))
# The loss is a single number, so it is easy to compare the values computed
# by the two implementations. The gradient on the other hand is a matrix, so
# we use the Frobenius norm to compare them.
difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro')
print('difference: %f' % difference)
svm = LinearSVM()
tic = time.time()
loss_hist = svm.train(X_train, y_train, learning_rate=1e-7, reg=2.5e4,
num_iters=1500, verbose=True)
toc = time.time()
print('That took %fs' % (toc - tic))
plt.plot(loss_hist)
plt.xlabel('Iteration number')
plt.ylabel('Loss value')
plt.show()
y_train_pred = svm.predict(X_train)
print('training accuracy: %f' % (np.mean(y_train == y_train_pred),))
y_val_pred = svm.predict(X_val)
print('validation accuracy: %f' % (np.mean(y_val == y_val_pred),))
learning_rates = [1.4e-7, 1.5e-7, 1.6e-7]
regularization_strengths = [3e4, 3.1e4, 3.2e4, 3.3e4, 3.4e4]
# results is dictionary mapping tuples of the form
# (learning_rate, regularization_strength) to tuples of the form
# (training_accuracy, validation_accuracy). The accuracy is simply the fraction
# of data points that are correctly classified.
results = {}
best_val = -1 # The highest validation accuracy that we have seen so far.
params = [(x, y) for x in learning_rates for y in regularization_strengths]
for lrate, regular in params:
svm = LinearSVM()
loss_hist = svm.train(X_train, y_train, learning_rate=lrate, reg=regular,
num_iters=700, verbose=False)
y_train_pred = svm.predict(X_train)
accuracy_train = np.mean(y_train == y_train_pred)
y_val_pred = svm.predict(X_val)
accuracy_val = np.mean(y_val == y_val_pred)
results[(lrate, regular)] = (accuracy_train, accuracy_val)
if (best_val < accuracy_val):
best_val = accuracy_val
best_svm = svm
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)
x_scatter = [math.log10(x[0]) for x in results]
y_scatter = [math.log10(x[1]) for x in results]
# plot training accuracy
marker_size = 100
colors = [results[x][0] for x in results]
plt.subplot(2, 1, 1)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 training accuracy')
# plot validation accuracy
colors = [results[x][1] for x in results] # default size of markers is 20
plt.subplot(2, 1, 2)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 validation accuracy')
plt.show()
y_test_pred = best_svm.predict(X_test)
test_accuracy = np.mean(y_test == y_test_pred)
print('linear SVM on raw pixels final test set accuracy: %f' % test_accuracy)
w = best_svm.W[:-1, :] # strip out the bias
w = w.reshape(32, 32, 3, 10)
w_min, w_max = np.min(w), np.max(w)
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for i in range(10):
plt.subplot(2, 5, i + 1)
# Rescale the weights to be between 0 and 255
wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)
plt.imshow(wimg.astype('uint8'))
plt.axis('off')
plt.title(classes[i]) | python | 13 | 0.68349 | 90 | 33.849246 | 199 | starcoderdata |
#pragma once
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "async_loop.h"
#include "msg_view.h"
#include "host_address.h"
namespace telling
{
class HttpClient_Base;
class HttpClient; // inherits HttpClient_Base
class HttpClient_Box; // inherits HttpClient
// Tag delivered to callbacks
struct HttpRequesting
{
HttpClient *comm;
QueryID id;
};
// Base class for asynchronous I/O
using AsyncHttpReq = AsyncQuery
using AsyncHttpRequest = AsyncHttpReq;
/*
Base type for HTTP clients.
*/
class HttpClient_Base
{
public:
const nng::url host;
public:
// Construct with URL of host.
HttpClient_Base(nng::url &&_host) : host(std::move(_host)) {}
virtual ~HttpClient_Base() {}
/*
Get statistics
*/
struct MsgStats
{
size_t
awaiting_send,
awaiting_recv;
};
virtual MsgStats msgStats() const noexcept = 0;
};
/*
HTTP Client with asynchronous events.
*/
class HttpClient : public HttpClient_Base
{
public:
using conn_view = nng::http::conn_view;
class Handler : public AsyncHttpRequest
{
public:
virtual ~Handler() {}
virtual void httpConn_open (conn_view conn) {}
virtual void httpConn_close (conn_view conn) {}
// Optional progress notification
virtual void async_response_progress(HttpRequesting, MsgCompletion, const MsgView::Reply&) {}
void async_prep (HttpRequesting, nng::msg &query) override {}
void async_sent (HttpRequesting) override {}
//void async_recv (HttpRequesting, nng::msg &&response) override = 0;
//void async_error(HttpRequesting, nng::error status) override = 0;
};
public:
// Construct with URL of host.
HttpClient(nng::url &&_host, std::weak_ptr = {});
~HttpClient() override;
/*
Install a handler after construction.
Throws nng::exception if a handler is already installed.
*/
void initialize(std::weak_ptr
/*
Initiate a request.
May fail, throwing nng::exception.
*/
QueryID request(nng::msg &&msg);
/*
Stats implementation
*/
MsgStats msgStats() const noexcept final;
protected:
nng::http::client client;
nng::tls::config tls;
std::weak_ptr _handler;
enum ACTION_STATE
{
IDLE = 0,
CONNECT = 1,
SEND = 2,
RECV = 3,
};
struct Action;
friend struct Action;
QueryID nextQueryID = 0;
mutable std::mutex mtx;
std::unordered_set active;
std::deque idle;
};
/*
Non-blocking client socket for requests.
Supports multiple pending requests.
Requests are handled with std::future.
*/
class HttpClient_Box : public HttpClient
{
public:
explicit HttpClient_Box(nng::url &&_host);
~HttpClient_Box() override {}
/*
Send a request to the server.
*/
std::future request(nng::msg &&req);
protected:
class Delegate;
void _init();
std::shared_ptr _httpBox;
};
} | c | 12 | 0.616306 | 96 | 18.993865 | 163 | starcoderdata |
// the mini lodash for bslib
// @author Dobby233Liu
class 常用 {
static 能否以句号结束(_tmp2) {
var tmp2 = _tmp2.trim(); // temp postprocess
return !tmp2.endsWith("。") && !tmp2.endsWith(".") && !tmp2.endsWith(":") && !tmp2.endsWith(":") && !tmp2.endsWith("?") && !tmp2.endsWith("?") && !tmp2.endsWith("!") && !tmp2.endsWith("!") && !tmp2.endsWith(",") && !tmp2.endsWith(",");
}
static 合并对象(less, much) {
var ret = much;
for (var i in less) {
if (i != "__proto__") {
ret[i] = less[i];
}
}
return ret;
}
}
module.exports = 常用; | javascript | 19 | 0.511278 | 242 | 34.052632 | 19 | starcoderdata |
package com.hyq.service.impl;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hyq.domain.BaseQuestion;
import com.hyq.domain.JudgeQuestion;
import com.hyq.domain.KnowLegePoint;
import com.hyq.domain.MutiChoiceQuestion;
import com.hyq.domain.QuestionType;
import com.hyq.domain.SingleChoiceQuestion;
import com.hyq.domain.WdQuestion;
import com.hyq.mapper.QuestionMapper;
import com.hyq.service.QuestionService;
import com.hyq.vo.QuestionLikeVo;
import com.hyq.vo.QuestionVo;
@Service
public class QustionServiceImpl implements QuestionService
{
@Autowired
private QuestionMapper questionMapper;
@Override
public List findAllQuestionTypes() {
return questionMapper.findAllQuestionTypes();
}
@Override
public void saveSingleChoice(SingleChoiceQuestion singleChoiceQuestion) {
questionMapper.saveSingleChoice(singleChoiceQuestion);
}
@Override
public void saveTopKpoint(KnowLegePoint kp) {
questionMapper.saveTopKpoint(kp);
}
@Override
public List getTopList() {
return questionMapper.getTopList();
}
@Override
public void saveSimpleKpoint(KnowLegePoint kp) {
questionMapper.saveSimpleKpoint(kp);
}
@Override
public JSONArray listAll2JsonArray() {
JSONArray totalArray = new JSONArray();
JSONObject o = null;
List topList = questionMapper.getTopList();
for(int i=0;i<topList.size();i++){
o = new JSONObject();
KnowLegePoint top = topList.get(i);
List children = questionMapper.getChildsByTopId(top.getId());
//设置顶级图表
if(children!=null && children.size()>0){
o.put("children",children);
}
o.put("id",top.getId());
o.put("text",top.getText());
o.put("description",top.getDescription());
totalArray.add(o);
}
return totalArray;
}
@Override
public List getChildsByTopId(Integer id) {
return questionMapper.getChildsByTopId(id);
}
@Override
public void editKpointById(KnowLegePoint knowLegePoint) {
questionMapper.editKpointById(knowLegePoint);
}
@Override
public void deleteKpointById(Integer id) {
questionMapper.deleteKpointById(id);
}
@Override
public void saveJudgeQuestion(JudgeQuestion judgeQuestion) {
questionMapper.saveJudgeQuestion(judgeQuestion);
}
@Override
public void saveWdQuestion(WdQuestion wdQuestion) {
questionMapper.saveWdQuestion(wdQuestion);
}
@Override
public void saveMutiChoic(MutiChoiceQuestion mutiChoiceQuestion) {
questionMapper.saveMutiChoic(mutiChoiceQuestion);
}
@Override
public List getTopKpoint() {
return questionMapper.getTopKpoint();
}
@Override
public JSONArray getAllQuestions2Array() {
List questions = questionMapper.getAllBaseQuestions();
return JSONArray.fromObject(questions);
}
@Override
public Integer getTotalRecord(QuestionLikeVo vo) {
return questionMapper.getTotalRecord(vo);
}
@Override
public void deleteQuestiosByIdAndTypeId(QuestionVo questionVo) {
questionMapper.deleteQuestiosByIdAndTypeId(questionVo);
}
@Override
public List findByMap(Map<String, Object> map) {
return questionMapper.findByMap(map);
}
@Override
public Integer getSingleTableRecord(QuestionLikeVo vo) {
return questionMapper.getSingleTableRecord(vo);
}
} | java | 13 | 0.777164 | 79 | 23.411348 | 141 | starcoderdata |
package org.jabref.gui.maintable;
import java.util.List;
import java.util.Optional;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import org.jabref.gui.StateManager;
import org.jabref.gui.groups.GroupViewMode;
import org.jabref.gui.groups.GroupsPreferences;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.search.matchers.MatcherSet;
import org.jabref.model.search.matchers.MatcherSets;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class MainTableDataModel {
private final FilteredList<BibEntryTableViewModel> entriesFiltered;
private final SortedList<BibEntryTableViewModel> entriesSorted;
private final ObjectProperty<MainTableFieldValueFormatter> fieldValueFormatter;
private final GroupsPreferences groupsPreferences;
private final NameDisplayPreferences nameDisplayPreferences;
private final BibDatabaseContext bibDatabaseContext;
public MainTableDataModel(BibDatabaseContext context, PreferencesService preferencesService, StateManager stateManager) {
this.groupsPreferences = preferencesService.getGroupsPreferences();
this.nameDisplayPreferences = preferencesService.getNameDisplayPreferences();
this.bibDatabaseContext = context;
this.fieldValueFormatter = new SimpleObjectProperty<>(
new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext));
ObservableList<BibEntry> allEntries = BindingsHelper.forUI(context.getDatabase().getEntries());
ObservableList<BibEntryTableViewModel> entriesViewModel = EasyBind.mapBacked(allEntries, entry ->
new BibEntryTableViewModel(entry, bibDatabaseContext, fieldValueFormatter));
entriesFiltered = new FilteredList<>(entriesViewModel);
entriesFiltered.predicateProperty().bind(
EasyBind.combine(stateManager.activeGroupProperty(),
stateManager.activeSearchQueryProperty(),
groupsPreferences.groupViewModeProperty(),
(groups, query, groupViewMode) -> entry -> isMatched(groups, query, entry))
);
IntegerProperty resultSize = new SimpleIntegerProperty();
resultSize.bind(Bindings.size(entriesFiltered));
stateManager.setActiveSearchResultSize(context, resultSize);
// We need to wrap the list since otherwise sorting in the table does not work
entriesSorted = new SortedList<>(entriesFiltered);
}
private boolean isMatched(ObservableList<GroupTreeNode> groups, Optional<SearchQuery> query, BibEntryTableViewModel entry) {
return isMatchedByGroup(groups, entry) && isMatchedBySearch(query, entry);
}
private boolean isMatchedBySearch(Optional<SearchQuery> query, BibEntryTableViewModel entry) {
return query.map(matcher -> matcher.isMatch(entry.getEntry()))
.orElse(true);
}
private boolean isMatchedByGroup(ObservableList<GroupTreeNode> groups, BibEntryTableViewModel entry) {
return createGroupMatcher(groups)
.map(matcher -> matcher.isMatch(entry.getEntry()))
.orElse(true);
}
private Optional<MatcherSet> createGroupMatcher(List<GroupTreeNode> selectedGroups) {
if ((selectedGroups == null) || selectedGroups.isEmpty()) {
// No selected group, show all entries
return Optional.empty();
}
final MatcherSet searchRules = MatcherSets.build(
groupsPreferences.getGroupViewMode() == GroupViewMode.INTERSECTION
? MatcherSets.MatcherType.AND
: MatcherSets.MatcherType.OR);
for (GroupTreeNode node : selectedGroups) {
searchRules.addRule(node.getSearchMatcher());
}
return Optional.of(searchRules);
}
public SortedList<BibEntryTableViewModel> getEntriesFilteredAndSorted() {
return entriesSorted;
}
public void refresh() {
this.fieldValueFormatter.setValue(new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext));
}
}
| java | 14 | 0.739532 | 128 | 44.656863 | 102 | research_code |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, unicode_literals)
import argparse
import logging
import os
import pytest
from fval import (_config_file_loader, _real_main)
from fval import parse_args, load_config
from fval.external.six import PY2, PY3
test_folder_path = os.path.join(os.getcwd(), 'test_folder')
test_config_path = os.path.join(os.getcwd(), 'test_folder', 'fval.cfg')
DEBUG_ARG = '--debug'
ALL_ARG = '--all'
PATH_ARG = '--path'
CONFIG_ARG = '--config'
def test_args():
parsed = parse_args(
[PATH_ARG, '/tmp', DEBUG_ARG, ALL_ARG, CONFIG_ARG, test_config_path])
assert parsed.path == '/tmp'
assert parsed.all
def test_config_file_loader():
""" Test configuration loader """
with pytest.raises(TypeError):
_config_file_loader()
assert isinstance(_config_file_loader(path='example_configs/config_1.yml'), dict)
assert 'failure_message' in _config_file_loader(path='example_configs/invalid_format.yml')
def test_load_config_bad_call():
with pytest.raises(AttributeError):
load_config()
def test_load_config_without_config_provided():
fake_args = argparse.Namespace
fake_args.config = None
fake_args.path = None
fake_args.quiet = None
fake_args.loglevel = None
fake_args.debug = None
fake_args.warn = None
fake_args.error = None
fake_args.all = None
fake_args.output = None
fake_args.depth = None
fake_args.theme = None
fake_args.multiline = None
assert isinstance(load_config(cmdline_args=fake_args), dict)
def test_load_config_with_config_1_provided():
fake_args = argparse.Namespace
fake_args.config = 'example_configs/config_1.yml'
fake_args.path = None
fake_args.quiet = None
fake_args.loglevel = None
fake_args.debug = None
fake_args.warn = None
fake_args.error = None
fake_args.all = None
fake_args.output = None
fake_args.depth = None
fake_args.theme = None
fake_args.multiline = None
loaded = load_config(cmdline_args=fake_args)
assert isinstance(loaded, dict)
assert not loaded.get('all')
assert not loaded.get('depth')
assert 'dirs' in loaded.get('exclusions')
assert 'paths' in loaded.get('exclusions')
assert isinstance(loaded.get('logger'), logging.Logger)
def test_real_main_empty_dir(tmpdir):
empty_dir = tmpdir.mkdir("empty").strpath
with pytest.raises(SystemExit) as se:
_real_main(['--path={0}'.format(empty_dir), '--error'])
if PY2:
assert se.value[0] == 0
elif PY3:
assert se.exconly() == 'SystemExit: 0'
# # def test_internal_folder_all(capsys):
# # parsed = parse_args(
# # [CONFIG_ARG, test_config_path, ALL_ARG])
# # config = load_config(args=parsed)
# # result, orphans = discover(args=parsed, config=config)
# # assert len(orphans) == 1
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config, args=parsed)
# # out, err = capsys.readouterr()
# # assert execution_result == 10
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
#
# #
# # def test_internal_folder_1(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_1'), CONFIG_ARG, test_config_path,
# # CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 1
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 0
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_2(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_2'), CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 1
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_3(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_3'), CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 2
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_4(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_4'), CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 0
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_5(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_5'), CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 2
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_6(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_6'), CONFIG_ARG, test_config_path, DEBUG_ARG])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 2
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err))
# #
# #
# # def test_internal_folder_7(capsys):
# # parsed = parse_args(
# # [PATH_ARG, os.path.join(test_folder_path, 'internal_folder_7'), CONFIG_ARG, test_config_path])
# # config = load_config(cmdline_args=parsed)
# # result, orphans = discover(config=config)
# # assert len(orphans) == 0
# # test_plan = build_plan(result, config=config)
# # execution_result = execute_plan(test_plan, config=config)
# # out, err = capsys.readouterr()
# # # assert execution_result == 0
# # # print(execution_result)
# # # print('\n\nxxx OUT = {0} xxx'.format(out))
# # # print('\n\nERR = {0}'.format(err)) | python | 12 | 0.62169 | 117 | 35.882629 | 213 | starcoderdata |
def collide(self, parent, position, height):
pad = 0.25
p = list(position)
np = normalize(position)
self.current_density = 1 # Reset it, incase we don't hit any water
for face in FACES: # check all surrounding blocks
for i in xrange(3): # check each dimension independently
if not face[i]:
continue
d = (p[i] - np[i]) * face[i]
if d < pad:
continue
for dy in xrange(height): # check each height
op = list(np)
op[1] -= dy
op[i] += face[i]
op = tuple(op)
# If there is no block or if the block is not a cube,
# we can walk there.
if op not in parent.world \
or parent.world[op].vertex_mode != G.VERTEX_CUBE:
continue
# if density <= 1 then we can walk through it. (water)
if parent.world[op].density < 1:
self.current_density = parent.world[op].density
continue
# if height <= 1 then we can walk on top of it. (carpet, half-blocks, etc...)
if parent.world[op].height < 0.5:
#current_height = parent.world[op].height
#x, y, z = self.position
#new_pos = (x, y + current_height, z)
#self.position = new_pos
continue
if parent.world[op].player_damage > 0:
if self.last_damage_block != np:
# this keeps a player from taking the same damage over and over...
self.change_health( - parent.world[op].player_damage)
parent.item_list.update_health()
self.last_damage_block = np
continue
else:
#do nothing
continue
p[i] -= (d - pad) * face[i]
if face == (0, -1, 0) or face == (0, 1, 0):
# jump damage
if self.game_mode == G.SURVIVAL_MODE:
damage = self.dy * -1000.0
damage = 3.0 * damage / 22.0
damage -= 2.0
if damage >= 0.0:
health_change = 0
if damage <= 0.839:
health_change = 0
elif damage <= 1.146:
health_change = -1
elif damage <= 1.44:
health_change = -2
elif damage <= 2.26:
health_change = -2
else:
health_change = -3
if health_change != 0:
self.change_health(health_change)
parent.item_list.update_health()
self.dy = 0
break
return tuple(p) | python | 21 | 0.368298 | 97 | 47.352113 | 71 | inline |
/*
Copyright (c) 2019, European X-Ray Free-Electron Laser Facility GmbH
All rights reserved.
You should have received a copy of the 3-Clause BSD License along with this
program. If not, see
Author:
*/
#ifndef XFAI_LINE_DETECTOR_H
#define XFAI_LINE_DETECTOR_H
namespace xfai
{
/**
* LineDetector base class.
*
* @tparam C: number of channels.
* @tparam L: channel length.
* @tparam D: derived detector type.
*/
template<std::size_t C, std::size_t L, typename D>
class LineDetector
{
public:
static constexpr std::size_t n_channels = C;
static constexpr std::size_t length = L;
using value_type = float;
};
class AdqDigitizer : LineDetector<4, 100000, AdqDigitizer>
{
};
};
#endif //XFAI_LINE_DETECTOR_H | c++ | 9 | 0.656471 | 79 | 20.25 | 40 | starcoderdata |
/*
* This file is part of Hopsworks
* Copyright (C) 2022, Logical Clocks AB. All rights reserved
*
* Hopsworks is free software: you can redistribute it and/or modify it under the terms of
* the GNU Affero General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Hopsworks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
*/
package io.hops.hopsworks.common.featurestore.storageconnectors.gcs;
import com.google.common.base.Strings;
import io.hops.hopsworks.common.featurestore.storageconnectors.StorageConnectorUtil;
import io.hops.hopsworks.exceptions.FeaturestoreException;
import io.hops.hopsworks.exceptions.ProjectException;
import io.hops.hopsworks.exceptions.UserException;
import io.hops.hopsworks.persistence.entity.featurestore.Featurestore;
import io.hops.hopsworks.persistence.entity.featurestore.storageconnector.FeaturestoreConnector;
import io.hops.hopsworks.persistence.entity.featurestore.storageconnector.gcs.FeatureStoreGcsConnector;
import io.hops.hopsworks.persistence.entity.project.Project;
import io.hops.hopsworks.persistence.entity.user.Users;
import io.hops.hopsworks.restutils.RESTCodes;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.transaction.Transactional;
import java.util.logging.Level;
import java.util.logging.Logger;
@Stateless
@TransactionAttribute(TransactionAttributeType.NEVER)
public class FeatureStoreGcsConnectorController {
private static final Logger LOGGER = Logger.getLogger(FeatureStoreGcsConnectorController.class.getName());
@EJB
private StorageConnectorUtil storageConnectorUtil;
public FeatureStoreGcsConnectorController() {}
public FeatureStoreGcsConnectorController(StorageConnectorUtil storageConnectorUtil) {
this.storageConnectorUtil = storageConnectorUtil;
}
public FeatureStoreGcsConnectorDTO getConnector(FeaturestoreConnector featurestoreConnector)
throws FeaturestoreException {
FeatureStoreGcsConnectorDTO gcsConnectorDTO = new FeatureStoreGcsConnectorDTO(featurestoreConnector);
gcsConnectorDTO.setKeyPath(featurestoreConnector.getGcsConnector().getKeyPath());
gcsConnectorDTO.setBucket(featurestoreConnector.getGcsConnector().getBucket());
if (featurestoreConnector.getGcsConnector().getEncryptionSecret() != null) {
EncryptionSecrets encryptionSecrets = storageConnectorUtil.getSecret(
featurestoreConnector.getGcsConnector().getEncryptionSecret(), EncryptionSecrets.class);
gcsConnectorDTO.setEncryptionKey(encryptionSecrets.getEncryptionKey());
gcsConnectorDTO.setEncryptionKeyHash(encryptionSecrets.getEncryptionKeyHash());
}
return gcsConnectorDTO;
}
public FeatureStoreGcsConnector createConnector(Project project, Users user, Featurestore featureStore,
FeatureStoreGcsConnectorDTO gcsConnectorDTO)
throws FeaturestoreException, ProjectException, UserException {
validateInput(project, user, gcsConnectorDTO);
FeatureStoreGcsConnector gcsConnector = new FeatureStoreGcsConnector();
gcsConnector.setKeyPath(gcsConnectorDTO.getKeyPath());
gcsConnector.setAlgorithm(gcsConnectorDTO.getAlgorithm());
gcsConnector.setBucket(gcsConnectorDTO.getBucket());
if (gcsConnectorDTO.getAlgorithm() != null) {
String secretName = storageConnectorUtil.createSecretName(featureStore.getId(), gcsConnectorDTO.getName(),
gcsConnectorDTO.getStorageConnectorType());
EncryptionSecrets secretsClass = new EncryptionSecrets(gcsConnectorDTO.getEncryptionKey(),
gcsConnectorDTO.getEncryptionKeyHash());
gcsConnector.setEncryptionSecret(storageConnectorUtil.createProjectSecret(user, secretName, featureStore,
secretsClass));
}
return gcsConnector;
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Transactional(rollbackOn = FeaturestoreException.class)
public FeatureStoreGcsConnector updateConnector(Project project, Users user, Featurestore featureStore,
FeatureStoreGcsConnectorDTO gcsConnectorDTO,
FeatureStoreGcsConnector gcsConnector)
throws FeaturestoreException, ProjectException, UserException {
validateInput(project, user, gcsConnectorDTO);
gcsConnector.setKeyPath(gcsConnectorDTO.getKeyPath());
gcsConnector.setAlgorithm(gcsConnectorDTO.getAlgorithm());
gcsConnector.setBucket(gcsConnectorDTO.getBucket());
if (gcsConnectorDTO.getAlgorithm() != null) {
String secretName = storageConnectorUtil.createSecretName(featureStore.getId(), gcsConnectorDTO.getName(),
gcsConnectorDTO.getStorageConnectorType());
EncryptionSecrets secretsClass = new EncryptionSecrets(gcsConnectorDTO.getEncryptionKey(),
gcsConnectorDTO.getEncryptionKeyHash());
gcsConnector.setEncryptionSecret(
storageConnectorUtil.updateProjectSecret(user, gcsConnector.getEncryptionSecret(),
secretName, featureStore, secretsClass));
} else {
gcsConnector.setEncryptionSecret(null);
}
return gcsConnector;
}
public void validateInput(Project project, Users user, FeatureStoreGcsConnectorDTO gcsConnectorDTO)
throws FeaturestoreException {
storageConnectorUtil.validatePath(project, user, gcsConnectorDTO.getKeyPath(), "Key file path");
if (Strings.isNullOrEmpty(gcsConnectorDTO.getKeyPath())) {
throw new FeaturestoreException(RESTCodes.FeaturestoreErrorCode.GCS_FIELD_MISSING, Level.FINE,
"Key File Path cannot be empty");
}
if (Strings.isNullOrEmpty(gcsConnectorDTO.getBucket())) {
throw new FeaturestoreException(RESTCodes.FeaturestoreErrorCode.GCS_FIELD_MISSING, Level.FINE,
"Bucket cannot be empty");
}
// either none of the three should be set or all
if (!Strings.isNullOrEmpty(gcsConnectorDTO.getEncryptionKey())
|| !Strings.isNullOrEmpty(gcsConnectorDTO.getEncryptionKeyHash())
|| gcsConnectorDTO.getAlgorithm() != null) {
if (Strings.isNullOrEmpty(gcsConnectorDTO.getEncryptionKey())
|| Strings.isNullOrEmpty(gcsConnectorDTO.getEncryptionKeyHash())
|| gcsConnectorDTO.getAlgorithm() == null) {
throw new FeaturestoreException(RESTCodes.FeaturestoreErrorCode.GCS_FIELD_MISSING, Level.FINE,
"Encryption algorithm, key and key hash have all to be set or all to be null, you provided: algorithm="
+ gcsConnectorDTO.getAlgorithm() + ", key="
+ gcsConnectorDTO.getEncryptionKey() + ", hashKey="
+ gcsConnectorDTO.getEncryptionKeyHash());
}
}
}
}
| java | 19 | 0.763893 | 113 | 48.393103 | 145 | research_code |
public void Init(float duration)
{
State = RecorderState.None;
m_MaxFrameCount = Mathf.RoundToInt(duration * m_FramePerSecond);
m_TimePerFrame = 1f / m_FramePerSecond;
m_Time = 0f;
// Make sure the output folder is set or use the default one
if (string.IsNullOrEmpty(SaveFolder))
{
#if UNITY_EDITOR
SaveFolder =
Application
.persistentDataPath; // Defaults to the asset folder in the editor for faster access to the gif file
#else
SaveFolder = Application.persistentDataPath;
#endif
}
} | c# | 10 | 0.568627 | 124 | 33.947368 | 19 | inline |
@Test
public void test_0010() throws LPInfeasible, Exception {
/*
* take the opposite/negative of the objective function in example 11.1 on page 273
* to convert maximization problem to minimization problem
*/
DenseVector c = new DenseVector(new double[]{1, -2, -1, -2});
Matrix ALessThan = new DenseMatrix(new double[][]{
{1, 1, -1, 3},
{0, 1, 3, -1}
});
DenseVector bLessThan = new DenseVector(new double[]{7, 5});
Matrix AGreaterThan = new DenseMatrix(new double[][]{
{3, 0, 0, 1}
});
DenseVector bGreaterThan = new DenseVector(new double[]{2});
ILPProblemImpl1 problem = new ILPProblemImpl1(c,
new LinearGreaterThanConstraints(AGreaterThan, bGreaterThan),
new LinearLessThanConstraints(ALessThan, bLessThan),
null, null, new int[]{1, 2, 3}, 1e-8);//only y1, y2, y3 has the restriction to be integer
ILPBranchAndBound bb = new ILPBranchAndBound();
MinimizationSolution<Vector> soln = bb.solve(problem);
assertEquals(-9.666666666666666, soln.minimum(), 1e-15);
assertArrayEquals(new double[]{1, 5, 0, 1. / 3}, soln.minimizer().toArray(), 1e-15);
} | java | 11 | 0.528237 | 143 | 53.923077 | 26 | inline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.