code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
package com.bolo1.mobilesafe1.service;
import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telecom.Call;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
import com.bolo1.mobilesafe1.db.dao.BlackNumberDao;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by 菠萝 on 2017/8/29.
*/
public class BlackNumberService extends Service {
private InnerSmsReceiver innerSmsReceiver;
private TelephonyManager tm;
private BlackNumberDao dao;
private String tag = "BlackNumberService";
private MyPhoneStateListener myPhoneStateListener;
private MyObserver observer;
@Override
public void onCreate() {
dao = BlackNumberDao.getInstance(getApplicationContext());
IntentFilter filter = new IntentFilter();
filter.setPriority(1000);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
innerSmsReceiver = new InnerSmsReceiver();
registerReceiver(innerSmsReceiver, filter);
tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
myPhoneStateListener = new MyPhoneStateListener();
tm.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
super.onCreate();
}
private class MyPhoneStateListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_RINGING:
//响铃时的电话状态
Log.d(tag, "来电人--------" + incomingNumber);
if (incomingNumber != null || incomingNumber.isEmpty()) {
endCall(incomingNumber);
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
private void endCall(String phone) {
int mode = dao.getMode(phone);
Log.d(tag, "拦截短信手机联系人的mode" + mode + "以及联系人:phone--" + phone);
if (mode == 2 || mode == 3) {
try {
Class clazz = Class.forName("android.os.ServiceManager");
Method method = clazz.getMethod("getService", String.class);
IBinder ibinder = (IBinder) method.invoke(null, new Object[]{TELEPHONY_SERVICE});
ITelephony iTelephony = ITelephony.Stub.asInterface(ibinder);
iTelephony.endCall();
} catch (Exception e) {
e.printStackTrace();
}
observer = new MyObserver(new Handler(), phone);
getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, observer);
}
}
private class MyObserver extends ContentObserver {
private String phone;
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public MyObserver(Handler handler, String phone) {
super(handler);
this.phone = phone;
}
@Override
public void onChange(boolean selfChange) {
delCallLog(phone);
super.onChange(selfChange);
}
}
private void delCallLog(String number) {
ContentResolver resolver = this.getContentResolver();
//通话记录的uri,可以通过CallLog.Calls.CONTENT_URI得到,"number"记录通话记录的号码
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Cursor cursor = resolver.
query(CallLog.Calls.CONTENT_URI, new String[]{"_id"}, "number=?", new String[]{number}, null);
if (cursor.moveToFirst()) {
String id = cursor.getString(0);
resolver.delete(CallLog.Calls.CONTENT_URI, "_id=?", new String[]{id});
}
}
private class InnerSmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Object[] objects = (Object[]) intent.getExtras().get("pdus");
for (Object obs : objects) {
SmsMessage smg = SmsMessage.createFromPdu((byte[]) obs);
String address = smg.getOriginatingAddress();
String body = smg.getMessageBody();
int mode = dao.getMode(address);
Log.d(tag, "拦截短信手机联系人的mode" + mode + "以及联系人--" + address);
if (mode == 1 || mode == 3) {
Log.d(tag, "onReceive:== 拦截了短信,--------------------------------");
this.abortBroadcast();
}
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (innerSmsReceiver != null) {
unregisterReceiver(innerSmsReceiver);
}
if (myPhoneStateListener != null) {
tm.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
if (observer != null) {
getContentResolver().unregisterContentObserver(observer);
}
super.onDestroy();
}
} | java | 16 | 0.62113 | 127 | 35.360656 | 183 | starcoderdata |
# Copyright [2021] [ <contacto {at} danigarcia.org>]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import yaml
from testrunner.util.log_setup import logger
from testrunner.factory.webdrivers.webdriverfactory_interface import WebDriverFactoryInterface
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
class ChromeDriverFactory(WebDriverFactoryInterface):
"""
Internal class that generates a ChromeDriver instance
"""
def __init__(self, driver_configuration: dict = None, config_file_path: str = None):
self.driver_configuration = driver_configuration
self.config_file_path = config_file_path
if config_file_path is not None and os.path.isfile(config_file_path):
self._load_default_options_(config_file_path)
def _load_default_options_(self, config_file_path: str = None):
if config_file_path is None:
cfg_path = os.path.join("config", "webdrivers", "default.yaml")
else:
cfg_path = config_file_path
try:
with open(cfg_path, 'rt') as fd:
self.driver_configuration = yaml.safe_load(fd.read())
if self.driver_configuration['driver']['type'] != "ChromeDriver":
raise Exception(__class__.__name__ + ": The provided configuration is not compatible with ChromeDriver")
except Exception as e:
logger.exception("Error loading chrome default configuration")
raise e
def _create_webdriver_options_(self):
try:
chrome_options = webdriver.ChromeOptions()
# Get chromedriver path
if not os.path.isfile(self.driver_configuration['driver']['executable_path']):
chrome_options.driver_executable_path = ChromeDriverManager().install()
else:
chrome_options.driver_executable_path = self.driver_configuration['driver']['executable_path']
# Browser binary, if provided
options = self.driver_configuration['options']
if os.path.isfile(options['binary_path']):
chrome_options.binary_location = options['binary_path']
# Arguments
if options['arguments'] is not None:
for key in options['arguments']:
if options['arguments'][key] == "":
chrome_options.add_argument(key)
else:
chrome_options.add_argument(key + "=" + options['arguments'][key])
# Experimental options
if options['experimental_options'] is not None:
for key in options['experimental_options']:
if options['experimental_options'][key] == "":
chrome_options.add_experimental_option(key, "")
else:
chrome_options.add_experimental_option(key, options['experimental_options'][key])
return chrome_options
except Exception as e:
logger.exception("Error creating Chrome options")
raise e
def create_instance(self):
"""
Creates a ChromeDriver instance by loading configuration parameters provided in constructor
:return: A configured ChromeDriver instance
"""
chrome_options = self._create_webdriver_options_()
try:
driver = webdriver.Chrome(executable_path=chrome_options.driver_executable_path,
chrome_options=chrome_options,
service_args=["--verbose"])
return driver
except WebDriverException as e:
logger.exception(__class__.__name__ + ": Error initializing ChromeWebDriver")
raise e | python | 21 | 0.611198 | 120 | 39.897196 | 107 | starcoderdata |
odoo.define('test_website_slides_full.tour.slide.certification.member', function (require) {
"use strict";
var tour = require('web_tour.tour');
/**
* The purpose of this tour is to check the whole certification flow:
*
* -> student (= demo user) checks 'on payment' course content
* -> clicks on "buy course"
* -> is redirected to webshop on the product page
* -> buys the course
* -> fails 3 times, exhausting his attempts
* -> is removed to the members of the course
* -> buys the course again
* -> succeeds the certification
* -> has the course marked as completed
* -> has the certification in his user profile
*
*/
var initTourSteps = [{
content: 'eLearning: go to certification course',
trigger: 'a:contains("DIY Furniture")'
}, {
content: 'eLearning: does not have access to certification',
trigger: '.o_wslides_course_main',
run: function () {
// check that user doesn't have access to course content
if ($('.o_wslides_slides_list_slide .o_wslides_js_slides_list_slide_link').length === 0) {
$('.o_wslides_course_main').addClass('empty-content-success');
}
}
}, {
content: 'eLearning: previous step check',
trigger: '.o_wslides_course_main.empty-content-success',
run: function () {} // check that previous step succeeded
}];
var buyCertificationSteps = [{
content: 'eLearning: try to buy course',
trigger: 'a:contains("Add to Cart")'
}, {
content: 'eCommerce: Process Checkout',
trigger: 'a:contains("Process Checkout")'
}, {
content: 'eCommerce: select Test payment acquirer',
trigger: '.o_payment_acquirer_select:contains("Test")'
}, {
content: 'eCommerce: add card number',
trigger: 'input[name="cc_number"]',
run: 'text 4242424242424242'
}, {
content: 'eCommerce: add card holder name',
trigger: 'input[name="cc_holder_name"]',
run: 'text
}, {
content: 'eCommerce: add card expiry date',
trigger: 'input[name="cc_expiry"]',
run: 'text 11 / 50'
}, {
content: 'eCommerce: add card cvc',
trigger: 'input[name="cvc"]',
run: 'text 999'
}, {
content: 'eCommerce: pay',
trigger: '#o_payment_form_pay'
}, {
content: 'eCommerce: check that the payment is successful',
trigger: '.oe_website_sale_tx_status:contains("Your payment has been successfully processed")',
run: function () {}
}, {
content: 'eCommerce: go back to e-learning home page',
trigger: '.nav-link:contains("Courses")'
}, {
content: 'eLearning: go into bought course',
trigger: 'a:contains("DIY Furniture")'
}, {
content: 'eLearning: user should be enrolled',
trigger: '.o_wslides_js_course_join:contains("You\'re enrolled")',
run: function () {}
}, {
content: 'eLearning: start course',
trigger: '.o_wslides_js_slides_list_slide_link'
}];
var failCertificationSteps = [{
content: 'eLearning: start certification',
trigger: 'a:contains("Start Certification")'
}, { // Question: What type of wood is the best for furniture?
content: 'Survey: selecting answer "Fir"',
trigger: 'div.js_question-wrapper:contains("What type of wood is the best for furniture") select',
run: 'text Fir',
}, { // Question: Select all the furniture shown in the video
content: 'Survey: ticking answer "Table"',
trigger: 'div.js_question-wrapper:contains("Select all the furniture shown in the video") label:contains("Table") input'
}, {
content: 'Survey: ticking answer "Bed"',
trigger: 'div.js_question-wrapper:contains("Select all the furniture shown in the video") label:contains("Bed") input'
}, {
content: 'Survey: submitting the certification with wrong answers',
trigger: 'button:contains("Submit Survey")'
}];
var retrySteps = [{
content: 'Survey: retry certification',
trigger: 'a:contains("Retry")'
}];
var succeedCertificationSteps = [{
content: 'eLearning: start certification',
trigger: 'a:contains("Start Certification")'
}, { // Question: What type of wood is the best for furniture?
content: 'Survey: selecting answer "Oak"',
trigger: 'div.js_question-wrapper:contains("What type of wood is the best for furniture") select',
run: 'text Oak',
}, { // Question: Select all the furniture shown in the video
content: 'Survey: ticking answer "Chair"',
trigger: 'div.js_question-wrapper:contains("Select all the furniture shown in the video") label:contains("Chair") input'
}, {
content: 'Survey: ticking answer "Shelve"',
trigger: 'div.js_question-wrapper:contains("Select all the furniture shown in the video") label:contains("Shelve") input'
}, {
content: 'Survey: ticking answer "Desk"',
trigger: 'div.js_question-wrapper:contains("Select all the furniture shown in the video") label:contains("Desk") input'
}, {
content: 'Survey: submitting the certification with correct answers',
trigger: 'button:contains("Submit Survey")'
}];
var certificationCompletionSteps = [{
content: 'Survey: check certification successful',
trigger: 'div:contains("Congratulations, you have passed the test")',
run: function () {}
}, {
content: 'Survey: back to course home page',
trigger: 'a:contains("Go back to course")'
}, {
content: 'eLearning: back to e-learning home page',
trigger: '.nav-link:contains("Courses")'
}, {
content: 'eLearning: course should be completed',
trigger: '.o_wslides_course_card:contains("DIY Furniture") .badge-pill:contains("Completed")',
run: function () {}
}];
var profileSteps = [{
content: 'eLearning: access user profile',
trigger: '.o_wslides_home_aside_loggedin a:contains("View")'
}, {
content: 'eLearning: check that the user profile certifications include the new certification',
trigger: '.o_wprofile_slides_course_card_body:contains("Furniture Creation Certification")',
run: function () {}
}];
tour.register('certification_member', {
url: '/slides',
test: true
}, [].concat(
initTourSteps,
buyCertificationSteps,
failCertificationSteps,
retrySteps,
failCertificationSteps,
retrySteps,
failCertificationSteps,
[{trigger: 'a:contains("Go back to course")'}],
buyCertificationSteps,
succeedCertificationSteps,
certificationCompletionSteps,
profileSteps
)
);
}); | javascript | 21 | 0.666404 | 125 | 35.28 | 175 | starcoderdata |
#include
#include
using namespace std;
int N,D,Opc;
double F,x,a,b,auxa,auxb,I,Func;
//Varables universales(por el momento)
void Biseccion();
void PuntoMedio();
void Div_a();
void Div_b();
void ReglaFalsa();
void PuntoMedioRF();
double f_a(double &A);
double f_b(double &B);
void Div_aRF();
void Div_bRF();
int main()
{
cout<<"METODOS PARA ENCONTRAR RAICES"<<endl<<endl;
cout<<"Por cual metodo quisiera encontrar la raices?"<<endl<<endl;
cout<<"1.- Biseccion"<<endl;
cout<<"2.- Regla Falsa ";
cin>>Opc; cout<<endl;
if(Opc==1)
{
Biseccion();
}
if(Opc==2)
{
ReglaFalsa();
}
system("pause");
return 1;
}
void Biseccion()
{
cout<<"Ingrese el intervalo de la funcion."<<endl;
cout<<"Ingrese el valor de (a): "; cin>>a;
cout<<"Ingrese el valor de (b): "; cin>>b; cout<<endl;
PuntoMedio();
}
void PuntoMedio()
{
x=(a+b)/2;
F=(pow(x,2))-2;
cout<<"\n Punto Medio"<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl<<endl;
if(F==0)
{
cout<<"Raiz Encontrada!! "<<endl;
cout<<"El valor de la funcion evaluada en X= "<<x<<" es: f(X)= "<<F<<endl;
cout<<"La Raiz es X = "<<x<<endl;
}
else
{
cout<<"Raiz no encontrada!! "<<endl;
cout<<"El valor de la funcion evaluada en X= "<<x<<" es: f(X)= "<<F<<endl<<endl;
cout<<"Cuantas iteraciones quiere hacer?"<<endl;
cout<<"Ingrese el numero de iteraciones a realizar: "; cin>>I; cout<<endl;
cout<<"Por cual lado desea empezar a dividir el intervalo? :"<<endl;
cout<<"1.- Lado (a)"<<endl;
cout<<"2.- Lado (b) ";
cin>>D; cout<<endl;
if(D==1)
{
for(int i=0;i<I;i++)
{
Div_a();
}
cout<<"Iteracion "<<I<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl;
cout<<"\n El valor de la funcion evaluada en "<<x<<" es: f(X)= "<<F<<endl<<endl;
}
if(D==2)
{
for(int j=0;j<I;j++)
{
Div_b();
}
cout<<"Iteracion "<<I<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl;
cout<<"\n El valor de la funcion evaluada en "<<x<<" es: f(X)= "<<F<<endl<<endl;
}
}
}
void Div_a()
{
a=(a+b)/2;
x=(a+b)/2;
F=(pow(x,2))-2;
}
void Div_b()
{
b=(a+b)/2;
x=(a+b)/2;
F=(pow(x,2))-2;
}
void ReglaFalsa()
{
cout<<"Ingrese el intervalo de la funcion."<<endl;
cout<<"Ingrese el valor de (a): ";cin>>a;
cout<<"Ingrese el valor de (b): ";cin>>b; cout<<endl;
PuntoMedioRF();
}
void PuntoMedioRF()
{
x=(b-a)/((f_b(b))-(f_a(a)));
x=x*(f_a(a));
x=a-x;
F=(pow(x,2))-2;
cout<<"\n Punto Medio"<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl<<endl;
if(F==0)
{
cout<<"Raiz Encontrada!! "<<endl;
cout<<"El valor de la funcion evaluada en X= "<<x<<" es: f(X)= "<<F<<endl;
cout<<"La Raiz es X = "<<x<<endl;
}
else
{
cout<<"Raiz no encontrada!! "<<endl;
cout<<"El valor de la funcion evaluada en X= "<<x<<" es: f(X)= "<<F<<endl<<endl;
cout<<"Cuantas iteraciones quiere hacer?"<<endl;
cout<<"Ingrese el numero de iteraciones a realizar: "; cin>>I; cout<<endl;
cout<<"Por cual lado desea empezar a dividir el intervalo? :"<<endl;
cout<<"1.- Lado (a)"<<endl;
cout<<"2.- Lado (b) ";
cin>>D; cout<<endl;
if(D==1)
{
for(int i=0;i<I;i++)
{
Div_aRF();
}
cout<<"Iteracion "<<I<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl;
cout<<"\n El valor de la funcion evaluada en "<<x<<" es: f(X)= "<<F<<endl;
}
if(D==2)
{
for(int j=0;j<I;j++)
{
Div_bRF();
}
cout<<"Iteracion "<<I<<endl;
cout<<"Valor de (a)= "<<a<<endl;
cout<<"Valor de (b)= "<<b<<endl;
cout<<"Valor de (x)= "<<x<<endl;
cout<<"\n El valor de la funcion evaluada en "<<x<<" es: f(X)= "<<F<<endl;
}
}
}
double f_a(double &A)
{
Func=(pow(A,2)) - 2;
return Func;
}
double f_b(double &B)
{
Func=(pow(B,2)) - 2;
return Func;
}
void Div_aRF()
{
auxa=a;
a=(b-auxa)/((f_b(b))-(f_a(auxa)));
a=a*(f_a(auxa));
a=auxa-a;
///////////////////////
x=(b-a)/(f_b(b)-f_a(a));
x=x*(f_a(a));
x=a-x;
F=(pow(x,2))-2;
}
void Div_bRF()
{
auxb=b;
b=(auxb-a)/(f_b(auxb)-f_a(a));
b=b*(f_a(a));
b=a-b;
///////////////////////
x=(b-a)/(f_b(b)-f_a(a));
x=x*(f_a(a));
x=a-x;
F=(pow(x,2))-2;
} | c++ | 16 | 0.418839 | 97 | 24.995327 | 214 | starcoderdata |
// Adafruit compatible touchscreen wrapper
// June 2017 by ChrisMicro
#include "TouchScreen_F7_Discovery.h"
#include
#include "stm32_ub_touch_480x272.h"
uint8_t UB_I2C3_ReadByte(uint8_t addressI2cDevice, uint8_t registerId)
{
uint8_t result;
addressI2cDevice = addressI2cDevice >> 1;
Wire.beginTransmission( addressI2cDevice );
Wire.write( registerId );
uint8_t error;
error = Wire.endTransmission();
Wire.requestFrom( addressI2cDevice, (uint8_t) 1 , (uint8_t) true );
while ( Wire.available() < 1 );
result = Wire.read() ;
return result;
}
void TouchScreen::Touch_Read()
{
if (!isInitialized)
{
Wire.setSDA(PH8);
Wire.setSCL(PH7);
Wire.begin();
UB_Touch_Init();
isInitialized=true;
}
UB_Touch_Read();
}
TSPoint::TSPoint(void) {
x = y = z = 0;
}
TSPoint::TSPoint(int16_t x0, int16_t y0, int16_t z0)
{
x = x0;
y = y0;
z = z0;
}
bool TSPoint::operator==(TSPoint p1)
{
return ((p1.x == x) && (p1.y == y) && (p1.z == z));
}
bool TSPoint::operator!=(TSPoint p1)
{
return ((p1.x != x) || (p1.y != y) || (p1.z != z));
}
TSPoint TouchScreen::getPoint(void)
{
TSPoint p;
Touch_Read();
p.x = Touch_Data.xp;
p.y = Touch_Data.yp;
p.z = P_Touch_GetContacts() * 500;
return p;
}
TouchScreen::TouchScreen(uint8_t xp, uint8_t yp, uint8_t xm, uint8_t ym, uint16_t rxplate = 0)
{
isInitialized = false;
}
TouchScreen::TouchScreen()
{
isInitialized = false;
}
int TouchScreen::readTouchX(void)
{
Touch_Read();
return Touch_Data.xp;
}
int TouchScreen::readTouchY(void)
{
Touch_Read();
return Touch_Data.yp;
}
uint16_t TouchScreen::pressure(void)
{
Touch_Read();
return P_Touch_GetContacts() * 500;
} | c++ | 10 | 0.637749 | 94 | 15.247619 | 105 | starcoderdata |
public double getDistanceFrom(int x, int y) {
int diffX = (int) Math.abs(getX() - x);
int diffY = (int) Math.abs(getY() - y);
// Similar to above, with different sources though.
double xs = Math.pow(diffX, 2);
double ys = Math.pow(diffY, 2);
return Math.sqrt(xs + ys);
} | java | 11 | 0.639576 | 53 | 34.5 | 8 | inline |
@Override
public void onClick(View v) {
if (getApplicationContext() != null) {
// Report "Stop Service" button click events to Firebase Analytics.
FirebaseAnalyticsEvents.getInstance().reportStopServiceButtonClickEvent(
getApplicationContext());
}
RobotService.stopService(MainActivity.this);
resetGUIState(false);
} | java | 10 | 0.540254 | 92 | 46.3 | 10 | inline |
LOCAL tOptionValue*
optionLoadNested(char const* pzTxt, char const* pzName, size_t nameLen)
{
tOptionValue* pRes;
tArgList* pAL;
/*
* Make sure we have some data and we have space to put what we find.
*/
if (pzTxt == NULL) {
errno = EINVAL;
return NULL;
}
while (isspace( (int)*pzTxt )) pzTxt++;
if (*pzTxt == NUL) {
errno = ENOENT;
return NULL;
}
pRes = AGALOC( sizeof(*pRes) + nameLen + 1, "nested args" );
if (pRes == NULL) {
errno = ENOMEM;
return NULL;
}
pRes->valType = OPARG_TYPE_HIERARCHY;
pRes->pzName = (char*)(pRes + 1);
memcpy( pRes->pzName, pzName, nameLen );
pRes->pzName[ nameLen ] = NUL;
pAL = AGALOC( sizeof(*pAL), "nested arg list" );
if (pAL == NULL) {
AGFREE( pRes );
return NULL;
}
pRes->v.nestVal = pAL;
pAL->useCt = 0;
pAL->allocCt = MIN_ARG_ALLOC_CT;
/*
* Scan until we hit a NUL.
*/
do {
while (isspace( (int)*pzTxt )) pzTxt++;
if (isalpha( (int)*pzTxt )) {
pzTxt = scanNameEntry( pzTxt, pRes );
}
else switch (*pzTxt) {
case NUL: goto scan_done;
case '<': pzTxt = scanXmlEntry( pzTxt, pRes );
if (*pzTxt == ',') pzTxt++; break;
case '#': pzTxt = strchr( pzTxt, '\n' ); break;
default: goto woops;
}
} while (pzTxt != NULL); scan_done:;
pAL = pRes->v.nestVal;
if (pAL->useCt != 0) {
sortNestedList( pAL );
return pRes;
}
woops:
AGFREE( pRes->v.nestVal );
AGFREE( pRes );
return NULL;
} | c | 15 | 0.507831 | 74 | 24.553846 | 65 | inline |
package com.base.data.remote;
import com.base.data.local.preference.PreferencesHelper;
import com.base.data.models.User;
import java.io.File;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
/**
* Created by Phong on 11/9/2016.
*/
public class DataManager {
private RemoteApiService mRemoteApiService;
private PreferencesHelper mPreferencesHelper;
public DataManager(RemoteApiService remoteApiService, PreferencesHelper preferencesHelper) {
this.mRemoteApiService = remoteApiService;
this.mPreferencesHelper = preferencesHelper;
}
public Observable login(String email, String password, String android_push_key) {
return mRemoteApiService.login(email, password, android_push_key);
}
public Observable register(String full_name, String email, String password, String android_push_key, File file) {
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
return mRemoteApiService.register(full_name, email, password, android_push_key, multipartBody);
}
} | java | 12 | 0.762519 | 123 | 32.794872 | 39 | starcoderdata |
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.award.contacts;
import org.kuali.kra.award.AwardForm;
import org.kuali.kra.award.home.ContactRole;
import org.kuali.kra.award.home.ContactType;
import java.util.List;
/**
* This class provides support for the Award Contacts Project Personnel panel
*/
public class AwardSponsorContactsBean extends AwardContactsBean {
private static final long serialVersionUID = -5443573805950047573L;
public AwardSponsorContactsBean(AwardForm awardForm) {
super(awardForm);
}
public AwardSponsorContact addSponsorContact() {
boolean success = new AwardSponsorContactAddRuleImpl().processAddAwardSponsorContactBusinessRules(getAward(), getSponsorContact());
if(success){
AwardSponsorContact contact = getSponsorContact();
getAward().add(contact);
init();
return contact;
}
return null;
}
public AwardSponsorContact getSponsorContact() {
return (AwardSponsorContact) newAwardContact;
}
public void deleteSponsorContact(int lineToDelete) {
List awardSponsorContacts = getSponsorContacts();
if(awardSponsorContacts.size() > lineToDelete) {
awardSponsorContacts.remove(lineToDelete);
}
}
/**
* This method finds the count of AwardContacts in the "Sponsor Contacts" category
* @return The list; may be empty
*/
public List getSponsorContacts() {
return getAward().getSponsorContacts();
}
/**
* This method finds the count of AwardContacts in the "Unit Contacts" category
* @return The count; may be 0
*/
public int getSponsorContactsCount() {
return getSponsorContacts().size();
}
@Override
protected AwardContact createNewContact() {
return new AwardSponsorContact();
}
@Override
protected Class<? extends ContactRole> getContactRoleType() {
return ContactType.class;
}
} | java | 11 | 0.695964 | 139 | 31.329268 | 82 | starcoderdata |
public void Update()
{
//Debug.Log("enemyCount = " + enemyCount);
if (enemyCount <= 0)
{
levelCompleteUI.SetActive(true);
gameOver = true;
}
if (Input.GetKeyUp(KeyCode.Escape))
{
if (!gameOver)
{
if (pausedState == false)
OnPauseClick(true);
else
OnPauseClick(false);
}
else
{
SceneManager.LoadScene(0);
}
}
} | c# | 14 | 0.387097 | 50 | 22.291667 | 24 | inline |
package IntList;
import static org.junit.Assert.*;
import org.junit.Test;
public class SetToZeroIfMaxFELTest {
@Test
public void testZeroOutFELMaxes1() {
IntList L = IntList.of(1, 22, 15);
IntListExercises.setToZeroIfMaxFEL(L);
assertEquals("0 -> 0 -> 15", L.toString());
}
@Test
public void testZeroOutFELMaxes2() {
IntList L = IntList.of(55, 22, 45, 44, 5);
IntListExercises.setToZeroIfMaxFEL(L);
assertEquals("0 -> 22 -> 45 -> 0 -> 0", L.toString());
}
@Test
public void testZeroOutFELMaxes3() {
IntList L = IntList.of(5, 535, 35, 11, 10, 0);
IntListExercises.setToZeroIfMaxFEL(L);
assertEquals("0 -> 0 -> 35 -> 0 -> 10 -> 0", L.toString());
}
} | java | 10 | 0.593176 | 67 | 26.214286 | 28 | starcoderdata |
#include "higanbana/graphics/common/gpu_group.hpp"
namespace higanbana
{
namespace backend
{
void GpuGroupChild::setParent(GpuGroup *device)
{
m_parentDevice = device->state();
}
GpuGroup GpuGroupChild::device()
{
return GpuGroup(m_parentDevice.lock());
}
}
} | c++ | 12 | 0.652318 | 51 | 17.9375 | 16 | starcoderdata |
'use strict';
const ARLexer = require('../ARLexer');
class RLinkLexer extends ARLexer {
static apply(text) {
return text.replace(/\[(.*?)][ ]?\(.*?\)/gi, match => {
const text = match.slice(1, match.indexOf(']'));
const link = match.slice(match.indexOf('(') + 1, -1);
return RLinkLexer.getMarkup(text, link);
});
}
/**
*
* @param text
* @param link
* @return {string}
*/
static getMarkup(text, link) {
// we'll catch both mailto: and here
// and scramble them so that they can't be as easily found by scrapers
if (link.match(/^(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)$/i))
link = RLinkLexer.scrambleEmail(link);
// if the text is exactly an email address, scramble it too
if (text.match(/^(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)$/i))
text = RLinkLexer.scrambleEmail(text);
return `<a href="${link}">${text}
}
/**
* Input: an email address, e.g. "
*
* Output: the email address as a mailto link, with each character
* of the address encoded as either a decimal or hex entity, in
* the hopes of foiling most address harvesting spam bots. E.g.:
*
* <a href="mailto:foo@e
* xample.com">foo
* @example.com
*
* Based on a filter by posted to the BBEdit-Talk
* mailing list:
* @param email {string}
* @return {string}
*/
static scrambleEmail(email) {
if (!email.includes('mailto:'))
email = 'mailto:' + email;
let final = '';
for (let char of email) {
// encode @, the original author insists
if (char === '@')
final += RLinkLexer._encode(char);
else if (char === ':') // leave ':' alone (to spot mailto: later)
final += char;
else
final += RLinkLexer._encode(char);
}
return final;
}
static _encode(char) {
// roughly 10% raw, 45% hex, 45% dec
let chance = Math.random();
if (chance > .9)
return char;
else if (chance < .45)
return '&#' + char.charCodeAt(0) + ';';
else
return '&#x' + char.charCodeAt(0).toString(16) + ';';
}
}
module.exports = RLinkLexer; | javascript | 18 | 0.500957 | 85 | 31.6625 | 80 | starcoderdata |
#include "Role.hpp"
void Role::unmarshal(const QJsonObject &obj)
{
// clazy:excludeall=qt4-qstring-from-array
m_id = obj["id"].toString().toULongLong();
m_name = obj["name"].toString();
m_permissions = obj["permissions"].toString();
m_color = obj["color"].toInteger();
m_position = obj["position"].toInteger();
m_hoisted = obj["hoist"].toBool();
m_managed = obj["managed"].toBool();
m_mentionable = obj["mentionable"].toBool();
if (!obj["tags"].isUndefined()) {
const auto &k{ obj["tags"].toObject() };
std::optional t1;
std::optional t2;
if (!k["bot_id"].isUndefined()) {
t1 = k["bot_id"].toString().toULongLong();
}
if (!k["integration_id"].isUndefined()) {
t2 = k["bot_id"].toString().toULongLong();
}
m_tags.emplace(Tags(t1, t2));
}
}
snowflake Role::id() const
{
return m_id;
}
const QString &Role::name() const
{
return m_name;
}
const QString &Role::permissions() const
{
return m_permissions;
}
bool Role::hoisted() const
{
return m_hoisted;
}
bool Role::managed() const
{
return m_managed;
}
bool Role::mentionable() const
{
return m_mentionable;
}
std::optional Role::getTags() const
{
return m_tags;
} | c++ | 16 | 0.576557 | 55 | 21.016129 | 62 | starcoderdata |
def get_cluster_controller_services(host_names, print_to_screen=False,
print_json_str=False):
""" Fetches the state of nodes and resources from the cluster
resource manager and calculate the state of the services
making up the cluster.
returns: json string
"""
services = _get_cluster_controller_services(host_names)
# Build Json Data
services_data = []
for service in services.list:
if print_to_screen:
print(" ")
print("servicename: %s" % service.name)
print("status : %s" % service.state)
instances_data = []
for instance in service.instances:
if print_to_screen:
print("\thostname: %s" % instance.host_name)
print("\tactivity: %s" % instance.activity)
print("\tstate : %s" % instance.state)
print("\treason : %s" % instance.reason)
print(" ")
instances_data += ([{'hostname': instance.host_name,
'activity': instance.activity,
'state': instance.state,
'reason': instance.reason}])
services_data += ([{'servicename': service.name,
'state': service.state,
'instances': instances_data}])
if print_json_str:
print(json.dumps(services_data))
return json.dumps(services_data) | python | 15 | 0.518787 | 70 | 34.302326 | 43 | inline |
public void GenerateFieldCtorCode(ILGenerator il, FieldBuilder fb) {
il.Emit(OpCodes.Ldarg_0);
foreach (var arg in Args)
DefaultValueAttribute.PushObject(il, arg);
var method = Type.GetMethod(MethodName, BindingFlags.Public | BindingFlags.Static); // todo: find with args
Debug.Assert(method != null);
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Stfld, fb);
/* il example
IL_0000: ldarg.0
IL_0001: call valuetype [mscorlib]System.Guid [mscorlib]System.Guid::NewGuid()
IL_0006: stfld valuetype [mscorlib]System.Guid ArtZilla.Config.Tests.Class1::_guid
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: nop
IL_0012: ret
*/
} | c# | 13 | 0.694102 | 110 | 33.761905 | 21 | inline |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from text_office.models import STATUS
from celery import task
from text_office.models import SMS
logger = logging.getLogger(__name__)
@task(bind=True, max_retries=3, default_retry_delay=30)
def send_sms(self, sms_id):
sms = SMS.objects.get(pk=sms_id)
logger.debug('Starting celery task send_sms with id: %s', sms_id)
try:
sms.sms_message().send()
except Exception as e:
logger.warning(
'Sending sms failed. Retrying...',
extra={'sms_id': sms_id}, exc_info=True
)
raise self.retry(exc=e)
logger.debug(u'Celery task send_sms id %s successful', sms_id)
return sms_id
@task()
def send_sms_callback(sms_id):
sms = SMS.objects.get(pk=sms_id)
sms.status = STATUS.sent
sms.save(update_fields=['status'])
@task()
def send_sms_errback(task_id, exc, traceback, sms_id):
sms = SMS.objects.get(pk=sms_id)
sms.status = STATUS.failed
sms.save(update_fields=['status']) | python | 14 | 0.655424 | 69 | 25.756098 | 41 | starcoderdata |
#include
#include
#include
#include "MyBinarySearch.h"
/* C source for the native binary search mehtod */
/* Summer 2004 */
int bs(jint *, jint, int, int, int);
/* Recursive binary search function */
JNIEXPORT jint JNICALL Java_MyBinarySearch_binsearch
(JNIEnv *env, jobject object, jintArray buf, jint target){
jsize len;
jint *myCopy;
int right, left, idx;
jint result;
jboolean *is_copy = 0;
len = (*env)->GetArrayLength(env, buf);
myCopy = (jint *) (*env)->GetIntArrayElements(env, buf, is_copy);
if (myCopy == NULL){
printf("Cannot obtain array from JVM\n");
exit(0);
}
right = (int) len - 1;
left = 0;
idx = left / 2;
result = bs(myCopy, target, left, idx, right);
return result;
}
/*---------------------------------------------------------------*/
int bs(jint *buf, jint target, int left , int idx, int right){
/* Recursive binary search function */
/* Parent: JNI entry point */
/* Subroutines: bs() */
if (right == left){
/* Single-element list */
return right;
}
if (buf[idx] == target){
/* Right on the split point */
return idx;
}
if (buf[idx] > target){
/* Left sublist */
right = idx;
idx = left + ((right - left) / 2);
return bs(buf, target, left, idx, right);
}
if (buf[idx] < target){
/* Right sublist */
left = idx;
idx = idx + ((right-idx)/ 2);
return bs(buf, target, left, idx, right);
}
} | c | 12 | 0.559471 | 67 | 20.714286 | 70 | starcoderdata |
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 标签值分布信息
*
* @author auto create
* @since 1.0, 2022-05-18 15:35:30
*/
public class TagDistDTO extends AlipayObject {
private static final long serialVersionUID = 4815534925134156396L;
/**
* 时间格式+不唯一
*/
@ApiField("date_format")
private String dateFormat;
/**
* 展示名称+不唯一
*/
@ApiField("display_name")
private String displayName;
/**
* 最大值+不唯一
*/
@ApiField("max")
private String max;
/**
* 最小值+不唯一
*/
@ApiField("mix")
private String mix;
/**
* 展示值+不唯一
*/
@ApiField("value")
private String value;
public String getDateFormat() {
return this.dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getMax() {
return this.max;
}
public void setMax(String max) {
this.max = max;
}
public String getMix() {
return this.mix;
}
public void setMix(String mix) {
this.mix = mix;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
} | java | 8 | 0.676768 | 67 | 14.888889 | 81 | starcoderdata |
// SPDX-License-Identifier: MIT
package ast
import (
"bytes"
"errors"
"io"
"sort"
"github.com/caixw/apidoc/v7/core"
"github.com/caixw/apidoc/v7/internal/locale"
"github.com/caixw/apidoc/v7/internal/xmlenc"
)
// ParseBlocks 从多个 core.Block 实例中解析文档内容
//
// g 必须是一个阻塞函数,直到所有代码块都写入参数之后,才能返回。
func (doc *APIDoc) ParseBlocks(h *core.MessageHandler, g func(chan core.Block)) {
done := make(chan struct{})
blocks := make(chan core.Block, 50)
go func() {
for block := range blocks {
doc.Parse(h, block)
}
done <- struct{}{}
}()
g(blocks)
close(blocks)
<-done
}
// Parse 将注释块的内容添加到当前文档
func (doc *APIDoc) Parse(h *core.MessageHandler, b core.Block) {
if !isValid(b) {
return
}
p, err := xmlenc.NewParser(h, b)
if err != nil {
h.Error(err)
return
}
switch getTagName(p) {
case "api":
if doc.APIs == nil {
doc.APIs = make([]*API, 0, 100)
}
api := &API{doc: doc}
xmlenc.Decode(p, api, core.XMLNamespace)
doc.APIs = append(doc.APIs, api)
if doc.Title.V() != "" { // apidoc 已经初始化,检测依赖于 apidoc 的字段
api.sanitizeTags(p)
}
case "apidoc":
if doc.Title != nil { // 多个 apidoc 标签
err := b.Location.NewError(locale.ErrDuplicateValue).WithField("apidoc").
Relate(doc.Location, locale.Sprintf(locale.ErrDuplicateValue))
h.Error(err)
return
}
xmlenc.Decode(p, doc, core.XMLNamespace)
default:
return
}
// api 进入 doc 的顺序是未知的,进行排序可以保证文档的顺序一致。
doc.sortAPIs()
}
// 简单预判是否是一个合规的 apidoc 内容
func isValid(b core.Block) bool {
bs := bytes.TrimSpace(b.Data)
if len(bs) < minSize {
return false
}
// 去除空格之后,必须保证以 < 开头,且不能以 </ 开关。
return bs[0] == '<' && bs[1] != '/'
}
// 获取根标签的名称
func getTagName(p *xmlenc.Parser) string {
start := p.Current()
for {
t, _, err := p.Token()
if errors.Is(err, io.EOF) {
return ""
} else if err != nil { // 获取第一个元素名称就出错,说明不是一个合则的 XML,直接忽略。
return ""
}
switch elem := t.(type) {
case *xmlenc.StartElement:
p.Move(start)
return elem.Name.Local.Value
case *xmlenc.EndElement, *xmlenc.CData: // 表示是一个非法的 XML,忽略!
return ""
default: // 其它标签忽略
}
}
}
func (doc *APIDoc) sortAPIs() {
sort.SliceStable(doc.APIs, func(i, j int) bool {
ii := doc.APIs[i]
jj := doc.APIs[j]
var iip string
if ii.Path != nil && ii.Path.Path != nil {
iip = ii.Path.Path.V()
}
var jjp string
if jj.Path != nil && jj.Path.Path != nil {
jjp = jj.Path.Path.V()
}
var iim string
if ii.Method != nil {
iim = ii.Method.V()
}
var jjm string
if jj.Method != nil {
jjm = jj.Method.V()
}
if iip == jjp {
return iim < jjm
}
return iip < jjp
})
} | go | 16 | 0.621236 | 81 | 17.633094 | 139 | starcoderdata |
const path = require('path');
var listenPort = 8091;
var uploadFolder = path.join(__dirname, '../uploads');
module.exports = {
listenPort,
uploadFolder
} | javascript | 4 | 0.706806 | 54 | 20.222222 | 9 | starcoderdata |
require("@babel/polyfill");
import generateReactDocs from '../generatereactdoc'
import path from 'path'
describe('GenerateReactDoc', () => {
it('Whole thing should work',async () => {
const output = await generateReactDocs({sourceDir:path.resolve(__dirname,'../__mocks__'),extensions:['js','jsx'],outputDir: path.resolve(__dirname,'../__mocks__/output.md')})
expect(output).toMatchSnapshot()
})
}) | javascript | 17 | 0.687259 | 182 | 38.846154 | 13 | starcoderdata |
package com.github.mahui53541.kedacom.core.domain;
import com.github.mahui53541.kedacom.core.domain.base.BaseModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
* @description:收货地址
* @author: MaHui
* @created: 2017/12/26 13:40
* @version:1.0.0
*/
@Entity
@Table(name="address")
public class Address extends BaseModel {
@Column(name="address",length = 256)
private String address;
@Column(name="user_id")
private Long userId;
@Column(name="create_time",length = 19)
private Date createTime;
@Column(name="modify_time",length = 19)
private Date modifyTime;
@Column(name="is_default")
private Boolean isDefault;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Boolean getDefault() {
return isDefault;
}
public void setDefault(Boolean aDefault) {
isDefault = aDefault;
}
} | java | 9 | 0.651827 | 64 | 19.337838 | 74 | starcoderdata |
package postgres
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
)
const DefaultQueryTimeout = 10 * time.Second
// DefaultQueryCtx returns a context with a sensible sanity limit timeout for SQL queries
func DefaultQueryCtx() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), DefaultQueryTimeout)
}
// DefaultQueryCtxWithParent returns a context with a sensible sanity limit timeout for
// SQL queries with the given parent context
func DefaultQueryCtxWithParent(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, DefaultQueryTimeout)
}
func IsSerializationAnomaly(err error) bool {
if err == nil {
return false
}
return strings.Contains(errors.Cause(err).Error(), "could not serialize access due to concurrent update")
} | go | 11 | 0.78219 | 106 | 27.655172 | 29 | starcoderdata |
private void createPiaAgents() throws IOException{
thisMachine = new Machine( host, port, null );
threadPool = new ThreadPool();
resolver = new Resolver();
Transaction.resolver = resolver;
// === This should really to through the installAgent code in Admin.
// Create the Root agent, and make its data directory the USR_ROOT
rootAgent = new Root(rootAgentName, null);
rootAgent.put(Root.agent_data_dir_name, usrRootStr);
adminAgent = new Admin(adminAgentName, null);
resolver.registerAgent( rootAgent );
resolver.registerAgent( adminAgent );
try{
accepter = new Accepter( realPort );
}catch(IOException e){
System.out.println("Can not create Accepter: " + e.getMessage());
System.out.println( " Try using a different port number:\n"
+ " pia -port nnnn\n"
+ " 8000+your user ID is a good choice.");
System.exit(1);
}
System.err.println("Point your browser to <URL: " + url + ">");
} | java | 12 | 0.647353 | 72 | 31.322581 | 31 | inline |
<?php
namespace uCMS\Processors;
use uCMS\Response;
/**
* Preprocessor that handles PHP scriptlets (that generate HTML fragment embedded in layout template).
*/
class Php implements IProcessor
{
public const PHP_FILE_EXTENSIONS = [ 'php' ];
/**
* Internal function that uses output buffering to gather the results of a PHP script
* and set it as response contents.
*/
private function executePhpScript(Response $response)
{
ob_start();
$result = require $response->filePath;
if ($result === false) {
$response->contents = null;
} else {
$response->contents = ob_get_contents();
}
ob_end_clean();
}
public function process(Response $response): bool
{
if ($response->contents !== null) {
return false;
}
if ($response->tryFilePathExtensions(self::PHP_FILE_EXTENSIONS)) {
$this->executePhpScript($response);
return true; // we have handled this
}
return false;
}
} | php | 12 | 0.597816 | 102 | 23.977273 | 44 | starcoderdata |
--TEST--
ASSIGN_OBJ on null reference returned from __get()
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.file_update_protection=0
opcache.jit_buffer_size=1M
--FILE--
<?php
class Test {
public $prop;
public function &__get($name) {
return $this->prop;
}
}
function test() {
$obj = new Test;
$obj->x->y = 1;
}
function test2() {
$obj = new Test;
$obj->x->y += 1;
}
try {
test();
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
try {
test2();
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
?>
--EXPECT--
Attempt to assign property "y" on null
Attempt to assign property "y" on null | php | 8 | 0.585516 | 50 | 16.540541 | 37 | starcoderdata |
# member/forms.py
# -*- coding: utf-8 -*-
from django import forms
from .models import Member
class MemberForm(forms.Form):
login_name = forms.CharField(max_length=32,required=True)
email = forms.EmailField(max_length=64)
full_name = forms.CharField(max_length=64)
admin = forms.BooleanField()
member_img = forms.ImageField(required=False)
no_image = forms.BooleanField(required=False)
def clean_login_name(self):
ln = self.cleaned_data.get('login_name')
try:
Member.objects.get(login_name=ln)
except:
return ln
raise forms.ValidationError('Login Name already exists')
def clean_email(self):
email = self.cleaned_data.get('email')
try:
Member.objects.get(email=email)
except:
return email
raise forms.ValidationError('Email Address already exists')
def clean_full_name(self):
full_name = self.cleaned_data.get('full_name')
# TODO check for right format
return full_name | python | 11 | 0.635084 | 67 | 27.052632 | 38 | starcoderdata |
package ir.pkokabi.pdialogs.DatePicker;
import android.app.Dialog;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import java.util.ArrayList;
import ir.pkokabi.pdialogs.R;
import ir.pkokabi.pdialogs.databinding.ViewDatePickerBinding;
public abstract class DatePicker extends Dialog implements View.OnClickListener {
private ViewDatePickerBinding binding;
private Context context;
private int minHour, maxHour, timStart, dateStart, dateEnd;
private LinearLayoutManager layoutManagerTime, layoutManagerDate;
private LinearSnapHelper snapHelperTime, snapHelperDate;
private TimeRVAdapter timeRVAdapter;
private DateRVAdapter dateRVAdapter;
protected DatePicker(@NonNull Context context, int minHour
, int maxHour, int timStart, int dateStart, int dateEnd) {
super(context);
this.context = context;
this.minHour = minHour;
this.maxHour = maxHour;
this.timStart = timStart;
this.dateStart = dateStart;
this.dateEnd = dateEnd;
show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.view_date_picker, null, true);
setContentView(binding.getRoot());
setCancelable(true);
if (getWindow() != null) {
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
findViews();
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.chooseTimeBtn) {
onDateTimeSelect();
dismiss();
} else if (view.getId() == R.id.cancelBtn)
dismiss();
}
private void findViews() {
snapHelperTime = new LinearSnapHelper();
snapHelperDate = new LinearSnapHelper();
layoutManagerDate = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
layoutManagerTime = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
/*Date*/
binding.dateRv.setHasFixedSize(true);
binding.dateRv.setLayoutManager(layoutManagerDate);
snapHelperDate.attachToRecyclerView(binding.dateRv);
dateRVAdapter = new DateRVAdapter(initDate());
binding.dateRv.setAdapter(dateRVAdapter);
dateRVAdapter.updateSelected(2);
/*Hour*/
binding.hourRv.setHasFixedSize(true);
binding.hourRv.setLayoutManager(layoutManagerTime);
snapHelperTime.attachToRecyclerView(binding.hourRv);
timeRVAdapter = new TimeRVAdapter(initHours());
binding.hourRv.setAdapter(timeRVAdapter);
if (timStart == 1) {
binding.hourRv.smoothScrollToPosition(timStart);
timeRVAdapter.updateSelected(timStart);
} else {
layoutManagerTime.scrollToPositionWithOffset(timStart, 0);
timeRVAdapter.updateSelected(timStart + 2);
}
binding.hourRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
View view = snapHelperTime.findSnapView(layoutManagerTime);
timeRVAdapter.updateSelected(binding.hourRv.getChildAdapterPosition(view));
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
binding.dateRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
View view = snapHelperDate.findSnapView(layoutManagerDate);
dateRVAdapter.updateSelected(binding.dateRv.getChildAdapterPosition(view));
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
setListenerForViews();
}
private void setListenerForViews() {
binding.chooseTimeBtn.setOnClickListener(this);
binding.cancelBtn.setOnClickListener(this);
}
public abstract void onDateTimeSelect();
private DialogLinkedMap<String, String> initDate() {
return new SolarDate().getDateList(dateStart, dateEnd);
}
private ArrayList initHours() {
boolean isThirty = false;
ArrayList hours = new ArrayList<>();
hours.add("");
hours.add("");
for (int i = minHour * 2; i <= maxHour * 2; i++) {
if (!isThirty)
hours.add(String.valueOf(i / 2) + ":" + "00");
else
hours.add(String.valueOf(i / 2) + ":" + "30");
isThirty = !isThirty;
}
hours.add("");
hours.add("");
return hours;
}
protected String getDate() {
View view = snapHelperDate.findSnapView(layoutManagerDate);
return dateRVAdapter.getDate(binding.dateRv.getChildAdapterPosition(view));
}
protected String getDateTime() {
View view = snapHelperDate.findSnapView(layoutManagerDate);
return dateRVAdapter.getDateString(binding.dateRv.getChildAdapterPosition(view))
+ " ساعت " + getTime();
}
protected String getTime() {
View view = snapHelperTime.findSnapView(layoutManagerTime);
return timeRVAdapter.getTime(binding.hourRv.getChildAdapterPosition(view));
}
protected int getHour() {
View view = snapHelperTime.findSnapView(layoutManagerTime);
return Integer.parseInt(timeRVAdapter.getTime(binding.hourRv.getChildAdapterPosition(view)).split(":")[0]);
}
protected int getMinute() {
View view = snapHelperTime.findSnapView(layoutManagerTime);
return Integer.parseInt(timeRVAdapter.getTime(binding.hourRv.getChildAdapterPosition(view)).split(":")[1]);
}
protected int dateDifference() {
View view = snapHelperDate.findSnapView(layoutManagerDate);
return binding.dateRv.getChildAdapterPosition(view) - 2;
}
} | java | 21 | 0.652035 | 116 | 35.175879 | 199 | starcoderdata |
package com.java24hours;
class Nines{
public static void main(String args[]){
for(int dex=0; dex<=500; dex++){
int multiple = 9*dex;
System.out.print(multiple + " ");
}
}
} | java | 10 | 0.521401 | 45 | 19.666667 | 12 | starcoderdata |
# code implemented by Git: aymenx17
import os
import subprocess
import json
import csv
import argparse
'''
This module is adpated to UCF-Anomaly-Detection dataset.
Three functions:
- split_videos ---> It runs ffmpeg on the dataset with fixed fps.
- pose_estimation ---> It runs demo.py from AlphaPose framework on folder frames.
- vis_stats ---> It prints and save statistichs about pose estimation on the dataset.
Note: Each of the first two functions create and new directory structure.
You can select target videos to work with by changing the python list named 'target'.
Example : target = ['Normal_Videos_event', 'Fighting', 'Robbery']
Expected dataset folder structure:
Videos: {
Normal_Videos_event:
{
vid1.mp4, vid2.mp4 . .. .
},
Fighting:
{
vid1.mp4, vid2.mp4 . .. .
},
Robbery:
{
vid1.mp4, vid2.mp4 . .. .
}
}
'''
parser = argparse.ArgumentParser('Pose estimation analysis on UCF-Anomaly-Detection dataset')
parser.add_argument('--split', action='store_true', default=False, help='Store true flag to split videos')
parser.add_argument('--pose', action='store_true', default=False, help='Store true flag to pose estimation')
parser.add_argument('--stats', action='store_true', default=False, help='Store true flag to print and save statistichs')
parser.add_argument('--target', action='store_true', default=False, help='Store true flag if you have choosed targets')
parser.add_argument('--limit', action='store_true', default=False, help='Store true flag to process only videos below certain length')
def load_json(p_ann):
'''
A for loop that reads a list of keypoints and rearrange in a directory whose keys are named as the input frames.
This is done to obtain a suitable format to work with.
'''
# load json
p_ann = os.path.join(p_ann, 'alphapose-results.json')
if os.path.isfile(p_ann):
results = json.load(open(p_ann, 'r'))
anns = {}
last_image_name = ' '
for i in range(len(results)):
imgpath = results[i]['image_id']
if last_image_name != imgpath:
anns[imgpath] = []
anns[imgpath].append({'keypoints':results[i]['keypoints'],'scores':results[i]['score']})
else:
anns[imgpath].append({'keypoints':results[i]['keypoints'],'scores':results[i]['score']})
last_image_name = imgpath
else:
anns = {}
return anns
def split_videos(dset_root, outpath, target):
for i, (dire, folds, fils) in enumerate(os.walk(dset_root)):
if i ==0:
print('Main dataset directory: {}\n Subdirectories within it: {}\n'.format(dire, folds))
continue
if i > 0 and len(fils) > 0 and (dire.split('/')[-1] not in target):
continue
# loop over videos
print('Processing videos in: {}'.format(dire))
for vid_name in fils:
# path to video
pvid = os.path.join(dire, vid_name)
# create a folder for each video
fname = vid_name.split('.mp4')[0]
path_fold = os.path.join(outpath, dire.split('/')[-1], fname)
if not os.path.isdir(path_fold):
os.makedirs(path_fold)
# executing ffmpeg -i file.mp4 -vf fps=5 path/%04d.jpg
print('*' *100)
print(pvid)
print(path_fold)
cmd = "ffmpeg -i {} -vf fps=5 {}/%04d.jpg".format(pvid, path_fold)
subprocess.call(cmd, shell=True)
def pose_estimation(outpath, outanns, target):
max_length = 2e03
args = parser.parse_args()
for i,(dire, folds, fils) in enumerate(os.walk(outpath)):
if i ==0:
print('Main dataset directory: {}\n Subdirectories within it: {}\n'.format(dire, folds))
continue
# run command on the frames
if len(folds) == 0 and len(fils) > 0 and (dire.split('/')[-2] in target):
if args.limit and len(fils) > max_length:
continue
# loop over video frames
print('Processing video frames in: {}'.format(dire))
# run a python module and output the json file at the correpondent annotation folder
ldir = dire.split('/')
out_json = os.path.join(outanns, ldir[-2], ldir[-1])
if not os.path.isdir(out_json):
os.makedirs(out_json)
cmd = "python demo.py --indir {} --outdir {}".format(dire, out_json)
subprocess.call(cmd , shell=True)
def vis_stats(out_splitted):
'''
The function will print and save statistichs and ratios related of detecting pose in UCF Anomaly dataset.
'''
csv_file = 'stats.csv'
with open(csv_file, 'w+') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=['VideoName' ,'NumberOfFramesWithKeypointDetections', 'TotalFrames', 'Percentage'])
writer.writeheader()
for (dire, folds, fils) in os.walk(out_splitted):
if len(folds) == 0 and len(fils) > 0:
num_frames = len(fils)
p_json = os.path.join(dire.replace('trainval', 'trainval_anns'))
anns = load_json(p_json)
if len(anns) >0:
# number of frames with at least one keypoint detection
num_preds = len(anns)
perc = round(num_preds/num_frames, 1) * 100
vn = dire.split('/')[-1]
writer.writerow({ 'VideoName': vn,'NumberOfFramesWithKeypointDetections': num_preds, 'TotalFrames': num_frames, 'Percentage':perc})
print('Number of pose detections over total frames per video: {}/{} Percentage: {}%'.format(num_preds, num_frames, perc))
def main():
# root directory
data_root = '/media/sdc1'
# UCF_Anomalies dataset path. Replace the name trial_dataset with the proper name. Default: Videos
dset_root = os.path.join(data_root, 'Videos')
args = parser.parse_args()
# trainval will be the main dataset folder for the processed videos
out_splitted = os.path.join(data_root, 'trainval')
if not os.path.isdir(out_splitted):
os.mkdir(out_splitted)
# you can select target folders you want to process using this list
if args.target:
target = ['Training-Normal-Videos-Part-1']
else:
target = os.listdir(dset_root)
print('targets: {}'.format(target))
# create new directory structure and write frames at path out_splitted
if args.split:
split_videos(dset_root, out_splitted, target)
# output annotation path (json files)
outanns = os.path.join(data_root, 'trainval_anns')
if not os.path.isdir(outanns):
os.mkdir(outanns)
# set working directory for AlphaPose framework
os.chdir('/home/ubuntu/work/pytorch/intuition/AlphaPose')
# create new directory structure and write annotation files at outanns
if args.pose:
print('\n'*5)
print('Running pose estimation\n\n')
pose_estimation(out_splitted, outanns, target)
# print statistichs
if args.stats:
os.chdir(data_root)
vis_stats(out_splitted)
print('stats.csv is saved in: {}'.format(data_root))
if __name__ == "__main__":
main() | python | 17 | 0.603467 | 151 | 33.938967 | 213 | starcoderdata |
private final void threadLocalAwareLog(String fQCN, Priority priority, Object message, Throwable t) {
if (isForcedToLog(priority)) {
final Appender forcedAppender = getForcedAppender();
// force the logging and modify the log message (the latter might return the original message)
if (forcedAppender!=null) {
// only call the forced appender
forcedAppender.doAppend(new LoggingEvent(fQCN, this, priority, modifyLogMessage(message), t));
} else {
// go via the normal appenders
forcedLog(fQCN, priority, modifyLogMessage(message), t);
}
} else {
// else not forced to log - use default behaviour
super.log(fQCN, priority, message, t);
}
} | java | 14 | 0.704611 | 101 | 32.095238 | 21 | inline |
import React, { useState } from 'react';
import { useRecoilState } from 'recoil';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import MenuItems from './menu-items';
import { itemsState } from 'js/store/items';
const AppMenu = () => {
const [items] = useRecoilState(itemsState);
const [open, setOpen] = useState(false);
const menuItems = items.map(({ route, title, type }) =>
type === 'SubHeader' ? (
<div key={title}>
<Divider />
<Subheader style={{ color: '#ee3467', fontSize: '26px' }}>
{title}
) : (
<MenuItems
key={route}
route={route}
title={title}
close={() => {
setOpen(false);
}}
/>
)
);
return (
<AppBar
title={<span style={{ color: '#FFFFFF' }}>Funathon
iconClassNameRight="muidocs-icon-navigation-expand-more"
onLeftIconButtonClick={() => setOpen(o => !o)}
style={{ backgroundColor: '#ee3467' }}
/>
<Drawer
docked={false}
open={open}
onRequestChange={() => setOpen(o => !o)}
style={{
width: 1000,
}}
width="25%"
>
{menuItems}
);
};
export default AppMenu; | javascript | 20 | 0.599376 | 62 | 21.508772 | 57 | starcoderdata |
package org.magicwerk.brownies.collections.helper;
import java.util.Comparator;
import java.util.List;
public class MergeSort {
List list;
Comparator<? super E> comparator;
private MergeSort(List list, Comparator<? super E> comparator) {
this.list = list;
if (comparator == null) {
comparator = NaturalComparator.INSTANCE();
}
this.comparator = comparator;
}
public static void sort(List list, Comparator<? super E> comparator) {
MergeSort sort = new MergeSort comparator);
sort.sort();
}
public static void sort(List list, Comparator<? super E> comparator, int from, int to) {
MergeSort sort = new MergeSort comparator);
sort.sort(from, to);
}
private void sort() {
sort(0, list.size());
}
private void sort(int from, int to) {
if (to - from < 12) {
insertSort(from, to);
return;
}
int middle = (from + to) / 2;
sort(from, middle);
sort(middle, to);
merge(from, middle, to, middle - from, to - middle);
}
private int compare(int idx1, int idx2) {
return comparator.compare(list.get(idx1), list.get(idx2));
}
private void swap(int idx1, int idx2) {
E val = list.get(idx1);
list.set(idx1, list.get(idx2));
list.set(idx2, val);
}
private int lower(int from, int to, int val) {
int len = to - from, half;
while (len > 0) {
half = len / 2;
int mid = from + half;
if (compare(mid, val) < 0) {
from = mid + 1;
len = len - half - 1;
} else
len = half;
}
return from;
}
private int upper(int from, int to, int val) {
int len = to - from, half;
while (len > 0) {
half = len / 2;
int mid = from + half;
if (compare(val, mid) < 0)
len = half;
else {
from = mid + 1;
len = len - half - 1;
}
}
return from;
}
private void insertSort(int from, int to) {
if (to > from + 1) {
for (int i = from + 1; i < to; i++) {
for (int j = i; j > from; j--) {
if (compare(j, j - 1) < 0)
swap(j, j - 1);
else
break;
}
}
}
}
private int gcd(int m, int n) {
while (n != 0) {
int t = m % n;
m = n;
n = t;
}
return m;
}
private void rotate(int from, int mid, int to) {
if (from == mid || mid == to) {
return;
}
int n = gcd(to - from, mid - from);
while (n-- != 0) {
E val = list.get(from + n);
int shift = mid - from;
int p1 = from + n, p2 = from + n + shift;
while (p2 != from + n) {
list.set(p1, list.get(p2));
p1 = p2;
if (to - p2 > shift) {
p2 += shift;
} else {
p2 = from + (shift - (to - p2));
}
}
list.set(p1, val);
}
}
private void merge(int from, int pivot, int to, int len1, int len2) {
if (len1 == 0 || len2 == 0) {
return;
}
if (len1 + len2 == 2) {
if (compare(pivot, from) < 0) {
swap(pivot, from);
}
return;
}
int first_cut, second_cut;
int len11, len22;
if (len1 > len2) {
len11 = len1 / 2;
first_cut = from + len11;
second_cut = lower(pivot, to, first_cut);
len22 = second_cut - pivot;
} else {
len22 = len2 / 2;
second_cut = pivot + len22;
first_cut = upper(from, pivot, second_cut);
len11 = first_cut - from;
}
rotate(first_cut, pivot, second_cut);
int newMid = first_cut + len22;
merge(from, first_cut, newMid, len11, len22);
merge(newMid, second_cut, to, len1 - len11, len2 - len22);
}
} | java | 16 | 0.446457 | 99 | 26.955696 | 158 | starcoderdata |
func RemoveSyncTablesIfNeeded(db *sql.DB) {
_, err := db.Exec(dropSyncModelTablesSQL)
if err != nil {
msg := "Error getting results from database. It may simply be that the tables do not exist, please confirm. Error:%s"
syncutil.Info(msg, err.Error())
//log.Println("Error inserting to database, inputData=", item)
}
syncutil.Info("Existing sync_* tables were dropped if available")
} | go | 10 | 0.72335 | 119 | 42.888889 | 9 | inline |
;(function (win, doc) {
var tabcontainers = doc.querySelectorAll('.tabcontainer');
var z = 0;
for (; z < tabcontainers.length; ++z) setupTabs(tabcontainers[z]);
// https://gist.github.com/revolunet/1908355
if (!('indexOf' in [])) {
Array.prototype.indexOf = function (el) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
for (; from < len; from++) if (from in this && this[from] === el) return from;
return -1;
};
}
function getSiblings (m) {
var r = [], n = m.parentNode.firstChild;
for (; n; n = n.nextSibling) if (n.nodeType === 1 && n !== m) r.push(n);
return r;
}
function amendCSS (classes, new_class, add_flag) {
var old_arr = classes.split(' ');
var new_arr = [];
var l = 0
for (; l < old_arr.length; ++l) if (old_arr[l].trim() !== new_class) new_arr[l] = old_arr[l].trim();
if (add_flag) new_arr.push(new_class);
return (classes === new_arr.join(' ') ? classes : new_arr.join(' '));
}
function tabClicked (tabs, tabpanes) {
return function (e) {
typeof e !== 'undefined' && e.preventDefault();
var c = (e.currentTarget || this);
var idx = [].indexOf.call(tabs, c);
var d = getSiblings(c);
var g = getSiblings(tabpanes[idx]);
var f = 0;
var h = 0;
var j;
var p;
for (; f < d.length; ++f) {
j = d[f].className;
if (d[f] !== c && j.split(' ').indexOf('tab') !== -1 && j.split(' ').indexOf('active') !== -1) {
d[f].className = amendCSS(j, 'active', !1);
d[f].setAttribute('aria-selected', 'false');
}
}
for (; h < g.length; ++h) {
p = g[h].className;
if (g[h] !== c && p.split(' ').indexOf('tabpane') !== -1 && p.split(' ').indexOf('active') !== -1) {
g[h].className = amendCSS(p, 'active', !1);
g[h].setAttribute('hidden', 'true');
g[h].setAttribute('aria-hidden', 'true');
}
}
c.className = amendCSS(c.className, 'active', !0);
c.setAttribute('aria-selected', 'true');
tabpanes[idx].className = amendCSS(tabpanes[idx].className, 'active', !0);
tabpanes[idx].removeAttribute('hidden');
tabpanes[idx].setAttribute('aria-hidden', 'false');
};
}
function setupTabs (t) {
var tabs = t.querySelectorAll('.tab');
var tabpanes = t.querySelectorAll('.tabpane');
var i = 0;
if (tabs.length !== tabpanes.length) return;
for (; i < tabs.length; ++i) {
if ('addEventListener' in win) tabs[i].addEventListener('click', tabClicked(tabs, tabpanes), false);
else if ('attachEvent' in win) tabs[i].attachEvent('onclick', tabClicked(tabs, tabpanes));
else tabs[i].onclick = tabClicked(tabs, tabpanes);
}
}
})(window, window.document); | javascript | 23 | 0.547644 | 108 | 35.3375 | 80 | starcoderdata |
package seedu.mark.logic.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.mark.testutil.Assert.assertThrows;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import seedu.mark.logic.commands.exceptions.CommandException;
import seedu.mark.logic.commands.results.CommandResult;
import seedu.mark.model.ModelStub;
import seedu.mark.model.autotag.SelectiveBookmarkTagger;
import seedu.mark.model.predicates.BookmarkPredicate;
import seedu.mark.model.tag.Tag;
import seedu.mark.storage.Storage;
import seedu.mark.storage.StorageStub;
/**
* Contains unit tests for {@link AutotagDeleteCommand}.
*/
public class AutotagDeleteCommandTest {
private final Storage storageStub = new StorageStub();
private final String tagName = "myTag";
@Test
public void constructor_nullString_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new AutotagDeleteCommand(null));
}
@Test
public void execute_taggerExistsInModel_deleteSuccessful() throws Exception {
CommandResult commandResult = new AutotagDeleteCommand(tagName)
.execute(new ModelStubWithAutotags(), storageStub);
assertEquals(String.format(AutotagDeleteCommand.MESSAGE_AUTOTAG_DELETED, tagName),
commandResult.getFeedbackToUser());
}
@Test
public void execute_duplicateBookmark_throwsCommandException() {
AutotagDeleteCommand autotagDeleteCommand = new AutotagDeleteCommand(tagName);
String expectedMessage = String.format(AutotagDeleteCommand.MESSAGE_AUTOTAG_DOES_NOT_EXIST, tagName);
assertThrows(CommandException.class, expectedMessage, () ->
autotagDeleteCommand.execute(new ModelStubNoAutotags(), storageStub));
}
@Test
public void equals() {
String quizTagName = "Quiz";
String readLaterTagName = "readLater";
AutotagDeleteCommand firstCommand = new AutotagDeleteCommand(quizTagName);
AutotagDeleteCommand secondCommand = new AutotagDeleteCommand(readLaterTagName);
// same object -> returns true
assertTrue(firstCommand.equals(firstCommand));
// same values -> returns true
AutotagDeleteCommand firstCommandCopy = new AutotagDeleteCommand(quizTagName);
assertTrue(firstCommand.equals(firstCommandCopy));
// different types -> returns false
assertFalse(firstCommand.equals(1));
// null -> returns false
assertFalse(firstCommand.equals(null));
// different bookmark -> returns false
assertFalse(firstCommand.equals(secondCommand));
}
/**
* A Model stub that always returns a tagger when #removeTagger(String) is called.
*/
private class ModelStubWithAutotags extends ModelStub {
@Override
public Optional removeTagger(String taggerName) {
return Optional.of(new SelectiveBookmarkTagger(new Tag(taggerName), new BookmarkPredicate()));
}
@Override
public void saveMark(String record) {
// called in AutotagDeleteCommand#execute()
}
}
/**
* A Model stub that always returns an empty {@code Optional} when attempting to remove a tagger.
*/
private class ModelStubNoAutotags extends ModelStub {
@Override
public Optional removeTagger(String taggerName) {
return Optional.empty();
}
@Override
public void saveMark(String record) {
// called in AutotagDeleteCommand#execute()
}
}
} | java | 14 | 0.712117 | 109 | 34.761905 | 105 | starcoderdata |
(function() {
/**
* @author 李球
* @class HteOS.tile.Photo 腾讯图片新闻
* @constructor
*/
var Photo = HteOS.controller.Photo = function(tile) {
var photo = this;
photo.$el = tile.getContent();
photo.duration = 1000 * 60 * 10;
photo.intervalId = window.setInterval(function() {
photo.load();
}, photo.duration);
photo.load();
photo.tpl = HteOS.Template.compile('<% for(i = 0;i < list.length; i++){ %>'
+ '<div class="hte-tile-live">'
+ '<a href=" target="_blank">'
+ '<img alt="" src="
+ '<div class="hte-tile-text">
+ '
+ '
+ '<% } %>');
window.cacheMoreData = null;
window.cacheMoreData = function(data){
HteOS.Masker.unmask(photo.$el);
photo.render(data);
photo.start();
}
};
Photo.prototype.start = function(){
var photo = this;
if (!photo.lived) {
photo.live = new HteOS.controller.Live(photo.$el,{});
photo.lived = true;
} else {
photo.live.slide();
}
}
/**
* 加载图片新闻列表
*/
Photo.prototype.load = function() {
var photo = this;
HteOS.Masker.loading(photo.$el,'正在加载...');
$.ajax({
url: "http://pic.news.163.com/photocenter/api/list/0001/00AN0001,00AO0001,00AP0001/0/10/cacheMoreData.json",
dataType: "script",
success: function(data) {
},
error: function() {
HteOS.Masker.unmask(photo.$el);
HteOS.Masker.error(photo.$el,'加载失败');
}
});
};
/**
* 渲染图片新闻
*/
Photo.prototype.render = function(data) {
this.$el.html(this.tpl({
list: data
}));
};
Photo.prototype.stop = function(){
window.clearInterval(this.intervalId);
if(this.live){
this.live.stop();
}
}
Photo.prototype.destroy = function(){
this.stop();
if(this.live){
this.live.destroy();
}
this.$el = null;
}
return Photo;
})(); | javascript | 23 | 0.550585 | 111 | 22.152941 | 85 | starcoderdata |
#pragma once
#include "DirectX.h"
#include "BufferManager.hpp"
#include "VertexBuffer.h"
#include "IndexBuffer.h"
namespace Rendering
{
namespace Sky
{
class SkyGeometry final
{
public:
void Initialize(Device::DirectX& dx, Manager::BufferManager& bufferMgr);
void Destroy();
GET_CONST_ACCESSOR(VertexBuffer, const auto&, _vertexBuffer);
GET_CONST_ACCESSOR(IndexBuffer, const auto&, _indexBuffer);
private:
Buffer::VertexBuffer _vertexBuffer;
Buffer::IndexBuffer _indexBuffer;
};
}
} | c | 12 | 0.740864 | 82 | 21.333333 | 27 | starcoderdata |
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "lastLatitude: " +location.getLatitude());
Log.d(TAG, "lastLongitude: " +location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.currentmarker));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13.0f));
if(circle != null){
circle.remove();
}
circle = mMap.addCircle(new CircleOptions()
.center(mCurrLocationMarker.getPosition())
.radius(4000)
.strokeColor(Color.BLUE)
.strokeWidth(2)
.fillColor(Color.parseColor("#500084d3")));
//just show marker in radius 1km
for (Marker marker : markers) {
if (SphericalUtil.computeDistanceBetween(latLng, marker.getPosition()) < 4000) {
marker.setVisible(true);
}
}
} | java | 15 | 0.609993 | 92 | 35.974359 | 39 | inline |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Categoria_model extends CI_Model {
public function get_categoria(){
$busca = $this->db->query('SELECT codigo, descricao FROM tb_categoria');
if($busca->num_rows()!=0){
return $busca;
}else{
return NULL;
}
}
} | php | 11 | 0.615854 | 76 | 17.222222 | 18 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HotCiv.Managers;
using HotCiv.Tiles;
using NSubstitute;
using NUnit.Framework;
using Squazz.HotCiv;
using Squazz.HotCiv.Managers;
namespace HotCiv.Core.Test
{
[TestFixture]
public class GameTest
{
Game _game;
IUnitManager _unitManager;
ICityManager _cityManager;
ITileManager _tileManager;
IPlayerManager _playerManager;
[SetUp]
public void Initialize()
{
_unitManager = Substitute.For
_cityManager = Substitute.For
_tileManager = Substitute.For
_playerManager = Substitute.For
WorldSetup();
_game = new Game(_tileManager, _unitManager, _cityManager, _playerManager);
}
[Test]
public void ShouldHaveCityAt1_1()
{
Assert.IsNotNull(_game.GetCityAt(new Position(1, 1)), "Should have a city at 1,1");
Assert.AreEqual(PlayerColor.Red, _game.GetCityAt(new Position(1, 1)).Owner.Color, "City at (1,1) should be owned by red");
}
[Test]
public void OceanAt1_0()
{
Assert.AreEqual("Ocean", _game.GetTileAt(new Position(1, 0)));
}
[Test]
public void WordLayOut()
{
Assert.AreEqual("Ocean", _game.GetTileAt(new Position(1, 0)));
Assert.AreEqual("hill", _game.GetTileAt(new Position(0, 1)));
Assert.AreEqual("Mountain", _game.GetTileAt(new Position(2, 2)));
}
[Test]
public void UnitMoveUp()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(2, 2)), "The unit moved a from 3,2 to 2,2 (One up)");
}
[Test]
public void UnitMoveRight()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(3, 3)), "The unit moved a from 3,2 to 3,3 (One right)");
}
[Test]
public void UnitMoveLeft()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(3, 1)), "The unit moved a from 3,2 to 3,1 (One Left)");
}
[Test]
public void UnitMoveDown()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(4, 2)), "The unit moved a from 3,2 to 4,2 (One down)");
}
[Test]
public void UnitMoveUpRight()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(2, 3)), "The unit moved a from 3,2 to 2,3 (One upright (diagonal))");
}
[Test]
public void UnitMoveUpLeft()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(2, 1)), "The unit moved a from 3,2 to 2,1 (One upleft (diagonal))");
}
[Test]
public void UnitMoveDownRight()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(3, 3)), "The unit moved a from 3,2 to 3,3 (One downright (diagonal))");
}
[Test]
public void UnitMoveDownLeft()
{
var unit = _game.GetUnitAt(new Position(3, 2));
Assert.IsTrue(_game.MoveUnit(unit, new Position(3, 1)), "The unit moved a from 3,2 to 3,1 (One downleft (diagonal))");
}
[Test]
public void UserCantMoveToMountain()
{
//to be implemented
}
[Test]
public void UserCantMoveToOcean()
{
//to be implemented
}
[Test]
public void UserCantMoveOverMountain()
{
//to be implemented
}
[Test]
public void UserCantMoveOverOcean()
{
//to be implemented
}
[Test]
public void RedCantMoveBluesUnits()
{
//to be implemented
}
[Test]
public void CityProduce6AfterEndTurn()
{
//to be implemented
}
[Test]
public void CityPopulation()
{
Assert.AreEqual(1, _game.GetCityAt(new Position(1, 1)).Size, "City at (1,1) should have 1 in population");
//to be implemented
}
[Test]
public void AfterRedEndTurnThenBlueTurn()
{
//to be implemented
}
[Test]
public void RedTurnThenBlueThenRed()
{
//to be implemented
}
[Test]
public void RedWinsInYear3000()
{
//to be implemented
}
[Test]
public void RedAttack()
{
//to be implemented
}
public void WorldSetup()
{
var list = new List
//create the special fields first
_tileManager.CreateOcean(new Position(1, 0));
_tileManager.CreateHill(new Position(0, 1));
_tileManager.CreateMountain(new Position(2, 2));
//fill the rest with plain fields
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
_tileManager.CreatePlain(new Position(i, j));
}
}
var playerRed = new Player(PlayerColor.Red, "First");
var playerBlue = new Player(PlayerColor.Blue, "Second");
_unitManager.CreateArcher(playerRed, _tileManager.GetLegalTileForItem(new Position(2, 0)));
_unitManager.CreateSettler(playerRed, _tileManager.GetLegalTileForItem(new Position(4, 3)));
_unitManager.CreateLegion(playerBlue, _tileManager.GetLegalTileForItem(new Position(3, 2)));
}
}
} | c# | 19 | 0.664516 | 125 | 22.069767 | 215 | starcoderdata |
import { Poll } from '../models'
// Get Authed User's Polls
const GetUserPolls = (req, res) => {
const userID = req.headers.userid
Poll.find({ author: userID }).exec((err, result) => {
if (err) throw err
res.json(result)
})
}
export default GetUserPolls | javascript | 11 | 0.639576 | 55 | 19.214286 | 14 | starcoderdata |
export const redirectionsFormDefault = {
label: '',
condition: '',
cible: '',
redirections: [],
};
export const redirectionsFormNew = {
label: '',
condition: '',
cible: '',
redirections: [
{
label: 'First redirection label',
condition: 'First redirection condition',
cible: 'First redirection cible',
},
{
label: 'Second redirection label',
condition: 'Second redirection condition',
cible: 'Second redirection cible',
},
],
};
export const redirectionsFormUpdate = {
label: '',
condition: '',
cible: '',
redirections: [
{
id: 'FIRST_REDIRECTION',
label: 'First redirection label',
condition: 'First redirection condition',
cible: 'First redirection cible',
},
{
id: 'SECOND_REDIRECTION',
label: 'Second redirection label',
condition: 'Second redirection condition',
cible: 'Second redirection cible',
},
],
};
export const redirectionsState = {
FIRST_REDIRECTION: {
id: 'FIRST_REDIRECTION',
label: 'First redirection label',
condition: 'First redirection condition',
cible: 'First redirection cible',
},
SECOND_REDIRECTION: {
id: 'SECOND_REDIRECTION',
label: 'Second redirection label',
condition: 'Second redirection condition',
cible: 'Second redirection cible',
},
};
export const redirectionsModel = [
{
id: 'FIRST_REDIRECTION',
label: 'First redirection label',
Expression: 'First redirection condition',
IfTrue: 'First redirection cible',
},
{
id: 'SECOND_REDIRECTION',
label: 'Second redirection label',
Expression: 'Second redirection condition',
IfTrue: 'Second redirection cible',
},
]; | javascript | 10 | 0.633835 | 48 | 22.324324 | 74 | starcoderdata |
package router
import (
"gin-vue-devops/api/v1"
"gin-vue-devops/middleware"
"github.com/gin-gonic/gin"
)
func InitK8sNamespacesRouter(Router *gin.RouterGroup) {
K8sNamespacesRouter := Router.Group("k8sNamespaces").Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
{
K8sNamespacesRouter.POST("createK8sNamespaces", v1.CreateK8sNamespaces) // 新建K8sNamespaces
K8sNamespacesRouter.DELETE("deleteK8sNamespaces", v1.DeleteK8sNamespaces) // 删除K8sNamespaces
K8sNamespacesRouter.DELETE("deleteK8sNamespacesByIds", v1.DeleteK8sNamespacesByIds) // 批量删除K8sNamespaces
K8sNamespacesRouter.PUT("updateK8sNamespaces", v1.UpdateK8sNamespaces) // 更新K8sNamespaces
K8sNamespacesRouter.GET("findK8sNamespaces", v1.FindK8sNamespaces) // 根据ID获取K8sNamespaces
K8sNamespacesRouter.GET("getK8sNamespacesList", v1.GetK8sNamespacesList) // 获取K8sNamespaces列表
}
} | go | 12 | 0.80131 | 111 | 44.8 | 20 | starcoderdata |
<?php
/*
* Dispatched request:
* - module: default
* - controller: index
* - action: index
*/
$page1 = new Zym_Navigation_Page_Mvc(array(
'label' => 'foo',
'action' => 'index',
'controller' => 'index'
));
$page2 = new Zym_Navigation_Page_Mvc(array(
'label' => 'foo',
'action' => 'bar',
'controller' => 'index'
));
$page1->isActive(); // returns true
$page2->isActive(); // returns false
/*
* Dispatched request:
* - module: blog
* - controller: post
* - action: view
* - id: 1337
*/
$page = new Zym_Navigation_Page_Mvc(array(
'label' => 'foo',
'action' => 'view',
'controller' => 'post',
'module' => 'blog'
));
// returns true, because request has the same module, controller and action
$page->isActive();
/*
* Dispatched request:
* - module: blog
* - controller: post
* - action: view
*/
$page = new Zym_Navigation_Page_Mvc(array(
'label' => 'foo',
'action' => 'view',
'controller' => 'post',
'module' => 'blog',
'id' => null
));
// returns false, because page requires the id param to be set in the request
$page->isActive(); // returns false | php | 9 | 0.536705 | 77 | 19.433333 | 60 | starcoderdata |
import asyncio, datetime, sqlite3
from math import floor
import kurisu.prefs
ibn = kurisu.prefs.Channels.dev
alpacaRole = kurisu.prefs.Roles.alpaca
async def alpacaLoop():
client = kurisu.prefs.discordClient
dealp = [False, 0]
while True:
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
if dealp[0]:
cursor.execute('delete from alpaca where userID = %s' % dealp[1])
s = client.get_server('380104197267521537')
u = s.get_member(dealp[1])
try:
await client.remove_roles(u, alpacaRole)
await client.send_message(ibn, "%s больше не Альпакамен." % u.mention)
except:
await client.send_message(ibn, "Пользователь с ID %s покинул сервер до снятия роли." % dealp[1])
dealp = [False, '']
conn.commit()
cursor.execute('select * from alpaca order by date asc limit 1')
a = cursor.fetchall()
if len(a) != 0:
t = datetime.datetime.fromtimestamp(a[0][2]) - datetime.timedelta(hours=3)
r = floor((t - datetime.datetime.now()).total_seconds())
if r <= 60:
dealp = [True, str(a[0][1])]
dt = r
print(r)
else:
dt = 60
else:
dt = 60
conn.close()
await asyncio.sleep(dt) | python | 18 | 0.662033 | 100 | 27.073171 | 41 | starcoderdata |
tCIDLib::TBoolean
TFacCQCIntfEng::bFindTarContainer( TCQCIntfContainer& iwdgStart
, const TString& strPath
, tCIDLib::TBoolean& bIsAncestor
, TCQCIntfContainer*& piwdgTar)
{
// Assume the worst
piwdgTar = 0;
bIsAncestor = kCIDLib::False;
// It has to be a relative path
if (!strPath.bStartsWith(L"./") && !strPath.bStartsWith(L"../"))
return kCIDLib::False;
// We start at the start container widget
TCQCIntfContainer* piwdgCur = &iwdgStart;
// And let's break it into path components
tCIDLib::TStrList colComps;
TStringTokenizer stokPath(&strPath, L"/");
const tCIDLib::TCard4 c4CompCount = stokPath.c4BreakApart(colComps);
//
// Now, for each component, we move up or down.
//
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4CompCount; c4Index++)
{
const TString& strCurComp = colComps[c4Index];
if (strCurComp == L".")
{
// Ignore it. It has no effect
}
else if (strCurComp == L"..")
{
// Move up to the parent container
piwdgCur = piwdgCur->piwdgParent();
}
else
{
//
// Find a child of the current container that has the current name,
// no recursion.
//
TCQCIntfWidget* piwdgNext = piwdgCur->piwdgFindByName
(
strCurComp, kCIDLib::False
);
// If not found or not a container, then we failed
if (!piwdgNext || !piwdgNext->bIsDescendantOf(TCQCIntfContainer::clsThis()))
return kCIDLib::False;
// Cast it to a container now that we know it is one
piwdgCur = static_cast<TCQCIntfContainer*>(piwdgNext);
}
// If we have maxed out, then we failed
if (!piwdgCur)
return kCIDLib::False;
}
CIDAssert(piwdgCur != 0, L"The target container return value was not set");
//
// See if the final target is an ancestor of the start widget. We indicate we
// want to recurse, not just check immediate children.
//
piwdgTar = piwdgCur;
bIsAncestor = piwdgTar->bContainsWidget(&iwdgStart, kCIDLib::True);
return kCIDLib::True;
} | c++ | 18 | 0.554493 | 88 | 31.945205 | 73 | inline |
package org.xson.core.deserializer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import org.xson.core.ReaderModel;
import org.xson.core.XsonReader;
public class CollectionDeserializer implements XsonReader {
@Override
public Object read(ReaderModel model) {
// 用户对象
Class type = model.getUserType();
Collection returnValue = createCollection(type);
model.appendObject(returnValue);
while (!model.isEnd() && model.isBound()) {
returnValue.add(model.getObject());
}
model.endObject();
return returnValue;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Collection createCollection(Class type) {
// 如果有有私有Class或者空构造函数,则会出现问题
Collection collection = null;
if (type == ArrayList.class) {
collection = new ArrayList
} else if (type == LinkedList.class) {
collection = new LinkedList
} else if (type == Vector.class) {
collection = new Vector
} else if (type == Stack.class) {
collection = new Stack
} else if (type == HashSet.class) {
collection = new HashSet
} else if (type == TreeSet.class) {
collection = new TreeSet
} else if (type == LinkedHashSet.class) {
collection = new LinkedHashSet
} else if (type.isAssignableFrom(EnumSet.class)) {
// list = EnumSet.noneOf((Class
collection = EnumSet.noneOf((Class type);
} else {
try {
collection = (Collection) type.newInstance();
} catch (Exception e) {
throw new XsonDeserializerException("create collection instane error, class " + type.getName());
}
}
return collection;
}
} | java | 23 | 0.679708 | 100 | 28.919355 | 62 | starcoderdata |
a=list(map(int,input().split()))
b=0
c=1
while(c*a[0]<(a[2]+0.5)):
b=b+a[1]
c=c+1
print(b) | python | 11 | 0.515464 | 32 | 11.25 | 8 | codenet |
package io.github.zeleven.playa.ui.module.main;
import javax.inject.Inject;
import io.github.zeleven.playa.ui.base.BasePresenter;
public class MainPresenter extends BasePresenter
implements MainContract.Presenter {
@Inject
public MainPresenter() {
}
} | java | 8 | 0.755932 | 67 | 21.692308 | 13 | starcoderdata |
using System.Collections.Generic;
using BeauData;
using RuleScript.Runtime;
using BeauUtil;
namespace RuleScript.Data
{
public struct RSPersistRuleData : ISerializedObject, ISerializedVersion
{
public string Id;
internal RSRuntimeRuleTable.RuleState State;
#region ISerializedObject
ushort ISerializedVersion.Version { get { return 1; } }
void ISerializedObject.Serialize(Serializer ioSerializer)
{
ioSerializer.Serialize("id", ref Id, FieldOptions.PreferAttribute);
ioSerializer.Enum("state", ref State, FieldOptions.PreferAttribute);
}
#endregion // ISerializedObject
}
} | c# | 12 | 0.69469 | 80 | 26.16 | 25 | starcoderdata |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Berita;
// use App\User;
class BeritaController extends Controller
{
public function data_berita()
{
$limit = request()->limit;
$data = Berita::orderByDesc('created_at')->paginate(20);
return response()->json([
'status' => 'success',
'data' => $data
]
);
}
public function data_berita_terbaru()
{
$limit = request()->limit;
$data = Berita::orderByDesc('created_at')->limit($limit)->get();
return response()->json([
'status' => 'success',
'data' => $data
]
);
}
public function data_by($slug)
{
$data = Berita::where('slug', $slug)->first();
return response()->json([
'status' => 'success',
'data' => $data
]
);
}
} | php | 13 | 0.478261 | 71 | 18.843137 | 51 | starcoderdata |
@using DancingGoat.Models
@model IEnumerable
<ul class="nav-menu">
@foreach (var menuItem in Model)
{
<a href="@menuItem.Url">@HtmlLocalizer[menuItem.Caption]
} | c# | 14 | 0.570866 | 72 | 19.333333 | 12 | starcoderdata |
using Discord.WebSocket;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace BotListAPI
{
/// BotListAPI client to post server count
public class ListClient
{
public readonly ListConfig Config = new ListConfig();
/// Discord client can be normal or sharded
public readonly BaseSocketClient Discord;
private readonly Timer Timer;
/// Log event for when a log message is triggered
public Action<LogType, string> MessageLog;
private HttpClient Http;
/// Log type for auto posting
public LogType LogType = LogType.Info;
public ListClient(BaseSocketClient client, ListConfig config)
{
if (config == null)
throw new ArgumentException("The list config cannot be null");
Discord = client;
Config = config;
if (Config.DiscordBotListv2 != "" && !Config.DiscordBotListv2.StartsWith("Bot"))
Config.DiscordBotListv2 = "Bot " + Config.DiscordBotListv2;
Timer = new Timer
{
Interval = 600000,
Enabled = false
};
Timer.Elapsed += Timer_Elapsed;
}
/// Disable all auto posting
public bool Disabled = false;
/// Start posting server count every 10 minutes
public void Start()
{
if (!Timer.Enabled)
{
Timer.Start();
Log(LogType.None, LogType.None, "Enabled auto posting server count");
}
}
/// Stop auto posting server count
public void Stop()
{
if (Timer.Enabled)
{
Timer.Stop();
Log(LogType.None, LogType.None, "Disabled auto posting server count");
}
}
/// Post server count every 10 minutes
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (Discord != null && !Disabled)
_ = SendBotBlock(LogType);
}
public readonly string Version = "1.1.1";
/// Post server count to BotBlock.org
public async Task SendBotBlock(LogType type)
{
bool isError = false;
if (Http == null)
{
if (Discord == null)
{
Log(type, LogType.Error, "Cannot post server count, Discord client is null");
isError = true;
}
else if (Discord.CurrentUser == null)
{
Log(type, LogType.Error, "Cannot post server count, CurrentUser is null");
isError = true;
}
Http = new HttpClient();
Http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Http.DefaultRequestHeaders.Add("User-Agent", $"BotListAPI {Version} - " + Discord.CurrentUser.ToString());
}
if (!isError)
{
ListJson Json = Config.GetJson();
Json.SetCount(Discord);
string JsonString = JsonConvert.SerializeObject(Json);
try
{
StringContent Content = new StringContent(JsonString, Encoding.UTF8, "application/json");
Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage Res = await Http.PostAsync("https://botblock.org/api/count", Content);
if (Res.IsSuccessStatusCode)
{
Log(type, LogType.Info, $"Successfully posted server count to BotBlock");
Log(type, LogType.Debug, "Request response in JSON\n" + JsonConvert.SerializeObject(Res, Formatting.Indented));
}
else
{
Log(type, LogType.Error, $"Error could not post server count to BotBlock, {(int)Res.StatusCode} {Res.ReasonPhrase}");
Log(type, LogType.Debug, "Request response in JSON\n" + JsonConvert.SerializeObject(Res, Formatting.Indented));
}
}
catch (Exception ex)
{
Log(type, LogType.Error, $"Error could not post server count to BotBlock, {ex.Message}");
Log(type, LogType.Debug, "Exception\n" + ex.ToString());
}
}
}
internal void Log(LogType type, LogType Match, string text)
{
MessageLog?.Invoke(type, text);
if (type >= Match)
Console.WriteLine("[BotListAPI] " + text);
}
}
public enum LogType
{
/// Dont log anything to console
None,
/// Only log errors
Error,
/// Log success and errors
Info,
/// Log everything including request responses in json to console
Debug
}
} | c# | 22 | 0.537165 | 141 | 35.289474 | 152 | starcoderdata |
<?php
declare(strict_types=1);
namespace Tests\Sylius\InvoicingPlugin\Behat\Context\Domain;
use Behat\Behat\Context\Context;
use Tests\Application\InvoicingPlugin\EventProducer\TestOrderPlacedProducer;
final class GeneratingInvoiceContext implements Context
{
/** @var TestOrderPlacedProducer */
private $orderPlacedEventProducer;
public function __construct(TestOrderPlacedProducer $orderPlacedEventProducer)
{
$this->orderPlacedEventProducer = $orderPlacedEventProducer;
}
/**
* @Given the invoices are not generated
*/
public function invoicesAreNotGenerated(): void
{
$this->orderPlacedEventProducer->disableInvoiceGeneration();
}
} | php | 9 | 0.746099 | 82 | 25.111111 | 27 | starcoderdata |
package com.pipan.filesystem;
import java.util.Hashtable;
import java.util.Map;
import com.pipan.filesystem.Directory;
import com.pipan.filesystem.File;
import com.pipan.filesystem.Filesystem;
import com.pipan.filesystem.SymbolicLink;
import org.junit.jupiter.api.Assertions;
public class FilesystemMock implements Filesystem {
private Map<String, File> files;
private Map<String, Directory> dirs;
private Map<String, SymbolicLink> symLinks;
private Map<String, Filesystem> subsystems;
private String base;
public FilesystemMock(String base) {
this.base = base;
this.files = new Hashtable<>();
this.dirs = new Hashtable<>();
this.symLinks = new Hashtable<>();
this.subsystems = new Hashtable<>();
}
public FilesystemMock() {
this("");
}
public void assertFileExists(String name) {
Assertions.assertTrue(this.getFile(name).exists());
}
public void assertFileContent(String name, String content) throws Exception {
Assertions.assertEquals(content, this.getFile(name).read(), "File content is different");
}
public FilesystemMock withFile(File file) {
this.files.put(file.getName(), file);
return this;
}
public FilesystemMock withFile(String name, String content) {
return this.withFile(new FileMock(this.base, name, content));
}
public FilesystemMock withFile(String name) {
return this.withFile(name, null);
}
public FilesystemMock withDir(String name, Directory dir) {
this.dirs.put(name, dir);
return this;
}
public FilesystemMock withSubsystem(String name, Filesystem subsystem) {
this.subsystems.put(name, subsystem);
return this;
}
public FilesystemMock withSymbolicLink(String name, SymbolicLink symlink) {
this.symLinks.put(name, symlink);
return this;
}
@Override
public String getBase() {
return this.base;
}
@Override
public Directory getDirectory(String name) {
return this.dirs.get(name);
}
@Override
public File getFile(String name) {
return this.files.get(name);
}
@Override
public SymbolicLink getSymbolicLink(String name) {
return this.symLinks.get(name);
}
@Override
public Filesystem withBase(String path) {
return this.subsystems.get(path);
}
} | java | 9 | 0.666124 | 97 | 25.408602 | 93 | starcoderdata |
<?php
class MemberPage extends Page {
function requireDefaultRecords() {
if (!DataObject::get_one('MemberPage')) {
$page = new MemberPage();
$page->Title = 'Member';
$page->URLSegment = 'member';
$page->Status = 'Published';
$page->write();
$page->publish('Stage', 'Live');
$page->flushCache();
DB::alteration_message('MemberPage created on page tree', 'created');
}
parent::requireDefaultRecords();
}
}
class MemberPage_Controller extends Page_Controller {
function index() {
return $this->customise(array(
'Title' => 'Member',
));
}
function ProfileForm() {
$fields = new FieldList();
$name = new TextField("Name", "");
$name->addPlaceholder("Name", "");
$name->addHolderClass("col-sm-6 breaking");
$name->addExtraClass("form-control");
$fields->push($name);
$email = new TextField("Email", "Email");
$email->addPlaceholder("Email");
$email->addHolderClass("col-sm-6 breaking");
$email->addExtraClass("form-control");
$fields->push($email);
$button = new FormAction('DoProfilForm', 'Send');
$button->addHolderClass("breaking col-md-12");
$button->addExtraClass("btn btn-primary");
$action = new FieldList(
$button
);
$validator = new RequiredFields('FirstName', 'Email', 'Address');
$form = new BootstrapForm($this, 'ProfilForm', $fields, $action, $validator);
$form->setGridActionClass("col-md-12");
return $form;
}
} | php | 12 | 0.658571 | 78 | 23.561404 | 57 | starcoderdata |
package jadx.core.dex.visitors;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for describe dependencies of jadx visitors
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JadxVisitor {
/**
* Visitor short name (identifier)
*/
String name();
/**
* Detailed visitor description
*/
String desc() default "";
/**
* This visitor must be run <b>after</b> listed visitors
*/
Class<? extends IDexTreeVisitor>[] runAfter() default {};
/**
* This visitor must be run <b>before</b> listed visitors
*/
Class<? extends IDexTreeVisitor>[] runBefore() default {};
}
| java | 8 | 0.716198 | 59 | 21.636364 | 33 | research_code |
package org.cbsa.api.controller.search;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.cbsa.api.conf.ConfigCBSI;
import org.cbsa.api.model.PageResult;
import org.cbsa.api.model.SearchResult;
public class PageByPageSearch {
private final Logger logger = Logger.getLogger(PageByPageSearch.class
.getName());
private int falseCounter = 0;
public PageByPageSearch() {
logger.setLevel(Level.INFO);
}
public List findpages(String path,
List searchKeywordList, int fileCounter) throws IOException {
int i; // page no.
boolean hasKeywords = false;
PDDocument finalDocument = new PDDocument();
List pageList = new ArrayList
File file = new File(path);
PDFParser parser = new PDFParser(new RandomAccessBuffer(
new FileInputStream(file)));
parser.parse();
COSDocument cosDoc = parser.getDocument();
PDFTextStripper reader = new PDFTextStripper();
PDDocument doc = new PDDocument(cosDoc);
List list = new ArrayList
for (i = 0; i <= doc.getNumberOfPages(); i++) {
reader.setStartPage(i);
reader.setEndPage(i);
hasKeywords = true;
for (String keyword : searchKeywordList) {
if (!reader.getText(doc).toLowerCase()
.contains(keyword.toLowerCase())) {
hasKeywords = false;
break;
}
}
if (hasKeywords) {
if (falseCounter > 1) {
SearchResult result = new PageResult();
result.setFileContent(reader.getText(doc));
result.setFilePath(path);
result.setPageNumber(i);
list.add(result);
pageList.add(doc.getPage(i));
}
falseCounter++;
}
}
for (PDPage page : pageList) {
finalDocument.addPage(page);
}
finalDocument
.save(ConfigCBSI.getResultPdfPath() + fileCounter + ".pdf");
finalDocument.close();
logger.info("Result Saved");
return list;
}
} | java | 16 | 0.602379 | 81 | 28.2 | 95 | starcoderdata |
// ==========================================================================
// Notifo.io
// ==========================================================================
// Copyright (c)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using BenchmarkDotNet.Attributes;
using FakeItEasy;
using Mjml.Net;
using Notifo.Domain.Apps;
using Notifo.Domain.Channels.Email;
using Notifo.Domain.Channels.Email.Formatting;
using Notifo.Domain.Users;
using Notifo.Domain.Utils;
namespace Benchmarks
{
[MemoryDiagnoser]
[SimpleJob]
public class EmailFormatterBenchmarks
{
private readonly App app = new App("1", default);
private readonly IEmailFormatter emailFormatterNormal = new EmailFormatterNormal(A.Fake A.Fake new MjmlRenderer());
private readonly IEmailFormatter emailFormatterLiquid = new EmailFormatterLiquid(A.Fake A.Fake new MjmlRenderer());
private readonly EmailTemplate emailTemplateNormal;
private readonly EmailTemplate emailTemplateLiquid;
private readonly User user = new User("1", "1", default);
public EmailFormatterBenchmarks()
{
emailTemplateNormal = emailFormatterNormal.CreateInitialAsync().AsTask().Result;
emailTemplateLiquid = emailFormatterLiquid.CreateInitialAsync().AsTask().Result;
}
[Benchmark]
public async ValueTask FormatNormal()
{
return await emailFormatterNormal.FormatAsync(EmailJob.ForPreview, emailTemplateNormal, app, user);
}
[Benchmark]
public async ValueTask FormatLiquid()
{
return await emailFormatterLiquid.FormatAsync(EmailJob.ForPreview, emailTemplateLiquid, app, user);
}
}
} | c# | 16 | 0.623438 | 157 | 39 | 48 | starcoderdata |
func SyncPolicies() {
log.Info("Syncing Policies")
// Create/Update Policies
rawPolicies := processDirectoryRaw(path.Join(Spec.ConfigurationPath, "policies"))
for policyName, rawPolicyDocument := range rawPolicies {
policy := Policy{Name: policyName, PolicyDocument: string(rawPolicyDocument)}
policyPath := path.Join("sys/policies/acl", policy.Name)
task := taskWrite{
Path: policyPath,
Description: fmt.Sprintf("Policy [%s]", policy.Name),
Data: structToMap(policy),
}
wg.Add(1)
taskChan <- task
policyList.Add(policyName)
}
// Clean up Policies
existing_policies, _ := VaultSys.ListPolicies()
for _, policy := range existing_policies {
// Ignore root and default policies. These cannot be removed
if !(policy == "root" || policy == "default") {
if policyList.Contains(policy) {
log.Debug(policy + " exists in configuration, no cleanup necessary")
} else {
task := taskDelete{
Description: fmt.Sprintf("Policy [%s]", policy),
Path: path.Join("sys/policies/acl", policy),
}
taskPromptChan <- task
}
}
}
} | go | 18 | 0.669084 | 82 | 28.837838 | 37 | inline |
#include
#include "index.h"
int main() {
std::cout << "learn boost" << std::endl;
learn_boost::UseCaseIndex index = learn_boost::UseCaseIndex::kMemorySmartPtr;
learn_boost::IRunUseCase *use_case = learn_boost::UseCaseSimpleFactory::Create(index);
if (use_case) {
use_case->Run();
}
else {
std::cout << "learn boost usecase index error" << std::endl;
}
int wait_char = std::getchar();
return 0;
} | c++ | 10 | 0.666667 | 87 | 19.090909 | 22 | starcoderdata |
/*
* Copyright 2019 聂钊
*
* 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 to of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qdigo.ebike.common.core.util.security;
import com.qdigo.ebike.common.core.constants.ConfigConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Arrays;
import java.util.Random;
/**
* Description:
* date: 2019/12/11 5:06 PM
*
* @author niezhao
* @since JDK 1.8
*/
public class SecurityUtil {
static {
//AesCbc解密初始化
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
Security.addProvider(new BouncyCastleProvider());
}
/**
* @return 生成6位数字的随机验证码
*/
public static String generatePinCode() {
return String.valueOf(new Random().nextInt(899999) + 100000);
}
public static String randomNum() {
//10位
return String.valueOf(new Random().nextInt(89999) + 10000) + new Random().nextInt(99999);
}
public static String generateAccessToken() {
return MD5Util.computeMD5(String.valueOf(new Random().nextLong()));
}
//加密后的sha
public static String getSHA256(String str) {
MessageDigest messageDigest;
String encodeStr = null;
try {
messageDigest = MessageDigest.getInstance("SHA-256"); //apache的工具
byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
encodeStr = Hex.encodeHexString(hash);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeStr;
}
//加密后的sha
public static String getSHA1(String str) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
// 字节数组转换为 十六进制 数
for (byte aMessageDigest : messageDigest) {
String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* 生成 HMACSHA256
*
* @param data 待处理数据
* @param key 密钥
* @return 加密结果
* @throws Exception
*/
public static String getHMACSHA256(String data, String key) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
//Decrypt 解密
public static String AesCbcDecrypt(String data, String key, String iv, String encodingFormat) {
try {
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key);
//偏移量
byte[] ivByte = Base64.decodeBase64(iv);
int base = 16; //如果密钥不足16位,就补足
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
return new String(resultByte, encodingFormat);
} else {
return null;
}
} catch (Exception e) {
Security.addProvider(new BouncyCastleProvider());
throw new RuntimeException(e);
}
}
/**
* 蓝牙的加密方法
*
* @param imei
* @return
*/
public static int[] bleCode(String imei) {
imei = StringUtils.substringAfter(imei, ConfigConstants.imei.getConstant());
// 1 0 0 8 8 8 8 8
int[] ints = new int[8];
for (int i = 0; i < imei.length(); i++) {
int t = Integer.parseInt(String.valueOf(imei.charAt(i)));
ints[i] = t;
}
int[] checkInt = new int[6];
checkInt[5] = (ints[0] ^ ints[1] ^ ints[2] ^ ints[3] + (ints[4] * ints[5] + ints[6] * ints[7])) & 0x00ff;
checkInt[4] = (ints[0] * ints[1] * ints[2] * ints[3] + ints[4] + ints[5] + ints[6] + ints[7]) & 0x00ff;
checkInt[3] = ((ints[0] + ints[1] + ints[2] + ints[3]) * (ints[4] + ints[5] + ints[6] + ints[7])) & 0xff;
checkInt[2] = ((ints[0] + ints[1] + ints[2] + ints[3]) | (ints[4] * ints[5] * ints[6] * ints[7])) & 0xff;
checkInt[1] = (ints[0] ^ ints[1] ^ ints[2] ^ ints[3] ^ ints[4] ^ ints[5] ^ ints[6] ^ ints[7]) & 0xff;
checkInt[0] = (ints[0] + ints[1] + ints[2] + ints[3] + ints[4] + ints[5] + ints[6] + ints[7]) & 0xff;
return checkInt;
}
} | java | 18 | 0.58641 | 113 | 34.411458 | 192 | starcoderdata |
<!DOCTYPE html>
<html lang="en">
<?php
/* include_once("../../../config.php");
print_r($_SESSION['OTP']);
if (isset($_POST['otpa'])) {
if($_SESSION['OTP']==$_POST['otpa'].$_POST['otpb'].$_POST['otpc'].$_POST['otpd'] ){
header("Location:".AppUrl."views/Franchisee/FpwdNewPassword.php");
}
else{
$status = "Invaild security code";
}
} */ ?>
<?php
include_once("../../../config.php");
if (isset($_POST['btnVerifyCode'])) {
$response = $webservice->getData("Franchisee","forgotPasswordOTPvalidation",$_POST);
if ($response['status']=="success") {
?>
<form action="FpwdNewPassword.php" id="reqFrm" method="post">
<input type="hidden" value="<?php echo $response['data']['reqID'];?>" name="reqID">
<input type="hidden" value="<?php echo $response['data']['email'];?>" name="reqEmail">
document.getElementById("reqFrm").submit();
<?php
}
else{
$errormessage = $response['message'];
}
}
?>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
Login
<link rel="stylesheet" href="../../assets/vendors/iconfonts/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="../../assets/vendors/iconfonts/puse-icons-feather/feather.css">
<link rel="stylesheet" href="../../assets/vendors/css/vendor.bundle.base.css">
<link rel="stylesheet" href="../../assets/vendors/css/vendor.bundle.addons.css">
<link rel="stylesheet" href="../../assets/css/style.css">
<link rel="shortcut icon" href="../../assets/images/favicon.png" />
<script src="../../assets/vendors/js/vendor.bundle.base.js">
<script src="../../assets/vendors/js/vendor.bundle.addons.js">
<script src="../../assets/js/off-canvas.js">
<script src="../../assets/js/hoverable-collapse.html">
<script src="../../assets/js/misc.js">
<script src="../../assets/js/settings.html">
<script src="../../assets/js/todolist.html">
<script src="../../assets/js/app.js?rnd=<?php echo rand(10,1000);?>" type='text/javascript'>
function VerificationCode() {
$('#Errscode').html("");
return IsNonEmpty("scode","Errscode","Please enter a received verification code");
return IsNumeric("scode","Errscode","Please enter Numeric characters only");
}
.errorstring {font-size:10px;color:red}
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper auth-page">
<div class="content-wrapper d-flex align-items-center auth auth-bg-1 theme-one">
<div class="row w-100">
<div class="col-lg-4 mx-auto">
<div class="auto-form-wrapper">
<div class="form-group">
<div align="center"> Password
<div class="input-group">
have sent an security code to your email. Please enter the code and continue.
<div class="form-group">
<form action="" method="post" onsubmit="return VerificationCode()">
<input type="hidden" value="<?php echo $_POST['reqEmail'];?>" name="reqEmail">
<input type="hidden" value="<?php echo $_POST['reqID'];?>" name="reqID">
<input type="text" class="form-control" maxlength="4" placeholder="Verification code here ..." id="scode" name="scode" value="<?php echo isset($_POST['scode']) ? $_POST['scode'] : '';?>" >
<span class="errorstring" id="Errscode"><?php echo isset($Errscode)? $Errscode : "";?>
<div class="form-group">
<?php
if (isset($errormessage)) {
echo "<span style='color:red;'>".$errormessage."
}
?>
<button type="submit" class="btn btn-primary submit-btn btn-block" name="btnVerifyCode">Verify your code
<div class="form-group d-flex justify-content-between">
<a href="ForgetPassword.php" class="text-small forgot-password text-black">Back to SignIn | php | 10 | 0.503917 | 214 | 49.326923 | 104 | starcoderdata |
from django.contrib.auth.models import User
from django.test import TestCase
from .models import *
from core.models import Patient, Doctor, Hospital
class AppointmentTests(TestCase):
"""
Tests for appointments
"""
def test_create_appointment(self):
"""
Checks if appointment can be created
:return: True if the appointment is created
"""
date = 10 / 12 / 20
pat = Patient(User, date, "Male", "AB-", 10, 10, None, None, None, None)
doc = Doctor(User, "634-1242")
hosp = Hospital(name = 'Hospital 1')
app = Appointment(patient=pat, doctor=doc, hospital=hosp, appointmentStart='1800-01-01 08:00:00',
appointmentNotes='Note!')
print(app.hospital.name)
self.assertEqual(app.hospital.name != 'Hospital 2', True) | python | 11 | 0.635769 | 105 | 26.787879 | 33 | starcoderdata |
package alararestaurant.service;
import alararestaurant.domain.dtos.orderImportDtos.ItemDto;
import alararestaurant.domain.dtos.orderImportDtos.OrderImportDto;
import alararestaurant.domain.dtos.orderImportDtos.OrderImportRootDto;
import alararestaurant.domain.entities.Employee;
import alararestaurant.domain.entities.Item;
import alararestaurant.domain.entities.Order;
import alararestaurant.domain.entities.OrderItem;
import alararestaurant.repository.EmployeeRepository;
import alararestaurant.repository.ItemRepository;
import alararestaurant.repository.OrderItemRepository;
import alararestaurant.repository.OrderRepository;
import alararestaurant.util.FileUtil;
import alararestaurant.util.ValidationUtil;
import alararestaurant.util.XmlParser;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import javax.xml.bind.JAXBException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import static alararestaurant.common.Constants.*;
@Service
public class OrderServiceImpl implements OrderService {
private static final String ORDERS_FILE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\files\\orders.xml";
private final OrderRepository orderRepository;
private final OrderItemRepository orderItemRepository;
private final EmployeeRepository employeeRepository;
private final ItemRepository itemRepository;
private final FileUtil fileUtil;
private final XmlParser xmlParser;
private final ValidationUtil validationUtil;
private final ModelMapper modelMapper;
public OrderServiceImpl(OrderRepository orderRepository, OrderItemRepository orderItemRepository, EmployeeRepository employeeRepository, ItemRepository itemRepository, FileUtil fileUtil, XmlParser xmlParser, ValidationUtil validationUtil, ModelMapper modelMapper) {
this.orderRepository = orderRepository;
this.orderItemRepository = orderItemRepository;
this.employeeRepository = employeeRepository;
this.itemRepository = itemRepository;
this.fileUtil = fileUtil;
this.xmlParser = xmlParser;
this.validationUtil = validationUtil;
this.modelMapper = modelMapper;
}
@Override
public Boolean ordersAreImported() {
return this.orderRepository.count() > 0;
}
@Override
public String readOrdersXmlFile() throws IOException {
return this.fileUtil.readFile(ORDERS_FILE_PATH);
}
@Override
public String importOrders() throws JAXBException, FileNotFoundException {
StringBuilder importResult = new StringBuilder();
OrderImportRootDto orderImportRootDto = this.xmlParser.parseXml(OrderImportRootDto.class, ORDERS_FILE_PATH);
for (OrderImportDto orderImportDto : orderImportRootDto.getOrderImportDtos()) {
if (!this.validationUtil.isValid(orderImportDto)) {
importResult.append(INVALID_DATA_FORMAT).append(System.lineSeparator());
continue;
}
Employee employee = this.employeeRepository.findByName(orderImportDto.getEmployee()).orElse(null);
if(employee == null){
importResult.append(INVALID_DATA_FORMAT).append(System.lineSeparator());
continue;
}
List itemDtos = orderImportDto.getItemRootDto().getItemDtos();
List orderItems = new ArrayList<>();
boolean hasInvalidItem = false;
for ( ItemDto itemDto: orderImportDto.getItemRootDto().getItemDtos()) {
Item item = this.itemRepository.findByName(itemDto.getName()).orElse(null);
if(item == null){
importResult.append(INVALID_DATA_FORMAT).append(System.lineSeparator());
hasInvalidItem = true;
break;
}
OrderItem orderItem = new OrderItem();
orderItem.setItem(item);
orderItem.setQuantity(itemDto.getQuantity());
orderItems.add(orderItem);
}
if(hasInvalidItem){
continue;
}
LocalDateTime dateTime = LocalDateTime.parse(orderImportDto.getDateTime(), DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
Order order = this.modelMapper.map(orderImportDto, Order.class);
order.setDateTime(dateTime);
order.setOrderItems(orderItems);
order.setEmployee(employee);
Order savedOrder = this.orderRepository.saveAndFlush(order);
if(savedOrder != null){
orderItems.forEach(orderItem -> {
orderItem.setOrder(savedOrder);
OrderItem savedOrderItem = this.orderItemRepository.saveAndFlush(orderItem);
});
savedOrder.setOrderItems(orderItems);
importResult
.append(String.format(SUCCESSFUL_ORDER_IMPORT_MESSAGE, savedOrder.getCustomer(), savedOrder.getDateTime().toString()))
.append(System.lineSeparator());
}
System.out.println();
}
return importResult.toString().trim();
}
@Override
public String exportOrdersFinishedByTheBurgerFlippers() {
StringBuilder result = new StringBuilder();
List orders = this.orderRepository.ordersByBurgerFlippers();
orders.forEach(order -> {
result.append(String.format("Name: %s", order.getEmployee().getName())).append(System.lineSeparator());
result.append("Orders: ").append(System.lineSeparator());
result.append(String.format("\tCustomer: %s", order.getCustomer())).append(System.lineSeparator());
result.append("\tItems: ").append(System.lineSeparator());
order.getOrderItems().forEach(orderItem -> {
result.append(String.format("\t\tName: %s", orderItem.getItem().getName())).append(System.lineSeparator());
result.append(String.format("\t\tPrice: %s", orderItem.getItem().getPrice())).append(System.lineSeparator());
result.append(String.format("\t\tQuantity: %s", orderItem.getQuantity())).append(System.lineSeparator());
result.append(System.lineSeparator());
});
});
return result.toString().trim();
}
} | java | 6 | 0.685023 | 269 | 40.3125 | 160 | starcoderdata |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Data;
//
using System.Windows.Markup;
//
using System.ComponentModel;
namespace ColorPickerLib
{
public class ColorPicker : Control
{
//
//
private Color _colorCache;
//
static ColorPicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorPicker), new FrameworkPropertyMetadata(typeof(ColorPicker)));
}
//
//
public ColorPicker()
{
_colorCache = (Color)ColorProperty.GetMetadata(this).DefaultValue;
SetupColorBindings();
}
//
//
private void SetupColorBindings()
{
MultiBinding binding = new MultiBinding();
binding.Converter = new ByteColorMultiConverter();
binding.Mode = BindingMode.TwoWay;
Binding redBinding = new Binding("Red");
redBinding.Source = this;
redBinding.Mode = BindingMode.TwoWay;
binding.Bindings.Add(redBinding);
Binding greenBinding = new Binding("Green");
greenBinding.Source = this;
greenBinding.Mode = BindingMode.TwoWay;
binding.Bindings.Add(greenBinding);
Binding blueBinding = new Binding("Blue");
blueBinding.Source = this;
blueBinding.Mode = BindingMode.TwoWay;
binding.Bindings.Add(blueBinding);
this.SetBinding(ColorProperty, binding);
}
//
//
public static DependencyProperty ColorProperty = DependencyProperty.Register(
"Color",
typeof(Color),
typeof(ColorPicker),
new PropertyMetadata(Colors.Black));
//
//
public Color Color
{
get
{
return (Color)GetValue(ColorProperty);
}
set
{
SetValue(ColorProperty, value);
}
}
//
//
public static DependencyProperty RedProperty = DependencyProperty.Register(
"Red",
typeof(byte),
typeof(ColorPicker));
public static DependencyProperty GreenProperty = DependencyProperty.Register(
"Green",
typeof(byte),
typeof(ColorPicker));
public static DependencyProperty BlueProperty = DependencyProperty.Register(
"Blue",
typeof(byte),
typeof(ColorPicker));
//
//
public byte Red
{
get { return (byte)GetValue(RedProperty); }
set { SetValue(RedProperty, value); }
}
public byte Green
{
get { return (byte)GetValue(GreenProperty); }
set { SetValue(GreenProperty, value); }
}
public byte Blue
{
get { return (byte)GetValue(BlueProperty); }
set { SetValue(BlueProperty, value); }
}
//
//
//
public static readonly RoutedEvent ColorChangedEvent =
EventManager.RegisterRoutedEvent("ColorChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler typeof(ColorPicker));
//
//
public event RoutedPropertyChangedEventHandler ColorChanged
{
add { AddHandler(ColorChangedEvent, value); }
remove { RemoveHandler(ColorChangedEvent, value); }
}
//
//
protected virtual void OnColorChanged(Color oldValue, Color newValue)
{
RoutedPropertyChangedEventArgs args = new RoutedPropertyChangedEventArgs newValue);
args.RoutedEvent = ColorPicker.ColorChangedEvent;
RaiseEvent(args);
}
//
//
//
//
private static void OnColorInvalidated(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ColorPicker picker = (ColorPicker)d;
Color oldValue = (Color)e.OldValue;
Color newValue = (Color)e.NewValue;
picker.OnColorChanged(oldValue, newValue);
}
//
//
}
//
public class ByteColorMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values.Length != 3)
{
throw new ArgumentException("need three values");
}
byte red = (byte)values[0];
byte green = (byte)values[1];
byte blue = (byte)values[2];
return Color.FromRgb(red, green, blue);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
Color color = (Color)value;
return new object[] { color.R, color.G, color.B };
}
}
//
//
public class ByteDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (double)(byte)value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (byte)(double)value;
}
}
//
//
[ValueConversion(typeof(Color), typeof(SolidColorBrush))]
public class ColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color color = (Color)value;
return new SolidColorBrush(color);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
//
} | c# | 16 | 0.605219 | 156 | 28.346847 | 222 | starcoderdata |
from django.conf import settings
from django.core.files.storage import Storage
from django.utils.functional import cached_property
from requests import Session
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
class HTTPStorage(Storage):
def __init__(self, base_url=None):
self._base_url = base_url
if not self._session:
self._session = Session()
def _value_or_setting(self, value, setting):
return setting if value is None else value
@cached_property
def base_url(self):
if self._base_url is not None and not self._base_url.endswith('/'):
self._base_url += '/'
return self._value_or_setting(self._base_url, settings.MEDIA_URL)
def _url(self, name):
url = urljoin(self.base_url, name.lstrip("/"))
assert(url.startswith(self.base_url))
return url
def url(self, name):
return self._url(name)
def delete(self, name):
self._session.delete(self._url(name))
def exists(self, name):
r = self._session.head(self._url(name))
if r.status_code >= 200 and r.status_code < 300:
return True
if r.status_code == 404:
return False
r.raise_for_status()
def _save(self, name, content):
self._session.put(self._url(name), data=content)
return name
def _open(name, mode='rb'):
raise NotImplementedError() # TODO
Storage = HTTPStorage | python | 12 | 0.704992 | 69 | 23.481481 | 54 | starcoderdata |
import numpy as np
import pandas
def normalize_features(array):
mu = array.mean()
array_normalized = (array-mu)/array.std()
sigma = array.std()
return array_normalized, mu, sigma
def compute_cost(features, values, theta):
m = len(values)
sum_of_square_errors = np.square(np.dot(features, theta) - values).sum()
cost = sum_of_square_errors / (2*m)
return cost
def gradient_descent(features, values, theta, alpha, num_iterations):
m = len(values)
cost_history = []
for i in range(num_iterations):
predicted_values = np.dot(features, theta)
theta = theta - alpha / m * np.dot((predicted_values - values), features)
cost = compute_cost(features, values, theta)
cost_history.append(cost)
print "Theta is ", theta
return theta, pandas.Series(cost_history)
def predictions(dataframe):
dummy_units = pandas.get_dummies(dataframe['UNIT'], prefix='unit')
features = dataframe[['rain', 'precipi', 'Hour', 'meantempi']].join(dummy_units)
values = dataframe[['ENTRIESn_hourly']]
m = len(values)
features, mu, sigma = normalize_features(features)
features['ones'] = np.ones(m)
features_array = np.array(features)
values_array = np.array(values).flatten()
alpha = 0.5
num_iterations = 50
#Initialize theta, perform gradient descent
theta_gradient_descent = np.zeros(len(features.columns))
theta_gradient_descent, cost_history = gradient_descent(features_array, values_array, theta_gradient_descent,
alpha, num_iterations)
predictions = np.dot(features_array, theta_gradient_descent)
return predictions
def compute_r_squared(data, predictions):
data_mean = data.mean()
r_squared = 1 - (
np.sum(np.square(data - predictions)) / np.sum(np.square(data - data_mean))
)
return r_squared
if __name__ == '__main__':
df = pandas.read_csv('./turnstile_data_master_with_weather.csv')
print "Prediction are ", predictions(df)
features['ones'] = np.ones(m)
data = np.array(df['ENTRIESn_hourly']).flatten()
print "R^2 results ", compute_r_squared(data, predictions) | python | 13 | 0.641071 | 113 | 30.111111 | 72 | starcoderdata |
func NewRangeIndex(kv KVStore, name, init []byte) (RangeIndex, error) {
if kv == nil {
return nil, errors.Wrap(ErrInvalid, "KVStore object is nil")
}
kvRange, ok := kv.(KVStoreForRangeIndex)
if !ok {
return nil, errors.Wrap(ErrInvalid, "range index can only be created from KVStoreForRangeIndex")
}
if len(name) == 0 {
return nil, errors.Wrap(ErrInvalid, "bucket name is nil")
}
// check whether init value exist or not
v, err := kv.Get(string(name), MaxKey)
if errors.Cause(err) == ErrNotExist || v == nil {
// write the initial value
if err := kv.Put(string(name), MaxKey, init); err != nil {
return nil, errors.Wrapf(err, "failed to create range index %x", name)
}
}
bucket := make([]byte, len(name))
copy(bucket, name)
return &rangeIndex{
kvstore: kvRange,
bucket: bucket,
}, nil
} | go | 12 | 0.6691 | 98 | 28.392857 | 28 | inline |
def topn_vocabulary(document, TFIDF_model, topn=100):
"""
Find the top n most important words in a document.
Parameters
----------
`document` : The document to find important words in.
`TFIDF_model` : The TF-IDF model that will be used.
`topn`: Default = 100. Amount of top words.
Returns
-------
`dictionary` : A dictionary containing words and their importance as a `float`.
"""
import custom_logic.src.utils
if type(document) == list:
document = " ".join(document)
weight_list = TFIDF_list_of_weigths(TFIDF_model=TFIDF_model, abstract=document)
temp_dict = utils.tuples_to_dict(weight_list[:topn])
return temp_dict | python | 10 | 0.665835 | 98 | 31.12 | 25 | starcoderdata |
public Pair<Integer, Integer> addChildren(Reduction r, int startPos, int childIdx,
HierarchyLayer nextLayer, State positives, State negatives) {
int maxOffset = 0;
int minOffset = nextLayer.getSize();
if (childIdx >= r.getNumSubtasks())
return new Pair<>(minOffset, maxOffset);
String task = r.getSubtask(childIdx);
List<Action> actions = actionMap.get(task);
if (actions != null) {
for (Action a : actions) {
if (childIdx == 0 && !isActionApplicable(a, positives, negatives))
continue;
nextLayer.addAction(startPos + childIdx, a);
// add preconditions, effects @ parentPos+pos(+1)
addActionFacts(a, startPos+childIdx, nextLayer);
maxOffset = Math.max(maxOffset, childIdx+1);
minOffset = Math.min(minOffset, 1);
}
} else {
List<Method> methods = new ArrayList<>();
for (Method m : htnLiftedProblem.getMethods()) {
if (matches(r.getBaseMethod().getSubtasks().get(childIdx), m)) {
m = m.getMethodBoundToArguments(r.getBaseMethod().getSubtasks().get(childIdx).getArguments(), m.getImplicitArguments());
methods.add(m);
}
}
if (!methods.isEmpty()) {
List<Reduction> instMethods = methodIndex.getRelevantReductions(methods);
for (Reduction child : instMethods) {
if (childIdx == 0 && !isReductionApplicable(r, positives, negatives))
continue;
nextLayer.addReduction(startPos + childIdx, child);
maxOffset = Math.max(maxOffset, childIdx+1);
minOffset = Math.min(minOffset, childIdx+1);
}
reductionMap.put(task, instMethods);
}
}
// Add constraints of r @ parentPos+pos
addCondition(r.getConstraint(childIdx+1), startPos+childIdx+1, nextLayer);
if (childIdx == 0)
addCondition(r.getConstraint(childIdx), startPos+childIdx, nextLayer);
return new Pair<>(minOffset, maxOffset);
} | java | 18 | 0.685449 | 125 | 37.104167 | 48 | inline |
/*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#ifndef _RMS_LIB_CACHECONTROL_H
#define _RMS_LIB_CACHECONTROL_H
namespace rmscore {
namespace modernapi {
enum ResponseCacheFlags {
RESPONSE_CACHE_NOCACHE = 0x00,
RESPONSE_CACHE_INMEMORY= 0x01,
RESPONSE_CACHE_ONDISK = 0x02,
RESPONSE_CACHE_CRYPTED = 0x04,
};
} // namespace modernapi
} // namespace rmscore
#endif // _RMS_LIB_CACHECONTROL_H | c | 9 | 0.569343 | 73 | 28.782609 | 23 | starcoderdata |
def _structures_query_for_user(request):
"""Returns query according to users permissions and current tags."""
tags_raw = request.GET.get(QUERY_PARAM_TAGS)
if tags_raw:
tags = tags_raw.split(",")
else:
tags = None
if request.user.has_perm("structures.view_all_structures"):
structures_query = Structure.objects.select_related_defaults()
if tags:
structures_query = structures_query.filter(tags__name__in=tags).distinct()
else:
if request.user.has_perm(
"structures.view_corporation_structures"
) or request.user.has_perm("structures.view_alliance_structures"):
corporation_ids = {
character_ownership.character.corporation_id
for character_ownership in request.user.character_ownerships.all()
}
corporations = list(
EveCorporationInfo.objects.select_related("alliance").filter(
corporation_id__in=corporation_ids
)
)
else:
corporations = []
if request.user.has_perm("structures.view_alliance_structures"):
alliances = {
corporation.alliance
for corporation in corporations
if corporation.alliance
}
for alliance in alliances:
corporations += alliance.evecorporationinfo_set.all()
corporations = list(set(corporations))
structures_query = Structure.objects.select_related_defaults().filter(
owner__corporation__in=corporations
)
structures_query = structures_query.prefetch_related("tags", "services").annotate(
has_poco_details=Exists(PocoDetails.objects.filter(structure_id=OuterRef("id")))
)
return structures_query | python | 17 | 0.60827 | 88 | 37.3125 | 48 | inline |
<?php
class siswa2 extends CI_Controller {
public function index()
{
$data['result'] = $this->Mpresensi->getListsiswa();
$data['welcome'] = true;
$this->load->view('welcome_message',$data);
}
public function add($id=NULL){
$data['welcome'] = true;
$data['result'] = $this->Mpresensi->getList();
$this->load->library('form_validation');
$submit = $this->input->post('submit');
if ($submit){
$nisn = $this->input->post('nisn');
$this->form_validation->set_rules('nisn', 'NISN', 'required');
if ($this->form_validation->run()==FALSE){
$data['errors'] = TRUE;
} else {
$error = array();
// cek apakah sedang dipinjam atau tidak
if (!$this->Mpresensi->cekpresensi($nomor_kendaraan, true)){
$error[] = "Anda berhasil melakukan presensi ".$nisn;
}
if (!$error){
$data['result'] = $this->Mpresensi->getList($nisn);
} else {
$data['error'] = $error;
$data['result'] = $this->Mpresensi->getList();
}
}
}
$this->load->view('welcome_message', $data);
}
} | php | 18 | 0.466565 | 76 | 32.769231 | 39 | starcoderdata |
package dbtools.schemagen;
import com.google.common.base.Joiner;
import dbtools.cmdopts.CmdEnv;
import dbtools.cmdopts.CmdRegistry;
import dbtools.cmdopts.ToolOptionParser;
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
new Commands(new CmdEnv()).showHelp(null);
}
CmdEnv env = new CmdEnv();
new CmdRegistry(new Commands(env))
.process(new ToolOptionParser()
.parse(Joiner.on(' ').join(args)));
}
} | java | 13 | 0.616822 | 59 | 23.318182 | 22 | starcoderdata |
def wordnet_get_glosses(_word,_sense_id):
"""
given a wordnet word (the lemma of the target word) number returns tuple of term glosses
the first one corresponds to the _sense_id, the 2nd on is a list
of all other glosses
"""
_sense_id = int(_sense_id)
if not _word: # if ref is empty
return ''
try:
all_synsets = wn.synsets(_word)
target_gloss = []
other_glosses = []
for syn in all_synsets:
split = syn.name().split('.')
wn_lemma = split[0]
sense_num = int(split[-1])
#if _word == wn_lemma:
if sense_num == _sense_id:
target_gloss.append(syn.definition())
else:
other_glosses.append(syn.definition())
return target_gloss,other_glosses
except (AttributeError,WordNetError,ValueError) as err:
return 'WN Error',None | python | 15 | 0.553283 | 92 | 36.2 | 25 | inline |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using ShaderTools.CodeAnalysis.Diagnostics;
using ShaderTools.CodeAnalysis.ShaderLab.Diagnostics;
using ShaderTools.CodeAnalysis.ShaderLab.Syntax;
using ShaderTools.CodeAnalysis.Text;
namespace ShaderTools.CodeAnalysis.ShaderLab.Parser
{
internal partial class UnityParser
{
private readonly UnityLexer _lexer;
private readonly List _tokens = new List
private int _tokenIndex;
private CancellationToken _cancellationToken;
public UnityParser(UnityLexer lexer)
{
_lexer = lexer;
}
protected SyntaxToken Current => Peek(0);
protected SyntaxToken Lookahead => Peek(1);
private int EnsureToken(int tokenIndex)
{
_cancellationToken.ThrowIfCancellationRequested();
if (_tokens.Any() && _tokens.Last().Kind == SyntaxKind.EndOfFileToken && tokenIndex == _tokens.Count - 1)
return _tokens.Count - 1;
List badTokens = null;
while (tokenIndex >= _tokens.Count)
{
var token = _lexer.Lex();
// Skip any bad tokens.
if (token.Kind == SyntaxKind.BadToken)
{
if (badTokens == null)
badTokens = new List
badTokens.Clear();
while (token.Kind == SyntaxKind.BadToken)
{
badTokens.Add(token);
token = _lexer.Lex();
}
}
if (badTokens != null && badTokens.Count > 0)
{
var trivia = ImmutableArray.Create(CreateSkippedTokensTrivia(badTokens))
.Concat(token.LeadingTrivia).ToImmutableArray();
token = token.WithLeadingTrivia(trivia);
}
_tokens.Add(token);
if (token.Kind == SyntaxKind.EndOfFileToken)
break;
}
return Math.Min(tokenIndex, _tokens.Count - 1);
}
private SyntaxToken Peek(int offset)
{
var i = EnsureToken(_tokenIndex + offset);
return _tokens[i];
}
protected SyntaxToken NextToken()
{
var result = Current;
_tokenIndex++;
return result;
}
private SyntaxToken NextTokenWithPrejudice(SyntaxKind kind)
{
var result = Current;
if (result.Kind != kind)
{
var diagnostics = new List
diagnostics.ReportTokenExpected(result.SourceRange, result, kind);
result = result.WithDiagnostics(diagnostics);
}
NextToken();
return result;
}
protected SyntaxToken NextTokenIf(SyntaxKind kind)
{
return Current.Kind == kind
? NextToken()
: null;
}
protected SyntaxToken Match(SyntaxKind kind)
{
if (Current.Kind == kind)
return NextToken();
if (Lookahead.Kind == kind)
{
// Skip current token, and carry on parsing.
var skippedTokensTrivia = CreateSkippedTokensTrivia(new[] { Current });
var diagnostics = new List
diagnostics.ReportTokenUnexpected(Current.SourceRange, Current);
NextToken();
var result = Current.WithDiagnostics(diagnostics).WithLeadingTrivia(new[] { skippedTokensTrivia });
NextToken();
return result;
}
// TODO: NQuery checks if user is currently typing an identifier, and
// the partial identifier is a keyword.
return InsertMissingToken(kind);
}
protected SyntaxToken MatchOneOf(SyntaxKind preferred, params SyntaxKind[] otherOptions)
{
var allOptions = new[] { preferred }.Concat(otherOptions).ToList();
if (allOptions.Contains(Current.Kind))
return NextToken();
if (allOptions.Contains(Lookahead.Kind))
{
// Skip current token, and carry on parsing.
var skippedTokensTrivia = CreateSkippedTokensTrivia(new[] { Current });
var diagnostics = new List
diagnostics.ReportTokenUnexpected(Current.SourceRange, Current);
NextToken();
var result = Current.WithDiagnostics(diagnostics).WithLeadingTrivia(new[] { skippedTokensTrivia });
NextToken();
return result;
}
// TODO: NQuery checks if user is currently typing an identifier, and
// the partial identifier is a keyword.
return InsertMissingToken(preferred, otherOptions);
}
protected TNode WithDiagnostic node, DiagnosticId diagnosticId, params object[] args)
where TNode : SyntaxNode
{
var diagnostic = Diagnostic.Create(ShaderLabMessageProvider.Instance, node.SourceRange, (int) diagnosticId, args);
return node.WithDiagnostic(diagnostic);
}
protected SyntaxToken InsertMissingToken(SyntaxKind kind)
{
var missingTokenSourceRange = new SourceRange(Current.FullSourceRange.Start, 0);
var diagnosticSpan = GetDiagnosticSourceRangeForMissingToken();
var diagnostics = new List
diagnostics.ReportTokenExpected(diagnosticSpan, Current, kind);
return SyntaxToken.CreateMissing(kind, missingTokenSourceRange, GetSourceFileSpan(missingTokenSourceRange)).WithDiagnostics(diagnostics);
}
protected SyntaxToken InsertMissingToken(SyntaxKind preferred, SyntaxKind[] otherOptions)
{
var missingTokenSourceRange = new SourceRange(Current.FullSourceRange.Start, 0);
var diagnosticSpan = GetDiagnosticSourceRangeForMissingToken();
var diagnostics = new List
diagnostics.ReportTokenExpectedMultipleChoices(diagnosticSpan, Current, new[] { preferred }.Concat(otherOptions));
return SyntaxToken.CreateMissing(preferred, missingTokenSourceRange, GetSourceFileSpan(missingTokenSourceRange)).WithDiagnostics(diagnostics);
}
private SourceFileSpan GetSourceFileSpan(SourceRange sourceRange)
{
return new SourceFileSpan(new SourceFile(_lexer.Text), new TextSpan(sourceRange.Start.Position, sourceRange.Length));
}
protected SourceRange GetDiagnosticSourceRangeForMissingToken()
{
if (_tokenIndex > 0)
{
var previousToken = _tokens[_tokenIndex - 1];
if (previousToken.TrailingTrivia.Any(x => x.Kind == SyntaxKind.EndOfLineTrivia))
return new SourceRange(previousToken.SourceRange.End, 2);
}
return Current.SourceRange;
}
private StructuredTriviaSyntax CreateSkippedTokensTrivia(IReadOnlyCollection tokens)
{
return new SkippedTokensTriviaSyntax(tokens);
}
}
} | c# | 25 | 0.576299 | 154 | 34.602804 | 214 | starcoderdata |
using System;
using UnityEngine;
namespace CustomBanners.Animations
{
// Borrowed mostly from ImageFactory which is mostly borrowed from BSML
internal class RendererAnimationControllerData
{
private int _uvIndex;
private readonly float[] _delays;
private readonly Texture2D[] _textures;
private readonly bool _isDelayConsistent = true;
public DateTime lastSwitch = DateTime.UtcNow;
public RendererAnimationControllerData(Texture2D[] textures, float[] delays)
{
_delays = delays;
_textures = textures;
float firstDelay = -1;
for (int i = 0; i < delays.Length; i++)
{
if (i == 0)
firstDelay = delays[i];
if (delays[i] != firstDelay)
_isDelayConsistent = false;
}
}
internal Texture2D CheckFrame(DateTime now)
{
double differenceMs = (now - lastSwitch).TotalMilliseconds;
if (differenceMs < _delays[_uvIndex])
return null;
if (_isDelayConsistent && _delays[_uvIndex] <= 10 && differenceMs < 100)
{
// Bump animations with consistently 10ms or lower frame timings to 100ms
return null;
}
lastSwitch = now;
do
{
_uvIndex++;
if (_uvIndex >= _textures.Length)
_uvIndex = 0;
}
while (!_isDelayConsistent && _delays[_uvIndex] == 0);
return _textures[_uvIndex];
}
}
} | c# | 15 | 0.522479 | 89 | 29.481481 | 54 | starcoderdata |
private bool AddElementInstancesAndDeploymentNodesAndInfrastructureNodes(DeploymentNode deploymentNode, bool addRelationships)
{
bool hasElementsInstancesOrInfrastructureNodes = false;
foreach (SoftwareSystemInstance softwareSystemInstance in deploymentNode.SoftwareSystemInstances)
{
try {
AddElement(softwareSystemInstance, addRelationships);
hasElementsInstancesOrInfrastructureNodes = true;
} catch (ElementNotPermittedInViewException e) {
// the element can't be added, so ignore it
}
}
foreach (ContainerInstance containerInstance in deploymentNode.ContainerInstances)
{
Container container = containerInstance.Container;
if (SoftwareSystem == null || container.Parent.Equals(SoftwareSystem))
{
try
{
AddElement(containerInstance, addRelationships);
hasElementsInstancesOrInfrastructureNodes = true;
} catch (ElementNotPermittedInViewException e) {
// the element can't be added, so ignore it
}
}
}
foreach (InfrastructureNode infrastructureNode in deploymentNode.InfrastructureNodes)
{
AddElement(infrastructureNode, addRelationships);
hasElementsInstancesOrInfrastructureNodes = true;
}
foreach (DeploymentNode child in deploymentNode.Children)
{
hasElementsInstancesOrInfrastructureNodes = hasElementsInstancesOrInfrastructureNodes | AddElementInstancesAndDeploymentNodesAndInfrastructureNodes(child, addRelationships);
}
if (hasElementsInstancesOrInfrastructureNodes)
{
AddElement(deploymentNode, addRelationships);
}
return hasElementsInstancesOrInfrastructureNodes;
} | c# | 14 | 0.603325 | 189 | 43.808511 | 47 | inline |
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.function;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.function.context.FunctionCatalog;
import org.springframework.cloud.function.context.catalog.FunctionInspector;
import org.springframework.cloud.stream.config.BindingServiceProperties;
import org.springframework.cloud.stream.converter.CompositeMessageConverterFactory;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
/**
* @author
* @author
* @author
* @since 2.1
*/
@Configuration
@ConditionalOnProperty("spring.cloud.stream.function.definition")
@EnableConfigurationProperties(StreamFunctionProperties.class)
public class FunctionConfiguration {
@Autowired(required = false)
private Source source;
@Autowired(required = false)
private Processor processor;
@Autowired(required = false)
private Sink sink;
@Bean
public IntegrationFlowFunctionSupport functionSupport(
FunctionCatalog functionCatalog, FunctionInspector functionInspector,
CompositeMessageConverterFactory messageConverterFactory,
StreamFunctionProperties functionProperties,
BindingServiceProperties bindingServiceProperties) {
return new IntegrationFlowFunctionSupport(functionCatalog, functionInspector,
messageConverterFactory, functionProperties, bindingServiceProperties);
}
// @Bean
// public FunctionCatalogWrapper functionCatalogWrapper(FunctionCatalog catalog) {
// return new FunctionCatalogWrapper(catalog);
// }
/**
* This configuration creates an instance of the {@link IntegrationFlow} from standard
* Spring Cloud Stream bindings such as {@link Source}, {@link Processor} and
* {@link Sink} ONLY if there are no existing instances of the {@link IntegrationFlow}
* already available in the context. This means that it only plays a role in
* green-field Spring Cloud Stream apps.
*
* For logic to compose functions into the existing apps please see
* "FUNCTION-TO-EXISTING-APP" section of AbstractMessageChannelBinder.
*
* The @ConditionalOnMissingBean ensures it does not collide with the the instance of
* the IntegrationFlow that may have been already defined by the existing (extended)
* app.
* @param functionSupport support for registering beans
* @return integration flow for Stream
*/
@ConditionalOnMissingBean
@Bean
public IntegrationFlow integrationFlowCreator(
IntegrationFlowFunctionSupport functionSupport) {
if (functionSupport.containsFunction(Consumer.class)
&& consumerBindingPresent()) {
return functionSupport
.integrationFlowForFunction(getInputChannel(), getOutputChannel())
.get();
}
else if (functionSupport.containsFunction(Function.class)
&& consumerBindingPresent()) {
return functionSupport
.integrationFlowForFunction(getInputChannel(), getOutputChannel())
.get();
}
else if (functionSupport.containsFunction(Supplier.class)) {
return functionSupport.integrationFlowFromNamedSupplier()
.channel(getOutputChannel()).get();
}
return null;
}
private boolean consumerBindingPresent() {
return this.processor != null || this.sink != null;
}
private SubscribableChannel getInputChannel() {
return this.processor != null ? this.processor.input() : this.sink.input();
}
private MessageChannel getOutputChannel() {
return this.processor != null ? this.processor.output()
: (this.source != null ? this.source.output() : new NullChannel());
}
} | java | 15 | 0.793158 | 148 | 37.9 | 130 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows;
namespace EasyWord.UI
{
public class BusyIndicator : UserControl
{
private static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register("IsBusy", typeof(bool), typeof(BusyIndicator), new PropertyMetadata(false, new PropertyChangedCallback(IsBusyPropertyChanged)));
private static void IsBusyPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
BusyIndicator bi = sender as BusyIndicator;
if (bi != null)
{
bi.OnIsBusyPropertyChanged(e.OldValue, e.NewValue);
}
}
public bool IsBusy
{
get
{
return (bool)this.GetValue(IsBusyProperty);
}
set
{
this.SetValue(IsBusyProperty, value);
if (value)
{
this.Visibility = Visibility.Visible;
}
else
{
this.Visibility = Visibility.Collapsed;
}
}
}
public BusyIndicator()
{
this.InitializeComponent();
this.Loaded += new RoutedEventHandler(BusyIndicator_Loaded);
}
void BusyIndicator_Loaded(object sender, RoutedEventArgs e)
{
if (this.Parent != null)
{
FrameworkElement fe = this.Parent as FrameworkElement;
//this.Margin = new Thickness((fe.ActualWidth - this.ActualWidth) / 2, (fe.ActualHeight - this.ActualHeight) / 2, 0, 0);
}
}
private void InitializeComponent()
{
this.HorizontalAlignment = HorizontalAlignment.Center;
this.HorizontalContentAlignment = HorizontalAlignment.Center;
this.VerticalAlignment = VerticalAlignment.Center;
this.VerticalContentAlignment = VerticalAlignment.Center;
this.IsBusy = false;
Grid g = new Grid();
//g.Width = 200;
//g.Height = 200;
this.Content = g;
List lstPath = new List
double dAnimationTimeSpan = 1000.0d / 12.0d;
for (int i = 0; i < 12; i++)
{
Path p = new Path();
p.Data = Geometry.Parse("M 0,0 L -10,0 L -10,50 L 0,60 L 10,50 L 10,0 Z");//路径标记语法
p.Opacity = 0.2;
p.Fill = new SolidColorBrush(Colors.LightBlue);
p.Stroke = new SolidColorBrush(Colors.DarkBlue);
p.StrokeThickness = 1;
TransformGroup tg = new TransformGroup();
p.RenderTransform = tg;
TranslateTransform tt = new TranslateTransform();//平移变换
tt.Y = 50;
RotateTransform rt = new RotateTransform();//旋转变换
rt.Angle = i * 30;
tg.Children.Add(tt);
tg.Children.Add(rt);
DoubleAnimation da = new DoubleAnimation();
da.Duration = new Duration(TimeSpan.FromSeconds(1));
da.From = 1.0;
da.To = 0.2;
da.BeginTime = TimeSpan.FromMilliseconds(dAnimationTimeSpan * i);
da.RepeatBehavior = RepeatBehavior.Forever;
g.Children.Add(p);
p.BeginAnimation(Path.OpacityProperty, da);
}
}
protected void OnIsBusyPropertyChanged(object oldValue, object newValue)
{
this.IsBusy = (bool)newValue;
}
}
} | c# | 18 | 0.542255 | 224 | 33.451327 | 113 | starcoderdata |
@Test
void testDropdown_isMultiple() {
Select carsDD = new Select(webDriver.findElement(By.tagName("select")));
//size of dropdown
Assertions.assertEquals(4, carsDD.getOptions().size());
//is multi-select dropdown
Assertions.assertFalse(carsDD.isMultiple());
//choose a selection from dropdown
carsDD.selectByVisibleText("Opel");
Assertions.assertEquals("Opel", carsDD.getFirstSelectedOption().getText());
carsDD.selectByIndex(1);
Assertions.assertEquals("Saab", carsDD.getFirstSelectedOption().getText());
} | java | 12 | 0.719424 | 79 | 31.764706 | 17 | inline |
def clustering(args, W_hat, beta, method='hclust'):
if method == 'hclust':
R, T, sil_score = hcluster_silhouette(args,
W_hat,
beta,
ax = None,
affinity='euclidean',
normalize = True,
weighted = False)
roworder = np.array(R['leaves'])[::-1]
T_sorted = T[roworder] - 1 # start from 0
return T_sorted, sil_score, roworder | python | 12 | 0.351525 | 65 | 47 | 13 | inline |
def get_job_tags(self) -> Dict[str, str]:
"""Get job tags
Returns:
Dict[str, str]: a dict of job tags
"""
assert self.res_job_id is not None
# For Job Runs APIs, see https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--runs-get
result = requests.get(url=self.workspace_instance_url+'/api/2.0/jobs/runs/get',
headers=self.auth_headers, params={'run_id': str(self.res_job_id)})
custom_tags = result.json()['cluster_spec']['new_cluster']['custom_tags']
return custom_tags | python | 13 | 0.586957 | 116 | 48.916667 | 12 | inline |
package org.jboss.weld.bootstrap;
import org.jboss.weld.literal.AnyLiteral;
import org.jboss.weld.literal.DefaultLiteral;
import javax.enterprise.context.spi.Context;
import java.lang.annotation.Annotation;
import java.util.Set;
import static org.jboss.weld.util.collections.Arrays2.asSet;
public class ContextHolder<T extends Context> {
private final T context;
private final Class type;
private final Set qualifiers;
public ContextHolder(T context, Class type, Annotation qualifier) {
super();
this.context = context;
this.type = type;
this.qualifiers = asSet(DefaultLiteral.INSTANCE, AnyLiteral.INSTANCE, qualifier);
}
public T getContext() {
return context;
}
public Class getType() {
return type;
}
public Set getQualifiers() {
return qualifiers;
}
} | java | 8 | 0.704733 | 89 | 24.578947 | 38 | starcoderdata |
'use strict'
let rl = require('readline').createInterface({
input: require('fs').createReadStream('./src/day9/input.txt')
})
let lookups = []
let places = []
rl.on('line', function (line) {
let split = line.split(' ')
let from = split[0]
let to = split[2]
let delta = split[4]
lookups[from + to] = +delta
lookups[to + from] = +delta
if (places.indexOf(from) === -1) {
places.push(from)
}
if (places.indexOf(to) === -1) {
places.push(to)
}
})
rl.on('close', function () {
rl.close()
var p = permutate(places)
let max = 0
for (let i = 0; i < p.length; i++) {
let dist = 0
for (let j = 0; j < p[i].length - 1; j++) {
dist += lookups[p[i][j] + p[i][j + 1]]
}
if (dist > max) {
max = dist
}
}
console.log(max)
})
function permutate (list) {
if (list.length === 0) {
return [[]]
}
var result = []
for (var i = 0; i < list.length; i++) {
var copy = Object.create(list)
var head = copy.splice(i, 1)
var rest = permutate(copy)
for (var j = 0; j < rest.length; j++) {
var next = head.concat(rest[j])
result.push(next)
}
}
return result
} | javascript | 16 | 0.536145 | 63 | 17.444444 | 63 | starcoderdata |
#ifndef LINUX_BCM47XX_WDT_H_
#define LINUX_BCM47XX_WDT_H_
#include
#include
#include
#include
struct bcm47xx_wdt {
u32 (*timer_set)(struct bcm47xx_wdt *, u32);
u32 (*timer_set_ms)(struct bcm47xx_wdt *, u32);
u32 max_timer_ms;
void *driver_data;
struct watchdog_device wdd;
struct notifier_block notifier;
struct timer_list soft_timer;
atomic_t soft_ticks;
};
static inline void *bcm47xx_wdt_get_drvdata(struct bcm47xx_wdt *wdt)
{
return wdt->driver_data;
}
#endif /* LINUX_BCM47XX_WDT_H_ */ | c | 9 | 0.723005 | 68 | 21.034483 | 29 | starcoderdata |
#pragma once
#include
#include
#include
#include
#include
#include
#include
#include | c | 5 | 0.805774 | 44 | 26.285714 | 14 | starcoderdata |
#include<stdio.h>
int main(void)
{
int rc[5],ac[5];
int r,a;
int i,j;
int hit,blow;
scanf("%d %d",&r,&a);
while(r!=0 && a!=0){
hit=0;
blow=0;
for(i=3;i>=0;i--){
rc[i]=r%10;
r=r/10;
ac[i]=a%10;
a=a/10;
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(rc[i]==ac[j]){
blow++;
}
}
if(rc[i]==ac[i]){
hit++;
}
}
blow=blow-hit;
printf("%d %d\n",hit,blow);
scanf("%d %d",&r,&a);
}
return 0;
} | c | 13 | 0.427928 | 29 | 12.088235 | 34 | codenet |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TopGearApi.Access;
using TopGearApi.Domain.Models;
using TopGearApi.Promotions;
namespace TopGearApi.Console
{
class Program
{
static void Main(string[] args)
{
Promotion p = new Promotion
{
CategoriaId = TopGearApi
Validade = new DateTime(2017, 12, 31),
Valor = 499.99,
QtdDias = 4
};
PromotionBusController.PostPromotion(p);
Promotion p2 = PromotionBusController.GetPromotion();
System.Console.WriteLine("Valor: " + p2.Valor + ", QtdDias: " + p2.QtdDias);
System.Console.ReadLine();
}
}
} | c# | 24 | 0.597914 | 101 | 25.96875 | 32 | starcoderdata |
<?php
$router->add('/', array(
'module' => 'frontend',
'controller' => 'index',
'action' => 'index',
));
$router->add('#^/articles[/]{0,1}$#', array(
'module' => 'frontend',
'controller' => 'article',
'action' => 'list',
));
$router->add('#^/articles/([a-zA-Z0-9\-]+)[/]{0,1}$#', array(
'module' => 'frontend',
'controller' => 'article',
'action' => 'read',
'slug' => 1,
)); | php | 8 | 0.47482 | 61 | 20.947368 | 19 | starcoderdata |
package org.openweathermap.api.example;
import org.openweathermap.api.DataWeatherClient;
import org.openweathermap.api.UrlConnectionDataWeatherClient;
import org.openweathermap.api.model.forecast.ForecastInformation;
import org.openweathermap.api.model.forecast.hourly.HourlyForecast;
import org.openweathermap.api.query.Language;
import org.openweathermap.api.query.QueryBuilderPicker;
import org.openweathermap.api.query.UnitFormat;
import org.openweathermap.api.query.forecast.hourly.ByCityName;
public class HourlyForecastExample {
private static final String API_KEY = "590661e9a75d81f118714bd102422eae";
public static void main(String[] args) {
DataWeatherClient client = new UrlConnectionDataWeatherClient(API_KEY);
ByCityName byCityNameForecast = QueryBuilderPicker.pick()
.forecast() // get forecast
.hourly() // it should be hourly forecast
.byCityName("Frydrychowice") // for Kharkiv city
.countryCode("PL") // in Ukraine
.unitFormat(UnitFormat.METRIC) // in Metric units
.language(Language.ENGLISH) // in English
.count(5) // limit results to 5 forecasts
.build();
ForecastInformation forecastInformation = client.getForecastInformation(byCityNameForecast);
System.out.println("Forecasts for " + forecastInformation.getCity() + ":");
for (HourlyForecast forecast : forecastInformation.getForecasts()) {
System.out.println(prettyPrint(forecast));
}
}
private static String prettyPrint(HourlyForecast hourlyForecast) {
return String.format(
"Forecast for %s:\ntemperature: %.1f ℃\nhumidity: %.1f %%\npressure: %.1f hPa\n",
hourlyForecast.getDateTime().toString(),
hourlyForecast.getMainParameters().getTemperature(),
hourlyForecast.getMainParameters().getHumidity(),
hourlyForecast.getMainParameters().getPressure()
);
}
} | java | 17 | 0.619048 | 116 | 52.232558 | 43 | starcoderdata |
//Fix the error
function myFunction() {
let myObject = {
objProperty: 'some text',
objMethod: function() {
console.log(myObject);
}
};
myObject.objMethod();
}
myFunction(); | javascript | 12 | 0.540179 | 34 | 15 | 14 | starcoderdata |
using EHM_Files_Editor.Resources;
using System.ComponentModel.DataAnnotations;
namespace EHM_Files_Editor.Enums
{
///
/// Représente l'énumération des pays.
///
public enum CountryEnum
{
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Canada))]
Canada = 1,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.USA))]
USA = 2,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Russia))]
Russia = 3,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Czech))]
Czech = 4,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Sweden))]
Sweden = 5,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Finland))]
Finland = 6,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Belarus))]
Belarus = 7,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Slovakia))]
Slovakia = 8,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Norway))]
Norway = 9,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Germany))]
Germany = 10,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Others))]
Others = 11,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Italia))]
Italia = 12,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Austria))]
Austria = 13,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Latvia))]
Latvia = 14,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Ukraine))]
Ukraine = 15,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Slovenia))]
Slovenia = 16,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Switzerland))]
Switzerland = 17,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Polonia))]
Polonia = 18,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.France))]
France = 19,
[Display(ResourceType = typeof(GlobalResx), Name = nameof(GlobalResx.Japan))]
Japan = 20,
}
} | c# | 14 | 0.690538 | 87 | 31 | 72 | starcoderdata |
public void Start()
{
double t = 0.0;
int index = 0;
Random rand = new Random();
while (t < tn)
{
double tau = GenPoisson(lambda);
//Console.WriteLine("tau {0} {1}", index, tau);
ls1.Add(tau);
t = t + tau;
Client client = new Client();
client.FullName = index.ToString();
addClient(client);
Thread.Sleep((int)tau * 1000);
index++;
}
//Console.Write("\nPress any key to continue... ");
//Console.ReadKey();
} | c# | 13 | 0.399698 | 63 | 32.2 | 20 | inline |
Ext.define('App.view.canvas.users.UserGrid', {
extend: 'App.view.baseComponents.BaseGrid',
xtype: 'user-grid',
requires: [
'Ext.ProgressBar',
'Ext.Action',
'Ext.toolbar.Paging',
'Ext.ux.ProgressBarPager'
],
controller: 'users',
width: '100%',
height: 523,
allowDeselect: true,
defaultActionType: 'button',
initComponent: function() {
var me = this;
Ext.apply(me, {
title: Literal.manageUsers,
store: Ext.data.StoreManager.lookup('UserStore'),
columns: me.buildColumns(),
viewConfig: {
listeners: {
itemcontextmenu: 'onGridContextMenu'
}
},
});
me.callParent(arguments);
},
bbar: {
xtype: 'pagingtoolbar',
displayInfo: true,
plugins: {
'ux-progressbarpager': true
}
},
tbar: {
xtype: 'toolbar',
items:{xtype:'textfield'}
},
actions: {
edit: {
iconCls: 'blue-icon x-fa fa-pencil',
text: 'Edit',
handler: 'onEdit'
},
remove: {
iconCls: 'blue-icon x-fa fa-trash',
text: 'Sell stock',
handler: 'onRemove'
}
},
buildColumns: function() {
var me = this;
return [{
text: Literal.id,
flex: 1,
hidden: true,
dataIndex: 'id'
}, {
text: Literal.name.toUpperCase(),
flex: 2,
dataIndex: 'name'
}, {
text: Literal.emailId.toUpperCase(),
flex: 2,
dataIndex: 'emailId'
}, {
text: Literal.contactNo.toUpperCase(),
flex: 1,
dataIndex: 'contactNo'
}, {
text: Literal.userType.toUpperCase(),
flex: 0.8,
dataIndex: 'role'
}, {
text: Literal.modifiedDate.toUpperCase(),
flex: 1,
renderer: function(v) {
return new Date(v);
},
dataIndex: 'modifiedDate'
}, {
xtype: 'actioncolumn',
text: Literal.action.toUpperCase(),
width: 70,
menuDisabled: true,
sortable: false,
items: ['@edit', '@remove']
}];
},
signTpl: '<span style="' +
'color:{value:sign(\'"#cf4c35"\',\'"#73b51e"\')}"' +
'>{text}
}); | javascript | 18 | 0.434156 | 61 | 25.185567 | 97 | starcoderdata |
#!/usr/bin/env python
#
# Copyright 2012 cloudysunny14.
#
# 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.
""" This is a sample application that Lakshmi an web crawler.
"""
__author__ = """ (
import re
import os
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import ndb
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.api import memcache
from mapreduce import base_handler
from lakshmi import pipelines
from lakshmi.datum import CrawlDbDatum
from lakshmi.datum import LinkDbDatum
from lakshmi.datum import ContentDbDatum
from lakshmi.datum import FetchedDbDatum
from lakshmi.cooperate import cooperate
from jinja2 import Environment, FileSystemLoader
ENTITY_KIND = "lakshmi.datum.CrawlDbDatum"
#specified some urls
def htmlParser(key, content):
outlinks = re.findall(r'href=[\'"]?([^\'" >]+)', content)
CrawlDbDatum
link_datums = []
for link in outlinks:
link_datum = LinkDbDatum(parent=key, link_url=link)
link_datums.append(link_datum)
ndb.put_multi(link_datums)
content_links = re.findall(r'src=[\'"]?([^\'" >]+)', content)
return content_links
class FecherJobPipeline(base_handler.PipelineBase):
def run(self, email):
memcache.set(key="email", value=email)
yield pipelines.FetcherPipeline("FetcherPipeline",
params={
"entity_kind": ENTITY_KIND
},
parser_params={
"text/html": "main.htmlParser",
"application/rss+xml": "main.htmlParser",
"application/atom+xml": "main.htmlParser",
"text/xml": "main.htmlParser"
},
shards=4)
def finalized(self):
"""Sends an email to admins indicating this Pipeline has completed.
For developer convenience. Automatically called from finalized for root
Pipelines that do not override the default action.
"""
status = 'successful'
if self.was_aborted:
status = 'aborted'
url = memcache.get("url")
email = memcache.get("email")
base_dir = os.path.realpath(os.path.dirname(__file__))
# Configure jinja for internal templates
env = Environment(
autoescape=True,
extensions=['jinja2.ext.i18n'],
loader=FileSystemLoader(
os.path.join(base_dir, 'templates')
)
)
subject = "Your Fetcher Job is "+status
crawl_db_datum = crawl_db_datums = CrawlDbDatum.query(CrawlDbDatum.url==url).fetch()
crawl_db_datum = crawl_db_datums[0]
content_db_datums = ContentDbDatum.query(ancestor=crawl_db_datum.key).fetch_async()
fetched_db_datums = FetchedDbDatum.query(ancestor=crawl_db_datum.key).fetch()
attachments = []
if len(fetched_db_datums)>0:
fetched_db_datum = fetched_db_datums[0]
attachments.append(("fetched_content.html", fetched_db_datum.fetched_content))
link_db_datums = LinkDbDatum.query(ancestor=crawl_db_datum.key).fetch_async()
html = env.get_template("mail_template.html").render(url=url,
contents=content_db_datums, links=link_db_datums)
attachments.append(("sendmail.html", html))
sender = "
mail.send_mail(sender=sender, to=email, subject=subject,
body="FetchResults", html=html, attachments=attachments)
class FetchStart(webapp.RequestHandler):
def get(self):
url = self.request.get("target", default_value=None)
email = self.request.get("email", default_value=None)
if url is None:
url = memcache.get("url")
else:
memcache.set(key="url", value=url)
if email is None:
return
data = CrawlDbDatum(
parent =ndb.Key(CrawlDbDatum, url),
url=url,
last_status=pipelines.UNFETCHED)
data.put()
pipeline = FecherJobPipeline(email)
pipeline.start()
path = pipeline.base_path + "/status?root=" + pipeline.pipeline_id
self.redirect(path)
class DeleteDatumHandler(webapp.RequestHandler):
def get(self):
pipeline = pipelines.CleanDatumPipeline("CleanAllDatumPipeline",
params={
"entity_kind": ENTITY_KIND
},
clean_all=True,
shards=8)
pipeline.start()
path = pipeline.base_path + "/status?root=" + pipeline.pipeline_id
self.redirect(path)
#Cooperate Handlers
FETCHED_DATUM_ENTITY_KIND = "lakshmi.datum.FetchedDatum"
GS_BUCKET = "your_backet_name"
class ExportHandler(webapp.RequestHandler):
def get(self):
pipeline = cooperate.ExportCloudStoragePipeline("ExportCloudStoragePipeline",
input_entity_kind="lakshmi.datum.FetchedDatum",
gs_bucket_name=GS_BUCKET,
shards=3)
pipeline.start()
path = pipeline.base_path + "/status?root=" + pipeline.pipeline_id
self.redirect(path)
application = webapp.WSGIApplication(
[("/start", FetchStart),
("/clean_all", DeleteDatumHandler),
("/export", ExportHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | python | 15 | 0.66637 | 88 | 33.478528 | 163 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.