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 |
---|---|---|---|---|---|---|---|
import unittest
from scratch_map import app
class TestInfo(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def test_info_with_git_info(self):
response = self.app.get("/info", follow_redirects=True)
self.assertEqual(response.status_code, 200)
self.assertIn('"version": "0.0.0"'.encode(), response.data) | python | 11 | 0.67233 | 67 | 26.466667 | 15 | starcoderdata |
func (c *Client) createRemoteBranch(authedClient *http.Client, b GerritProjectBranch, dryRun bool) error {
if dryRun {
return nil
}
agClient, err := gerritapi.NewClient(b.GerritURL, authedClient)
if err != nil {
return fmt.Errorf("failed to create Gerrit client: %v", err)
}
bi, resp, err := agClient.Projects.CreateBranch(b.Project, b.Branch, &gerritapi.BranchInput{Revision: b.SrcRef})
defer resp.Body.Close()
if err != nil {
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
// shouldn't happen
return err2
}
if resp.StatusCode == http.StatusConflict && strings.Contains(string(body), "already exists") {
// Branch already exists, so there's nothing to do.
c.LogOut("branch %s already exists for %s/%s, nothing to do here", b.Branch, b.GerritURL, b.Project)
return nil
}
return errors.Annotate(err, "failed to create branch. Got response %v and branch info %v", string(body), bi).Err()
}
return nil
} | go | 13 | 0.700315 | 116 | 37.08 | 25 | inline |
export {default as PushButton} from './components/push-buttons/PushButton';
export {default as HelpButton} from './components/help-buttons/HelpButton';
export {default as ToolbarItem} from './components/toolbars/ToolbarItem';
export {default as Dock} from './components/docks/Dock';
export {default as DockContainer} from './components/docks/DockContainer';
export {default as DockItem} from './components/docks/DockItem';
export {default as DockDivider} from './components/docks/DockDivider';
export {default as DropdownList} from './components/lists/DropdownList';
export {default as List} from './components/lists/List';
export {default as ListDivider} from './components/lists/ListDivider';
export {default as ListHeader} from './components/lists/ListHeader';
export {default as ListItem} from './components/lists/ListItem';
export {default as MenuBarMenus} from './components/menus/MenuBarMenus';
export {default as Menu} from './components/menus/Menu';
export {default as MenuList} from './components/menus/MenuList';
export {default as MenuGroup} from './components/menus/MenuGroup';
export {default as MenuItem} from './components/menus/MenuItem';
export {default as MenuDivider} from './components/menus/MenuDivider';
export {default as MenuBarButton} from './components/menus/MenuBarButton';
export {default as MenuBarButtons} from './components/menus/MenuBarButtons';
export {default as Notification} from './components/notification-centers/Notification';
export {default as NotificationCenter} from './components/notification-centers/NotificationCenter';
export {default as Notifications} from './components/notification-centers/Notifications';
export {default as Widget} from './components/notification-centers/Widget';
export {default as Widgets} from './components/notification-centers/Widgets';
export {default as CircularBar} from './components/circular-bars/CircularBar';
export {default as Segment} from './components/segmented-controls/Segment';
export {default as Segments} from './components/segmented-controls/Segments';
export {default as Slider} from './components/sliders/Slider';
export {default as Spinner} from './components/progress-indicators/Spinner';
export {default as Tooltip} from './components/tooltips/Tooltip';
export {default as TrafficLights} from './components/traffic-lights/TrafficLights';
export {default as AnimatedWindow} from './components/windows/AnimatedWindow';
export {default as TitleBarWindow} from './components/windows/TitleBarWindow';
export {default as ToolbarWindow} from './components/windows/ToolbarWindow';
export {default as ColumnView} from './components/column-views/ColumnView';
export {default as ColumnViewFactory} from './components/column-views/ColumnViewFactory'
export {default as Control} from './components/control-centers/Control';
export {default as Controls} from './components/control-centers/Controls';
export {default as Popover} from './components/popovers/Popover'; | javascript | 4 | 0.791653 | 99 | 72.7 | 40 | starcoderdata |
import os
import sys
import cv2
import yaml
import time
import datetime
from model import Model
from dataset import ImageDataset, BatchDataset
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision.models import vgg
root_path = os.getcwd()
if __name__ == '__main__':
store_path = os.path.abspath(root_path + '/models/vgg')
if not os.path.isdir(store_path):
print ('No folder named \"models/\"')
exit()
model_lst = [x for x in sorted(os.listdir(store_path)) if x.endswith('.pkl')]
with open(root_path+'/config/config.yaml', 'r') as f:
config = yaml.safe_load(f)
path = config['kitti_path']
epochs = config['epochs']
batches = config['batches']
bins = config['bins']
alpha = config['alpha']
w = config['w']
data = ImageDataset(path + '/training')
data = BatchDataset(data, batches, bins, mode = 'eval')
if len(model_lst) == 0:
print ('No previous model found, please check it')
exit()
else:
print ('Find previous model %s'%model_lst[-1])
vgg = vgg.vgg19_bn(pretrained=False)
model = Model(features=vgg.features, bins=bins).cuda()
params = torch.load(store_path + '/%s'%model_lst[-1])
model.load_state_dict(params)
model.eval()
angle_error = []
dimension_error = []
for i in range(data.num_of_patch):
batch, centerAngle, info = data.EvalBatch()
dimGT = info['Dimension']
angle = info['LocalAngle'] / np.pi * 180
Ry = info['Ry']
batch = Variable(torch.FloatTensor(batch), requires_grad=False).cuda()
[orient, conf, dim] = model(batch)
orient = orient.cpu().data.numpy()[0, :, :]
conf = conf.cpu().data.numpy()[0, :]
dim = dim.cpu().data.numpy()[0, :]
argmax = np.argmax(conf)
orient = orient[argmax, :]
cos = orient[0]
sin = orient[1]
theta = np.arctan2(sin, cos) / np.pi * 180
theta = theta + centerAngle[argmax] / np.pi * 180
theta = 360 - info['ThetaRay'] - theta
if theta > 0: theta -= int(theta / 360) * 360
elif theta < 0: theta += (int(-theta / 360) + 1) * 360
if Ry > 0: Ry -= int(Ry / 360) * 360
elif Ry < 0: Ry += (int(-Ry / 360) + 1) * 360
theta_error = abs(Ry - theta)
if theta_error > 180: theta_error = 360 - theta_error
angle_error.append(theta_error)
dim_error = np.mean(abs(np.array(dimGT) - dim))
dimension_error.append(dim_error)
#if i % 60 == 0:
# print (theta, Ry)
# print (dim.tolist(), dimGT)
if i % 1000 == 0:
now = datetime.datetime.now()
now_s = now.strftime('%Y-%m-%d-%H-%M-%S')
print ('------- %s %.5d -------'%(now_s, i))
print ('Angle error: %lf'%(np.mean(angle_error)))
print ('Dimension error: %lf'%(np.mean(dimension_error)))
print ('-----------------------------')
print ('Angle error: %lf'%(np.mean(angle_error)))
print ('Dimension error: %lf'%(np.mean(dimension_error))) | python | 17 | 0.557776 | 81 | 32.705263 | 95 | starcoderdata |
#ifndef COMMON_CLOCK_H
#define COMMON_CLOCK_H
namespace Common {
class Clock {
public:
Clock();
double limitFPS(int fps, bool output = true);
static double getTime();
private:
double mLastTime;
double mStatTime;
int mFrames;
};
class Countdown {
public:
Countdown(float from);
void doCountdown(float howmuch);
bool checkAndRewind();
bool countdownAndRewind(float howmuch);
void rewind();
bool check();
bool running() const;
float timeLeft() const;
void clear();
float getMaxTime() const;
private:
float mFrom;
float mNow;
bool mChecked;
};
class SteadyTimer {
public:
SteadyTimer(float steptime, float randomInit = 0.0f);
bool check(float elapsedtime);
private:
float mStepTime;
float mLeftTime;
};
}
#endif | c | 11 | 0.700521 | 55 | 15 | 48 | starcoderdata |
#ifndef _RTSP_API_H_
#define _RTSP_API_H_
#include "dlist.h"
#include "basic_types.h"
#include "osdep_service.h"
#if defined(CONFIG_PLATFORM_8195A)
#include "mmf_dbg.h"
#endif
#if defined(CONFIG_PLATFORM_8195BHP)
#include "mmf2_dbg.h"
#endif
#include "rtsp/rtp_api.h"
#include "avcodec.h"
#include "rtsp/sdp.h"
//Trigger for softphone feature, when open it, run sip example and close rtsp example
//#define ENABLE_SIP_MMFV2
#define ENABLE_PROXY_SEVER 0
#if ENABLE_PROXY_SEVER
#define PROXY_SERVER_IP "172.16.58.3"
#define PROXY_SERVER_PORT 5000
#endif
/* clock usage */
#define RTSP_DEPEND_CLK_HZ configTICK_RATE_HZ
#define RTSP_SERVICE_PRIORITY 3
#define RTSP_MAX_STREAM_NUM 2
#define RTSP_REQUEST_BUF_SIZE 512
#define RTSP_RESPONSE_BUF_SIZE MAX_SDP_SIZE //max size for response buffer
#define DEF_RTSP_PORT 554
#define DEF_HTTP_PORT 5008
#define RTSP_SELECT_SOCK 8
/*rtsp request type list*/
#define REQUEST_OPTIONS 1
#define REQUEST_DESCRIBE 2
#define REQUEST_SETUP 3
#define REQUEST_TEARDOWN 4
#define REQUEST_PLAY 5
#define REQUEST_PAUSE 6
#define REQUEST_GET_PARAM 7
#define RTSP_INTERLEAVED_FRAME 8
/*rtsp cast mode list*/
#define UNICAST_UDP_MODE 1
#define UNICAST_TCP_MODE 2
#define MULTICAST_MODE 3
#define BOUNDARY "amebaimagetest"
/*RTSP KEEPALIVE TIMEOUT ENABLE*/
#define KEEPALIVE_TIMEOUT_ENABLE
enum _rtsp_state {
RTSP_INIT = 0,
RTSP_READY = 1,
RTSP_PLAYING = 2,
};
typedef enum _rtsp_state rtsp_state;
struct rtsp_session
{
uint32_t id;
uint8_t version;
uint32_t start_time;
uint32_t end_time;
uint8_t *user;
uint8_t *name;
};
struct rtsp_transport
{
uint8_t isRtp; //transport protocol
uint8_t isTcp; //lower transport protocol
uint8_t castMode; //unicast UDP(1) or unicast TCP(2) or multicast(3)
int port_low;
int port_high;
int clientport_low;
int clientport_high;
int serverport_low;
int serverport_high;
uint8_t ttl; //multicast time to live
//to be added if necessary
int interleaved_low; // for RTSP over TCP
int interleaved_high; // for RTSP over TCP
};
struct __internal_payload{
int codec_id;
struct rtp_object payload;
};
struct stream_context
{
struct rtsp_context *parent;
int stream_id; //sync with stream_flow id
struct list_head input_queue;
_mutex input_lock;
struct list_head output_queue;
_mutex output_lock;
struct codec_info *codec;
uint8_t media_type;
uint8_t framerate;
uint32_t bitrate;
uint32_t samplerate;
uint32_t channel;
uint32_t old_depend_clock_tick;
uint32_t rtp_timestamp;
uint8_t use_rtp_tick_inc;
uint8_t index; // index in rtsp_context
uint8_t setup_done;
struct rtp_statistics statistics;
struct rtp_periodic_report_s periodic_report;
struct __internal_payload rtpobj;
};
struct rtsp_context
{
int id;
uint8_t allow_stream;
rtsp_state state;
uint8_t request_type;
uint8_t request_incomplete;
uint32_t CSeq;
char *response;
struct connect_context connect_ctx;
int proxy_socket;
int proxy_port;
uint8_t is_connected_to_proxy;
struct rtsp_transport transport[RTSP_MAX_STREAM_NUM];
struct rtsp_session session;
u16 rtpseq[RTSP_MAX_STREAM_NUM];
uint8_t is_rtsp_start;
_sema start_rtsp_sema;
uint8_t is_rtp_start;
_sema start_rtp_sema;
void (* rtp_service_handle) (struct rtsp_context* rtsp_ctx);
_sema start_proxy_connect_sema;
_sema rtp_input_sema;
_sema rtp_output_sema;
#ifdef SUPPORT_RTCP
uint8_t is_rtcp_start;
_sema start_rtcp_sema;
void (* rtcp_service_handle) (struct rtsp_context* rtsp_ctx);
#endif
#ifdef SUPPORT_HTTP
//to be added
#endif
uint8_t nb_streams_setup;
int8_t setup_stream_index;
uint8_t nb_streams;
struct stream_context *stream_ctx;
uint32_t pre_filter_packet;
int client_socket;
_mutex socket_lock;
// callback
int (*cb_start)(void*); // play
int (*cb_stop)(void*); // teardown
int (*cb_pause)(void*); // pause
int (*cb_custom)(void*); // setparam
};
uint32_t rtsp_get_timestamp(struct stream_context *stream_ctx, uint32_t current_clock_tick);
int rtsp_get_number(int number_base, uint32_t *number_bitmap, _mutex *bitmap_lock);
void rtsp_put_number(int number, int number_base, uint32_t *number_bitmap, _mutex *bitmap_lock);
struct rtsp_context *rtsp_context_create(uint8_t nb_streams);
void rtsp_context_free(struct rtsp_context *rtsp_ctx);
int rtsp_is_stream_enabled(struct rtsp_context *rtsp_ctx);
int rtsp_is_service_enabled(struct rtsp_context *rtsp_ctx);
int rtsp_open(struct rtsp_context *rtsp_ctx);
void rtsp_close(struct rtsp_context *rtsp_ctx);
void rtsp_start(struct rtsp_context *rtsp_ctx);
void rtsp_stop(struct rtsp_context *rtsp_ctx);
void rtp_object_in_stream_queue(struct rtp_object *payload, struct stream_context *stream_ctx);
struct rtp_object *rtp_object_out_stream_queue(struct stream_context *stream_ctx);
void set_profile_lv_string(char * plid);
void set_sps_string(char * sps);
void set_pps_string(char * pps);
int rtsp_parse_stream_media_type(struct codec_info *codec);
void rtsp_stream_context_init(struct rtsp_context *rtsp_ctx, struct stream_context *stream_ctx);
void set_prefilter_packet(struct rtsp_context *rtsp_ctx,uint32_t num);
void time_sync_disable(void);
void time_sync_enable(void);
#endif | c | 10 | 0.739308 | 96 | 25.791667 | 192 | starcoderdata |
// Copyright 2019 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.
package org.chromium.components.thinwebview.internal;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.DoNotInline;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.embedder_support.delegate.WebContentsDelegateAndroid;
import org.chromium.components.thinwebview.CompositorView;
import org.chromium.components.thinwebview.ThinWebView;
import org.chromium.components.thinwebview.ThinWebViewConstraints;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.WindowAndroid;
/**
* An android view backed by a {@link Surface} that is able to display a live {@link WebContents}.
*/
@JNINamespace("thin_webview::android")
public class ThinWebViewImpl extends FrameLayout implements ThinWebView {
private final CompositorView mCompositorView;
private WindowAndroid mWindowAndroid;
private long mNativeThinWebViewImpl;
private WebContents mWebContents;
private View mContentView;
// Passed to native and stored as a weak reference, so ensure this strong
// reference is not optimized away by R8.
@DoNotInline
private WebContentsDelegateAndroid mWebContentsDelegate;
/**
* Creates a {@link ThinWebViewImpl} backed by a {@link Surface}.
* @param context The Context to create this view.
* @param windowAndroid The associated {@code WindowAndroid} on which the view is to be
* displayed.
* @param constraints A set of constraints associated with this view.
*/
public ThinWebViewImpl(Context context, ThinWebViewConstraints constraints) {
super(context);
if (ContextUtils.activityFromContext(context) != null) {
mWindowAndroid = new ActivityWindowAndroid(context, /* listenToActivityState= */ true);
} else {
mWindowAndroid = new WindowAndroid(context);
}
mCompositorView = new CompositorViewImpl(context, mWindowAndroid, constraints);
LayoutParams layoutParams = new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
addView(mCompositorView.getView(), layoutParams);
mNativeThinWebViewImpl = ThinWebViewImplJni.get().init(
ThinWebViewImpl.this, mCompositorView, mWindowAndroid);
}
@Override
public View getView() {
return this;
}
@Override
public void attachWebContents(WebContents webContents, @Nullable View contentView,
@Nullable WebContentsDelegateAndroid delegate) {
if (mNativeThinWebViewImpl == 0) return;
mWebContents = webContents;
// Native code holds only a weak reference to this object.
mWebContentsDelegate = delegate;
setContentView(contentView);
ThinWebViewImplJni.get().setWebContents(
mNativeThinWebViewImpl, ThinWebViewImpl.this, webContents, delegate);
webContents.onShow();
}
@Override
public void destroy() {
if (mNativeThinWebViewImpl == 0) return;
if (mContentView != null) {
removeView(mContentView);
mContentView = null;
}
mCompositorView.destroy();
ThinWebViewImplJni.get().destroy(mNativeThinWebViewImpl, ThinWebViewImpl.this);
mNativeThinWebViewImpl = 0;
mWindowAndroid.destroy();
}
@Override
public void setAlpha(float alpha) {
mCompositorView.setAlpha(alpha);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mNativeThinWebViewImpl == 0) return;
if (w != oldw || h != oldh) {
ThinWebViewImplJni.get().sizeChanged(
mNativeThinWebViewImpl, ThinWebViewImpl.this, w, h);
}
}
private void setContentView(View contentView) {
if (mContentView == contentView) return;
if (mContentView != null) {
assert getChildCount() > 1;
removeViewAt(1);
}
mContentView = contentView;
if (mContentView != null) addView(mContentView, 1);
}
@NativeMethods
interface Natives {
long init(
ThinWebViewImpl caller, CompositorView compositorView, WindowAndroid windowAndroid);
void destroy(long nativeThinWebView, ThinWebViewImpl caller);
void setWebContents(long nativeThinWebView, ThinWebViewImpl caller, WebContents webContents,
WebContentsDelegateAndroid delegate);
void sizeChanged(long nativeThinWebView, ThinWebViewImpl caller, int width, int height);
}
} | java | 11 | 0.702547 | 100 | 37.075758 | 132 | starcoderdata |
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import
#import
#import
NS_ASSUME_NONNULL_BEGIN
@class ABI31_0_0RCTShadowView;
typedef NS_ENUM(NSInteger, ABI31_0_0RCTDisplayType) {
ABI31_0_0RCTDisplayTypeNone,
ABI31_0_0RCTDisplayTypeFlex,
ABI31_0_0RCTDisplayTypeInline,
};
struct ABI31_0_0RCTLayoutMetrics {
CGRect frame;
CGRect contentFrame;
UIEdgeInsets borderWidth;
ABI31_0_0RCTDisplayType displayType;
UIUserInterfaceLayoutDirection layoutDirection;
};
typedef struct CG_BOXABLE ABI31_0_0RCTLayoutMetrics ABI31_0_0RCTLayoutMetrics;
struct ABI31_0_0RCTLayoutContext {
CGPoint absolutePosition;
__unsafe_unretained NSHashTable<ABI31_0_0RCTShadowView *> *_Nonnull affectedShadowViews;
__unsafe_unretained NSHashTable<NSString *> *_Nonnull other;
};
typedef struct CG_BOXABLE ABI31_0_0RCTLayoutContext ABI31_0_0RCTLayoutContext;
static inline BOOL ABI31_0_0RCTLayoutMetricsEqualToLayoutMetrics(ABI31_0_0RCTLayoutMetrics a, ABI31_0_0RCTLayoutMetrics b)
{
return
CGRectEqualToRect(a.frame, b.frame) &&
CGRectEqualToRect(a.contentFrame, b.contentFrame) &&
UIEdgeInsetsEqualToEdgeInsets(a.borderWidth, b.borderWidth) &&
a.displayType == b.displayType &&
a.layoutDirection == b.layoutDirection;
}
ABI31_0_0RCT_EXTERN ABI31_0_0RCTLayoutMetrics ABI31_0_0RCTLayoutMetricsFromYogaNode(ABI31_0_0YGNodeRef yogaNode);
/**
* Converts float values between Yoga and CoreGraphics representations,
* especially in terms of edge cases.
*/
ABI31_0_0RCT_EXTERN float ABI31_0_0RCTYogaFloatFromCoreGraphicsFloat(CGFloat value);
ABI31_0_0RCT_EXTERN CGFloat ABI31_0_0RCTCoreGraphicsFloatFromYogaFloat(float value);
/**
* Converts compound `ABI31_0_0YGValue` to simple `CGFloat` value.
*/
ABI31_0_0RCT_EXTERN CGFloat ABI31_0_0RCTCoreGraphicsFloatFromYogaValue(ABI31_0_0YGValue value, CGFloat baseFloatValue);
/**
* Converts `ABI31_0_0YGDirection` to `UIUserInterfaceLayoutDirection` and vise versa.
*/
ABI31_0_0RCT_EXTERN ABI31_0_0YGDirection ABI31_0_0RCTYogaLayoutDirectionFromUIKitLayoutDirection(UIUserInterfaceLayoutDirection direction);
ABI31_0_0RCT_EXTERN UIUserInterfaceLayoutDirection ABI31_0_0RCTUIKitLayoutDirectionFromYogaLayoutDirection(ABI31_0_0YGDirection direction);
/**
* Converts `ABI31_0_0YGDisplay` to `ABI31_0_0RCTDisplayType` and vise versa.
*/
ABI31_0_0RCT_EXTERN ABI31_0_0YGDisplay ABI31_0_0RCTYogaDisplayTypeFromReactABI31_0_0DisplayType(ABI31_0_0RCTDisplayType displayType);
ABI31_0_0RCT_EXTERN ABI31_0_0RCTDisplayType ABI31_0_0RCTReactABI31_0_0DisplayTypeFromYogaDisplayType(ABI31_0_0YGDisplay displayType);
NS_ASSUME_NONNULL_END | c | 11 | 0.798967 | 139 | 37.223684 | 76 | starcoderdata |
forall_out_edges(G, e, node) {
NodeID target = G.getEdgeTarget(e);
if(G.getPartitionIndex(target) == 0 || G.getPartitionIndex(target) == 1) {
// outer boundary node
outer_lhs_boundary_nodes.push_back(node);
break;
}
} | c++ | 9 | 0.38404 | 98 | 49.25 | 8 | inline |
PLY_NO_INLINE void DirectoryWatcher_Win32::runWatcher() {
// FIXME: prepend \\?\ to the path to get past MAX_PATH limitation
HANDLE hDirectory =
CreateFileW(win32PathArg(m_root), FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
PLY_ASSERT(hDirectory != INVALID_HANDLE_VALUE);
HANDLE hChangeEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
PLY_ASSERT(hChangeEvent != INVALID_HANDLE_VALUE);
static const DWORD notifyInfoSize = 65536;
FILE_NOTIFY_INFORMATION* notifyInfo = (FILE_NOTIFY_INFORMATION*) PLY_HEAP.alloc(notifyInfoSize);
for (;;) {
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = hChangeEvent;
BOOL rc = ReadDirectoryChangesW(hDirectory, notifyInfo, notifyInfoSize, TRUE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_LAST_WRITE,
NULL, &overlapped, NULL);
// FIXME: Handle ERROR_NOTIFY_ENUM_DIR
HANDLE events[2] = {m_endEvent, hChangeEvent};
DWORD waitResult = WaitForMultipleObjects(2, events, FALSE, INFINITE);
PLY_ASSERT(waitResult >= WAIT_OBJECT_0 && waitResult <= WAIT_OBJECT_0 + 1);
if (waitResult == WAIT_OBJECT_0)
break;
FILE_NOTIFY_INFORMATION* r = notifyInfo;
for (;;) {
// "The file name is in the Unicode character format and is not null-terminated."
// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-_file_notify_information
WStringView win32Path{r->FileName, r->FileNameLength / sizeof(WCHAR)};
String path = TextConverter::convert<UTF8, UTF16_Native>(win32Path.stringView());
bool isDirectory = false;
DWORD attribs;
{
// FIXME: Avoid some of the UTF-8 <--> UTF-16 conversions done here
String fullPath = WindowsPath::join(m_root, path);
attribs = GetFileAttributesW(win32PathArg(fullPath));
}
if (attribs == INVALID_FILE_ATTRIBUTES) {
PLY_ASSERT(GetLastError() == ERROR_FILE_NOT_FOUND);
} else {
isDirectory = (attribs & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
SLOG(m_log, "{} \"{}\" changed", isDirectory ? "Directory" : "File", path);
if (isDirectory) {
if (r->Action == FILE_ACTION_REMOVED || r->Action == FILE_ACTION_RENAMED_OLD_NAME ||
r->Action == FILE_ACTION_RENAMED_NEW_NAME) {
m_callback(path, true);
}
} else {
m_callback(path, false);
}
if (r->NextEntryOffset == 0)
break;
r = (FILE_NOTIFY_INFORMATION*) PLY_PTR_OFFSET(r, r->NextEntryOffset);
}
}
PLY_HEAP.free(notifyInfo);
CloseHandle(hChangeEvent);
CloseHandle(hDirectory);
} | c++ | 15 | 0.569767 | 105 | 51.725806 | 62 | inline |
package class
import (
"testing"
)
func TestFindClass(t *testing.T) {
class := findClass(&[]Class{
{Notation: "TQ"},
}, "TQ17")
if class == nil {
t.Fatal("expected non-nil; got nil")
}
} | go | 15 | 0.635965 | 38 | 14.2 | 15 | starcoderdata |
<?php
namespace Wikichua\LaravelBread;
use File;
use Illuminate\Support\ServiceProvider;
class LaravelBreadServiceProvider extends ServiceProvider
{
protected $defer = false;
public function boot(\Illuminate\Routing\Router $router)
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('DataTables', Yajra\DataTables\Facades\DataTables::class);
$this->publishes([
__DIR__ . '/../publish/migrations/' => database_path('migrations'),
__DIR__ . '/../publish/Model/' => app_path(),
__DIR__ . '/../publish/Controllers/' => app_path('Http/Controllers'),
__DIR__ . '/../publish/resources/' => base_path('resources'),
__DIR__ . '/../publish/crudgenerator.php' => config_path('crudgenerator.php'),
__DIR__ . '/../publish/menus.php' => config_path('menus.php'),
__DIR__ . '/views' => base_path('resources/views/vendor/laravel-bread'),
], 'views');
$this->loadViewsFrom(__DIR__ . '/views', 'laravel-bread');
view()->share('laravelAdminMenus', config('menus'));
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->commands(
'Wikichua\LaravelBread\LaravelBreadCommand',
'Wikichua\LaravelBread\Commands\CrudCommand',
'Wikichua\LaravelBread\Commands\CrudControllerCommand',
'Wikichua\LaravelBread\Commands\CrudModelCommand',
'Wikichua\LaravelBread\Commands\CrudMigrationCommand',
'Wikichua\LaravelBread\Commands\CrudViewCommand',
'Wikichua\LaravelBread\Commands\CrudLangCommand',
'Wikichua\LaravelBread\Commands\CrudApiCommand',
'Wikichua\LaravelBread\Commands\CrudApiControllerCommand'
);
$this->app->bind('Setting', \Wikichua\LaravelBread\Setting::class);
}
} | php | 15 | 0.614987 | 90 | 38.489796 | 49 | starcoderdata |
using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace ClienteRest
{
class Program
{
static void Main(string[] args)
{
using (var cliente = new HttpClient()) {
var respuesta = cliente.GetStringAsync("https://restcountries.eu/rest/v2/all").GetAwaiter().GetResult();
// List paises = new List
//List paises = JsonConvert.SerializeObject
}
}
}
} | c# | 21 | 0.60453 | 121 | 25.090909 | 22 | starcoderdata |
int main(int argc, char *argv[]) {
if (argc < 4) {
std::cout << "Usage: " << argv[0] << " <csv-file> <rows> <columns> <threads default=#cpus>\n";
return 1;
}
//EPP::testMexPolygon();
long cost = 0;
int measurements = std::stoi(argv[3]);
long events = std::stoi(argv[2]);
int threads = std::thread::hardware_concurrency();
if (argc > 4)
threads = std::stoi(argv[4]);
// int threads = 1;
// get some data from somewhere? CSV?
float *data = new float[measurements * events]; //released when main exits
std::ifstream datafile(argv[1], std::ios::in);
if (!datafile.good()) {
std::cout << "Cannot open file " << argv[1] << std::endl;
return 1;
}
std::string line;
std::string value;
std::getline(datafile, line); // skip over header
long i = 0;
std::string lastLine;
for (; i < events; i++) {
if (i == events - 1) {
lastLine += "Row #" + std::to_string(i) + ": ";
}
std::getline(datafile, line);
std::stringstream sstr(line, std::ios::in);
for (int j = 0; j < measurements; j++) {
std::getline(sstr, value, ',');
data[i + events * j] = std::stof(value); // MATLAB column wise expected
if (i == events - 1) {
lastLine += value + ", ";
}
}
}
datafile.close();
std::cout << lastLine << std::endl;
//EPP::testMex(data, events, measurements, 0, 1, .26, .3, "kld");
EPP::testMex(data, events, measurements, 0, 1);
EPP::testMex(data, events, measurements, 0, 6);
// EPP::testMex(data, events, measurements);
// EPP::Modal2WaySplit split(data, events, measurements, threads);
// double *sptx = new double[split.size() * 2];
// split.copyPoints(sptx, true, true);
// split.print();
std::cout << std::endl;
} | c++ | 13 | 0.536948 | 102 | 34.509434 | 53 | inline |
window.onload = function() {demoTooltip()};
function demoTooltip() {
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
};
export { demoTooltip }; | javascript | 13 | 0.661905 | 46 | 20.1 | 10 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OWFControls.DataGrid.Drawing
{
[Flags]
public enum OWFDrawMode
{
None = 0,
Resize = 1,
Zoom = 2,
Selection = 4,
EditCell = 8,
Scroll = 16,
RowColChange = 32,
DataChange = 64,
All = 128
}
} | c# | 6 | 0.57284 | 38 | 17.409091 | 22 | starcoderdata |
#ifndef VX_INTRINSICS_H
#define VX_INTRINSICS_H
#ifdef __cplusplus
extern "C" {
#endif
// Spawn warps
void vx_wspawn(int num_warps, unsigned func_ptr);
// Set thread mask
void vx_tmc(int num_threads);
// Warp Barrier
void vx_barrier(int barried_id, int num_warps);
// Split on a predicate
void vx_split(int predicate);
// Join
void vx_join();
// Return the warp's unique thread id
int vx_thread_id();
// Return the core's unique warp id
int vx_warp_id();
// Return processsor unique core id
int vx_core_id();
// Return processsor global thread id
int vx_thread_gid();
// Return processsor global warp id
int vx_warp_gid();
// Return the number of threads in a warp
int vx_num_threads();
// Return the number of warps in a core
int vx_num_warps();
// Return the number of cores in the processsor
int vx_num_cores();
// Return the number of cycles
int vx_num_cycles();
// Return the number of instructions
int vx_num_instrs();
// Return if L3 cache-split is activated
int vx_cache_split();
#define __if(b) vx_split(b); \
if (b)
#define __else else
#define __endif vx_join();
#ifdef __cplusplus
}
#endif
#endif | c | 10 | 0.692178 | 49 | 16.5 | 68 | starcoderdata |
#ifndef PROJECT_VISITOR_H
#define PROJECT_VISITOR_H
#include
#include
#include
#include
#include
#include "../abstract_domain/AbstractDomain.h"
#include "../util/util.h"
#include "branch_conditions.h"
#include "state.h"
#include "worklist.h"
#include
using namespace llvm;
namespace pcpo {
class VsaVisitor : public InstVisitor<VsaVisitor, void> {
public:
VsaVisitor(WorkList &q, DominatorTree& DT, std::map<BasicBlock *, State>& programPoints)
: worklist(q), DT(DT), newState(), programPoints(programPoints), bcs(programPoints){};
/// create lub of states of preceeding basic blocks and use it as newState;
/// the visitor automatically visits all instructions of this basic block
void visitBasicBlock(BasicBlock &BB);
/// visit TerminatorInstruction:
/// compare lub(oldState, newState) with oldState of basic block; if state
/// has changed: update state and push direct successors basic block into
/// the working list
void visitTerminatorInst(TerminatorInst &I);
/// visit BranchInstruction:
/// before calling visitTerminatorInst, it evaluates branch conditions
void visitBranchInst(BranchInst &I);
/// visit SwitchInstruction:
/// before calling visitTerminatorInst, it evaluates branch conditions
void visitSwitchInst(SwitchInst &I);
/// visit LoadInstruction:
/// set variable explicitly top
void visitLoadInst(LoadInst &I);
/// visit PHINode:
/// visitBasicBlock has already created lub of states of preceeding bbs
/// here we only add the
void visitPHINode(PHINode &I);
/*void visitIndirectBrInst(IndirectBrInst &I);
void visitResumeInst(ResumeInst &I);
void visitICmpInst(ICmpInst &I);
void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
void visitTruncInst(TruncInst &I);
void visitZExtInst(ZExtInst &I);
void visitSExtInst(SExtInst &I);
void visitBitCastInst(BitCastInst &I);
void visitSelectInst(SelectInst &I);
void visitVAArgInst(VAArgInst &I);
void visitExtractElementInst(ExtractElementInst &I);
void visitExtractValueInst(ExtractValueInst &I);*/
/// Call and Invoke
// void visitCallInst(CallInst &I);
// void visitInvokeInst(InvokeInst &I);
/// BinaryOperators
void visitAdd(BinaryOperator &I);
void visitSub(BinaryOperator &I);
void visitMul(BinaryOperator &I);
void visitURem(BinaryOperator &I);
void visitSRem(BinaryOperator &I);
void visitUDiv(BinaryOperator &I);
void visitSDiv(BinaryOperator &I);
void visitAnd(BinaryOperator &I);
void visitOr(BinaryOperator &I);
void visitXor(BinaryOperator &I);
void visitShl(Instruction &I);
void visitLShr(Instruction &I);
void visitAShr(Instruction &I);
/// if not specific get the whole class
// void visitCastInst(CastInst &I);
void visitBinaryOperator(BinaryOperator &I);
// void visitCmpInst(CmpInst &I);
void visitUnaryInstruction(UnaryInstruction &I);
/// default
void visitInstruction(Instruction &I);
/// print state of all basic blocks
void print() const;
/// return the program points
std::map<BasicBlock *, State> &getProgramPoints();
private:
/// push directly reachable basic blocks onto worklist
void pushSuccessors(TerminatorInst &I);
void putBothBranchConditions(BranchInst& I, Value* op,
std::pair shared_ptr &valuePair);
WorkList &worklist;
DominatorTree& DT;
State newState;
std::map<BasicBlock *, State>& programPoints;
BranchConditions bcs;
};
}
#endif // PROJECT_VISITOR_H | c | 14 | 0.740155 | 92 | 29.820513 | 117 | starcoderdata |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#endregion
namespace Components
{
using System;
using System.Data;
using DotNetNuke.Framework;
public abstract class DataProvider
{
public abstract string ObjectQualifier { get; }
public abstract string DatabaseOwner { get; }
#region Event PayPal Functions
public abstract IDataReader EventsPpErrorLogAdd(int signupId, string
payPalStatus, string payPalReason, string payPalTransId,
string payPalPayerId, string payPalPayerStatus,
string payPalRecieverEmail, string payPalUserEmail,
string payPalPayerEmail,
string payPalFirstName, string payPalLastName,
string payPalAddress, string payPalCity,
string payPalState, string payPalZip, string payPalCountry,
string payPalCurrency,
DateTime payPalPaymentDate, double payPalAmount,
double payPalFee);
#endregion
#region Shared/Static Methods
// singleton reference to the instantiated object
private static DataProvider _objProvider;
// constructor
static DataProvider()
{
CreateProvider();
}
// dynamically create provider
private static void CreateProvider()
{
_objProvider = (DataProvider) Reflection.CreateObject("data", "DotNetNuke.Modules.Events", "");
}
// return the provider
public new static DataProvider Instance()
{
return _objProvider;
}
#endregion
#region Event Functions
public abstract void EventsDelete(int eventId, int moduleId);
public abstract IDataReader EventsGet(int eventId, int moduleId);
public abstract IDataReader EventsGetByRange(string modules, DateTime beginDate, DateTime endDate,
string categoryIDs, string locationIDs, int socialGroupId,
int socialUserId);
public abstract IDataReader EventsSave(int portalId, int eventId, int recurMasterId, int moduleId,
DateTime eventTimeBegin, int duration, string eventName,
string eventDesc, int importance, string createdById, string notify,
bool approved, bool signups, int maxEnrollment, int enrollRoleId,
decimal enrollFee, string enrollType, string payPalAccount,
bool cancelled, bool detailPage, bool detailNewWin, string detailUrl,
string imageUrl, string imageType, int imageWidth, int imageHeight,
bool imageDisplay, int location, int category, string reminder,
bool sendReminder, int reminderTime, string reminderTimeMeasurement,
string reminderFrom, bool searchSubmitted, string customField1,
string customField2, bool enrollListView, bool displayEndDate,
bool allDayEvent, int ownerId, int lastUpdatedId,
DateTime originalDateBegin, bool newEventEmailSent, bool allowAnonEnroll,
int contentItemId, bool journalItem, string summary, bool saveOnly);
public abstract IDataReader EventsModerateEvents(int moduleId, int socialGroupId);
public abstract int EventsTimeZoneCount(int moduleId);
public abstract void EventsUpgrade(string moduleVersion);
public abstract void EventsCleanupExpired(int portalId, int moduleId);
public abstract IDataReader EventsGetRecurrences(int recurMasterId, int moduleId);
#endregion
#region Master Event Functions
public abstract void EventsMasterDelete(int masterId, int moduleId);
public abstract IDataReader EventsMasterGet(int moduleId, int subEventId);
public abstract IDataReader EventsMasterAssignedModules(int moduleId);
public abstract IDataReader EventsMasterAvailableModules(int portalId, int moduleId);
public abstract IDataReader EventsMasterSave(int masterId, int moduleId, int subEventId);
#endregion
#region Event Categories and Locations Functions
public abstract void EventsCategoryDelete(int category, int portalId);
public abstract IDataReader EventsCategoryGetByName(string categoryName, int portalId);
public abstract IDataReader EventsCategoryGet(int category, int portalId);
public abstract IDataReader EventsCategoryList(int portalId);
public abstract IDataReader EventsCategorySave(int portalId, int category, string
categoryName, string color, string fontColor);
public abstract void EventsLocationDelete(int location, int portalId);
public abstract IDataReader EventsLocationGetByName(string locationName, int portalId);
public abstract IDataReader EventsLocationGet(int location, int portalId);
public abstract IDataReader EventsLocationList(int portalId);
public abstract IDataReader EventsLocationSave(int portalId, int location, string
locationName, string mapUrl, string street,
string postalCode, string city, string region,
string country);
#endregion
#region Event Enrollment and Moderation Functions
public abstract void EventsSignupsDelete(int signupId, int moduleId);
public abstract IDataReader EventsModerateSignups(int moduleId, int socialGroupId);
public abstract IDataReader EventsSignupsGet(int signupId, int moduleId, bool ppipn);
public abstract IDataReader EventsSignupsGetEvent(int eventId, int moduleId);
public abstract IDataReader EventsSignupsGetEventRecurMaster(int recurMasterId, int moduleId);
public abstract IDataReader EventsSignupsGetUser(int eventId, int userId, int moduleId);
public abstract IDataReader EventsSignupsGetAnonUser(int eventId, string anonEmail, int moduleId);
public abstract IDataReader EventsSignupsMyEnrollments(int moduleId, int userId, int socialGroupId,
string categoryIDs, DateTime beginDate,
DateTime endDate);
public abstract IDataReader EventsSignupsSave(int eventId, int signupId, int moduleId,
int userId, bool approved, string
payPalStatus, string payPalReason, string payPalTransId,
string payPalPayerId, string payPalPayerStatus,
string payPalRecieverEmail, string payPalUserEmail,
string payPalPayerEmail,
string payPalFirstName, string payPalLastName,
string payPalAddress, string payPalCity,
string payPalState, string payPalZip, string payPalCountry,
string payPalCurrency,
DateTime payPalPaymentDate, decimal payPalAmount,
decimal payPalFee,
int noEnrolees, string anonEmail, string anonName,
string anonTelephone, string anonCulture,
string anonTimeZoneId, string firstName, string lastName,
string company,
string jobTitle, string referenceNumber, string street,
string postalCode, string city, string region, string country);
#endregion
#region Event Notification Functions
public abstract void EventsNotificationTimeChange(int eventId, DateTime eventTimeBegin, int moduleId);
public abstract void EventsNotificationDelete(DateTime deleteDate);
public abstract IDataReader EventsNotificationGet(int eventId, string userEmail, int moduleId);
public abstract IDataReader EventsNotificationsToSend(DateTime notifyTime);
public abstract IDataReader EventsNotificationSave(int notificationId, int eventId, int portalAliasId,
string userEmail, bool notificationSent,
DateTime notifyByDateTime, DateTime eventTimeBegin,
string notifyLanguage, int
moduleId, int tabId);
#endregion
#region Event Recur Master Functions
public abstract void EventsRecurMasterDelete(int recurMasterId, int moduleId);
public abstract IDataReader EventsRecurMasterGet(int recurMasterId, int moduleId);
public abstract IDataReader EventsRecurMasterSave(int recurMasterId, int moduleId, int portalId, string rrule,
DateTime dtstart, string duration, DateTime Until,
string eventName, string eventDesc, int importance,
string notify, bool approved, bool signups, int maxEnrollment,
int enrollRoleId, decimal enrollFee, string enrollType,
string payPalAccount, bool detailPage, bool detailNewWin,
string detailUrl, string imageUrl, string imageType,
int imageWidth, int imageHeight, bool imageDisplay,
int location, int category, string reminder,
bool sendReminder, int reminderTime,
string reminderTimeMeasurement, string reminderFrom,
string customField1, string customField2, bool enrollListView,
bool displayEndDate, bool allDayEvent, string cultureName,
int ownerId, int createdById, int updatedById,
string eventTimeZoneId, bool allowAnonEnroll,
int contentItemId, int socialGroupId, int socialUserId,
string summary);
public abstract IDataReader EventsRecurMasterModerate(int moduleId, int socialGroupId);
#endregion
#region Event Subscription Functions
public abstract void EventsSubscriptionDeleteUser(int userId, int moduleId);
public abstract IDataReader EventsSubscriptionGetUser(int userId, int moduleId);
public abstract IDataReader EventsSubscriptionGetModule(int moduleId);
public abstract IDataReader EventsSubscriptionGetSubModule(int moduleId);
public abstract IDataReader EventsSubscriptionSave(int subscriptionId, int moduleId, int portalId, int userId);
#endregion
}
} | c# | 5 | 0.566877 | 120 | 59.595652 | 230 | starcoderdata |
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type smoker struct {
ID uint64
infinite_supply ingredients_t
ag_supply *ingredients
}
func makeSmoker(id uint64, inf_supp ingredients_t, ingreds *ingredients) smoker {
fmt.Println("T:", ingreds.tabacco, ", P:", ingreds.paper, ", M:", ingreds.matches)
return smoker{id, inf_supp, ingreds}
}
func (s smoker) make_cigarettes() {
s.ag_supply.reset()
}
func (s smoker) smoke() {
fmt.Println("Somker#", s.ID, " is smoking")
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
}
func (s smoker) run(wg *sync.WaitGroup) {
defer func() {
if wg != nil {
wg.Done()
}
}()
for {
//fmt.Println(s.ag_supply.complete_with_internal_supply(s.infinite_supply))
//s.ag_supply.wait_for_complete_with_internal_supply(s.infinite_supply)
//s.make_cigarettes()
//s.smoke()
cond_supply_ready.L.Lock()
for !s.ag_supply.complete_with_internal_supply(s.infinite_supply) {
cond_supply_ready.Wait()
}
cond_supply_ready.L.Unlock()
s.make_cigarettes()
s.smoke()
}
} | go | 12 | 0.659535 | 83 | 18.907407 | 54 | starcoderdata |
DWORD
CTimerQueue::GetTimeToTimeout(
)
{
if ( IsEmpty() ) return INFINITE;
CFilterInfo *FirstEntry = m_Head.m_pNext;
DWORD FirstTimeout = FirstEntry->m_WaitTime;
// get current time
DWORD CurrentTime = timeGetTime();
// get the minimum time difference between the two
// this should get rid of the wrap problem
BOOL bIsWrap;
DWORD TimeDiff = GetMinDiff(CurrentTime, FirstTimeout, bIsWrap);
// if this time diff value is > MAX_TIMEOUT, it has to be in the
// past - schedule it now
if (TimeDiff > MAX_TIMEOUT) return 0;
// check if the timeout event is in the past - schedule it for now
if ( bIsWrap )
{
// if there is a wrap around, the first timeout must be the
// one causing it (the wrap around), otherwise its in the past
if ( CurrentTime <= FirstTimeout ) return 0;
}
else
{
// no wrap around, so if we timeout is behind current time, its past
if ( FirstTimeout <= CurrentTime ) return 0;
}
return TimeDiff;
} | c++ | 9 | 0.609645 | 76 | 27.756757 | 37 | inline |
#ifndef VSSIMULATOR_H
#define VSSIMULATOR_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
class FeatureStack;
class Simulator
{
public:
Simulator();
void setVelocity(const vpColVector &v);
vpHomogeneousMatrix currentPose() const
{
return cMo;
}
vpHomogeneousMatrix desiredPose() const
{
return cdMo;
}
vpPoint cog() const
{
return center;
}
std::vector observedPoints() const
{
return points;
}
void plot()
{
logger.plot();
config_manager.saveConfig();
}
bool clicked(bool wait = false)
{
return vpDisplay::getClick(Iint,wait);
}
protected:
friend class FeatureStack;
vpImage Iint, Iext;
vpDisplayOpenCV Dint, Dext;
vpWireFrameSimulator sim;
vpCameraParameters cam;
vpRobotCamera robot;
std::vector history;
std::vector points;
vpPoint center;
vpColVector uv, vel;
// time sampling
const double dt_ms = 0.01 * 1000; // ms
double t0;
// from configuration
vpHomogeneousMatrix cMo, cdMo;
vpPoseVector pose;
log2plot::ConfigManager config_manager;
log2plot::Logger logger;
void initLog(const std::string &base_path, const std::string &exp_id, const std::string &legend);
double computeV(const vpPoint &P) const
{
return Iint.getRows() - (cam.get_v0() + cam.get_py()*P.get_y());
}
double computeU(const vpPoint &P) const
{
return cam.get_u0() + cam.get_px()*P.get_x();
}
};
#endif // VSSIMULATOR_H | c | 11 | 0.697739 | 99 | 19.602273 | 88 | starcoderdata |
const joi = require('joi');
const registerAll = (current, subObj, subObjName) => {
Object.keys(subObj).forEach(methodName => {
const method = subObj[methodName];
if (subObjName) {
methodName = `${subObjName}.${methodName}`;
}
if (typeof method === 'function') {
const methodDescription = { name: methodName };
if (method.description) {
methodDescription.description = method.description;
}
if (method.schema) {
methodDescription.schema = joi.describe(method.schema);
}
if (method.cache) {
methodDescription.cacheEnabled = true;
}
return current.push(methodDescription);
}
if (typeof method === 'object') {
// otherwise method is an object:
registerAll(current, method, methodName);
}
});
return current.sort((a, b) => a.name.toLowerCase().toLowerCase().localeCompare(b.name.toLowerCase()));
};
module.exports = registerAll; | javascript | 18 | 0.634872 | 104 | 30.451613 | 31 | starcoderdata |
using System.Threading.Tasks;
using SFA.DAS.EmployerIncentives.Functions.LegalEntities.Services.PausePayments.Types;
using SFA.DAS.EmployerIncentives.Functions.LegalEntities.Services.Withdrawals.Types;
namespace SFA.DAS.EmployerIncentives.Functions.LegalEntities.Services.PausePayments
{
public interface IPausePaymentsService
{
Task SetPauseStatus(PausePaymentsRequest request);
}
} | c# | 11 | 0.818182 | 86 | 33.833333 | 12 | starcoderdata |
/*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* com.google.common.base.Charsets
*/
package us.myles.viaversion.libs.bungeecordchat.chat;
import com.google.common.base.Charsets;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import us.myles.viaversion.libs.gson.Gson;
import us.myles.viaversion.libs.gson.JsonElement;
import us.myles.viaversion.libs.gson.JsonObject;
public final class TranslationRegistry {
public static final TranslationRegistry INSTANCE = new TranslationRegistry();
private final List providers = new LinkedList
private void addProvider(TranslationProvider provider) {
this.providers.add(provider);
}
public String translate(String s) {
for (TranslationProvider provider : this.providers) {
String translation = provider.translate(s);
if (translation == null) continue;
return translation;
}
return s;
}
public List getProviders() {
return this.providers;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TranslationRegistry)) {
return false;
}
TranslationRegistry other = (TranslationRegistry)o;
List this$providers = this.getProviders();
List other$providers = other.getProviders();
return !(this$providers == null ? other$providers != null : !((Object)this$providers).equals(other$providers));
}
public int hashCode() {
int PRIME = 59;
int result = 1;
List $providers = this.getProviders();
result = result * 59 + ($providers == null ? 43 : ((Object)$providers).hashCode());
return result;
}
public String toString() {
return "TranslationRegistry(providers=" + this.getProviders() + ")";
}
private TranslationRegistry() {
}
static {
try {
INSTANCE.addProvider(new JsonProvider("/assets/minecraft/lang/en_us.json"));
}
catch (Exception exception) {
// empty catch block
}
try {
INSTANCE.addProvider(new JsonProvider("/mojang-translations/en_us.json"));
}
catch (Exception exception) {
// empty catch block
}
try {
INSTANCE.addProvider(new ResourceBundleProvider("mojang-translations/en_US"));
}
catch (Exception exception) {
// empty catch block
}
}
private static class JsonProvider
implements TranslationProvider {
private final Map<String, String> translations = new HashMap<String, String>();
public JsonProvider(String resourcePath) throws IOException {
try (InputStreamReader rd = new InputStreamReader(JsonProvider.class.getResourceAsStream(resourcePath), Charsets.UTF_8);){
JsonObject obj = new Gson().fromJson((Reader)rd, JsonObject.class);
for (Map.Entry<String, JsonElement> entries : obj.entrySet()) {
this.translations.put(entries.getKey(), entries.getValue().getAsString());
}
}
}
@Override
public String translate(String s) {
return this.translations.get(s);
}
public Map<String, String> getTranslations() {
return this.translations;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof JsonProvider)) {
return false;
}
JsonProvider other = (JsonProvider)o;
if (!other.canEqual(this)) {
return false;
}
Map<String, String> this$translations = this.getTranslations();
Map<String, String> other$translations = other.getTranslations();
return !(this$translations == null ? other$translations != null : !((Object)this$translations).equals(other$translations));
}
protected boolean canEqual(Object other) {
return other instanceof JsonProvider;
}
public int hashCode() {
int PRIME = 59;
int result = 1;
Map<String, String> $translations = this.getTranslations();
result = result * 59 + ($translations == null ? 43 : ((Object)$translations).hashCode());
return result;
}
public String toString() {
return "TranslationRegistry.JsonProvider()";
}
}
private static class ResourceBundleProvider
implements TranslationProvider {
private final ResourceBundle bundle;
public ResourceBundleProvider(String bundlePath) {
this.bundle = ResourceBundle.getBundle(bundlePath);
}
@Override
public String translate(String s) {
return this.bundle.containsKey(s) ? this.bundle.getString(s) : null;
}
public ResourceBundle getBundle() {
return this.bundle;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof ResourceBundleProvider)) {
return false;
}
ResourceBundleProvider other = (ResourceBundleProvider)o;
if (!other.canEqual(this)) {
return false;
}
ResourceBundle this$bundle = this.getBundle();
ResourceBundle other$bundle = other.getBundle();
return !(this$bundle == null ? other$bundle != null : !this$bundle.equals(other$bundle));
}
protected boolean canEqual(Object other) {
return other instanceof ResourceBundleProvider;
}
public int hashCode() {
int PRIME = 59;
int result = 1;
ResourceBundle $bundle = this.getBundle();
result = result * 59 + ($bundle == null ? 43 : $bundle.hashCode());
return result;
}
public String toString() {
return "TranslationRegistry.ResourceBundleProvider(bundle=" + this.getBundle() + ")";
}
}
private static interface TranslationProvider {
public String translate(String var1);
}
} | java | 17 | 0.59634 | 135 | 31.895522 | 201 | starcoderdata |
import bpy
from __future__ import print_function
DATA = bpy.data
outputFolder= "\\data\\OUTPUT.csv"
for clip in DATA.movieclips:
width=clip.size[0]
height=clip.size[1]
for object in clip.tracking.objects:
for track in object.tracks:
file_name = outputFolder
f = open(file_name, 'w')
framenum = 0
if framenum ==0:
print('x,y',file=f)
while framenum < clip.frame_duration:
markerAtFrame = track.markers.find_frame(framenum)
if markerAtFrame:
coords = markerAtFrame.co.xy
print('{0},{1}'.format(coords[0]*width, coords[1]*height), file=f)
framenum += 1
f.close() | python | 18 | 0.486423 | 86 | 26.322581 | 31 | starcoderdata |
package de.unirostock.wumpus.core.world;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
/**
* Saves the world state for a client
*/
public class AgentWorldState extends WorldState {
private static final Logger logger = LogManager.getLogger(AgentWorldState.class);
private Coordinate currentPosition;
public AgentWorldState() {};
public AgentWorldState(Field[][] world) {
super(world);
}
public Coordinate getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(Coordinate currentPosition) {
this.currentPosition = currentPosition;
};
public void merge(AgentWorldState otherState) {
merge(otherState, new HashSet<>());
}
public void merge(AgentWorldState otherState, HashSet ignoreCoordinates) {
Field[][] currWorld = getWorld();
Field[][] otherWorld = otherState.getWorld();
for(int y = 0; y < WorldCreator.Y_DIM; y++) {
for(int x = 0; x < WorldCreator.X_DIM ; x++) {
if (ignoreCoordinates.contains(new Coordinate(x, y)))
continue;
Field currField = currWorld[y][x];
Field otherField = otherWorld[y][x];
List currGS = currField.getGroundStates();
List otherGS = otherField.getGroundStates();
// If the other agent says it's free we can guarantee that it's the best outcome
boolean shouldPrint = !currField.isUnknown()
&& !otherField.isUnknown()
&& !(currGS.containsAll(otherGS) && otherGS.containsAll(currGS));
if (shouldPrint)
logger.debug(currGS + " merging with " + otherGS + " at " + new Coordinate(x, y));
if (otherField.isFree()) {
currField.getGroundStates().clear();
currField.addGroundState(GroundState.FREE);
}
else if (!otherField.isUnknown()) {
if (currField.isUnknown()) {
currField.removeGroundState(GroundState.UNKNOWN);
currGS.addAll(otherGS);
} else {
currGS.removeIf(gs -> !otherGS.contains(gs));
if (currGS.isEmpty())
currGS.add(GroundState.FREE);
}
}
if (shouldPrint)
logger.debug(" => result: " + currGS);
}
}
}
} | java | 21 | 0.682547 | 87 | 30.208333 | 72 | starcoderdata |
@Override
public int compare(MetricsDiffSummary aObj1, MetricsDiffSummary aObj2) {
if (aObj1 == null && aObj2 == null) {
return 0;
} else if (aObj1 == null) {
return -1;
} else if (aObj2 == null) {
return 1;
} else {
float d1 = aObj1.getPcDiff();
float d2 = aObj2.getPcDiff();
if (d1 == d2) {
// secondary lexigraphical sort
return aObj1.getName().compareTo(aObj2.getName());
} else if (d1 > d2) {
return 1;
} else {
return -1;
}
}
} | java | 14 | 0.390177 | 80 | 33.952381 | 21 | inline |
void DirectMuonNavigation::outInForward(const FreeTrajectoryState& fts, vector<const DetLayer*>& output) const {
// default forward layers are in out, reverse order
bool cont = false;
const vector<const DetLayer*>& forward = theMuonDetLayerGeometry->allForwardLayers();
vector<const DetLayer*>::const_iterator rbegin = forward.end();
rbegin--;
vector<const DetLayer*>::const_iterator rend = forward.begin();
rend--;
for (vector<const DetLayer*>::const_iterator iter_E = rbegin; iter_E != rend; iter_E--) {
if (cont)
output.push_back((*iter_E));
else if (checkCompatible(fts, dynamic_cast<const ForwardDetLayer*>(*iter_E))) {
output.push_back((*iter_E));
cont = true;
}
}
} | c++ | 16 | 0.68516 | 112 | 39.111111 | 18 | inline |
void SocketManager::bindSocket(uint16_t port)
{
// Create the underlaying socket for this port
mSocket = SocketUtil::CreateUDPSocket(INET);
// Create a wildcard input address to bind to
SocketAddress ownAddress(INADDR_ANY, port);
mSocket->Bind(ownAddress);
// did we bind okay?
if (mSocket == nullptr)
{
throw std::runtime_error("Failed binding socket");
}
INFO("Bound address {}", ownAddress.ToString());
} | c++ | 9 | 0.66886 | 58 | 29.466667 | 15 | inline |
//
// TrackerHelper.h
// Google-Analytics-for-OS-X-macOS
//
// Created by Splenden on 2018/2/21.
//
#import
@interface TrackerHelper : NSObject
/**
* When iOS, generated by UIDevice identifierForVendor, which will change when app re-install. OSX, generated by device serial number and user name.
* @see: http://www.cocoachina.com/industry/20130422/6040.html
*/
- (NSString * _Nonnull)userIdentifier;
/**
* Gnerated by executing javascript `navigator.userAgent` on UI_WebView(iOS)\WebView(OSX)
*/
- (NSString * _Nonnull)userAgentString;
/**
* Returns screen size and preferred language
**/
- (NSString * _Nonnull)systemInfo;
/**
* Generated by NSBundle kCFBundleNameKey
**/
- (NSString * _Nonnull)applicationName;
/**
* Generated by NSBundle CFBundleVersion
**/
- (NSString * _Nonnull)applicationVersion;
@end | c | 5 | 0.723854 | 148 | 25.59375 | 32 | starcoderdata |
//Copyright (c) 2004-2020 Microchip Technology Inc. and its subsidiaries.
//SPDX-License-Identifier: MIT
#ifndef __H2PCS1G_H__
#define __H2PCS1G_H__
#if MAC_TO_MEDIA
typedef enum {
MAC_IF_INTERNAL = 0,
MAC_IF_EXTERNAL = 1,
MAC_IF_SGMII = 2,
MAC_IF_100FX = 8,
MAC_IF_SERDES = 9,
MAC_IF_SFP = 0xa,
MAC_IF_NONE = 0xff
} mac_if_type_t;
void h2_pcs1g_clause_37_control_set(const uchar port_no);
uchar h2_pcs1g_clause_37_status_get(const uchar port_no);
uchar h2_pcs1g_100fx_status_get(const uchar port_no);
void h2_pcs1g_clock_stop (uchar port_no);
void h2_pcs1g_setup (uchar port_no, uchar mode);
#endif
#endif | c | 8 | 0.685426 | 73 | 24.666667 | 27 | starcoderdata |
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
use yii\web\View;
/**
* Class GalleryAsset
* @package frontend\assets
*/
class GalleryAsset extends AssetBundle
{
public $css = [
'css/gallery/style.css',
];
public $js = [
'js/isotope/jquery.isotope.js',
// 'js/gallery/scripts.js',
];
public $depends = [
'yii\web\JqueryAsset',
];
public $jsOptions = [
'position' => View::POS_END,
];
} | php | 9 | 0.571429 | 39 | 14.387097 | 31 | starcoderdata |
package adsdemo.utils;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import oracle.adf.controller.ControllerContext;
import oracle.adf.controller.internal.ViewPortContextFwk;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCUtil;
import oracle.adf.view.rich.change.MDSDocumentChangeManager;
import oracle.adf.view.rich.component.fragment.UIXRegion;
import oracle.adf.view.rich.dt.Page;
import org.apache.myfaces.trinidad.change.AddChildDocumentChange;
import org.apache.myfaces.trinidad.change.AttributeComponentChange;
import org.apache.myfaces.trinidad.change.ComponentChange;
import org.apache.myfaces.trinidad.change.DocumentChange;
import org.apache.myfaces.trinidad.context.RequestContext;
import org.w3c.dom.DocumentFragment;
public class MdsUtils
{
public static String getPhysicalPagePath(UIComponent component)
{
String pagePath = getPagePath(FacesContext.getCurrentInstance(), component);
String pageURI = getDocument(FacesContext.getCurrentInstance(), pagePath);
return pageURI;
}
public static Page getPageObject(String pagePath)
{
// first get the binding context
FacesContext ftx = FacesContext.getCurrentInstance();
ExternalContext extContext = ftx.getExternalContext();
HttpServletRequest servletRequest =
(HttpServletRequest) extContext.getRequest();
BindingContext bindingContext =
DCUtil.getBindingContext(servletRequest);
// lastly, return the instance of the design-time page.
return Page.getInstance(bindingContext, pagePath);
}
public static String getPagePath(FacesContext facesContext,
UIComponent component)
{
boolean facetRef = false;
UIComponent currAncestor = component.getParent();
while (currAncestor != null)
{
if (currAncestor instanceof UIXRegion)
{
UIXRegion region = (UIXRegion) currAncestor;
return RegionUtility.getRegionURI(facesContext, component, region);
}
//else if (currAncestor instanceof UIXPageTemplate)
//{
// if (!facetRef)
// {
// //If it reaches this loop, The component is part of pageTemplate
// // definition document. get the doc and apply the change
// return ((UIXPageTemplate) currAncestor).getViewId();
// }
// else
// {
// // This is made false to add the id's in the path to the list
// // to make sure that we parse the correct path while parsing the
// //XML Document in _getComponentNode() method
// facetRef = false;
// }
// }
// else if (currAncestor instanceof ComponentRefTag.FacetWrapper)
// {
// //If this is reached, the surrounding pageTemplate def doesn't
// // contain the required component but the component is child of
// //pageTemplate component so skip the id's found in between(which
// // are part of pageTemplate def document) so we no more need to parse
// // the pageTemplate def file.
// facetRef = true;
//}
currAncestor = currAncestor.getParent();
}
return null;
}
public static String getDocument(FacesContext context, String pagePath)
{
if (pagePath == null)
{
pagePath = context.getViewRoot().getViewId();
//Bug 5745464 MDS-00013 FROM MDSDOCUMENTCHANGEMANAGER WHEN
//CLICKING A TAB INSIDE A REGION
ControllerContext ctrl = ControllerContext.getInstance();
if (ctrl != null)
{
ViewPortContextFwk root = (ViewPortContextFwk) ctrl.getCurrentRootViewPort();
if (root != null)
{
pagePath = root.getPhysicalURI(pagePath);
}
}
else
{
//Bug 5692317 view Id may not be the physical URI of the page
RequestContext reqContext = RequestContext.getCurrentInstance();
if (reqContext != null)
{
pagePath = reqContext.getPageResolver().getPhysicalURI(pagePath);
}
}
}
// Bug 6209943 - em:blk error updatinga component attribute fora file
// residing inweb context root
// pagePath need not be the absolute path
if (pagePath != null && (!pagePath.startsWith("/")))
{
pagePath = "/" + pagePath;
}
return pagePath;
}
public static void saveToMds(DocumentFragment df, UIComponent parent)
{
// Content updatableContent =
// ContentFactory.getInstance().getContent(pageURI);
// AbstractUsageImpl usage =
// (AbstractUsageImpl) updatableContent.createUsage("cb8",
// "region",
// "http://xmlns.oracle.com/adf/faces/rich");
// Get the taskflow fragment
// DocumentFragment docFrag = usage.getFragment();
// Document doc = docFrag.getOwnerDocument();
try
{
// Get the ID of the component we'll be adding just before
String insertBeforeId = null;
try
{
// insertBeforeId = container.getChildren().get(0).getId();
}
catch (Exception e)
{
// Usually ArrayIndexOutOfBounds, no need to log even otherwise.
}
// Get the change manager, e.g. MDS
// dont use only return doc change manager in page composer edit mode ...
// ChangeManager apm =
// RequestContext.getCurrentInstance().getChangeManager();
// Add an "add child" document change, i.e. inserting the fragment
DocumentChange change = null;
if (insertBeforeId != null)
{
change = new AddChildDocumentChange(insertBeforeId, df);
}
else
{
change = new AddChildDocumentChange(df);
}
saveToMds(change, parent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void saveToMds(AttributeComponentChange change, UIComponent component)
{
MDSDocumentChangeManager mdsChangeManager =
new MDSDocumentChangeManager();
UIComponent container = component;
mdsChangeManager.addComponentChange(FacesContext.getCurrentInstance(),
container, change);
RequestContext.getCurrentInstance().addPartialTarget(component.getParent());
}
public static void saveToMds(DocumentChange change, UIComponent parent)
{
MDSDocumentChangeManager mdsChangeManager =
new MDSDocumentChangeManager();
UIComponent container = parent;
mdsChangeManager.addDocumentChange(FacesContext.getCurrentInstance(),
container, change);
RequestContext.getCurrentInstance().addPartialTarget(container.getParent());
}
} | java | 16 | 0.625726 | 103 | 33.273171 | 205 | starcoderdata |
<?php
if(!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED!==true)
die();
class CCrmProductSectionTreeHelper
{
public function checkRights()
{
$permissions = CCrmPerms::GetCurrentUserPermissions();
if (!(CCrmPerms::IsAccessEnabled($permissions) && $permissions->HavePerm('CONFIG', BX_CRM_PERM_CONFIG, 'READ')))
return false;
return true;
}
public function getInitialTree($catalogId, $sectionId)
{
$initialTree = array();
$resRootElements = CIBlockSection::GetTreeList(
array(
'=IBLOCK_ID' => $catalogId,
'=DEPTH_LEVEL' => 1,
'CHECK_PERMISSIONS' => 'N'
),
array('ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN')
);
$parentIndex = array();
$i = 0;
while ($arElement = $resRootElements->Fetch())
{
$bSelected = (intval($arElement['ID']) === intval($sectionId));
$initialTree[$i] = array(
'ID' => $arElement['ID'],
'NAME' => $arElement['NAME'],
'SELECTED' => $bSelected ? 'Y' : 'N',
'HAS_CHILDREN' =>
((intval($arElement["RIGHT_MARGIN"]) - intval($arElement["LEFT_MARGIN"])) > 1) ? 'Y' : 'N',
'CHILDREN' => array()
);
$parentIndex[$arElement['ID']] = $i;
$i++;
}
$resHeadElements = CIBlockSection::GetNavChain(
$catalogId, $sectionId,
array('ID', 'NAME', 'DEPTH_LEVEL', 'LEFT_MARGIN', 'RIGHT_MARGIN')
);
$parentElement = null;
while ($arHead = $resHeadElements->Fetch())
{
/*if (intval($arHead['ID']) === intval($sectionId))
break;*/
if ($parentElement === null)
{
$parentElement = &$initialTree[$parentIndex[$arHead['ID']]];
}
else
{
$tmp = &$parentElement['CHILDREN'][$parentIndex[$arHead['ID']]];
unset($parentElement);
$parentElement = &$tmp;
unset($tmp);
}
$resElement = CIBlockSection::GetTreeList(
array(
'=IBLOCK_ID' => $catalogId,
'=SECTION_ID' => $arHead['ID'],
'=DEPTH_LEVEL' => 1 + $arHead['DEPTH_LEVEL'],
'CHECK_PERMISSIONS' => 'N'
),
array('ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN')
);
$parentIndex = array();
$i = 0;
while ($arElement = $resElement->Fetch())
{
$bSelected = (intval($arElement['ID']) === intval($sectionId));
$parentElement['CHILDREN'][$i] = array(
'ID' => $arElement['ID'],
'NAME' => $arElement['NAME'],
'SELECTED' => $bSelected ? 'Y' : 'N',
'HAS_CHILDREN' =>
((intval($arElement["RIGHT_MARGIN"]) - intval($arElement["LEFT_MARGIN"])) > 1) ? 'Y' : 'N',
'CHILDREN' => array()
);
$parentIndex[$arElement['ID']] = $i;
$i++;
}
}
return $initialTree;
}
public function getSubsections($catalogId, $sectionId)
{
$arSubsections = array();
$resSection = CIBlockSection::GetList(
array(), array('ID'=>intval($sectionId)), false,
array('ID', 'NAME', 'DEPTH_LEVEL', 'LEFT_MARGIN', 'RIGHT_MARGIN')
);
if ($resSection)
{
if ($arSection = $resSection->Fetch())
{
$resElement = CIBlockSection::GetTreeList(
array(
'=IBLOCK_ID' => $catalogId,
'=SECTION_ID' => $arSection['ID'],
'=DEPTH_LEVEL' => 1 + $arSection['DEPTH_LEVEL'],
'CHECK_PERMISSIONS' => 'N'
),
array('ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN')
);
while ($arElement = $resElement->Fetch())
$arSubsections[] = array(
'ID' => $arElement['ID'],
'NAME' => $arElement['NAME'],
'HAS_CHILDREN' =>
((intval($arElement["RIGHT_MARGIN"]) - intval($arElement["LEFT_MARGIN"])) > 1) ? 'Y' : 'N',
'SELECTED' => 'N',
'CHILDREN' => array()
);
}
}
return $arSubsections;
}
} | php | 24 | 0.569932 | 114 | 25.556391 | 133 | starcoderdata |
package org.zalando.nakadi.controller.advice;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.jetty.io.EofException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.nakadi.exceptions.runtime.AccessDeniedException;
import org.zalando.nakadi.exceptions.runtime.BlockedException;
import org.zalando.nakadi.exceptions.runtime.DbWriteOperationsBlockedException;
import org.zalando.nakadi.exceptions.runtime.FeatureNotAvailableException;
import org.zalando.nakadi.exceptions.runtime.ForbiddenOperationException;
import org.zalando.nakadi.exceptions.runtime.IllegalClientIdException;
import org.zalando.nakadi.exceptions.runtime.InternalNakadiException;
import org.zalando.nakadi.exceptions.runtime.InvalidLimitException;
import org.zalando.nakadi.exceptions.runtime.InvalidVersionNumberException;
import org.zalando.nakadi.exceptions.runtime.NakadiBaseException;
import org.zalando.nakadi.exceptions.runtime.NakadiRuntimeException;
import org.zalando.nakadi.exceptions.runtime.NoSuchEventTypeException;
import org.zalando.nakadi.exceptions.runtime.NoSuchSchemaException;
import org.zalando.nakadi.exceptions.runtime.NoSuchSubscriptionException;
import org.zalando.nakadi.exceptions.runtime.RepositoryProblemException;
import org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException;
import org.zalando.nakadi.exceptions.runtime.UnprocessableEntityException;
import org.zalando.nakadi.exceptions.runtime.ValidationException;
import org.zalando.nakadi.problem.ValidationProblem;
import org.zalando.problem.Problem;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import javax.annotation.Priority;
import static org.zalando.problem.Status.BAD_REQUEST;
import static org.zalando.problem.Status.FORBIDDEN;
import static org.zalando.problem.Status.INTERNAL_SERVER_ERROR;
import static org.zalando.problem.Status.NOT_FOUND;
import static org.zalando.problem.Status.NOT_IMPLEMENTED;
import static org.zalando.problem.Status.SERVICE_UNAVAILABLE;
import static org.zalando.problem.Status.UNPROCESSABLE_ENTITY;
@Priority(20)
@ControllerAdvice
public class NakadiProblemExceptionHandler implements ProblemHandling {
private static final Logger LOG = LoggerFactory.getLogger(NakadiProblemExceptionHandler.class);
@Override
public String formatFieldName(final String fieldName) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName);
}
@Override
@ExceptionHandler
public ResponseEntity handleThrowable(final Throwable throwable, final NativeWebRequest request) {
final String errorTraceId = generateErrorTraceId();
LOG.error("InternalServerError (" + errorTraceId + "):", throwable);
return create(Problem.valueOf(INTERNAL_SERVER_ERROR, "An internal error happened. Please report it. ("
+ errorTraceId + ")"), request);
}
private String generateErrorTraceId() {
return "ETI" + RandomStringUtils.randomAlphanumeric(24);
}
@Override
@ExceptionHandler
public ResponseEntity handleMessageNotReadableException(final HttpMessageNotReadableException exception,
final NativeWebRequest request) {
/*
Unwrap nested JsonMappingException because the enclosing HttpMessageNotReadableException adds some ugly, Java
class and stacktrace like information.
*/
final Throwable mostSpecificCause = exception.getMostSpecificCause();
final String message;
if (mostSpecificCause instanceof JsonMappingException) {
message = mostSpecificCause.getMessage();
} else {
message = exception.getMessage();
}
return create(Problem.valueOf(BAD_REQUEST, message), request);
}
@ExceptionHandler(EofException.class)
public void handleEofException() {
LOG.info("Client closed connection");
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity handleAccessDeniedException(final AccessDeniedException exception,
final NativeWebRequest request) {
return create(Problem.valueOf(FORBIDDEN, exception.explain()), request);
}
@ExceptionHandler(DbWriteOperationsBlockedException.class)
public ResponseEntity handleDbWriteOperationsBlockedException(
final DbWriteOperationsBlockedException exception, final NativeWebRequest request) {
LOG.warn(exception.getMessage());
return create(Problem.valueOf(SERVICE_UNAVAILABLE,
"Database is currently in read-only mode"), request);
}
@ExceptionHandler(FeatureNotAvailableException.class)
public ResponseEntity handleFeatureNotAvailableException(
final FeatureNotAvailableException ex,
final NativeWebRequest request) {
LOG.debug(ex.getMessage());
return create(Problem.valueOf(NOT_IMPLEMENTED, ex.getMessage()), request);
}
@ExceptionHandler(InternalNakadiException.class)
public ResponseEntity handleInternalNakadiException(final InternalNakadiException exception,
final NativeWebRequest request) {
LOG.error(exception.getMessage(), exception);
return create(Problem.valueOf(INTERNAL_SERVER_ERROR, exception.getMessage()), request);
}
@ExceptionHandler({InvalidLimitException.class, InvalidVersionNumberException.class})
public ResponseEntity handleBadRequestResponses(final NakadiBaseException exception,
final NativeWebRequest request) {
LOG.debug(exception.getMessage());
return create(Problem.valueOf(BAD_REQUEST, exception.getMessage()), request);
}
@ExceptionHandler(NakadiBaseException.class)
public ResponseEntity handleNakadiBaseException(final NakadiBaseException exception,
final NativeWebRequest request) {
LOG.error("Unexpected problem occurred", exception);
return create(Problem.valueOf(INTERNAL_SERVER_ERROR, exception.getMessage()), request);
}
@ExceptionHandler
public ResponseEntity handleNakadiRuntimeException(final NakadiRuntimeException exception,
final NativeWebRequest request) throws Exception {
final Throwable cause = exception.getCause();
if (cause instanceof InternalNakadiException) {
return create(Problem.valueOf(INTERNAL_SERVER_ERROR, exception.getMessage()), request);
}
throw exception.getException();
}
@ExceptionHandler({NoSuchEventTypeException.class, NoSuchSchemaException.class, NoSuchSubscriptionException.class})
public ResponseEntity handleNotFoundResponses(final NakadiBaseException exception,
final NativeWebRequest request) {
LOG.debug(exception.getMessage());
return create(Problem.valueOf(NOT_FOUND, exception.getMessage()), request);
}
@ExceptionHandler(RepositoryProblemException.class)
public ResponseEntity handleRepositoryProblemException(final RepositoryProblemException exception,
final NativeWebRequest request) {
LOG.error("Repository problem occurred", exception);
return create(Problem.valueOf(SERVICE_UNAVAILABLE, exception.getMessage()), request);
}
@ExceptionHandler(ServiceTemporarilyUnavailableException.class)
public ResponseEntity handleServiceTemporarilyUnavailableException(
final ServiceTemporarilyUnavailableException exception, final NativeWebRequest request) {
LOG.error(exception.getMessage(), exception);
return create(Problem.valueOf(SERVICE_UNAVAILABLE, exception.getMessage()), request);
}
@ExceptionHandler(UnprocessableEntityException.class)
public ResponseEntity handleUnprocessableEntityException(
final UnprocessableEntityException exception,
final NativeWebRequest request) {
LOG.debug(exception.getMessage());
return create(Problem.valueOf(UNPROCESSABLE_ENTITY, exception.getMessage()), request);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity handleValidationException(final ValidationException exception,
final NativeWebRequest request) {
return create(new ValidationProblem(exception.getErrors()), request);
}
@ExceptionHandler({ForbiddenOperationException.class, BlockedException.class, IllegalClientIdException.class})
public ResponseEntity handleForbiddenResponses(final NakadiBaseException exception,
final NativeWebRequest request) {
LOG.debug(exception.getMessage());
return create(Problem.valueOf(FORBIDDEN, exception.getMessage()), request);
}
} | java | 14 | 0.731914 | 119 | 50.468085 | 188 | starcoderdata |
using System;
using NUnit.Framework;
namespace Xamarin.Forms.Core.UnitTests
{
[TestFixture]
public class EasingTests : BaseTestFixture
{
[Test]
public void Linear ([Range (0, 10)] double input)
{
Assert.AreEqual (input, Easing.Linear.Ease (input));
}
[Test]
public void AllRunFromZeroToOne ([Values (0.0, 1.0)] double val)
{
const double epsilon = 0.001;
Assert.True (Math.Abs (val - Easing.Linear.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.BounceIn.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.BounceOut.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.CubicIn.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.CubicInOut.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.CubicOut.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.SinIn.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.SinInOut.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.SinOut.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.SpringIn.Ease (val)) < epsilon);
Assert.True (Math.Abs (val - Easing.SpringOut.Ease (val)) < epsilon);
}
[Test]
public void TestEasingTypeConverter()
{
var converter = new EasingTypeConverter();
Assert.True(converter.CanConvertFrom(typeof(string)));
Assert.Null(converter.ConvertFromInvariantString(null));
Assert.Null(converter.ConvertFromInvariantString(string.Empty));
Assert.AreEqual(Easing.Linear, converter.ConvertFromInvariantString("Linear"));
Assert.AreEqual(Easing.Linear, converter.ConvertFromInvariantString("linear"));
Assert.AreEqual(Easing.Linear, converter.ConvertFromInvariantString("Easing.Linear"));
Assert.AreEqual(Easing.SinOut, converter.ConvertFromInvariantString("SinOut"));
Assert.AreEqual(Easing.SinOut, converter.ConvertFromInvariantString("sinout"));
Assert.AreEqual(Easing.SinOut, converter.ConvertFromInvariantString("Easing.SinOut"));
Assert.AreEqual(Easing.SinIn, converter.ConvertFromInvariantString("SinIn"));
Assert.AreEqual(Easing.SinIn, converter.ConvertFromInvariantString("sinin"));
Assert.AreEqual(Easing.SinIn, converter.ConvertFromInvariantString("Easing.SinIn"));
Assert.AreEqual(Easing.SinInOut, converter.ConvertFromInvariantString("SinInOut"));
Assert.AreEqual(Easing.SinInOut, converter.ConvertFromInvariantString("sininout"));
Assert.AreEqual(Easing.SinInOut, converter.ConvertFromInvariantString("Easing.SinInOut"));
Assert.AreEqual(Easing.CubicOut, converter.ConvertFromInvariantString("CubicOut"));
Assert.AreEqual(Easing.CubicOut, converter.ConvertFromInvariantString("cubicout"));
Assert.AreEqual(Easing.CubicOut, converter.ConvertFromInvariantString("Easing.CubicOut"));
Assert.AreEqual(Easing.CubicIn, converter.ConvertFromInvariantString("CubicIn"));
Assert.AreEqual(Easing.CubicIn, converter.ConvertFromInvariantString("cubicin"));
Assert.AreEqual(Easing.CubicIn, converter.ConvertFromInvariantString("Easing.CubicIn"));
Assert.AreEqual(Easing.CubicInOut, converter.ConvertFromInvariantString("CubicInOut"));
Assert.AreEqual(Easing.CubicInOut, converter.ConvertFromInvariantString("cubicinout"));
Assert.AreEqual(Easing.CubicInOut, converter.ConvertFromInvariantString("Easing.CubicInOut"));
Assert.AreEqual(Easing.BounceOut, converter.ConvertFromInvariantString("BounceOut"));
Assert.AreEqual(Easing.BounceOut, converter.ConvertFromInvariantString("bounceout"));
Assert.AreEqual(Easing.BounceOut, converter.ConvertFromInvariantString("Easing.BounceOut"));
Assert.AreEqual(Easing.BounceIn, converter.ConvertFromInvariantString("BounceIn"));
Assert.AreEqual(Easing.BounceIn, converter.ConvertFromInvariantString("bouncein"));
Assert.AreEqual(Easing.BounceIn, converter.ConvertFromInvariantString("Easing.BounceIn"));
Assert.AreEqual(Easing.SpringOut, converter.ConvertFromInvariantString("SpringOut"));
Assert.AreEqual(Easing.SpringOut, converter.ConvertFromInvariantString("springout"));
Assert.AreEqual(Easing.SpringOut, converter.ConvertFromInvariantString("Easing.SpringOut"));
Assert.AreEqual(Easing.SpringIn, converter.ConvertFromInvariantString("SpringIn"));
Assert.AreEqual(Easing.SpringIn, converter.ConvertFromInvariantString("springin"));
Assert.AreEqual(Easing.SpringIn, converter.ConvertFromInvariantString("Easing.SpringIn"));
Assert.Throws => converter.ConvertFromInvariantString("WrongEasingName"));
Assert.Throws => converter.ConvertFromInvariantString("Easing.Linear.SinInOut"));
}
}
} | c# | 19 | 0.775027 | 114 | 59.324675 | 77 | starcoderdata |
from grapht.plotting import *
from grapht.sampling import sample_edges
from matplotlib.axes._subplots import Axes
from sklearn import datasets
import networkx as nx
import pandas as pd
def test_highlight_edges():
G = nx.barabasi_albert_graph(100, 3)
m = G.number_of_edges()
for num_highlight_edges in [0, m, int(m/2)]:
edges = sample_edges(G, num_highlight_edges)
ax = highlight_edges(G, edges)
assert isinstance(ax, Axes)
def test_heatmap():
iris = pd.DataFrame(datasets.load_iris()['data'],
columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])
ax = heatmap(iris, x='sepal_length', y='sepal_width', hue='petal_length')
assert isinstance(ax, Axes) | python | 10 | 0.667118 | 93 | 36 | 20 | starcoderdata |
def get_hotel_info(request):
# get all Hotel Categories
if request.method == 'GET':
print (request.body)
body_unicode = request.body.decode('utf-8')
zomato_url="https://developers.zomato.com/api/v2.1/categories"
headers={"Accept":"applicaiton/json",
"user-key": "b0fcc8e574f96ad3e80be23d898aa861"}
resp=requests.get(zomato_url,headers=headers)
print (resp.content)
jresp=json.loads(resp.text)
print (jresp)
return Response(jresp)
if request.method == 'POST':
print (request.body)
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
fb = FB(body)
zom = Zomat()
loc = str("Pune")
entity_id = 0
cuisine_id = 0
entity_type = str()
query_json = body['result']['parameters']
#try:
if 'postback' in body['originalRequest']['data']:
#if body['originalRequest']['data']['postback']['payload']:
fb_rating = Postbacks(
first_name=fb.userInfo['first_name'],
last_name=fb.userInfo['last_name'],
gender=fb.userInfo['gender'],
postback=str(body['originalRequest']['data']['postback']['payload']),
fb_userId=str(fb.sender_id)
)
fb_rating.save_to_db()
postback = body['originalRequest']['data']['postback']['payload']
handle_postback(postback, fb)
# if "NEW_USER_STARTED" in body['originalRequest']['data']['postback']['payload']:
# fb.independantTextMessage(fb.sender_id, "Hey there, Foodie !!! I'm JugheadBot, your friendly neighbourhood Restaurant finding Bot")
# sleep(1)
# fb.independantTextMessage(fb.sender_id, "You can ask me following questions:")
# fb.independantTextMessage(fb.sender_id, "\"Which are the best Restaurants in Kothrud, Pune\"")
# sleep(1)
# fb.independantTextMessage(fb.sender_id, "\"Which are the best Chinese Restaurants in Dadar, Mumbai\"")
# sleep(1)
# fb.independantTextMessage(fb.sender_id, "\"What is the review of Blue Nile in Camp Area, Pune\"")
# sleep(1)
# elif "HELP_TEXT" in body['originalRequest']['data']['postback']['payload']:
# fb.independantTextMessage(fb.sender_id, "Currently, I understand only the following 3 types of questions")
# fb.independantTextMessage(fb.sender_id, "\"Which are the best Restaurants in Kothrud, Pune\"")
# sleep(1)
# fb.independantTextMessage(fb.sender_id, "\"Which are the best Chinese Restaurants in Dadar, Mumbai\"")
# sleep(1)
# fb.independantTextMessage(fb.sender_id, "\"What is the review of Blue Nile in Camp Area, Pune\"")
# sleep(1)
# fb,independantTextMessage(fb.sender_id, "And PLEASE remember to specify the Area AND City. For example: \"Manhattan, New York\" or \"Dadar, Mumbai\"")
# sleep(1)
# else:
# fb.independantTextMessage(fb.sender_id, "Thanks !! I'll let Raseel know how much you liked me !!")
return Response("{}")
# except:
# # Not a Postback, so continue
# print("Not a Postback, so continue")
# pass
if 'geo-city' in query_json:
city = query_json['geo-city']
loc = city
print (city)
if 'area' in query_json:
area = query_json['area']
print (area)
loc = area + " " + loc
entity_id, entity_type = zom.getLocation(str(loc))
print ("entity_id = ",entity_id, ", entity_type = ", entity_type)
messages = []
restaurant_list = []
if "Cuisines" in query_json:
cuisine = str()
cuisine = query_json['Cuisines']
print (cuisine)
cuisine_id = zom.getCuisineID(city, cuisine)
print("cuisine_id = ", cuisine_id)
if int(cuisine_id) == 0:
messages = fb.textMessage(messages, "Could not find Restaurants for your specific Cuisine. Could you maybe re-check the spelling and try again?")
else:
restaurant_list = zom.getBestRestaurants(entity_id, entity_type, cuisine_id)
# Update FB Card message with Restaurant list
messages = fb.cardMessage(messages, restaurant_list)
elif "res-name" in query_json:
print ("This is a query for a Review")
res_name = query_json['res-name']
print (res_name)
restaurant_review = zom.getReviews(res_name, entity_id, entity_type)
messages = fb.cardMessage(messages, restaurant_review)
else:
# Just get the Top 5 Restaurants in the location
restaurant_list = zom.getBestRestaurants(entity_id, entity_type)
messages = fb.cardMessage(messages, restaurant_list)
response = {
"messages" : messages
}
print(response)
return Response(response) | python | 19 | 0.553307 | 168 | 47.435185 | 108 | inline |
/*
Copyright 2012-2017
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.
*/
using System;
using System.Collections;
using System.Data;
using RDFSharp.Model;
using RDFSharp.Store;
namespace RDFSharp.Query {
///
/// RDFDescribeQueryResult is a container for SPARQL "DESCRIBE" query results.
///
public class RDFDescribeQueryResult {
#region Properties
///
/// Tabular response of the query
///
public DataTable DescribeResults { get; internal set; }
///
/// Gets the number of results produced by the query
///
public Int64 DescribeResultsCount {
get {
return this.DescribeResults.Rows.Count;
}
}
#endregion
#region Ctors
///
/// Default-ctor to build an empty DESCRIBE result
///
internal RDFDescribeQueryResult(String tableName) {
this.DescribeResults = new DataTable(tableName);
}
#endregion
#region Methods
///
/// Builds a graph corresponding to the query result
///
public RDFGraph ToRDFGraph() {
RDFGraph result = new RDFGraph();
RDFPatternMember subj = null;
RDFPatternMember pred = null;
RDFPatternMember obj = null;
//Iterate the datatable rows and generate the corresponding triples to be added to the result graph
IEnumerator resultRows = this.DescribeResults.Rows.GetEnumerator();
while (resultRows.MoveNext()) {
subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["SUBJECT"].ToString());
pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["PREDICATE"].ToString());
obj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["OBJECT"].ToString());
if (obj is RDFResource) {
result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
}
else {
result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
}
}
return result;
}
///
/// Builds a memory store corresponding to the query result
///
public RDFMemoryStore ToRDFMemoryStore() {
RDFMemoryStore result = new RDFMemoryStore();
RDFPatternMember ctx = null;
RDFPatternMember subj = null;
RDFPatternMember pred = null;
RDFPatternMember obj = null;
//Iterate the datatable rows and generate the corresponding triples to be added to the result memory store
IEnumerator resultRows = this.DescribeResults.Rows.GetEnumerator();
while (resultRows.MoveNext()) {
ctx = (this.DescribeResults.Columns.Contains("CONTEXT") ?
new RDFContext(RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["CONTEXT"].ToString()).ToString()) :
new RDFContext(RDFNamespaceRegister.DefaultNamespace.NamespaceUri));
subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["SUBJECT"].ToString());
pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["PREDICATE"].ToString());
obj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["OBJECT"].ToString());
if (obj is RDFResource) {
result.AddQuadruple(new RDFQuadruple((RDFContext)ctx, (RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
}
else {
result.AddQuadruple(new RDFQuadruple((RDFContext)ctx, (RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
}
}
return result;
}
///
/// Builds a query result corresponding to the given graph
///
public static RDFDescribeQueryResult FromRDFGraph(RDFGraph graph) {
RDFDescribeQueryResult result = new RDFDescribeQueryResult(String.Empty);
if (graph != null) {
//Transform the graph into a datatable and assign it to the query result
result.DescribeResults = graph.ToDataTable();
}
return result;
}
///
/// Builds a query result corresponding to the given memory store
///
public static RDFDescribeQueryResult FromRDFMemoryStore(RDFMemoryStore store) {
RDFDescribeQueryResult result = new RDFDescribeQueryResult(String.Empty);
if (store != null) {
//Transform the memory store into a datatable and assign it to the query result
result.DescribeResults = store.ToDataTable();
}
return result;
}
#endregion
}
} | c# | 27 | 0.582003 | 161 | 40.055944 | 143 | starcoderdata |
using System.Linq;
using System.Text;
namespace GRomash.CrmWebApiEarlyBoundGenerator.Infrastructure.Extensions
{
///
/// Contains string extensions
///
public static class StringExtensions
{
///
/// Removes the special characters.
///
/// <param name="str">The string.
///
public static string RemoveSpecialCharacters(this string str)
{
var sb = new StringBuilder();
foreach (var c in str.Where(c => (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || char.IsWhiteSpace(c)))
{
if (char.IsWhiteSpace(c))
{
sb.Append("_");
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}
} | c# | 20 | 0.471767 | 157 | 29.4 | 35 | starcoderdata |
func (s *Server) subscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.Error) {
streamName, err := reqParams.Value(0).GetString()
if err != nil {
return nil, response.ErrInvalidParams
}
event, err := response.GetEventIDFromString(streamName)
if err != nil || event == response.MissedEventID {
return nil, response.ErrInvalidParams
}
// Optional filter.
var filter interface{}
if p := reqParams.Value(1); p != nil {
// It doesn't accept filters.
if event == response.BlockEventID {
return nil, response.ErrInvalidParams
}
switch event {
case response.TransactionEventID:
if p.Type != request.TxFilterT {
return nil, response.ErrInvalidParams
}
case response.NotificationEventID:
if p.Type != request.NotificationFilterT {
return nil, response.ErrInvalidParams
}
case response.ExecutionEventID:
if p.Type != request.ExecutionFilterT {
return nil, response.ErrInvalidParams
}
}
filter = p.Value
}
s.subsLock.Lock()
defer s.subsLock.Unlock()
select {
case <-s.shutdown:
return nil, response.NewInternalServerError("server is shutting down", nil)
default:
}
var id int
for ; id < len(sub.feeds); id++ {
if sub.feeds[id].event == response.InvalidEventID {
break
}
}
if id == len(sub.feeds) {
return nil, response.NewInternalServerError("maximum number of subscriptions is reached", nil)
}
sub.feeds[id].event = event
sub.feeds[id].filter = filter
s.subscribeToChannel(event)
return strconv.FormatInt(int64(id), 10), nil
} | go | 12 | 0.708687 | 102 | 26.854545 | 55 | inline |
public void OnEvent(EventData photonEvent)
{
if (photonEvent.Code == PunEvents.QualifierQuestionAnswered)
{
var data = (object[]) photonEvent.CustomData;
//If answered correctly
if ((bool) data[0])
{
_playersScores[photonEvent.Sender] += (timeToAnswer - (float) data[1]) * scoreMultiplier;
}
_playersAnswered[photonEvent.Sender] = true;
}
} | c# | 17 | 0.5 | 109 | 33.066667 | 15 | inline |
let e = 1;
module.exports = {
credentials: {
'userAgent': 'Xero Sample App - Krishna',
'consumerKey': process.env.consumerKey,
'consumerSecret': process.env.consumerSecret,
'privateKeyPath': './src/services/privatekey.pem'
},
qbcredentials: {
'api_uri': 'https://sandbox-quickbooks.api.intuit.com/v3/company/',
'tokenUrl': 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer',
'refresh_token': '
'client_id': process.env.client_id,
'client_secret': process.env.client_secret,
'realmId': '193514591409719'
},
emailConfig: {
// 'emailUrl': 'https://api.'+process.env.domainkey+'/vmailmicro/sendEmail',
'emailUrl': 'https://api.' + process.env.domainKey + '/vmailmicro/sendemaildata',
}
}; | javascript | 9 | 0.667497 | 85 | 31.12 | 25 | starcoderdata |
import pylab, optparse, os
#opt parse arguements, type advect_ini.dat, advect_fin.dat, and norm.dat
#---------------------------------------------------------------------------------
# Not in use now
parser = optparse.OptionParser()
opts, args = parser.parse_args()
#Method that runs the advection program in C for a certain method, initial con
#-ditions and Nx. It makes a plot of the analytical and estimated solutions
# and it also
#----------------------------------------------------------------------------
def advect(initial, initialName, method, methodName, Nx):
#Initialize parmeter file
#--------------------------------------------------------
filename = "param.cfg"
pfile = open(filename, 'w')
pfile.write("Nx = %d \n" % Nx)
pfile.write("x1 = 1.0 \n")
pfile.write("x0 = -1.0 \n")
pfile.write("CFL = 0.5 \n")
pfile.write("a = 1.0 \n")
pfile.write("t_max = 2.0 \n ")
pfile.write("init = %d \n " % initial)
pfile.write("meth = %d \n" % method)
pfile.close()
# run c program
#-----------------------------
os.system("./advect_dbr250")
#recover the calculation of the norm
#-----------------------------------
normFile = open("norm.dat", 'r')
lines = normFile.readlines()
norm = float(lines[0])
Nx = int(lines[1])
#Plot results
#-------------------------------------------------------
pylab.title("Advection of a %s wave using the %s method \n The L1_norm is calculated to be: %f" % (initialName ,methodName, norm))
plotTitles = ["Initial Condition","Analytical Solution", "Estimated Solution"]
plotFiles = ["advect_ini.dat", "advect_ana.dat", "advect_fin.dat"]
for infile_title,infile_name in zip(plotTitles,plotFiles):
infile = open(infile_name)
lines = infile.readlines()
strvals = [l.strip().split() for l in lines]
x = [float(v[0]) for v in strvals]
y = [float(v[1]) for v in strvals]
pylab.plot(x,y, label = infile_title)
pylab.xlabel("x (with Nx = %d )" % Nx )
pylab.ylabel("u")
pylab.legend()
#----------------------------------------------------------
#Method that runs the advection program in C for a certain method, initial con
#-ditions and values of Nx. It makes a plot of the convergence rate and prints
# the slope
#----------------------------------------------------------------------------
def advectConv(initial, initialName, method, methodName, Nxs):
L1 = list()
Nx = list()
for Nxvalue in Nxs:
#Initialize parmeter file
#--------------------------------------------------------
filename = "param.cfg"
pfile = open(filename, 'w')
pfile.write("Nx = %d \n" % Nxvalue)
pfile.write("x1 = 1.0 \n")
pfile.write("x0 = -1.0 \n")
pfile.write("CFL = 0.5 \n")
pfile.write("a = 1.0 \n")
pfile.write("t_max = 2.0 \n ")
pfile.write("init = %d \n " % initial)
pfile.write("meth = %d \n" % method)
pfile.close()
# run c program
#-----------------------------
os.system("./advect_dbr250")
#recover the calculation of the norm
#-----------------------------------
normFile = open("norm.dat", 'r')
lines = normFile.readlines()
norm = float(lines[0])
#append result onto list of norms and nx values
#---------------------------------
L1.append(norm)
Nx.append(Nxvalue)
#Calculate slope of convergence
#---------------------------------------------------------------
slope = (pylab.log(L1[-1])-pylab.log(L1[1]))/(pylab.log(Nx[-1])-pylab.log(Nx[1]))
#Plot Results
#---------------------------------------------------------------
pylab.loglog(Nx,L1,'-o', label = "%s with slope= %f" % (methodName, slope))
pylab.xlabel("Nx")
pylab.ylabel("L1_norm")
pylab.legend()
#Run advection for Square wave and Gaussian with both methods
#-------------------------------------------------------------------
pylab.figure()
initialConditions = ["Gaussian","Square"]
methodNames = ["Lax-Friedrichs", "Lax-Wendroff"]
Nx = 40
count = 1
for j in range(0,2):
for i in range(0,2):
pylab.subplot(2,2,count)
advect(i+1,initialConditions[i],j+1,methodNames[j], Nx)
count = count +1
#Run advection and plot convergence for both with both methods
#-------------------------------------------------------------------
Nxs = [10,30,100,300,1000,3000]
initialConditions = ["Gaussian","Square"]
methodNames = ["Lax-Friedrichs", "Lax-Wendroff"]
pylab.figure()
for j in range(0,2):
pylab.subplot(2,1,j+1)
pylab.title("Convergence rates for %s wave" % initialConditions[j])
for i in range(0,2):
advectConv(j+1,initialConditions[j],i+1,methodNames[i], Nxs)
pylab.show() | python | 12 | 0.482025 | 134 | 29.925466 | 161 | starcoderdata |
import json
import urllib.request
import re
import csv
import sys
import time
import argparse
from datetime import datetime
from urllib.parse import quote_plus
parser = argparse.ArgumentParser()
parser.add_argument("month", help="specify the month for example: March")
parser.add_argument("year", help="specify the year for example: 2020")
args = parser.parse_args()
month = args.month
year = args.year
wikiPrefix =''
if(args.month == 'March'):
wikiPrefix='Responses_to'
else:
wikiPrefix='Timeline_of'
# Path for Timeline info of COVID-19 in wikipedia
wikiPath = 'https://en.wikipedia.org/w/api.php?action=parse&page='+quote_plus(wikiPrefix)+'_the_2019%E2%80%9320_coronavirus_pandemic_in_'+quote_plus(month)+'_'+quote_plus(year)+'&prop=wikitext&formatversion=2&format=json'
print(wikiPath)
jsonResponse = urllib.request.urlopen(wikiPath).read().decode(encoding="utf-8", errors="ignore")
# Start of Reactions and Measures outside China Section
startSection = '== Reactions and measures outside mainland China =='
startSection = jsonResponse.find(startSection)
if startSection == -1:
print("The page does not contain Measures. Check your parameters")
sys.exit(0)
# Headings for Dates format
firstDate = '=== 1 %s ===' % (month)
firstDateSection = jsonResponse[startSection:].find(firstDate) + startSection
# Each Measure starts with a new line character and ends with a link reference
eventRegex = r"(?<=\\n)(.*?)(?=<ref)"
# Date Headings have === Date === format
dateRegex = r"(?<=\=\=\=).*?(?=\=\=\=)"
# Fetch whole section with Reactions and measures
allEvents=jsonResponse[firstDateSection:]
# Get all Measures and remove link references etc
events = re.finditer(eventRegex, allEvents, re.MULTILINE)
# CSV output file
csvOutputFilename = '../csvOutput/Covid19MeasuresandEvents' + year + month + '.csv'
# Function to match Country name, who takes the measure
def matchCountry(row):
i=0
matches={}
with open('../resources/country-keyword-list.csv', 'r', newline='') as f:
thereader=csv.reader(f)
for column in thereader:
checkMatchCountry= re.search(column[0], row, re.IGNORECASE)
if checkMatchCountry:
# We found a country name in the text
matches[i] = column[0]
i+=1
if len(column)>1 :
checkMatchNationality = re.search(column[1], row, re.IGNORECASE)
if checkMatchNationality:
# We found a nationality name in the text
matches[i] = column[0]
i+=1
if i==0:
return 'Other'
if i==1 :
return matches[0]
if i>1 :
# We have several country names referenced in the sentence.
# This part normally requires NLP and probably Spacy, to check who really the subject is
# I just took the first word, as it is highly likely that the first menioned country is the one taking the measure in the sentence.
return matches[0]
with open(csvOutputFilename, 'w', newline='') as f:
thewriter = csv.writer(f)
thewriter.writerow(['Date', 'Country','Event'])
currentDate = re.search(dateRegex,firstDate).group()
for eventNum, event in enumerate(events, start=1):
# A bit cleanup to remove special characters
event = event.group()
event = event.replace("[","")
event = event.replace("]","")
event = event.replace("\\n","")
# Match the date
datematch = re.search(dateRegex,event)
if datematch:
currentDate = datematch.group()
# Lets cleanup the date from events, as it is already fetched in the csv
event = re.sub(r"(\=\=\=).*?(\=\=\=)", '' , event)
# February 29 causes exception due to leap year. For now this is a dirty fix.
try:
currentDateISO8601 = datetime.strptime(currentDate.strip(), '%d %B')
currentDateISO8601 = currentDateISO8601.strftime('2020-%m-%d')
except:
currentDateISO8601 = '2020-02-29'
# Match the name of Country
countryName = matchCountry(event)
#Write to Csv and we are done
thewriter.writerow([currentDateISO8601, countryName, event]) | python | 14 | 0.642841 | 221 | 30.452555 | 137 | starcoderdata |
import asyncio
import datetime
import os
import discord
from discord.ext import commands
class CloseTicket(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="close", aliases=["delete", "remove"])
@commands.guild_only()
async def close(self, ctx):
if not ctx.message.channel.name.startswith("ticket-"):
message = await ctx.send(f"Ticketチャンネルではありません!")
await asyncio.sleep(5)
await message.delete()
else:
creator = discord.utils.get(ctx.guild.members, id=int(ctx.message.channel.name.replace("ticket-", "")))
with open(f"{ctx.channel.name}.txt", mode='a') as f:
f.write(f"{creator}'s ticket was opened at {ctx.channel.created_at} and "
f"closed at {datetime.datetime.utcnow()} by {ctx.author}.\n\n")
async for msg in ctx.message.channel.history(oldest_first=True):
f.write(f"[{msg.created_at}] {msg.author}: {msg.clean_content}\n")
await ctx.channel.delete()
notify = discord.utils.get(ctx.guild.text_channels, name="ticket-notify")
if notify is not None:
with open(f"{ctx.channel.name}.txt", mode='rb') as f:
notifyembed = discord.Embed(
title="Ticketがクローズされました",
timestamp=datetime.datetime.utcnow(),
color=discord.Color.red()
)
notifyembed.add_field(
name="Ticket作成者",
value=f"{creator.mention}\n"
f"({creator.id})"
)
notifyembed.add_field(
name="クローズしたユーザー",
value=f"{ctx.author.mention}\n"
f"({ctx.author.id})"
)
notifyembed.add_field(
name="チャンネル",
value=ctx.channel.name,
inline=False
)
await notify.send(embed=notifyembed, file=discord.File(f))
with open(f"{ctx.channel.name}.txt", mode="rb") as f:
try:
channel = await creator.create_dm()
await channel.send(embed=notifyembed, file=discord.File(f))
except discord.Forbidden:
pass
os.remove(f"{ctx.channel.name}.txt")
def setup(bot):
bot.add_cog(CloseTicket(bot)) | python | 22 | 0.48966 | 115 | 41 | 63 | starcoderdata |
######################################################################
# PWM_LED_2.py
#
# This program produce a pwm and control light exposure of an LED
# in such a way that exposure increase until reach to maximum
# then decrease until reach to minimum periodically
######################################################################
import RPi.GPIO as GPIO
import time
ledPin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT)
ledPwm = GPIO.PWM(ledPin, 50)
ledPwm.start(100)
while(True):
print("Increase Mode")
for i in range(0, 100):
ledPwm.ChangeDutyCycle(i)
time.sleep(0.01)
print("Decrease Mode")
for i in range(100, 0, -1):
ledPwm.ChangeDutyCycle(i)
time.sleep(0.01) | python | 8 | 0.556011 | 70 | 24.241379 | 29 | starcoderdata |
<?php
/** @noinspection PhpDocSignatureInspection */
namespace webignition\HtmlValidatorOutput\Parser\Tests;
use webignition\HtmlValidatorOutput\Models\AbstractIssueMessage;
use webignition\HtmlValidatorOutput\Models\InfoMessage;
use webignition\HtmlValidatorOutput\Models\ValidationErrorMessage;
use webignition\HtmlValidatorOutput\Parser\MessageFactory;
class MessageFactoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @var MessageFactory
*/
private $messageFactory;
protected function setUp()
{
parent::setUp();
$this->messageFactory = new MessageFactory();
}
/**
* @dataProvider createMessageFromArrayDataProvider
*/
public function testCreateMessageFromArray(array $values, AbstractIssueMessage $expectedMessage)
{
$this->assertEquals($expectedMessage, $this->messageFactory->createMessageFromArray($values));
}
public function createMessageFromArrayDataProvider(): array
{
return [
'error message' => [
'values' => [
'lastLine' => 188,
'lastColumn' => 79,
'message' => 'An img element must have an alt attribute, except under certain conditions.',
'messageid' => 'html5',
'explanation' => 'image missing alt attribute explanation',
'type' => 'error',
],
'expectedMessage' => new ValidationErrorMessage(
'An img element must have an alt attribute, except under certain conditions.',
'html5',
'image missing alt attribute explanation',
188,
79
),
],
'info message, has explanation' => [
'values' => [
'message' => 'Info message message',
'messageid' => 'html5',
'explanation' => 'Info message explanation',
'type' => 'info',
],
'expectedMessage' => new InfoMessage(
'Info message message',
'html5',
'Info message explanation'
),
],
'info message, no explanation' => [
'values' => [
'message' => 'Info message message',
'messageid' => 'html5',
'type' => 'info',
],
'expectedMessage' => new InfoMessage(
'Info message message',
'html5'
),
],
'info message, no messageid, no explanation' => [
'values' => [
'message' => 'Info message message',
'type' => 'info',
],
'expectedMessage' => new InfoMessage(
'Info message message'
),
],
];
}
} | php | 14 | 0.495546 | 111 | 33.443182 | 88 | starcoderdata |
package com.ucar.zkdoctor.util.tool;
import org.junit.Test;
import java.io.Serializable;
/**
* Description: 序列化测试类
* Created on 2018/2/5 9:50
*
* @author 吕小玲(
*/
public class HessianSerializerUtilsTest implements Serializable {
private static final long serialVersionUID = 6510936416683102059L;
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "HessianSerializerUtilsTest{" +
"id=" + id +
'}';
}
@Test
public void serialize() throws Exception {
HessianSerializerUtilsTest object = new HessianSerializerUtilsTest();
object.setId(100);
byte[] data = HessianSerializerUtils.serialize(object);
System.out.println(HessianSerializerUtils.deserialize(data));
}
} | java | 10 | 0.64153 | 77 | 20.809524 | 42 | starcoderdata |
<?php
declare(strict_types=1);
namespace WTG\RestClient\Model\Parser;
use Carbon\CarbonImmutable;
use WTG\RestClient\Model\Rest\GetInvoices\Response\Invoice;
/**
* Invoice parser.
*
* @package WTG\RestClient
* @author
*/
class InvoiceParser
{
public const STATUS_CODE_OPEN = 'G';
public const STATUS_CODE_PAID = 'Z';
private const DATE_FORMAT = 'Y-m-d';
private const STATUS_OPEN = 'Openstaand';
private const STATUS_PAID = 'Betaald';
/**
* Parse a response product.
*
* @param array $item
* @return Invoice
*/
public function parse(array $item): Invoice
{
$dueDate = $item['dueDate'] ? CarbonImmutable::createFromFormat(self::DATE_FORMAT, $item['dueDate']) : null;
$invoice = new Invoice();
$invoice->erpId = $item['id'];
$invoice->debtorCode = $item['debtorCode'];
$invoice->code = $item['salesInvoiceCode'];
$invoice->vatCode = $item['orderCostsVatGroup'];
$invoice->date = CarbonImmutable::createFromFormat(self::DATE_FORMAT, $item['invoiceDate']);
$invoice->dueDate = $dueDate;
$invoice->statusCode = $item['financialStatusCode'];
$invoice->statusDescription = $this->parseStatusCode($item['financialStatusCode']);
$invoice->subtotal = $item['amountGoods'];
$invoice->vat = $item['amountVat'];
$invoice->total = $item['amountInvoice'];
$invoice->description = $item['description'] ?: null;
$invoice->paymentCondition = $item['paymentConditionInfo']['description'];
return $invoice;
}
private function parseStatusCode(string $financialStatusCode)
{
switch ($financialStatusCode) {
case self::STATUS_CODE_OPEN:
return self::STATUS_OPEN;
case self::STATUS_CODE_PAID:
default:
return self::STATUS_PAID;
}
}
} | php | 13 | 0.613437 | 116 | 29.714286 | 63 | starcoderdata |
import path from 'path';
import { message } from 'antd';
import { promisify } from 'util';
import axios from 'axios';
import makeDir from 'make-dir';
import fs from 'fs';
import _ from 'lodash';
import Zip from 'adm-zip';
import { downloadFile, downloadArr } from '../utils/downloader';
import { PACKS_PATH, INSTANCES_PATH, META_PATH } from '../constants';
import {
extractAssets,
extractMainJar,
extractNatives,
computeVanillaAndForgeLibraries
} from '../utils/getMCFilesList';
import { arraify } from '../utils/strings';
export const START_DOWNLOAD = 'START_DOWNLOAD';
export const CLEAR_QUEUE = 'CLEAR_QUEUE';
export const ADD_TO_QUEUE = 'ADD_TO_QUEUE';
export const DOWNLOAD_COMPLETED = 'DOWNLOAD_COMPLETED';
export const UPDATE_TOTAL_FILES_TO_DOWNLOAD = 'UPDATE_TOTAL_FILES_TO_DOWNLOAD';
export const UPDATE_PROGRESS = 'UPDATE_PROGRESS';
export function addToQueue(pack, version, forgeVersion = null) {
return (dispatch, getState) => {
const { downloadManager } = getState();
dispatch({
type: ADD_TO_QUEUE,
payload: pack,
version,
forgeVersion
});
if (downloadManager.actualDownload === null) {
dispatch({
type: START_DOWNLOAD,
payload: pack
});
dispatch(downloadPack(pack));
}
};
}
export function clearQueue() {
// This needs to clear any instance that is already installed
return (dispatch, getState) => {
const { downloadManager } = getState();
const completed = Object.keys(downloadManager.downloadQueue).filter(
act => downloadManager.downloadQueue[act].status === 'Completed'
);
// It makes no sense to dispatch if no instance is to remove
if (completed.length !== 0) {
dispatch({
type: CLEAR_QUEUE,
payload: completed
});
}
};
}
export function downloadPack(pack) {
return async (dispatch, getState) => {
const { downloadManager, packCreator } = getState();
const currPack = downloadManager.downloadQueue[pack];
let vnlJSON = null;
try {
vnlJSON = JSON.parse(
await promisify(fs.readFile)(
path.join(
META_PATH,
'net.minecraft',
currPack.version,
`${currPack.version}.json`
)
)
);
} catch (err) {
const versionURL = packCreator.versionsManifest.find(
v => v.id === currPack.version
).url;
vnlJSON = (await axios.get(versionURL)).data;
await makeDir(path.join(META_PATH, 'net.minecraft', currPack.version));
await promisify(fs.writeFile)(
path.join(
META_PATH,
'net.minecraft',
currPack.version,
`${currPack.version}.json`
),
JSON.stringify(vnlJSON)
);
}
let forgeJSON = null;
const assets = await extractAssets(vnlJSON);
const mainJar = await extractMainJar(vnlJSON);
let forgeFileName = null;
if (currPack.forgeVersion !== null) {
const { branch } = packCreator.forgeManifest[
Object.keys(packCreator.forgeManifest).find(v => v === currPack.version)
].find(v => Object.keys(v)[0] === currPack.forgeVersion)[
currPack.forgeVersion
];
forgeFileName = `${currPack.version}-${currPack.forgeVersion}${
branch !== null ? `-${branch}` : ''
}`;
try {
forgeJSON = JSON.parse(
await promisify(fs.readFile)(
path.join(
META_PATH,
'net.minecraftforge',
forgeFileName,
`${forgeFileName}.json`
)
)
);
await promisify(fs.access)(
path.join(
INSTANCES_PATH,
'libraries',
...arraify(forgeJSON.versionInfo.libraries[0].name)
)
);
} catch (err) {
await downloadFile(
path.join(INSTANCES_PATH, 'temp', `${forgeFileName}.jar`),
`https://files.minecraftforge.net/maven/net/minecraftforge/forge/${forgeFileName}/forge-${forgeFileName}-installer.jar`,
p => {
dispatch({
type: UPDATE_PROGRESS,
payload: { pack, percentage: ((p * 18) / 100).toFixed(0) }
});
}
);
const zipFile = new Zip(
path.join(INSTANCES_PATH, 'temp', `${forgeFileName}.jar`)
);
forgeJSON = JSON.parse(zipFile.readAsText('install_profile.json'));
await makeDir(
path.dirname(
path.join(
INSTANCES_PATH,
'libraries',
...arraify(forgeJSON.versionInfo.libraries[0].name)
)
)
);
await promisify(fs.unlink)(
path.join(INSTANCES_PATH, 'temp', `${forgeFileName}.jar`)
);
await makeDir(
path.join(META_PATH, 'net.minecraftforge', forgeFileName)
);
await promisify(fs.writeFile)(
path.join(
META_PATH,
'net.minecraftforge',
forgeFileName,
`${forgeFileName}.json`
),
JSON.stringify(forgeJSON)
);
}
}
const libraries = await computeVanillaAndForgeLibraries(vnlJSON, forgeJSON);
// This is the main config file for the instance
await promisify(fs.writeFile)(
path.join(PACKS_PATH, pack, 'config.json'),
JSON.stringify({
version: currPack.version,
forgeVersion: forgeFileName
})
);
const totalFiles = libraries.length + assets.length + mainJar.length;
dispatch({
type: UPDATE_TOTAL_FILES_TO_DOWNLOAD,
payload: {
pack,
total: totalFiles
}
});
const updatePercentage = downloaded => {
const actPercentage = ((downloaded * 82) / totalFiles + 18).toFixed(0);
if (currPack.percentage !== actPercentage)
return dispatch({
type: UPDATE_PROGRESS,
payload: {
pack,
percentage: actPercentage
}
});
};
await downloadArr(
[...libraries, ...assets, ...mainJar],
updatePercentage,
pack
);
await extractNatives(libraries.filter(lib => 'natives' in lib), pack);
dispatch({
type: DOWNLOAD_COMPLETED,
payload: pack
});
message.success(`${pack} has been downloaded!`);
dispatch(addNextPackToActualDownload());
};
}
function addNextPackToActualDownload() {
return (dispatch, getState) => {
const { downloadManager } = getState();
const queueArr = Object.keys(downloadManager.downloadQueue);
queueArr.some(pack => {
if (downloadManager.downloadQueue[pack].status !== 'Completed') {
dispatch({
type: START_DOWNLOAD,
payload: pack
});
dispatch(downloadPack(pack));
return true;
}
return false;
});
};
} | javascript | 29 | 0.58212 | 130 | 27.736402 | 239 | starcoderdata |
console.debug("init install.js");
// Check whether new version is installed
chrome.runtime.onInstalled.addListener(details => {
const manifest = chrome.runtime.getManifest();
console.debug(`app ${details.reason} ${details.previousVersion} to ` + manifest.version);
chrome.storage.local.get(null, storage => {
// const initialStorage = { );
switch (details.reason) {
case 'install':
if (!Object.keys(storage).length) {
chrome.runtime.openOptionsPage();
// chrome.storage.local.set(initialStorage);
// console.debug('Apply initial configuration', JSON.stringify(initialStorage));
}
break;
// case 'update':
// break;
}
});
}); | javascript | 20 | 0.593506 | 95 | 31.083333 | 24 | starcoderdata |
def get_all_dync_properties_data():
#output: a list contains elements, each element is a dict representing one node of property list
tag,val = get_current_thisbinding()
if m_debug.Debug: m_debug.dbg_print("tag=", tag, "val=", val)
if tag and val:
addr = get_realAddr_by_index(val)
if m_debug.Debug: m_debug.dbg_print("real addr=", addr)
#only when prop_list returns non-0 address, could the prop_list starts
# to have meaningful data filled in.
# also nite, prop_list_head is in struct of struct __jsprop. reference this
# structure, we can get the list node data immediately
prop_list_head = get_realAddr_data(addr, tag)
if m_debug.Debug: m_debug.dbg_print("prop_list_head=", prop_list_head)
if not prop_list_head:
gdb_print("prop_list no data filled in yet")
return None
else:
# get all the node data from property list
data = get_prop_list_data(prop_list_head)
if m_debug.Debug: m_debug.dbg_print("data=", data)
return data | python | 14 | 0.627165 | 100 | 46.73913 | 23 | inline |
import {LitElement, html} from 'https://unpkg.com/@polymer/[email protected]/lit-element.js?module';
/**
* Default Empty Overlay
* Used to display help content when there is no data.
* @return {string}
*/
const defaultEmptyOverlay = html`<div class="data-table-empty">No results
/**
* Default Error Overlay
* Used to display any errors that are passed in via the errors prop.
* @param {Array} errors - List of errors to display
* @return {string|html}
*/
const defaultErrorOverlay = (errors) => {
return html`
<div class="data-table-error">
${errors.map((error) => html`
`;
};
/**
* Default Sort Closure
* @param {Column} column - The column to sort
*/
const defaultSort = (column) => {
/**
* Default sort function.
* @param {any} first - First item to compare
* @param {any} second - Second item to compare
* @return {number}
*/
return (first, second) => {
const firstItem = column.getData(first);
const secondItem = column.getData(second);
const compared = firstItem.toString().localeCompare(secondItem);
return column.sortDirection === 'DESC' ? compared : -compared;
};
};
/**
* Column Header Display
* If the column is sortable this will include controls and a callback to
* update the sortIndex and or the direction on the column.
* @param {function} sortIndexCallback - Function to update the sort index.
* @return {function}
*
*/
const displayHeader = (sortIndexCallback) => {
/**
* Column Header Display
* If the column is sortable this will include controls and a callback to
* update the sortIndex and or the direction on the column.
*
* @param {Column} column - The column to display the header and controls for.
* @param {number} index - The index of the column.
* @return {string|html}
*/
return (column, index) => {
const { sortable, sortDirection, header, sorted, align } = column;
let columnIndex = index;
if (!sortable) {
return html`
}
const sortedIcon = sortDirection === 'DESC' ? 'sort-down' : 'sort-up';
const icon = sorted ? sortedIcon : 'sort';
return html`<th class="sortable ${align}" @click=${() => sortIndexCallback(columnIndex)}>${header} <hx-icon class="toggle-icon" type="${icon}">
};
};
export class DataTable extends LitElement {
constructor () {
super();
this.columns = [];
this.data = [];
this.errors = [];
this.displayData = [];
this.emptyOverlay = defaultEmptyOverlay;
this.errorOverlay = defaultErrorOverlay;
this.className = 'hxHoverable';
this.sortIndex = -1;
}
static get properties() {
return {
data: { type: Array },
columns: { type: Array },
errors: { type: Array },
emptyOverlay: { type: String },
errorOverlay: { type: String },
className: { type: String }
};
}
_getHeader() {
const { columns, _updateSortIndex } = this;
const headerDisplay = displayHeader(_updateSortIndex.bind(this));
return html`
${columns.map(headerDisplay)}
`;
}
_showEmpty() {
const { emptyOverlay } = this;
const numberOfColumns = this.columns.length;
return html`
<td colspan="${numberOfColumns}">${emptyOverlay}
`;
}
_showError() {
const { errorOverlay, errors } = this;
const numberOfColumns = this.columns.length;
return html`
<td colspan="${numberOfColumns}">${errorOverlay(errors)}
`;
}
_getFilteredData(data) {
// TODO: make this work
return data;
}
_getSortedData(data) {
const { sortIndex, columns } = this;
if (sortIndex >= 0) {
let column = columns[sortIndex];
return data.sort(defaultSort(column));
}
return data;
}
_filterAndSort(data) {
let filtered = this._getFilteredData(data);
let sorted = this._getSortedData(filtered);
return sorted;
}
_updateSortIndex(index) {
const { sortIndex, columns } = this;
if (sortIndex === index) {
columns[index].toggleSortDirection();
} else {
columns[this.sortIndex].sorted = false;
columns[index].sorted = true;
this.sortIndex = index;
}
this.update();
}
_getBody() {
const { data, columns, errors } = this;
if (errors && errors.length !== 0) {
return this._showError();
}
if (!data || data.length === 0) {
return this._showEmpty();
}
let sortedData = this._filterAndSort(data);
return html`
${sortedData.map((item) => {
return html`
${columns.map((column) => {return html`<td class="${column.align}">${column.getCell(item)}
`;
})}
`;
}
connectedCallback() {
super.connectedCallback();
const { columns } = this;
columns.map((column, index) => {
if (column.sorted) {
this.sortIndex = index;
}
});
}
createRenderRoot() {
return this;
}
render() {
return html`
<table class="hxTable ${this.className}">
`;
}
}
customElements.define('data-table', DataTable); | javascript | 28 | 0.602706 | 164 | 24.338095 | 210 | starcoderdata |
import React from 'react';
import { cleanup, render } from '@testing-library/react';
import SimpleSpinner from './SimpleSpinner';
describe('SimpleSpinner component', () => {
let wrapper;
let container;
describe('with props', () => {
beforeAll(() => {
wrapper = render(<SimpleSpinner size={20} mainColor="#000000" altColor="red" />);
({ container } = wrapper);
});
afterAll(cleanup);
it('renders correctly', () => {
expect(container).toMatchSnapshot();
});
});
}); | javascript | 23 | 0.608949 | 87 | 23.47619 | 21 | starcoderdata |
#!/usr/bin/python
# 列表综合
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listone)
print(listtwo) | python | 6 | 0.686667 | 41 | 15.777778 | 9 | starcoderdata |
<?php
namespace App\Http\Controllers\POS\Diskon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Datatables;
class TambahDiskonController extends Controller
{
public function index()
{
return view('pos.pages.diskon.tambahDiskon.tampilTambahDiskon');
}
public function formDiskonPenjualan()
{
return view('pos.pages.diskon.tambahDiskon.formDiskonPenjualan');
}
public function formDiskonItem()
{
return view('pos.pages.diskon.tambahDiskon.formDiskonItem');
}
public function formDiskonAB()
{
return view('pos.pages.diskon.tambahDiskon.formDiskonAB');
}
public function formDiskonJumlahMinimalN()
{
// return 'hello';
return view('pos.pages.diskon.tambahDiskon.formJumlahMinimalN');
}
public function cariBarcode(Request $request)
{
$barcode = $request->barcode;
$cari = DB::table('tb_stok')
->where('barcode',$barcode)
->get();
return response()->json($cari);
}
} | php | 13 | 0.668016 | 125 | 21.87037 | 54 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomCodeOrg.ENetFramework.Statements {
public interface IBinding {
string Name { get; }
string Identifier { get; }
object GetValue();
void SetValue(object value);
}
} | c# | 8 | 0.715 | 60 | 22.529412 | 17 | starcoderdata |
<?php
/*
* Copyright (C) 2011 OpenSIPS Project
*
* This file is part of opensips-cp, a free Web Control Panel Application for
* OpenSIPS SIP server.
*
* opensips-cp is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* opensips-cp 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
require("template/header.php");
if (isset($_POST['action'])) $action=$_POST['action'];
else if (isset($_GET['action'])) $action=$_GET['action'];
else $action="";
if ($action=="gw_types")
{
extract($_POST);
$gw_error="";
$rows=explode("\n",$data);
if ((sizeof($rows)==1) && (trim($rows[0])=="")) $gw_error="no Gateway Types defined";
else
{
for($i=0;$i<sizeof($rows);$i++)
{
$pos=strpos($rows[$i]," ");
if ($pos===false) $gw_error="invalid Gateway Types Format";
$value[$i]=trim(substr($rows[$i],0,$pos));
$content[$i]=trim(substr($rows[$i],$pos,strlen($rows[$i])));
if ((!is_numeric($value[$i])) || ($content[$i]=="")) $gw_error="invalid Gateway Types Format";
}
$result=array_unique($value);
if (sizeof($result)!=sizeof($value)) $gw_error="duplicate Gateway Types";
}
if ($gw_error=="") {
$filename="../../../../config/tools/system/drouting/gw_types.txt";
$handle=fopen($filename,"w");
fwrite($handle,$data);
fclose($handle);
}
}
if ($action=="groups")
{
extract($_POST);
$groups_error="";
$rows=explode("\n",$data);
if ((sizeof($rows)==1) && (trim($rows[0])=="")) $groups_error="no Group IDs defined";
else
{
for($i=0;$i<sizeof($rows);$i++)
{
$pos=strpos($rows[$i]," ");
if ($pos===false) $groups_error="invalid Group ID Format";
$value[$i]=trim(substr($rows[$i],0,$pos));
$content[$i]=trim(substr($rows[$i],$pos,strlen($rows[$i])));
if ((!is_numeric($value[$i])) || ($content[$i]=="")) $groups_error="invalid Group ID Format";
}
$result=array_unique($value);
if (sizeof($result)!=sizeof($value)) $groups_error="duplicate Group ID";
}
if ($groups_error=="") {
$filename="../../../../config/tools/system/drouting/group_ids.txt";
$handle=fopen($filename,"w");
fwrite($handle,$data);
fclose($handle);
}
}
require("template/".$page_id.".main.php");
require("template/footer.php");
exit();
?> | php | 21 | 0.593146 | 99 | 32.488636 | 88 | starcoderdata |
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
string s;
vector<pair<string, int>>v;
v.push_back(make_pair("AC", 0));
v.push_back(make_pair("WA", 0));
v.push_back(make_pair("TLE", 0));
v.push_back(make_pair("RE", 0));
for (int i = 0;i < n;i++)
{
cin >> s;
if (s == "AC")
v[0].second++;
else if (s == "WA")
v[1].second++;
else if (s == "TLE")
v[2].second++;
else if (s == "RE")
v[3].second++;
}
for (int i = 0;i < 4;i++)
{
cout << v[i].first << " " << "x" << " " << v[i].second;
if (i < 3)
{
cout << endl;
}
}
return 0;
} | c++ | 17 | 0.490132 | 57 | 16.4 | 35 | codenet |
package com.example.mobilesafe74.activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.mobilesafe74.R;
import com.example.mobilesafe74.bean.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yueyue on 2017/1/18.
*/
public class ContactlistActivity extends AppCompatActivity {
private ListView lv_contact;
private static final String TAG = "ContactlistActivity";
private List contactlists = new ArrayList<>();
public Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
lv_contact.setAdapter(new MyAdapter());
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
//初始化UI
initUI();
//初始化数据
initData();
}
/**
* 初始化数据
*/
private void initData() {
new Thread(new Runnable() {
@Override
public void run() {
//获得内容解析者
ContentResolver resolver = getContentResolver();
// 查询raw_contacts表.获得联系人游标
Cursor cursor = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts"),
new String[]{"contact_id"}, null, null, null);
//使用之前先清空里面原有的数据
contactlists.clear();
//通过cursor拿出整张raw_contacts联系人表id
while (cursor.moveToNext()) {
String id = cursor.getString(0);
Log.i(TAG, id);
Cursor indexCursor = resolver.query(Uri.parse("content://com.android.contacts/data"),
new String[]{"data1", "mimetype"}, "raw_contact_id=?",
new String[]{id}, null);
Person person = new Person();
//indexCursor拿到我们需要的名字以及电话号码.接着Person类的数据封装到contactlists中
while (indexCursor.moveToNext()) {
String data1 = indexCursor.getString(0);
String type = indexCursor.getString(1);
Log.i(TAG, data1);
Log.i(TAG, type);
//如果联系人的表格中data1数据不为空,那么才执行操作
if (!TextUtils.isEmpty(data1)) {
//判断data1表中的数据,获得我们需要的数据如名字以及电话号码
if (type.equals("vnd.android.cursor.item/name")) {
person.setName(data1);
} else if (type.equals("vnd.android.cursor.item/phone_v2")) {
person.setPhone(data1);
}
}
}
//关闭indexCursor游标,释放资源
if (indexCursor != null) {
indexCursor.close();
}
contactlists.add(person);
}
//关闭cursor游标,释放资源
if (cursor != null) {
cursor.close();
}
//发送消息机制,通知主线程已经把数据准备好了,可以拿去用了
mHandler.sendEmptyMessage(0);
}
}) {
}.start();
}
/**
* 初始化UI
*/
private void initUI() {
//找到我们需要的组件
lv_contact = (ListView) findViewById(R.id.lv_contact);
//为listView组件注册一个监听事件
lv_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Person person = contactlists.get(position);
if (person!=null){
String phone = person.getPhone();
Intent intent = new Intent();
intent.putExtra("phone",phone);
setResult(100,intent);
finish();
}
}
});
}
/**
* 设置一个内容适配器,主要用来显示ContactActivity界面的数据
*/
private class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return contactlists.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ItemHolder itemHolder;
if (convertView==null){
view=View.inflate(getApplicationContext(),R.layout.listview_contact_item,null);
itemHolder=new ItemHolder();
itemHolder.tv_name= (TextView) view.findViewById(R.id.tv_name);
itemHolder.tv_phone= (TextView) view.findViewById(R.id.tv_phone);
view.setTag(itemHolder);
}else {
view=convertView;
itemHolder= (ItemHolder) view.getTag();
}
//设置显示的数据
Person person = contactlists.get(position);
itemHolder.tv_name.setText(person.getName());
itemHolder.tv_phone.setText(person.getPhone());
return view;
}
//设置一个内部类,主要用来装两个组件
private class ItemHolder {
TextView tv_name;
TextView tv_phone;
}
}
} | java | 25 | 0.534757 | 105 | 30.968254 | 189 | starcoderdata |
def returns_in_sim_order_nb(value_iso: tp.Array2d,
group_lens: tp.Array1d,
init_cash_grouped: tp.Array1d,
call_seq: tp.Array2d) -> tp.Array2d:
"""Get portfolio return series in simulation order."""
check_group_lens(group_lens, value_iso.shape[1])
out = np.empty_like(value_iso)
from_col = 0
for group in range(len(group_lens)):
to_col = from_col + group_lens[group]
group_len = to_col - from_col
input_value = init_cash_grouped[group]
for j in range(value_iso.shape[0] * group_len):
i = j // group_len
col = from_col + call_seq[i, from_col + j % group_len]
output_value = value_iso[i, col]
out[i, col] = get_return_nb(input_value, output_value)
input_value = output_value
from_col = to_col
return out | python | 13 | 0.547855 | 66 | 42.333333 | 21 | inline |
#include<bits/stdc++.h>
using namespace std;
#define nn 100008
#define int long long
struct fs{
int x,y;
fs(int a=0,int b=0){
x=a,y=b;
}
void refresh(){
int d=__gcd(x,y);
x/=d,y/=d;
}
};
bool operator<(fs a,fs b){
return (a.x*b.y<a.y*b.x);
}
int n,ai[nn],bi[nn];
int sum[nn];vector<int> ap;
signed main(){
scanf("%lld",&n);
for(int i=1;i<=n;i++) scanf("%lld%lld",&ai[i],&bi[i]);
int base=0;
for(int i=1;i<=n;i++) if(bi[i]>ai[i]){
base+=bi[i]-ai[i];
ap.push_back(bi[i]);
}
else{
ap.push_back(ai[i]);
}
sort(ap.begin(),ap.end());
sum[0]=ap[0];for(int i=1;i<ap.size();i++) sum[i]=sum[i-1]+ap[i];
int l=1,r=n-1;int res=0;
while(l<=r){
int mid=(l+r)/2;
int ans=base;
for(int i=0;i<mid;i++) ans-=ap[i];
if(ans>=0)
res=mid,l=mid+1;
else r=mid-1;
}
fs ans=fs(0,1);
for(int i=1;i<=n;i++){
int ui;
if(bi[i]>ai[i]){
ui=base;-ai[i]+bi[i];
if(ap[res]>=bi[i]) ui-=sum[res]-bi[i];
else if(res) ui-=sum[res-1];
}
else{
ui=base-ai[i]+bi[i];
if(ap[res]>=ai[i]) ui-=sum[res]-ai[i];
else if(res) ui-=sum[res-1];
}
if(ui>=0) ans=max(ans,fs(ui,bi[i]));
}
ans.x=ans.x+ans.y*res;ans.y*=n;
ans.refresh();
cout<<ans.x<<" "<<ans.y;
return 0;
} | c++ | 16 | 0.524161 | 65 | 15.972222 | 72 | codenet |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_WHILE_TRANSFORMER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_WHILE_TRANSFORMER_H_
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/statusor.h"
namespace xla {
namespace gpu {
// Runs an analysis of the while loop instruction 'while_hlo' (and its
// associated sub-computations) to determine if it can be transformed into an
// equivalent "for" loop with the following "for" loop parameters:
//
// *) 'loop_start': loop induction variable starting value.
// *) 'loop_limit': loop induction variable limit value.
// *) 'loop_increment': loop induction variable per-iteration increment value.
//
// Returns an std::tuple = (loop_start, loop_limit, loop_increment) on success.
// The values in the returned tuple are values extracted from the 'while_hlo'
// operand (and its sub-computations) during analysis.
// Returns an error status on failure.
StatusOr<std::tuple<int64, int64, int64>> CanTransformWhileToFor(
const HloInstruction* while_hlo);
} // namespace gpu
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_WHILE_TRANSFORMER_H_ | c | 13 | 0.736786 | 80 | 42 | 44 | starcoderdata |
<?php
class M_team extends CI_Model{
private $table = 'tb_team';
public function get(){
return $this->db->get($this->table)->result();
}
public function get_where(){
return $this->db->get_where('tb_user',['email' => $this->session->userdata('email')])->row_array();
}
public function insert($data){
$this->db->insert($this->table,$data);
}
public function edit($where,$data){
$this->db->where($where);
$this->db->update($this->table,$data);
}
public function delete($where){
$this->db->delete($this->table,$where);
}
public function kodeTeam(){
// $this->db->select('RIGHT(tb_team.kode_team,5) as kode', FALSE);
// $this->db->order_by('kode_team','DESC');
// $this->db->limit(1);
// $query = $this->db->get($this->table);
// if ($query->num_rows() > 0) {
// $data = $query->row();
// $kode = intval($data->kode)+1;
// }
// else{
// $kode=1;
// }
// $kode_max = str_pad($kode,5,"0",STR_PAD_LEFT);
// $kode_fix = "TM" .$kode_max;
// return $kode_fix;
$this->db->select('RIGHT(tb_team.kode_team,5) as kode', FALSE);
$this->db->order_by('kode_team','DESC');
$this->db->limit(1);
$query = $this->db->get('tb_team');
if ($query->num_rows() > 0) {
$data = $query->row();
$kode = intval($data->kode)+1;
}
else{
$kode=1;
}
$kode_max = str_pad($kode,5,"0",STR_PAD_LEFT);
$kode_fix = "TM" .$kode_max;
return $kode_fix;
}
} | php | 16 | 0.56342 | 101 | 20.313433 | 67 | starcoderdata |
/**
* Title: ToDo Class
* Description: Controls all about ToDo view.
* Author:
* Date: 06/August/2021
*/
export default class ToDo {
/**
* Controls everything about this ToDo App.
*
* @param {HTMLLIElement} newToDo - The new ToDo text which will be added.
*/
constructor(newToDo) {
this.newToDo = newToDo;
this.todoId = Math.floor(Math.random() * (9999 - 1000) + 1000);
}
/**
* Initialization of the todo app.
*
* @return {Object[]} - Return the existing todo list if localstorage contains any previous todo list otherwise return an empty todo list.
*/
static init() {
if (!localStorage.getItem("todo")) {
// if localstorage has no todo then I'll set it a empty array.
localStorage.setItem("todo", JSON.stringify([]));
} else {
// if localstorage has already a todo then I just return it.
return JSON.parse(localStorage.getItem("todo"));
}
}
/**
* Render existing todo element.
*
* @param {HTMLUListElement} todoList - The parent element where the existing list element will be appended.
* @param {Object} todo - The every single todo object.
*/
static renderToDo(todoList, todo) {
// set the display flex if the todo list container has any todo.
if (window.getComputedStyle(todoList.parentNode).display !== "flex") {
todoList.parentNode.style.display = "flex";
}
// render the existing todo from localstorage.
todoList.innerHTML += `
<li data-todo="${JSON.stringify(todo).split('"').join("'")}">
<input type="checkbox" id="${todo.todoId}" />
<label for="${todo.todoId}">${todo.newToDo}
`;
}
/**
* Remove a todo from todo list.
*
* @param {Object} todo - The todo object which is attempt to removed.
*/
static removeToDo(todo) {
const existingToDo = JSON.parse(localStorage.getItem("todo"));
// take the all todo from localstorage except the given todo object as argument.
const updatedTodo = existingToDo.filter((el) => {
return JSON.stringify(el) !== JSON.stringify(todo);
});
// finally update the localstorage without the given todo object.
localStorage.setItem("todo", JSON.stringify(updatedTodo));
}
/**
* Manipulate a new ToDo element and render it.
*
* @param {HTMLUListElement} parentEl - The parent element where the manipulated element will be appended.
* @return {HTMLLIElement} - Return the manipulated list element.
*/
addToDo(parentEl) {
// set the display flex if the todo list container has any todo.
if (window.getComputedStyle(parentEl.parentNode).display !== "flex") {
parentEl.parentNode.style.display = "flex";
}
const list = document.createElement("li");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.type = "checkbox";
checkbox.id = this.todoId;
label.setAttribute("for", this.todoId);
label.textContent = this.newToDo;
list.append(checkbox, label);
parentEl.appendChild(list);
return list;
}
/**
* Update the browser localstorage with adding new ToDo.
*
* @param {Object} todo - The constructed ToDo Object for every single todo.
*/
updateStorage(todo) {
const existingToDo = JSON.parse(localStorage.getItem("todo"));
existingToDo.push(todo);
localStorage.setItem("todo", JSON.stringify(existingToDo));
}
} | javascript | 16 | 0.611365 | 142 | 34.701923 | 104 | starcoderdata |
import { minify } from 'html-minifier-terser';
import prettier from 'prettier';
import { join, dirname } from 'path';
import { rmSync, mkdirSync, writeFileSync, readdirSync, copyFileSync, statSync } from 'fs';
export class Builder {
constructor(output_dir, options = { debug: false }) {
this.options = options;
this.output_dir = output_dir;
rmSync(this.output_dir, { recursive: true, force: true });
mkdirSync(this.output_dir, { recursive: true });
}
async generateHtmlFile(filename, lang, func, ...args) {
this.addHtmlFile(filename, await func(lang, `/${filename}`, ...args));
}
addHtmlFile(filename, html) {
let content = html;
if(this.options.debug) {
content = prettier.format(content, { parser: 'html', tabWidth: 4 });
} else {
content = minify(html, {
minifyCSS: true,
minifyJS: true,
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeComments: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeTagWhitespace: true,
});
}
this.addFile(filename, content);
}
addFile(filename, content) {
mkdirSync(dirname(join(this.output_dir, filename)), { recursive: true });
writeFileSync(join(this.output_dir, filename), content, { encoding: 'utf-8' });
}
copyDirContent(directory, to) {
const output_dir = join(this.output_dir, to || '');
if(to) {
mkdirSync(output_dir, { recursive: true });
}
const files = readdirSync(directory);
for(const file of files) {
if(statSync(join(directory, file)).isDirectory()) {
this.copyDirContent(join(directory, file), join(to || '', file));
} else {
copyFileSync(join(directory, file), join(output_dir, file));
}
}
}
} | javascript | 17 | 0.56271 | 91 | 33.683333 | 60 | starcoderdata |
package org.atomnuke.lifecycle;
/**
* The resource life-cycle defines two methods that will be called once during
* the lifetime of the object bound to the life-cycle.
*
* The init method will always be called before the destroy method and ideally
* will be called when the object is being prepared for use. The init method
* will never be called after the destroy method.
*
* The destroy method may be called at any time and may be called before the
* init method. Once this method is called, it is assumed that the object will
* no longer be in use.
*
* @author zinic
*/
public interface ResourceLifeCycle extends Reclaimable {
/**
* Initializes this task.
*
* @param contextObject
* @throws InitializationException
*/
void init(T contextObject) throws InitializationException;
} | java | 6 | 0.731235 | 78 | 30.769231 | 26 | starcoderdata |
'use strict';
const colors = require('colors/safe');
const handleCommandStream = require('../command-stream-handler');
const Logger = require('../logger.js');
const User = require('../models/user.js');
function profile (api) {
const s_currentUser = User.getCurrent(api)
.map(({ name, email, preferredMFA }) => {
const has2FA = (preferredMFA != null && preferredMFA !== 'NONE') ? 'yes' : 'no';
const formattedName = name || colors.red.bold('[not specified]');
Logger.println('You\'re currently logged in as:');
Logger.println('Name: ', formattedName);
Logger.println('Email: ', email);
Logger.println('Two factor auth:', has2FA);
});
handleCommandStream(s_currentUser);
};
module.exports = profile; | javascript | 16 | 0.640644 | 86 | 31.28 | 25 | starcoderdata |
func (c *Collection) IsSupported(feature sgbucket.DataStoreFeature) bool {
switch feature {
case sgbucket.DataStoreFeatureSubdocOperations, sgbucket.DataStoreFeatureXattrs, sgbucket.DataStoreFeatureCrc32cMacroExpansion:
// Available on all supported server versions
return true
case sgbucket.DataStoreFeatureN1ql:
router, routerErr := c.Bucket().Internal().IORouter()
if routerErr != nil {
return false
}
return len(router.N1qlEps()) > 0
case sgbucket.DataStoreFeatureCreateDeletedWithXattr:
status, err := c.Bucket().Internal().CapabilityStatus(gocb.CapabilityCreateAsDeleted)
if err != nil {
return false
}
return status == gocb.CapabilityStatusSupported
default:
return false
}
} | go | 13 | 0.772664 | 128 | 31.636364 | 22 | inline |
package com.summon23.marketplacers.service.implement;
import com.summon23.marketplacers.dao.ProductVariantDao;
import com.summon23.marketplacers.entity.ProductVariant;
import com.summon23.marketplacers.service.ProductVariantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProductVariantServiceImpl implements ProductVariantService {
@Autowired
ProductVariantDao productVariantDao;
@Override
public void updateName(Long catalogId, String newName) {
productVariantDao.updateName(catalogId, newName);
}
} | java | 8 | 0.818466 | 73 | 30.95 | 20 | starcoderdata |
#ifndef GD_MCMC_DISTRIBUTIONS
#define GD_MCMC_DISTRIBUTIONS
#include
#include
#include
double
gamma_pdf(double, double, double, double);
double
gamma_sum_pdf(double, double, double, double, double, double, double = 0.999, std::string = "moments");
double
gaussian_pdf(double, double, double);
void
multinomial_1(std::mt19937 &, std::vector &, std::vector &);
void
dirichlet(std::mt19937 &, std::vector &, std::vector &);
#endif | c | 7 | 0.716327 | 103 | 20.347826 | 23 | starcoderdata |
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\App;
use Illuminate\Http\Request;
use App\Http\Controllers\PermissionsController;
use App\Helpers\ConnectionManager;
use App\Exchange_asset_list;
use App\Exchange_language_list;
use App\Exchange;
use App\Asset;
use Amranidev\Ajaxis\Ajaxis;
use App\Http\Traits\PermissionTrait;
use Session;
use DB;
use Redirect;
use URL;
/**
* Class Exchange_asset_listController.
*
*/
class Exchange_asset_listController extends PermissionsController
{
use PermissionTrait;
public function __construct()
{
parent::__construct();
$connectionStatus = ConnectionManager::setDbConfig('Exchange_asset_list');
if ($connectionStatus['type'] === "error") {
Session::flash('type', $connectionStatus['type']);
Session::flash('msg', $connectionStatus['message']);
return Redirect::back()->send();
}
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if($this->permissionDetails('Exchange_asset_list','access') || $this->permissionDetails('Exchange_language_list','access')) {
$permissions_asset = $this->getPermission("Exchange_asset_list");
$permissions_language = $this->getPermission("Exchange_language_list");
$exchange_asset_lists = Exchange_asset_list::distinct()->select('exchange_asset_list.*',
'identity_exchange.identity_name as exchange_name',
'identity_asset.identity_name as asset_name'
)
->join('exchange','exchange.exchange_id','=','exchange_asset_list.exchange_id')
->join('identity_exchange','exchange.identity_id','=','identity_exchange.identity_id')
->leftjoin('asset','asset.asset_id','exchange_asset_list.asset_id')
->leftjoin('identity_asset','identity_asset.identity_id','asset.identity_id')->get();
$exchange_language_lists = Exchange_language_list::distinct()->select('exchange_language_list.*',
'identity_exchange.identity_name as exchange_name',
'languages.language_name'
)
->join('exchange','exchange.exchange_id','=','exchange_language_list.exchange_id')
->join('identity_exchange','exchange.identity_id','=','identity_exchange.identity_id')
->leftjoin('languages','languages.language_id','exchange_language_list.language_id')->get();
return view('exchange_asset_list.index',compact('exchange_asset_lists','exchange_language_lists','permissions_asset','permissions_language'));
}
else {
return Redirect::back()->with('message', 'You are not authorized to use this functionality!');
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
if($this->permissionDetails('Exchange_asset_list','add')) {
$exchanges = Exchange::select('identity_exchange.identity_code as exchange_code','identity_exchange.identity_name as exchange_name','identity_exchange.identity_website as exchange_website','exchange.*')
->join('identity_exchange','identity_exchange.identity_id','=','exchange.identity_id')
->get();
$assets = Asset::select('identity_asset.identity_name as asset_name','asset.asset_id',
'identity_asset.identity_code as asset_code')
->join('identity_asset','identity_asset.identity_id','=','asset.identity_id')
->where('identity_asset.identity_id','!=',0)
->get();
return view('exchange_asset_list.create',compact('exchanges','assets'));
} else {
return Redirect::back()->with('message', 'You are not authorized to use this functionality!');
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if(isset($request->asset_id) && count($request->asset_id) !== 0){
Exchange_asset_list::
where('exchange_id',$request->exchange_id)
->whereNotIn('asset_id',$request->asset_id)
->delete();
foreach ($request->assets as $value) {
$asset_exist = Exchange_asset_list::
where('exchange_id',$request->exchange_id)
->where('asset_id',$value['asset_id'])
->get()->first();
if(count($asset_exist) === 0){
$exchange_asset_list = new Exchange_asset_list();
}else{
$exchange_asset_list = Exchange_asset_list::findOrfail($asset_exist->list_id);
}
$exchange_asset_list->exchange_id = $request->exchange_id;
$exchange_asset_list->asset_id = $value['asset_id'];
$exchange_asset_list->asset_code = $value['asset_code'];
$exchange_asset_list->priority = $value['priority'];
$exchange_asset_list->status = isset($value['status'])?1:0;
$exchange_asset_list->save();
}
}else{
Exchange_asset_list::
where('exchange_id',$request->exchange_id)
->delete();
}
Session::flash('type', 'success');
Session::flash('msg', 'Exchange Asset List Successfully Inserted');
if ($request->submitBtn === "Save") {
return redirect('exchange_asset_list/'. $exchange_asset_list->list_id . '/edit');
} else {
return redirect('exchange_asset_list');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
if($this->permissionDetails('Exchange_asset_list','delete')) {
$exchange_asset_list = Exchange_asset_list::findOrfail($id);
$exchange_asset_list->delete();
Session::flash('type', 'success');
Session::flash('msg', 'Exchange Asset List Successfully Deleted');
return redirect('exchange_asset_list');
} else {
return Redirect::back()->with('message', 'You are not authorized to use this functionality!');
}
}
public function getExchangeAsset(Request $request) {
if($request->exchange_id) {
$exchangeAssets = Exchange_asset_list::select('exchange_asset_list.*','identity_asset.identity_name as asset_name','identity_asset.identity_code as asset_code','exchange_asset_list.asset_code as new_asset_code')
->join('asset','exchange_asset_list.asset_id','=','asset.asset_id')
->join('identity_asset','identity_asset.identity_id','=','asset.identity_id')
->where('exchange_asset_list.exchange_id','=', $request->exchange_id)
->get();
}
echo json_encode($exchangeAssets);
}
} | php | 19 | 0.580856 | 223 | 38.219251 | 187 | starcoderdata |
# -*- coding: utf-8 -*-
"""
This is a simple example of dynamic DNN
"""
import random
import torch
from torch.autograd import Variable
# data type: CPU or GPU
# dtype = torch.FloatTensor
dtype = torch.cuda.FloatTensor
# N batch: size
# D_in: input size
# D_out: output size
# H: hidden size
N, D_in, H, D_out = 16, 1024, 256, 128
# create input and output data
x = Variable(torch.randn(N, D_in).type(dtype))
y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
class DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.hidden_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)
def forward(self, x):
h_relu = self.input_linear(x).clamp(min=0)
for _ in range(random.randint(0, 3)):
h_relu = self.hidden_linear(h_relu).clamp(min=0)
output = self.output_linear(h_relu)
return output
# create a model instance and send it to GPU
model = DynamicNet(D_in, H, D_out)
model.cuda()
# some training criterons
loss_fn = torch.nn.MSELoss(size_average=False)
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Training
for t in range(1000):
# forward
y_pred = model(x)
# loss
loss = loss_fn(y_pred, y)
if t % 100 == 99:
print(t+1, loss.data[0])
# backward and update
optimizer.zero_grad()
loss.backward()
optimizer.step() | python | 13 | 0.64127 | 68 | 24.836066 | 61 | starcoderdata |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Spi
{
public class ConsoleAndFileWriter : IDisposable
{
private readonly TextWriter ConsoleWriter;
private TextWriter FileWriter;
private readonly string Filename;
private readonly System.Text.Encoding encoding;
public ConsoleAndFileWriter(TextWriter ConsoleWriter, string Filename, Encoding encoding)
{
this.ConsoleWriter = ConsoleWriter;
this.Filename = Filename;
this.encoding = encoding;
}
public ConsoleAndFileWriter(TextWriter ConsoleWriter, string Filename)
: this(ConsoleWriter, Filename, Encoding.UTF8)
{
}
public void WriteException(Exception ex)
{
this.WriteLine(ex.Message);
this.WriteLine(ex.StackTrace);
if (ex.InnerException != null)
{
this.WriteLine("--- inner exception ---");
this.WriteLine(ex.InnerException.Message);
this.WriteLine(ex.InnerException.StackTrace);
this.WriteLine("--- inner exception ---");
}
}
public void WriteLine(string Format, params object[] args)
{
_internal_WriteLine(ConsoleWriter, Format, args);
if (String.IsNullOrEmpty(Filename))
{
return;
}
if (FileWriter == null)
{
lock (this)
{
if (FileWriter == null)
{
FileWriter = new StreamWriter(
path: Filename,
append: false,
encoding: this.encoding);
FileWriter = TextWriter.Synchronized(FileWriter);
}
}
}
_internal_WriteLine(FileWriter, Format, args);
}
public bool hasDataWritten()
{
return FileWriter != null;
}
public void Dispose()
{
if ( FileWriter != null )
{
FileWriter.Close();
}
}
///
/// This functions exists for the following problem:
/// If you pass no "args" (args==null) it would be a WriteLine(Format,null).
/// Then if the string (Format) you passed has "{" "}" in it, the call will mostly crash because of a bad c# format string.
///
/// <param name="writer">
/// <param name="Format">
/// <param name="args">
private void _internal_WriteLine(TextWriter writer, string Format, params object[] args)
{
if ( writer == null )
{
return;
}
if (args == null || args.Length == 0)
{
writer.WriteLine(Format);
}
else
{
writer.WriteLine(Format, args);
}
}
}
} | c# | 20 | 0.487092 | 131 | 30.831683 | 101 | starcoderdata |
import { gql } from "apollo-boost";
import client from "./client";
const cardsQuery = gql`
query getCards($deckId: ID!) {
cards(deckId: $deckId) {
prompt
target
promptExample
targetExample
}
}
`;
const cardsQueryWithProgress = gql`
query getCards($deckId: ID!) {
cards(deckId: $deckId) {
prompt
target
promptExample
targetExample
timeAdded
nextReview
intervalProgress
}
}
`;
const cardsQueryNextReview = gql`
query getCards($deckId: ID!) {
cards(deckId: $deckId) {
nextReview
}
}
`;
const cardIdsQuery = gql`
query getCards($deckId: ID!) {
cards(deckId: $deckId) {
prompt
_id
}
}
`;
const addCardMutation = gql`
mutation CreateNewCard($input: NewCardInput!) {
newCard(input: $input) {
prompt
target
promptExample
targetExample
}
}
`;
const updateCardMutation = gql`
mutation UpdateCard($id: ID!, $input: UpdateCardInput!) {
updateCard(id: $id, input: $input) {
prompt
target
promptExample
targetExample
}
}
`;
const removeCardMutation = gql`
mutation RemoveCard($id: ID!) {
removeCard(id: $id) {
_id
}
}
`;
async function addCard(variables) {
return await client.mutate({ mutation: addCardMutation, variables });
}
async function updateCard(variables) {
return await client.mutate({ mutation: updateCardMutation, variables });
}
async function removeCard(variables) {
return await client.mutate({ mutation: removeCardMutation, variables });
}
async function getCardId(prompt, deckId) {
var data = await client.query({
query: cardIdsQuery,
variables: { deckId },
fetchPolicy: "no-cache"
});
var cards = data.data.cards;
return cards.filter(card => card.prompt == prompt)[0]._id;
}
// helper func to update card in database
async function updateCardInDB(oldData, newData, deckId) {
var id = await getCardId(oldData.prompt, deckId);
var variables = {
input: {
prompt: newData.prompt,
target: newData.target,
promptExample: newData.promptExample,
targetExample: newData.targetExample
},
id
};
try {
return await updateCard(variables);
} catch (e) {
console.log(e);
}
}
async function updateCardProgress(data, deckId) {
var id = await getCardId(data.prompt, deckId);
var variables = {
input: {
nextReview: data.nextReview,
intervalProgress: data.newIntervalProgress
},
id
};
try {
return await updateCard(variables);
} catch (e) {
console.log(e);
}
}
export {
cardsQuery,
cardsQueryWithProgress,
cardsQueryNextReview,
getCardId,
addCard,
updateCard,
updateCardInDB,
updateCardProgress,
removeCard
}; | javascript | 11 | 0.644685 | 74 | 18.405594 | 143 | starcoderdata |
package ru.openet.nix.opennetclient;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
/**
* Created by Nix on 01.02.2018.
*/
@GlideModule
public final class MyGlideAppModule extends AppGlideModule {} | java | 4 | 0.80198 | 61 | 26.545455 | 11 | starcoderdata |
'use strict'
const bunyan = require('bunyan')
function reqSerializer (ctx = {}) {
return {
method: ctx.method,
path: ctx.path,
url: ctx.url,
headers: ctx.headers,
protocol: ctx.protocol,
ip: ctx.ip,
query: ctx.query
}
}
function resBodySerializer ({ status, code, message } = {}) {
const body = { status, message }
if (code) body.code = code
return body
}
function resSerializer (ctx = {}) {
return {
statusCode: ctx.status,
responseTime: ctx.responseTime,
type: ctx.type,
headers: (ctx.response || {}).headers,
body: resBodySerializer(ctx.body)
}
}
/**
* Return middleware that attachs logger to context and
* logs HTTP request/response.
*
* @param {Object} options={} - Optional configuration.
* @param {Object} options.logger - Logger instance of bunyan.
* @return {function} Koa middleware.
*/
function log (options = {}) {
const { logger = null } = options
if (typeof logger !== 'object' || logger === null)
throw new TypeError('Logger required')
return async (ctx, next) => {
const startTime = new Date()
ctx.log = logger.child({ reqId: ctx.reqId })
ctx.log.addSerializers({
req: reqSerializer,
res: resSerializer,
err: bunyan.stdSerializers.err
})
ctx.log.info(
{ req: ctx, event: 'request' },
`Request start for id: ${ctx.reqId}`
)
try {
await next()
} catch (err) {
ctx.log.error(
{ err, event: 'error' },
`Unhandled exception occured on the request: ${ctx.reqId}`
)
throw err
}
ctx.responseTime = new Date() - startTime
ctx.log.info(
{ req: ctx, res: ctx, event: 'response' },
`Request successfully completed for id: ${ctx.reqId}`
)
}
}
module.exports = log | javascript | 17 | 0.554369 | 74 | 24.75 | 80 | starcoderdata |
#include
#include
#include
#include
#include
#include
#include "io.h"
int conf_init(io_config* config)
{
unsigned cnt_bus = 0;
unsigned cnt_dev = 0;
config->num_busses = 0;
for (cnt_bus = 0; cnt_bus < MAX_BUSSES; cnt_bus++)
{
io_bus* current_bus = config->busses + cnt_bus;
current_bus->num_devices = 0;
for (cnt_dev = 0; cnt_dev < MAX_IO_DEVICES; cnt_dev++)
{
io_dev* current_dev = current_bus->devices + cnt_dev;
current_dev->dev_bus_data = NULL;
current_dev->dev_data = NULL;
current_dev->drv_handle = NULL;
}
current_bus->bus_data = NULL;
}
return EXIT_SUCCESS;
}
int conf_deinit(io_config* config)
{
unsigned cnt_bus = 0;
unsigned cnt_dev = 0;
config->num_busses = 0;
for (cnt_bus = 0; cnt_bus < MAX_BUSSES; cnt_bus++)
{
io_bus* current_bus = (config->busses + cnt_bus);
for (cnt_dev = 0; cnt_dev < MAX_IO_DEVICES; cnt_dev++)
{
io_dev* current_dev = current_bus->devices + cnt_dev;
if (NULL != current_bus->drv_handle
&& NULL != current_bus->drv_handle->discard_bus_dev_data)
{
current_bus->drv_handle->discard_bus_dev_data(
current_dev->dev_bus_data);
current_dev->dev_bus_data = NULL;
}
}
if (NULL != current_bus->drv_handle
&& NULL != current_bus->drv_handle->discard_bus_data)
{
current_bus->drv_handle->discard_bus_data(current_bus->bus_data);
current_bus->bus_data = NULL;
}
}
return EXIT_SUCCESS;
}
int io_init(io_config* config)
{
idx_t cnt_bus = 0;
idx_t cnt_dev = 0;
for (cnt_bus = 0; cnt_bus < config->num_busses; cnt_bus++)
{
io_bus* current_bus = config->busses + cnt_bus;
if (NULL != current_bus->drv_handle
&& NULL != current_bus->drv_handle->open)
{
current_bus->drv_handle->open(current_bus);
}
for (cnt_dev = 0; cnt_dev < current_bus->num_devices; cnt_dev++)
{
io_dev* current_dev = current_bus->devices + cnt_dev;
if (NULL != current_dev->drv_handle
&& NULL != current_dev->drv_handle->init)
{
current_dev->drv_handle->init(current_bus, current_dev);
}
}
}
return EXIT_SUCCESS;
}
int io_deinit(io_config* config)
{
idx_t cnt_bus = 0;
idx_t cnt_dev = 0;
for (cnt_bus = 0; cnt_bus < config->num_busses; cnt_bus++)
{
io_bus* current_bus = config->busses + cnt_bus;
for (cnt_dev = 0; cnt_dev < current_bus->num_devices; cnt_dev++)
{
io_dev* current_dev = current_bus->devices + cnt_dev;
if (NULL != current_dev->drv_handle
&& NULL != current_dev->drv_handle->deinit)
{
current_dev->drv_handle->deinit(current_bus, current_dev);
}
}
if (NULL != current_bus->drv_handle
&& NULL != current_bus->drv_handle->close)
{
current_bus->drv_handle->close(current_bus);
}
}
return EXIT_SUCCESS;
}
int perform_io(io_config* config, io_data* data, io_cmd cmd,
int (*cb_success)(io_data* data, char* buf, int buf_size),
int (*cb_error)(char* error_msg, char* buf, int buf_size), char* buf,
int buf_size)
{
int num_read = 0;
value_t value = data->value;
if (data->idx_bus == IDX_INVALID || data->idx_bus >= config->num_busses)
{
cb_error("Bus ID not existing.", buf, buf_size);
return EXIT_FAILURE;
}
if (data->idx_dev == IDX_INVALID
|| data->idx_dev >= (config->busses + data->idx_bus)->num_devices)
{
cb_error("Device ID not existing.", buf, buf_size);
return EXIT_FAILURE;
}
if (cmd != CMD_WRITE && cmd != CMD_READ)
{
cb_error("Illegal command.", buf, buf_size);
return EXIT_FAILURE;
}
if (cmd == CMD_WRITE)
{
if (data->idx_sub_dev != IDX_INVALID)
{
num_read = ((config->busses + data->idx_bus)->devices
+ data->idx_dev)->drv_handle->read(
(config->busses + data->idx_bus),
((config->busses + data->idx_bus)->devices + data->idx_dev),
&value, cb_error, buf, buf_size);
if (num_read <= 0)
{
cb_error("Could not read from device.", buf, buf_size);
return EXIT_FAILURE;
}
if (data->value)
{
value |= 1 << data->idx_sub_dev;
}
else
{
value &= ~(1 << data->idx_sub_dev);
}
}
if (((config->busses + data->idx_bus)->devices + data->idx_dev)->drv_handle->write(
(config->busses + data->idx_bus),
((config->busses + data->idx_bus)->devices + data->idx_dev),
&value, cb_error, buf, buf_size) > 0)
{
cb_success(data, buf, buf_size);
}
}
else
{
if (((config->busses + data->idx_bus)->devices + data->idx_dev)->drv_handle->read(
(config->busses + data->idx_bus),
((config->busses + data->idx_bus)->devices + data->idx_dev),
&data->value, cb_error, buf, buf_size) > 0)
{
if (data->idx_sub_dev != IDX_INVALID)
{
if (data->idx_sub_dev >= 0
&& data->idx_sub_dev < (sizeof(data->value) * 8))
{
data->value = (data->value >> data->idx_sub_dev) & 1;
}
else
{
cb_error("Invalid sub device-index given.", buf, buf_size);
}
}
cb_success(data, buf, buf_size);
}
}
return EXIT_SUCCESS;
} | c | 19 | 0.602174 | 85 | 23.959799 | 199 | starcoderdata |
import {
useState,
useCallback
} from 'haunted';
import { useHandleDrop } from './use-handle-drop';
export const useDroppedFiles = el => {
const [files, setFiles] = useState([]),
handleDrop = useCallback(event => setFiles(event.dataTransfer.files), [setFiles]);
useHandleDrop(el, handleDrop);
return files;
}; | javascript | 15 | 0.710692 | 84 | 25.5 | 12 | starcoderdata |
require("babel/register");
var Stex = require('stex');
module.exports = Stex.new(__dirname + "/..", function(stex) {
var router = stex.router;
var controllers = stex.controllers;
app.use(controllers.middlewares.rawBody);
router.post('/receive', controllers.receive);
}); | javascript | 12 | 0.691489 | 61 | 24.636364 | 11 | starcoderdata |
static const char *searchpath (lua_State *L, const char *name,
const char *path,
const char *sep,
const char *dirsep) {
luaL_Buffer buff;
char *pathname; /* path with name inserted */
char *endpathname; /* its end */
const char *filename;
/* separator is non-empty and appears in 'name'? */
if (*sep != '\0' && strchr(name, *sep) != NULL)
name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
luaL_buffinit(L, &buff);
/* add path to the buffer, replacing marks ('?') with the file name */
luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
luaL_addchar(&buff, '\0');
pathname = luaL_buffaddr(&buff); /* writable list of file names */
endpathname = pathname + luaL_bufflen(&buff) - 1;
while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
if (readable(filename)) /* does file exist and is readable? */
return lua_pushstring(L, filename); /* save and return name */
}
luaL_pushresult(&buff); /* push path to create error message */
pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */
return NULL; /* not found */
} | c | 11 | 0.576339 | 73 | 49.08 | 25 | inline |
#!/usr/bin/python
#
# Open shutter script for INDI Dome Scripting Gateway
#
# Arguments: none
# Exit code: 0 for success, 1 for failure
#
import sys
coordinates = open('/tmp/indi-status', 'r')
str = coordinates.readline()
coordinates.close()
str = str[0] + ' 1 ' + str[4:]
coordinates = open('/tmp/indi-status', 'w')
coordinates.truncate()
coordinates.write(str)
coordinates.close()
sys.exit(0) | python | 6 | 0.696742 | 53 | 18 | 21 | starcoderdata |
@Override
public boolean isCompatibleWith(TypeBinding targetType, Scope scope) {
ReferenceExpression copy = cachedResolvedCopy(targetType);
if (copy == null) {
return contextHasSyntaxError(); // in case of syntax error avoid secondary errors
} else if (copy.resolvedType != null && copy.resolvedType.isValidBinding() && copy.binding != null && copy.binding.isValidBinding()) {
return true;
} else {
boolean notPertinentToApplicability = targetType instanceof ParameterizedTypeBinding && !isPertinentToApplicability(targetType, null); // not mentioned in JLS (see prior art in LE.internalIsCompatibleWith()
return notPertinentToApplicability;
}
} | java | 12 | 0.765321 | 209 | 54.833333 | 12 | inline |
Eigen::MatrixXd TrajectoryGeneratorWaypoint::PolyQPGeneration(
const int d_order, // the order of derivative
const Eigen::MatrixXd &Path, // waypoints coordinates (3d)
const Eigen::MatrixXd &Vel, // boundary velocity
const Eigen::MatrixXd &Acc, // boundary acceleration
const Eigen::VectorXd &Time) // time allocation in each segment
{
// enforce initial and final velocity and accleration, for higher order derivatives, just assume them be 0;
int p_order = 2 * d_order - 1; // the order of polynomial
int p_num1d = p_order + 1; // the number of variables in each segment
int m = Time.size(); // the number of segments
MatrixXd PolyCoeff = MatrixXd::Zero(m, 3 * p_num1d); // position(x,y,z), so we need (3 * p_num1d) coefficients
VectorXd Px(p_num1d * m), Py(p_num1d * m), Pz(p_num1d * m);
/* Produce Mapping Matrix A to the entire trajectory, A is a mapping matrix that maps polynomial coefficients to derivatives. */
/* Produce the dereivatives in X, Y and Z axis directly. */
/* Produce the Minimum Snap cost function, the Hessian Matrix */
return PolyCoeff;
} | c++ | 8 | 0.577975 | 136 | 23.618182 | 55 | inline |
package example
import (
"beyondinfo.com/baselib/go/base_package.git/bfile"
"fmt"
)
func ExampleCopy() {
bfile.Mkdir("test")
bfile.Mkdir("test/a")
bfile.Mkdir("test/b")
bfile.SetContents("test/test.txt", "asd123")
bfile.Copy("test/test.txt", "test/test2.txt")
fmt.Println(bfile.GetContents("test/test2.txt"))
bfile.Copy("test", "test2")
sub, _ := bfile.DirSubs("test2")
bfile.Remove("test")
bfile.Remove("test2")
fmt.Println(sub)
// output:
// asd123
// [a b test.txt test2.txt]
}
func ExampleCopyFile() {
bfile.Mkdir("test")
bfile.Mkdir("test/a")
bfile.Mkdir("test/b")
bfile.SetContents("test/test.txt", "asd123")
bfile.CopyFile("test/test.txt", "test/test2.txt")
fmt.Println(bfile.GetContents("test/test2.txt"))
bfile.CopyFile("test", "test2")
sub, _ := bfile.DirSubs("test3")
bfile.Remove("test")
bfile.Remove("test2")
fmt.Println(sub)
// output:
// asd123
// []
}
func ExampleCopyDir() {
bfile.Mkdir("test")
bfile.Mkdir("test/a")
bfile.Mkdir("test/b")
bfile.SetContents("test/test.txt", "asd123")
bfile.CopyDir("test/test.txt", "test/test2.txt")
fmt.Println(bfile.GetContents("test/test2.txt"))
bfile.CopyDir("test", "test2")
sub, _ := bfile.DirSubs("test3")
bfile.Remove("test")
bfile.Remove("test2")
fmt.Println(sub)
// output:
// asd123
// [a b test.txt test2.txt]
} | go | 9 | 0.665428 | 51 | 18.492754 | 69 | starcoderdata |
@Override
public void setGenes(final Double[] list) throws NeuralNetworkError {
// copy the new genes
super.setGenes(list);
calculateCost();
} | java | 6 | 0.718954 | 70 | 16.111111 | 9 | inline |
@ReactMethod
public void hello() {
// Display a pop-up alert
AlertDialog.Builder builder = new AlertDialog.Builder(getCurrentActivity());
builder.setMessage("Hi, everybody!")
.setTitle("Foo")
.setPositiveButton("OK", null);
AlertDialog dialog = builder.create();
dialog.show();
} | java | 9 | 0.666667 | 80 | 30.6 | 10 | inline |
#!/usr/bin/env python
import os
import os.path as op
import sys
import argparse
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description = 'translate mo17 cds sequences'
)
parser.add_argument(
'fi', help = 'input file (.tsv)'
)
parser.add_argument(
'fo', help = 'output file (.tsv)'
)
parser.add_argument(
'fs', help = 'output fasta file (.fasta)'
)
args = parser.parse_args()
fi, fo, fs = args.fi, args.fo, args.fs
fhi, fho, fhs = open(fi, "r"), open(fo, "w"), open(fs, "w")
rcds = []
for line in fhi:
line = line.strip("\n")
ary = line.split("\t")
if len(ary) != 4:
print("not 4 fields:\n$line")
sys.exit(1)
tid, srd, bseq, mseq = ary
dna = Seq(bseq)
if srd == '-': dna = dna.reverse_complement()
n1 = dna.translate().count("*")
bseq = dna.translate(to_stop = True)
bpro = str(bseq)
dna = Seq(mseq)
if srd == '-': dna = dna.reverse_complement()
n2 = dna.translate().count("*")
mseq = dna.translate(to_stop = True)
mpro = str(mseq)
fho.write("%s\t%d\t%d\t%s\t%s\n" % (tid, n1, n2, bpro, mpro))
rcd = SeqRecord(mseq, id = tid, description = '')
rcds.append(rcd)
SeqIO.write(rcds, fhs, "fasta") | python | 12 | 0.524324 | 69 | 28.6 | 50 | starcoderdata |
export const getDateByParam = selectedDate => {
if (!selectedDate) {
return new Date();
}
return new Date(...selectedDate.split('.'));
};
export const currentTasks = data => data.tasks.filter(t => new Date(t.dateAt).toString() === getDateByParam().toString());
const APPID = "6b19232ef146adecb4a1f928c4c9812a";
const getWeatherUrl = (lat, lon) => "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + APPID;
export const fetchWeather = ($http, lat, lon) => $http.get(getWeatherUrl(lat, lon));
export const getWeather = ($http) => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
resolve({ lat, lon })
}, error => reject(console.log(`code:${error.code} message: ${error.message}`)),
{ timeout: 30000, enableHighAccuracy: true, maximumAge: 75000 });
})
.then(({ lat, lon }) => fetchWeather($http, lat, lon))
.catch(console.error)
};
/**
const icon = res.data.weather[0].icon;
const temp = Math.round(res.data.main.temp - 275) + " °C";
const img = document.querySelector("#img-weather");
angular.element(img).attr("src", "http://openweathermap.org/img/w/" + icon + '.png');
this.update({ temp });
*/ | javascript | 26 | 0.651584 | 132 | 32.175 | 40 | starcoderdata |
package com.kdl.rf.modules.schedule.constant;
/**
* Create by Kalvin on 2019/8/17
*/
public class JobConstant {
// 任务状态
public final static int JOB_STATUS_RUNNING = 0;
public final static int JOB_STATUS_PAUSE = 1;
public final static int JOB_STATUS_FINISH = 2;
public final static int JOB_STATUS_FAIL = 3;
public final static String JOB_MAP_KEY = "JOB_KEY";
} | java | 6 | 0.709402 | 77 | 26.529412 | 17 | starcoderdata |
TEST_F(LevelDbFactoryTest, GetOrCreateDb) {
// Create a new instance.
Status status;
std::unique_ptr<Db> db;
bool called;
db_factory_.GetOrCreateDb(
db_path_.SubPath("db"), DbFactory::OnDbNotFound::CREATE,
callback::Capture(callback::SetWhenCalled(&called), &status, &db));
RunLoopUntilIdle();
ASSERT_TRUE(called);
EXPECT_EQ(Status::OK, status);
EXPECT_NE(nullptr, db);
// Write one key-value pair.
RunInCoroutine([&](coroutine::CoroutineHandler* handler) {
std::unique_ptr<Db::Batch> batch;
EXPECT_EQ(Status::OK, db->StartBatch(handler, &batch));
EXPECT_EQ(Status::OK, batch->Put(handler, "key", "value"));
EXPECT_EQ(Status::OK, batch->Execute(handler));
});
// Close the previous instance and open it again.
db.reset();
db_factory_.GetOrCreateDb(
db_path_.SubPath("db"), DbFactory::OnDbNotFound::RETURN,
callback::Capture(callback::SetWhenCalled(&called), &status, &db));
RunLoopUntilIdle();
ASSERT_TRUE(called);
EXPECT_EQ(Status::OK, status);
EXPECT_NE(nullptr, db);
// Expect to find the previously written key-value pair.
RunInCoroutine([&](coroutine::CoroutineHandler* handler) {
std::string value;
EXPECT_EQ(Status::OK, db->Get(handler, "key", &value));
EXPECT_EQ("value", value);
});
} | c++ | 14 | 0.673643 | 73 | 34.861111 | 36 | inline |
// **********************************************************************
//
//
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
//
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/CartesianLoader.java,v $
// $RCSfile: CartesianLoader.java,v $
// $Revision: 1.2 $
// $Date: 2006/02/24 20:43:27 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.proj;
import java.awt.geom.Point2D;
import java.util.Properties;
import com.bbn.openmap.util.Debug;
import com.bbn.openmap.util.PropUtils;
/**
* ProjectionLoader to add the Cartesian projection to an OpenMap application.
* There are some properties you can set for the Cartesian projection, namely
* limits on where it can pan. If you don't set the limits, the projection will
* just keep going. You can use the anchorX and anchorY settings to hold the map
* against some of the limits.
*
*
* topLimit=top coordinate limit
* bottomLimit=bottom coordinate limit
* leftLimit=left side coordinate limit
* rightLimit=right side coordinate limit
* anchorX=horizontal coordinate to set on projection before checking limits
* anchorY=vertical coordinate to set on projection before checking limits
*
*
* @see BasicProjectionLoader
*/
public class CartesianLoader extends BasicProjectionLoader implements
ProjectionLoader {
public final static String TopLimitProperty = "topLimit";
public final static String BottomLimitProperty = "bottomLimit";
public final static String RightLimitProperty = "rightLimit";
public final static String LeftLimitProperty = "leftLimit";
public final static String AnchorXProperty = "anchorX";
public final static String AnchorYProperty = "anchorY";
/**
* The coordinate limit of the left side of the projection. If the left side
* of the map projection would show coordinates more left than this value,
* the center of the map will be changed so that this value is on the edge.
*/
protected double leftLimit = Double.NEGATIVE_INFINITY;
/**
* The coordinate limit of the right side of the projection. If the right
* side of the map projection would show coordinates more right than this
* value, the center of the map will be changed so that this value is on the
* edge.
*/
protected double rightLimit = Double.POSITIVE_INFINITY;
/**
* The coordinate limit of the top side of the projection. If the top side
* of the map projection would show coordinates higher than this value, the
* center of the map will be changed so that this value is on the edge.
*/
protected double topLimit = Double.POSITIVE_INFINITY;
/**
* The coordinate limit of the bottom side of the projection. If the bottom
* side of the map projection would show coordinates lower than this value,
* the center of the map will be changed so that this value is on the edge.
*/
protected double bottomLimit = Double.NEGATIVE_INFINITY;
/**
* A point that can be used for force the projection against the limits. Is
* only used if the limits are set to be something other than infinity.
*/
protected Point2D limitAnchorPoint;
public CartesianLoader() {
super(Cartesian.class,
Cartesian.CartesianName,
"Cartesian projection for displaying projected data.");
}
/**
* Create the projection with the given parameters.
*
* @throws exception if a parameter is missing or invalid.
*/
public Projection create(Properties props) throws ProjectionException {
try {
Point2D center = (Point2D) props.get(ProjectionFactory.CENTER);
float scale = PropUtils.floatFromProperties(props,
ProjectionFactory.SCALE,
10000000);
int height = PropUtils.intFromProperties(props,
ProjectionFactory.HEIGHT,
100);
int width = PropUtils.intFromProperties(props,
ProjectionFactory.WIDTH,
100);
Cartesian proj = new Cartesian(center, scale, width, height);
proj.setLimits(topLimit,
bottomLimit,
leftLimit,
rightLimit,
limitAnchorPoint);
return proj;
} catch (Exception e) {
if (Debug.debugging("proj")) {
Debug.output("CartesianLoader: problem creating Cartesian projection "
+ e.getMessage());
}
}
throw new ProjectionException("CartesianLoader: problem creating Cartesian projection");
}
public void setProperties(String prefix, Properties props) {
super.setProperties(prefix, props);
prefix = PropUtils.getScopedPropertyPrefix(prefix);
leftLimit = PropUtils.doubleFromProperties(props, prefix
+ LeftLimitProperty, Double.NEGATIVE_INFINITY);
rightLimit = PropUtils.doubleFromProperties(props, prefix
+ RightLimitProperty, Double.POSITIVE_INFINITY);
topLimit = PropUtils.doubleFromProperties(props, prefix
+ TopLimitProperty, Double.POSITIVE_INFINITY);
bottomLimit = PropUtils.doubleFromProperties(props, prefix
+ BottomLimitProperty, Double.NEGATIVE_INFINITY);
double x = PropUtils.doubleFromProperties(props, prefix
+ AnchorXProperty, Double.POSITIVE_INFINITY);
double y = PropUtils.doubleFromProperties(props, prefix
+ AnchorYProperty, Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY && y != Double.POSITIVE_INFINITY) {
limitAnchorPoint = new Point2D.Double(x, y);
}
}
public Properties getProperties(Properties props) {
props = super.getProperties(props);
String prefix = PropUtils.getScopedPropertyPrefix(this);
String x = "";
String y = "";
String top = "";
String bottom = "";
String left = "";
String right = "";
if (leftLimit != Double.NEGATIVE_INFINITY) {
left = Double.toString(leftLimit);
}
if (topLimit != Double.POSITIVE_INFINITY) {
top = Double.toString(topLimit);
}
if (rightLimit != Double.POSITIVE_INFINITY) {
right = Double.toString(rightLimit);
}
if (bottomLimit != Double.NEGATIVE_INFINITY) {
bottom = Double.toString(bottomLimit);
}
props.put(prefix + TopLimitProperty, top);
props.put(prefix + BottomLimitProperty, bottom);
props.put(prefix + RightLimitProperty, right);
props.put(prefix + LeftLimitProperty, left);
if (limitAnchorPoint != null) {
x = Double.toString(limitAnchorPoint.getX());
y = Double.toString(limitAnchorPoint.getY());
}
props.put(prefix + AnchorXProperty, x);
props.put(prefix + AnchorYProperty, y);
return props;
}
public Properties getPropertyInfo(Properties props) {
props = super.getPropertyInfo(props);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
LeftLimitProperty,
"Left Limit",
"Coordinate limit for the left side of the map.",
null);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
RightLimitProperty,
"Right Limit",
"Coordinate limit for the right side of the map.",
null);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
TopLimitProperty,
"Top Limit",
"Coordinate limit for the top of the map.",
null);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
BottomLimitProperty,
"Bottom Limit",
"Coordinate limit for the bottom of the map.",
null);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
AnchorXProperty,
"Anchor X",
"Horizontal Coordinate for anchor point, used to hold projection against limits.",
null);
PropUtils.setI18NPropertyInfo(i18n,
props,
CartesianLoader.class,
AnchorYProperty,
"Anchor Y",
"Horizontal Coordinate for anchor point, used to hold projection against limits.",
null);
props.put(initPropertiesProperty, PrettyNameProperty + " "
+ DescriptionProperty + " " + TopLimitProperty + " "
+ BottomLimitProperty + " " + RightLimitProperty + " "
+ LeftLimitProperty + " " + AnchorXProperty + " "
+ AnchorYProperty);
return props;
}
public double getBottomLimit() {
return bottomLimit;
}
public void setBottomLimit(double bottomLimit) {
this.bottomLimit = bottomLimit;
}
public double getLeftLimit() {
return leftLimit;
}
public void setLeftLimit(double leftLimit) {
this.leftLimit = leftLimit;
}
public Point2D getLimitAnchorPoint() {
return limitAnchorPoint;
}
public void setLimitAnchorPoint(Point2D limitAnchorPoint) {
this.limitAnchorPoint = limitAnchorPoint;
}
public double getRightLimit() {
return rightLimit;
}
public void setRightLimit(double rightLimit) {
this.rightLimit = rightLimit;
}
public double getTopLimit() {
return topLimit;
}
public void setTopLimit(double topLimit) {
this.topLimit = topLimit;
}
} | java | 23 | 0.605368 | 98 | 34.584775 | 289 | starcoderdata |
# Distributed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE, distributed with this software.
#
# Author:
# Copyright (c) 2020, European X-Ray Free-Electron Laser Facility GmbH.
# All rights reserved.
__version__ = '1.0.0'
from functools import wraps
from .context import (
MapContext, SerialContext, ThreadContext, ProcessContext) # noqa
from .functor import ( # noqa
SequenceFunctor, NdarrayFunctor, DataArrayFunctor, ExtraDataFunctor)
_default_context = None
def get_default_context():
"""Get default map context.
By default, this returns a ProcessContext.
Args:
None
Returns:
(MapContext) Default map context.
"""
global _default_context
if _default_context is None:
_default_context = ProcessContext()
return _default_context
def set_default_context(ctx_or_method, *args, **kwargs):
"""Set default map context.
Args:
ctx_or_method (MapContext or str): New map context either
directly or the parallelization method as a string, which
may either be 'serial', 'threads' or 'processes'
Any further arguments are passed to the created map context
object if specified as a string.
Returns:
None
"""
if isinstance(ctx_or_method, str):
if ctx_or_method == 'serial':
ctx_cls = SerialContext
elif ctx_or_method == 'threads':
ctx_cls = ThreadContext
elif ctx_or_method == 'processes':
ctx_cls = ProcessContext
else:
raise ValueError('invalid map method')
ctx = ctx_cls(*args, **kwargs)
else:
ctx = ctx_or_method
global _default_context
_default_context = ctx
@wraps(MapContext.array)
def array(*args, **kwargs):
return get_default_context().array(*args, **kwargs)
@wraps(MapContext.array_like)
def array_like(*args, **kwargs):
return get_default_context().array_like(*args, **kwargs)
@wraps(MapContext.array_per_worker)
def array_per_worker(*args, **kwargs):
return get_default_context().array_per_worker(*args, **kwargs)
@wraps(MapContext.map)
def map(*args, **kwargs):
return get_default_context().map(*args, **kwargs) | python | 12 | 0.652116 | 74 | 23.652174 | 92 | starcoderdata |
<?php
namespace Razorpay\Magento\Model\ResourceModel\OrderLink;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* Initialize resource collection
*
* @return void
*/
public function _construct()
{
$this->_init('Razorpay\Magento\Model\OrderLink', 'Razorpay\Magento\Model\ResourceModel\OrderLink');
}
} | php | 10 | 0.736111 | 107 | 25.578947 | 19 | starcoderdata |
const sql = require("./db.js");
// Implementación del modelo User con notación clase ES6
class Role {
constructor(role) {
this.name = role.name;
};
static create(newRole, result) {
sql.query("INSERT INTO roles SET ?", newRole, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created role: ", { id: res.insertId, ...newRole });
result(null, { id: res.insertId, ...newRole });
});
}
static getAll(name, result) { //result es un callback
let query = "SELECT * FROM roles";
if (name) {
query += ` WHERE name LIKE '%${name}%'`;
}
sql.query(query, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err); // llamada a callback
return;
}
console.log("role: ", res);
result(null, res);
});
}
static findById(id, result) {
sql.query(`SELECT * FROM roles WHERE id = ${id}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("found role: ", res);
result(null, res);
});
}
// static updateById(id, user, result) {
// sql.query(
// "UPDATE users SET username = ?, description = ?, published = ? WHERE id = ?",
// [user.username, user.email, user.password, id],
// (err, res) => {
// if (err) {
// console.log("error: ", err);
// result(null, err);
// return;
// }
// console.log("updated user: ", { id: id, ...user });
// result(null, { id: id, ...user });
// }
// );
// };
// static remove(id, result) {
// sql.query("DELETE FROM users WHERE id = ?", id, (err, res) => {
// if (err) {
// console.log("error: ", err);
// result(null, err);
// return;
// }
// console.log("deleted user with id: ", id);
// result(null, res);
// });
// }
// static removeAll(result) {
// sql.query("DELETE FROM users", (err, res) => {
// if (err) {
// console.log("error: ", err);
// result(null, err);
// return;
// }
// console.log(`deleted ${res.affectedRows} users`);
// result(null, res);
// });
// }
}
module.exports = Role; | javascript | 13 | 0.452237 | 89 | 25.656566 | 99 | starcoderdata |
#include "fmod_output.hpp"
#include "media_stream.hpp"
namespace carpi::spotify::media {
LOGGER_IMPL(FmodSystem);
FMOD_RESULT pcm_read_data(FMOD_SOUND *sound, void *data, unsigned int datalen) {
FmodSystem *user_data = nullptr;
FMOD_Sound_GetUserData(sound, (void **) &user_data);
auto *read_buffer = (uint8_t *) data;
auto num_read = std::size_t{0};
while (num_read < datalen) {
const auto read = user_data->_active_stream->read(read_buffer + num_read, datalen - num_read);
if (!read) {
return FMOD_ERR_FILE_EOF;
}
num_read += read;
}
return FMOD_OK;
}
FmodSystem::FmodSystem() : _system{nullptr} {
auto status = FMOD::System_Create(&_system);
if (status != FMOD_OK) {
log_error(status, "FMOD::System_Create");
throw std::runtime_error{"Error creating FMOD system"};
}
status = _system->init(64, FMOD_INIT_NORMAL, nullptr);
if (status != FMOD_OK) {
log_error(status, "FMOD::System::init");
throw std::runtime_error{"Error initializing FMOD"};
}
_system_updater = std::thread{[=]() { main_loop(); }};
}
FmodSystem::~FmodSystem() {
_is_running = false;
if (_system_updater.joinable()) {
_system_updater.join();
}
}
void FmodSystem::log_error(FMOD_RESULT result, const std::string &prefix) {
log->error("Error calling FMOD function '{}': {} (error={})", prefix, FMOD_ErrorString(result), result);
}
void FmodSystem::print_version() {
uint32_t version = 0;
_system->getVersion(&version);
const auto minor = version & 0xFFu;
const auto major = (version >> 8u) & 0xFFu;
const auto product = (version >> 16u) & 0xFFFFu;
log->info("FMOD version: {}.{}.{}", product, major, minor);
}
void FmodSystem::open_sound(std::shared_ptr stream, std::size_t pcm_offset, bool paused) {
if (!stream->read_supported()) {
log->warn("Stream is not readable");
throw std::runtime_error{"Stream is not readable"};
}
_active_stream = stream;
if (_active_channel != nullptr) {
_active_channel->stop();
_active_channel = nullptr;
}
if (_active_sound != nullptr) {
_active_sound->release();
_active_sound = nullptr;
}
FMOD_CREATESOUNDEXINFO sound_info{};
sound_info.cbsize = sizeof sound_info;
sound_info.format = FMOD_SOUND_FORMAT::FMOD_SOUND_FORMAT_PCM16;
sound_info.userdata = this;
sound_info.pcmreadcallback = pcm_read_data;
sound_info.defaultfrequency = 44100;
sound_info.decodebuffersize = 44100;
sound_info.numchannels = 2;
sound_info.initialseekposition = static_cast<unsigned int>(pcm_offset);
sound_info.initialseekpostype = FMOD_TIMEUNIT_PCM;
sound_info.length = static_cast<unsigned int>(-1);
auto error = _system->createStream("file1", FMOD_OPENUSER | FMOD_LOOP_OFF | FMOD_CREATESTREAM, &sound_info, &_active_sound);
if (error != FMOD_OK) {
log_error(error, "FMOD::System::createSound");
throw std::runtime_error{"Error creating sound"};
}
error = _system->playSound(_active_sound, nullptr, paused, &_active_channel);
if (error != FMOD_OK) {
log_error(error, "FMOD::System::playSound");
throw std::runtime_error{"Error playing sound"};
}
}
void FmodSystem::main_loop() {
while(_is_running) {
_system->update();
if(_active_channel && _media_callback) {
auto is_playing = false;
_active_channel->isPlaying(&is_playing);
if(is_playing) {
uint32_t position = 0;
_active_channel->getPosition(&position, FMOD_TIMEUNIT_MS);
_media_callback(position);
}
}
std::this_thread::sleep_for(std::chrono::milliseconds{20});
}
}
void FmodSystem::paused(bool paused) {
if(_active_channel) {
_active_channel->setPaused(paused);
}
}
} | c++ | 15 | 0.555428 | 132 | 32.713178 | 129 | starcoderdata |
package errors
import (
"bytes"
"fmt"
"strings"
)
// ErrorType 代表错误类型。
type ErrorType string
// 错误类型常量。
const (
// ERROR_TYPE_DOWNLOADER 代表下载器错误。
ERROR_TYPE_DOWNLOADER ErrorType = "downloader error"
// ERROR_TYPE_ANALYZER 代表分析器错误。
ERROR_TYPE_ANALYZER ErrorType = "analyzer error"
// ERROR_TYPE_PIPELINE 代表条目处理管道错误。
ERROR_TYPE_PIPELINE ErrorType = "pipeline error"
// ERROR_TYPE_SCHEDULER 代表调度器错误。
ERROR_TYPE_SCHEDULER ErrorType = "scheduler error"
)
// CrawlerError 代表爬虫错误的接口类型。
type CrawlerError interface {
// Type 用于获得错误的类型。
Type() ErrorType
// Error 用于获得错误提示信息。
Error() string
}
// myCrawlerError 代表爬虫错误的实现类型。
type myCrawlerError struct {
// errType 代表错误的类型。
errType ErrorType
// errMsg 代表错误的提示信息。
errMsg string
// fullErrMsg 代表完整的错误提示信息。
fullErrMsg string
}
// NewCrawlerError 用于创建一个新的爬虫错误值。
func NewCrawlerError(errType ErrorType, errMsg string) CrawlerError {
return &myCrawlerError{
errType: errType,
errMsg: strings.TrimSpace(errMsg),
}
}
// NewCrawlerErrorBy 用于根据给定的错误值创建一个新的爬虫错误值。
func NewCrawlerErrorBy(errType ErrorType, err error) CrawlerError {
return NewCrawlerError(errType, err.Error())
}
func (ce *myCrawlerError) Type() ErrorType {
return ce.errType
}
func (ce *myCrawlerError) Error() string {
if ce.fullErrMsg == "" {
ce.genFullErrMsg()
}
return ce.fullErrMsg
}
// genFullErrMsg 用于生成错误提示信息,并给相应的字段赋值。
func (ce *myCrawlerError) genFullErrMsg() {
var buffer bytes.Buffer
buffer.WriteString("crawler error: ")
if ce.errType != "" {
buffer.WriteString(string(ce.errType))
buffer.WriteString(": ")
}
buffer.WriteString(ce.errMsg)
ce.fullErrMsg = fmt.Sprintf("%s", buffer.String())
return
}
// IllegalParameterError 代表非法的参数的错误类型。
type IllegalParameterError struct {
msg string
}
// NewIllegalParameterError 会创建一个IllegalParameterError类型的实例。
func NewIllegalParameterError(errMsg string) IllegalParameterError {
return IllegalParameterError{
msg: fmt.Sprintf("illegal parameter: %s",
strings.TrimSpace(errMsg)),
}
}
func (ipe IllegalParameterError) Error() string {
return ipe.msg
} | go | 13 | 0.751453 | 69 | 20.957447 | 94 | starcoderdata |
angular
.module("umbraco.resources")
.factory("mediaExtendedResource", function($q, $http) {
return {
copy: function(params) {
var dfrd = $.Deferred();
$http({
url: "backoffice/MediaCopy/MediaCopy/PostCopy",
method: "POST",
params: params
})
.success(function(result) { dfrd.resolve(result); })
.error(function(result) { dfrd.resolve(result); });
return dfrd.promise();
}
};
}); | javascript | 17 | 0.497101 | 91 | 33.5 | 20 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.