identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/baranovxyz/next-global-css/blob/master/__tests__/__fixtures__/3d-party-library/component/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
next-global-css
|
baranovxyz
|
JavaScript
|
Code
| 18
| 50
|
const React = require('react')
require('./styles.css')
module.exports.Component = () => {
return React.createElement('div', { className: 'Component' }, 'Component!')
}
| 17,881
|
https://github.com/madun/bawaslu-admin/blob/master/application/controllers/Jobvacancies.php
|
Github Open Source
|
Open Source
|
MIT
| null |
bawaslu-admin
|
madun
|
PHP
|
Code
| 149
| 649
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Jobvacancies extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('model_jobVacancies');
}
public function index()
{
$this->model_security->getsecurity();
$isikonten['content'] = 'jobvacancies/jobvacancies'; // content harus sama dengan yang ada di tampilan_home $content (agar dinamis)
// breadcrumb
$isikonten['judul'] = 'Bawaslu'; //untuk $judul dan $sub_judul yg ada di tampilan_home.php (breadcrumb)
$isikonten['menu'] = 'Job Vacancies';
$isikonten['sub_judul'] = ''; //untuk $judul dan $sub_judul yg ada di tampilan_home.php (breadcrumb)
// breadcrumb
$this->load->view('body', $isikonten);
}
public function getDataKab(){
$this->model_security->getsecurity();
$result = $this->model_jobVacancies->getDataKab();
echo json_encode($result);
}
public function getData(){
$this->model_security->getsecurity();
$result = $this->model_jobVacancies->getData();
echo json_encode($result);
}
public function insertData(){
// echo var_dump($_FILES);
$this->model_security->getsecurity();
$result = $this->model_jobVacancies->insertData();
echo json_encode($result);
// return $result;
}
public function getIdJobvacancies(){
$this->model_security->getsecurity();
$id = $this->input->post('id_job_vacancy');
$result = $this->model_jobVacancies->getIdJobvacancies($id);
echo json_encode($result);
}
// public function updateData(){
// $this->model_security->getsecurity();
// $result = $this->model_jobVacancies->updateData();
// echo json_encode($result);
// }
public function deleteData(){
$this->model_security->getsecurity();
$result = $this->model_jobVacancies->deleteData();
echo json_encode($result);
}
}
| 5,183
|
https://github.com/staltz/kotlin/blob/master/libraries/tools/kotlin-gradle-plugin/src/test/kotlin/org/jetbrains/kotlin/gradle/KotlinGradlePluginIT.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
kotlin
|
staltz
|
Kotlin
|
Code
| 172
| 1,059
|
package org.jetbrains.kotlin.gradle
import org.junit.Test
import org.jetbrains.kotlin.gradle.BaseGradleIT.Project
class KotlinGradleIT: BaseGradleIT() {
Test fun testCrossCompile() {
val project = Project("kotlinJavaProject", "1.6")
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertReportExists()
assertContains(":compileKotlin", ":compileTestKotlin", ":compileDeployKotlin")
}
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertContains(":compileKotlin UP-TO-DATE", ":compileTestKotlin UP-TO-DATE", ":compileDeployKotlin UP-TO-DATE", ":compileJava UP-TO-DATE")
}
}
Test fun testKotlinOnlyCompile() {
val project = Project("kotlinProject", "1.6")
project.build("build") {
assertSuccessful()
assertReportExists()
assertContains(":compileKotlin", ":compileTestKotlin")
}
project.build("build") {
assertSuccessful()
assertContains(":compileKotlin UP-TO-DATE", ":compileTestKotlin UP-TO-DATE")
}
}
Test fun testKotlinClasspath() {
Project("classpathTest", "1.6").build("build") {
assertSuccessful()
assertReportExists()
assertContains(":compileKotlin", ":compileTestKotlin")
}
}
Test fun testMultiprojectPluginClasspath() {
Project("multiprojectClassPathTest", "1.6").build("build") {
assertSuccessful()
assertReportExists("subproject")
assertContains(":subproject:compileKotlin", ":subproject:compileTestKotlin")
}
}
Test fun testKotlinInJavaRoot() {
Project("kotlinInJavaRoot", "1.6").build("build") {
assertSuccessful()
assertReportExists()
assertContains(":compileKotlin", ":compileTestKotlin")
}
}
Test fun testKaptSimple() {
Project("kaptSimple", "1.12").build("build") {
assertSuccessful()
assertContains("kapt: Class file stubs are not used")
assertContains(":compileKotlin")
assertContains(":compileJava")
assertFileExists("build/tmp/kapt/main/wrappers/annotations.main.txt")
assertFileExists("build/generated/source/kapt/main/TestClassGenerated.java")
assertFileExists("build/classes/main/example/TestClass.class")
assertFileExists("build/classes/main/example/TestClassGenerated.class")
}
}
Test fun testKaptStubs() {
Project("kaptStubs", "1.12").build("build") {
assertSuccessful()
assertContains("kapt: Using class file stubs")
assertContains(":compileKotlin")
assertContains(":compileJava")
assertFileExists("build/tmp/kapt/main/wrappers/annotations.main.txt")
assertFileExists("build/generated/source/kapt/main/TestClassGenerated.java")
assertFileExists("build/classes/main/example/TestClass.class")
assertFileExists("build/classes/main/example/TestClassGenerated.class")
}
}
Test fun testKaptArguments() {
Project("kaptArguments", "1.12").build("build") {
assertSuccessful()
assertContains("kapt: Using class file stubs")
assertContains(":compileKotlin")
assertContains(":compileJava")
assertFileExists("build/tmp/kapt/main/wrappers/annotations.main.txt")
assertFileExists("build/generated/source/kapt/main/TestClassCustomized.java")
assertFileExists("build/classes/main/example/TestClass.class")
assertFileExists("build/classes/main/example/TestClassCustomized.class")
}
}
}
| 31,070
|
https://github.com/usupsuparma/Sistem-Pelaporan/blob/master/application/views/front/media.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Sistem-Pelaporan
|
usupsuparma
|
PHP
|
Code
| 102
| 377
|
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('front/head'); ?>
</head>
<body class="hold-transition layout-top-nav">
<div class="wrapper">
<!-- Navbar -->
<?php $this->load->view('front/navbar'); ?>
<!-- /.navbar -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<?php $this->load->view('front/content_header'); ?>
<!-- /.content-header -->
<!-- Main content -->
<?php $this->load->view($content); ?>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
<div class="p-3">
<h5>Title</h5>
<p>Sidebar content</p>
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Main Footer -->
<?php $this->load->view('front/footer'); ?>
</div>
<!-- ./wrapper -->
<!-- REQUIRED SCRIPTS -->
<?php $this->load->view('front/footerjs'); ?>
</body>
</html>
| 9,832
|
https://github.com/cuslytic/dolla-site-neat/blob/master/source/stylesheets/lib/2-elements/_icons.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
dolla-site-neat
|
cuslytic
|
Sass
|
Code
| 10
| 30
|
// .lnr
// +position(absolute, 50% 5% auto auto)
// +size(20px)
| 25,730
|
https://github.com/ohinton/taproom/blob/master/app/keg.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
taproom
|
ohinton
|
TypeScript
|
Code
| 55
| 216
|
import {Component, EventEmitter} from 'angular2/core';
import { Keg } from './keg.model';
@Component({
selector:'keg-display',
inputs: ['keg'],
template:`
<h1>{{ keg.name }}</h1>
<h2>{{keg.brand}}</h2>
<ul>
<li> Price: $ {{keg.price}} </li>
<li> Alcohol Content: {{keg.alcoholContent}} </li>
<li> Remaining Pints: {{keg.pints}} </li>
</ul>
<button (click)="pourPint()" name="label">Pour A Pint</button>
`
})
export class KegComponent{
public keg: Keg;
pourPint(){
this.keg.pints --;
}
}
| 30,558
|
https://github.com/javaseeds/jvm-tools/blob/master/sjk-agent/src/test/java/org/gridkit/jvmtool/agent/SjkAgentLocatorCheck.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
jvm-tools
|
javaseeds
|
Java
|
Code
| 47
| 231
|
package org.gridkit.jvmtool.agent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.junit.Test;
public class SjkAgentLocatorCheck {
@Test
public void checkZipURL() {
URL url = SjkAgent.class.getClassLoader().getResource("java/lang/String.class");
System.out.println(url.toString());
}
@Test
public void checkFileURL() {
URL url = SjkAgent.class.getClassLoader().getResource("org/gridkit/jvmtool/agent/SjkAgent.class");
System.out.println(url.toString());
}
@Test
public void checkLocator() throws IOException, URISyntaxException {
System.out.println(SjkAgentLocator.getJarPath());
}
}
| 11,275
|
https://github.com/crdroidreloaded/android_external_ImageMagick/blob/master/coders/dds.c
|
Github Open Source
|
Open Source
|
ImageMagick
| 2,019
|
android_external_ImageMagick
|
crdroidreloaded
|
C
|
Code
| 13,729
| 35,270
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
#include "MagickCore/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if ((ssize_t) max - min < steps) \
max = MagickMin(min + steps, 255); \
if ((ssize_t) max - min < steps) \
min = MagickMax(0, (ssize_t) max - steps)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,
DDSVector4 *, DDSVector4 *, unsigned char *, size_t),
ReadDDSInfo(Image *,DDSInfo *),
ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),
SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
WriteDDSImage(const ImageInfo *,Image *,ExceptionInfo *),
WriteMipmaps(Image *,const ImageInfo*,const size_t,const size_t,const size_t,
const MagickBooleanType,const MagickBooleanType,const MagickBooleanType,
ExceptionInfo *);
static void
RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),
WriteDDSInfo(Image *,const size_t,const size_t,const size_t),
WriteFourCC(Image *,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteIndices(Image *,const DDSVector3,const DDSVector3,unsigned char *),
WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),
WriteUncompressed(Image *,ExceptionInfo *);
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3* end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4* points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadDDSImage method is:
%
% Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: The image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
PixelTrait
alpha_trait;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
alpha_trait = BlendPixelTrait;
decoder = ReadUncompressedRGBA;
}
else
{
alpha_trait = UndefinedPixelTrait;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
alpha_trait = UndefinedPixelTrait;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
alpha_trait = UndefinedPixelTrait;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
alpha_trait = BlendPixelTrait;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
alpha_trait = BlendPixelTrait;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
if (num_images < 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->alpha_trait=alpha_trait;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType SetDXT1Pixels(Image *image,ssize_t x,ssize_t y,
DDSColors colors,size_t bits,Quantum *q)
{
register ssize_t
i;
ssize_t
j;
unsigned char
code;
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) image->columns &&
(y + j) < (ssize_t) image->rows)
{
code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q);
SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q);
SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q);
SetPixelOpacity(image,ScaleCharToQuantum(colors.a[code]),q);
if ((colors.a[code] != 0) &&
(image->alpha_trait == UndefinedPixelTrait))
return(MagickFalse);
q+=GetPixelChannels(image);
}
}
}
return(MagickTrue);
}
static MagickBooleanType ReadDXT1(Image *image,DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
register Quantum
*q;
register ssize_t
x;
size_t
bits;
ssize_t
y;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) image->rows; y += 4)
{
for (x = 0; x < (ssize_t) image->columns; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x),
MagickMin(4,image->rows-y),exception);
if (q == (Quantum *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0=ReadBlobLSBShort(image);
c1=ReadBlobLSBShort(image);
bits=ReadBlobLSBLong(image);
CalculateColors(c0,c1,&colors,MagickFalse);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
if (SetDXT1Pixels(image,x,y,colors,bits,q) == MagickFalse)
{
/* Correct alpha */
SetImageAlpha(image,QuantumRange,exception);
q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x),
MagickMin(4,image->rows-y),exception);
if (q != (Quantum *) NULL)
SetDXT1Pixels(image,x,y,colors,bits,q);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
register Quantum
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
ssize_t
j,
y;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (Quantum *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q);
SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q);
SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q);
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) alpha),q);
q+=GetPixelChannels(image);
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
MagickSizeType
alpha_bits;
register Quantum
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
ssize_t
j,
y;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (Quantum *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width &&
(y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q);
SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q);
SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q);
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) alpha),q);
q+=GetPixelChannels(image);
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
register Quantum
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType,exception);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(image,ScaleCharToQuantum(ReadBlobByte(image)),q);
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)),q);
}
else
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,3,exception));
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
register Quantum
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleAlphaType,exception);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(image,(color & (1 << 15)) ? QuantumRange : 0,q);
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)),q);
}
else if (alphaBits == 2)
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
(color >> 8)),q);
SetPixelGray(image,ScaleCharToQuantum((unsigned char)color),q);
}
else
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)),q);
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)),q);
}
}
else
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,4,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = AcquireMagickInfo("DDS","DDS","Microsoft DirectDraw Surface");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry = AcquireMagickInfo("DDS","DXT1","Microsoft DirectDraw Surface");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry = AcquireMagickInfo("DDS","DXT5","Microsoft DirectDraw Surface");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
if (SeekBlob(image, offset, SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
if (SeekBlob(image, offset, SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t *alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4 *points, const ssize_t *map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if ((clusterFit == MagickFalse) || (count == 0))
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image, ExceptionInfo *exception)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
fromlist,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace,exception);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (image->alpha_trait == UndefinedPixelTrait)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (IsStringTrue(option) != MagickFalse)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (IsStringTrue(option) != MagickFalse)
weightByAlpha=MagickTrue;
}
}
}
mipmaps=0;
fromlist=MagickFalse;
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
{
if (LocaleNCompare(option,"fromlist",8) == 0)
{
Image
*next;
fromlist=MagickTrue;
next=image->next;
while(next != (Image *) NULL)
{
mipmaps++;
next=next->next;
}
}
}
if ((mipmaps == 0) &&
((image->columns & (image->columns - 1)) == 0) &&
((image->rows & (image->rows - 1)) == 0))
{
maxMipmaps=SIZE_MAX;
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
exception);
if ((mipmaps > 0) && (WriteMipmaps(image,image_info,pixelFormat,compression,
mipmaps,fromlist,clusterFit,weightByAlpha,exception) == MagickFalse))
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MagickPathExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (format == DDPF_FOURCC)
flags=flags | DDSD_LINEARSIZE;
else
flags=flags | DDSD_PITCH;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->alpha_trait != UndefinedPixelTrait)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (pixelFormat == DDPF_FOURCC)
{
/* Compressed DDS requires linear compressed size of first image */
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8));
else /* DXT5 */
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16));
}
else
{
/* Uncompressed DDS requires byte pitch of first image */
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4));
else
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3));
}
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) CopyMagickString(software,"IMAGEMAGICK",MagickPathExtent);
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
register const Quantum
*p;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const Quantum *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(image,p));
else
alpha = 255;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(image,p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(image,p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(image,p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p+=GetPixelChannels(image);
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression,const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value, const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char *indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image,const ImageInfo *image_info,
const size_t pixelFormat,const size_t compression,const size_t mipmaps,
const MagickBooleanType fromlist,const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha,ExceptionInfo *exception)
{
const char
*option;
Image
*mipmap_image,
*resize_image;
MagickBooleanType
fast_mipmaps,
status;
register ssize_t
i;
size_t
columns,
rows;
columns=DIV2(image->columns);
rows=DIV2(image->rows);
option=GetImageOption(image_info,"dds:fast-mipmaps");
fast_mipmaps=IsStringTrue(option);
mipmap_image=image;
resize_image=image;
status=MagickTrue;
for (i=0; i < (ssize_t) mipmaps; i++)
{
if (fromlist == MagickFalse)
{
mipmap_image=ResizeImage(resize_image,columns,rows,TriangleFilter,
exception);
if (mipmap_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
}
else
{
mipmap_image=mipmap_image->next;
if ((mipmap_image->columns != columns) || (mipmap_image->rows != rows))
ThrowBinaryException(CoderError,"ImageColumnOrRowSizeIsNotSupported",
image->filename);
}
DestroyBlob(mipmap_image);
mipmap_image->blob=ReferenceBlob(image->blob);
WriteImageData(mipmap_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
if (fromlist == MagickFalse)
{
if (fast_mipmaps == MagickFalse)
mipmap_image=DestroyImage(mipmap_image);
else
{
if (resize_image != image)
resize_image=DestroyImage(resize_image);
resize_image=mipmap_image;
}
}
columns=DIV2(columns);
rows=DIV2(rows);
}
if (resize_image != image)
resize_image=DestroyImage(resize_image);
return(status);
}
static void WriteSingleColorFit(Image *image, const DDSVector4 *points,
const ssize_t *map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(image,p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(image,p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(image,p)));
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));
p+=GetPixelChannels(image);
}
}
}
| 46,611
|
https://github.com/adi-g15/nitp-notes/blob/master/src/pages/highlighted/cs4401.tsx
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
nitp-notes
|
adi-g15
|
TypeScript
|
Code
| 43
| 113
|
// import HighlightedComponent from "../../components/HighlightedComponent";
// export default HighlightedComponent.bind(this, {sub: "cs4401", msg: "Yaha jo maine read kiye hai wohi hai, if you have highlighted/marked notes PLEASE provide"});
import React from 'react';
export default function HCS4401(props) {
return (
<><div>"Not yet implemented"</div></>
);
}
| 23,633
|
https://github.com/keithb418/medcheckerapp/blob/master/test/selenium-ruby/spec/search_page_spec.rb
|
Github Open Source
|
Open Source
|
CC0-1.0
| null |
medcheckerapp
|
keithb418
|
Ruby
|
Code
| 84
| 318
|
require_relative '../../selenium-ruby/pages/Welcome'
require_relative '../../selenium-ruby/pages/Search'
describe 'Search page' do
# GSA-2: Search Meds
before(:all) do
@welcome = Welcome.new (@driver)
@search = Search.new (@driver)
@welcome.return_proceed_button.click
end
it 'will have a search bar' do
expect(@search.return_search_field).to be_truthy
end
it 'will autocomplete medicine names - generic name' do
@search.enter_search_term('acetaminophen')
expect(@search.return_result_text).to match "OXYCODONE HYDROCHLORIDE AND ACETAMINOPHEN"
end
it 'will autocomplete medicine names - brand name' do
@search.enter_search_term('aspirin')
expect(@search.return_result_text).to match "ASPIRIN"
end
it 'will return no results if input is nomedname' do
@search.enter_search_term('nomedname')
expect(@search.return_result_text).to match "No results to display"
end
end
| 42,708
|
https://github.com/OrangeBuffalo/TheArenaExperience/blob/master/TheArenaExperience/Settings.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
TheArenaExperience
|
OrangeBuffalo
|
C#
|
Code
| 255
| 675
|
using MCM.Abstractions.Attributes;
using MCM.Abstractions.Attributes.v2;
using MCM.Abstractions.Settings.Base.Global;
namespace TheArenaExperience
{
class Settings : AttributeGlobalSettings<Settings>
{
public override string Id => "TheArenaExperience";
public override string DisplayName => "The Arena Experience";
public override string FolderName => "TheArenaExperience";
public override string FormatType => "json2";
[SettingPropertyFloatingInteger("XP Gains in Practice Fights", 0f, 1f, "0%", Order = 0, RequireRestart = false, HintText = "XP gains in practice fights (Vanilla=6%, Default=25%).")]
[SettingPropertyGroup("The Arena Experience")]
public float XpGainsPracticeFights { get; set; } = 0.25f;
[SettingPropertyFloatingInteger("XP Gains in Tournaments", 0f, 1f, "0%", Order = 1, RequireRestart = false, HintText = "XP gains in tournaments (Vanilla=33%, Default=50%).")]
[SettingPropertyGroup("The Arena Experience")]
public float XpGainsTournaments { get; set; } = 0.5f;
[SettingPropertyFloatingInteger("Impressed Notable Chance", 0f, 1f, "0%", Order = 2, RequireRestart = false, HintText = "Chance to impress a local notable when winning a tournament (Default=50%)")]
[SettingPropertyGroup("The Arena Experience")]
public float ImpressedNotableChance { get; set; } = 0.5f;
[SettingPropertyFloatingInteger("Impressed Noble Chance", 0f, 1f, "0%", Order = 3, RequireRestart = false, HintText = "Chance to impress a local noble when winning a tournament (Default=50%)")]
[SettingPropertyGroup("The Arena Experience")]
public float ImpressedNobleChance { get; set; } = 0.5f;
[SettingPropertyFloatingInteger("Impressed Wanderer Chance", 0f, 1f, "0%", Order = 4, RequireRestart = false, HintText = "Chance to impress a local wanderer when winning a tournament (Default=50%)")]
[SettingPropertyGroup("The Arena Experience")]
public float ImpressedWandererChance { get; set; } = 0.5f;
[SettingPropertyFloatingInteger("Base Relationship Change", 0, 10, "0 Points", Order = 5, RequireRestart = false, HintText = "Base relationship change with impressed heroes (Default=1).")]
[SettingPropertyGroup("The Arena Experience")]
public int BaseRelationChange { get; set; } = 1;
}
}
| 22,962
|
https://github.com/chenshun00/data-code/blob/master/src/main/java/io/github/chenshun00/data/tree/binary/InvertTree.java
|
Github Open Source
|
Open Source
|
MIT
| null |
data-code
|
chenshun00
|
Java
|
Code
| 174
| 622
|
package io.github.chenshun00.data.tree.binary;
/**
* https://twitter.com/mxcl/status/608682016205344768
* <p>
* https://leetcode-cn.com/problems/invert-binary-tree/
* <p>
* 翻转二叉树: 前序遍历的时候先把当前节点的左右子树翻转,然后递归翻转他们的孩子.
*
* @author chenshun00@gmail.com
* @since 2022/1/9 4:54 下午
*/
public class InvertTree {
public static void main(String[] args) {
TreeNode root = new TreeNode(4);
{
root.left = new TreeNode(2, new TreeNode(1), new TreeNode(3));
root.right = new TreeNode(7, new TreeNode(6), new TreeNode(9));
}
InvertTree invertTree = new InvertTree();
final TreeNode treeNode = invertTree.invertTree(root);
System.out.println(1);
}
/**
* 翻转二叉树
* <p>
* 交换节点的左子树和右子树
*
* <p>
* https://leetcode-cn.com/problems/invert-binary-tree/
*
* @param root 根
* @return {@link TreeNode}
*/
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
doInvert(root);
return root;
}
private void doInvert(TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
return;
}
if (root.left == null) {
root.left = root.right;
root.right = null;
} else if (root.right == null) {
root.right = root.left;
root.left = null;
} else {
final TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
doInvert(root.left);
doInvert(root.right);
}
}
| 239
|
https://github.com/ni/hoplite/blob/master/tests/utils.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
hoplite
|
ni
|
Python
|
Code
| 346
| 1,065
|
from hoplite.serializer import hoplite_dumps
class StatusCodeTestMixin(object):
def assertStatusCode(self, response, status_code):
"""Assert the status code of a Flask test client response
:param response: The test client response object
:param status_code: The expected status code
"""
self.assertEquals(status_code, response.status_code)
return response
def assertOk(self, response):
"""Test that response status code is 200
:param response: The test client response object
"""
return self.assertStatusCode(response, 200)
def assertBadRequest(self, response):
"""Test that response status code is 400
:param response: The test client response object
"""
return self.assertStatusCode(response, 400)
def assertForbidden(self, response):
"""Test that response status code is 403
:param response: The test client response object
"""
return self.assertStatusCode(response, 403)
def assertNotFound(self, response):
"""Test that response status code is 404
:param response: The test client response object
"""
return self.assertStatusCode(response, 404)
def assertContentType(self, response, content_type):
"""Assert the content-type of a Flask test client response
:param response: The test client response object
:param content_type: The expected content type
"""
self.assertEquals(content_type, response.headers['Content-Type'])
return response
def assertOkHtml(self, response):
"""Assert the response status code is 200 and an HTML response
:param response: The test client response object
"""
return self.assertOk(
self.assertContentType(response, 'text/html; charset=utf-8'))
def assertJson(self, response):
"""Test that content returned is in JSON format
:param response: The test client response object
"""
return self.assertContentType(response, 'application/json')
def assertOkJson(self, response):
"""Assert the response status code is 200 and a JSON response
:param response: The test client response object
"""
return self.assertOk(self.assertJson(response))
def assertBadJson(self, response):
"""Assert the response status code is 400 and a JSON response
:param response: The test client response object
"""
return self.assertBadRequest(self.assertJson(response))
class FlaskTestCaseMixin(object):
def _json_data(self, kwargs, csrf_enabled=True):
if 'data' in kwargs:
kwargs['data'] = hoplite_dumps(kwargs['data'])
if not kwargs.get('content_type'):
kwargs['content_type'] = 'application/json'
return kwargs
def _request(self, method, *args, **kwargs):
kwargs.setdefault('content_type', 'text/html')
kwargs.setdefault('follow_redirects', True)
return method(*args, **kwargs)
def _jrequest(self, *args, **kwargs):
return self._request(*args, **kwargs)
def get(self, *args, **kwargs):
return self._request(self.client.get, *args, **kwargs)
def delete(self, *args, **kwargs):
return self._request(self.client.delete, *args, **kwargs)
def jget(self, *args, **kwargs):
return self._jrequest(self.client.get, *args, **kwargs)
def jpost(self, *args, **kwargs):
return self._jrequest(self.client.post, *args, **self._json_data(kwargs))
def jput(self, *args, **kwargs):
return self._jrequest(self.client.put, *args, **self._json_data(kwargs))
def jpatch(self, *args, **kwargs):
return self._jrequest(self.client.patch, *args, **self._json_data(kwargs))
def jdelete(self, *args, **kwargs):
return self._jrequest(self.client.delete, *args, **self._json_data(kwargs))
| 40,964
|
https://github.com/ccyz/Summary-model-for-judgment-document/blob/master/keras_textclassification/m09_TextCRNN/graph.py
|
Github Open Source
|
Open Source
|
Unlicense
| 2,022
|
Summary-model-for-judgment-document
|
ccyz
|
Python
|
Code
| 192
| 885
|
# -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/6/3 10:51
# @author :Mo
# @function :graph of CRNN
# @paper :A C-LSTM Neural Network for Text Classification(https://arxiv.org/abs/1511.08630)
from keras import regularizers
from keras.models import Model
from keras.layers import SpatialDropout1D, Conv1D
from keras.layers import Dropout, Flatten, Dense, Concatenate
from keras.layers import LSTM, GRU, Bidirectional, CuDNNLSTM, CuDNNGRU
from keras_textclassification.base.graph import graph
class CRNNGraph(graph):
def __init__(self, hyper_parameters):
"""
初始化
:param hyper_parameters: json,超参
"""
self.rnn_type = hyper_parameters['model'].get('rnn_type', 'LSTM')
self.rnn_units = hyper_parameters['model'].get('rnn_units', 650) # large, small is 300
self.dropout_spatial = hyper_parameters['model'].get('dropout_spatial', 0.2)
self.l2 = hyper_parameters['model'].get('l2', 0.001)
super().__init__(hyper_parameters)
def create_model(self, hyper_parameters):
"""
构建神经网络
:param hyper_parameters:json, hyper parameters of network
:return: tensor, moedl
"""
super().create_model(hyper_parameters)
x = self.word_embedding.output
embedding_output_spatial = SpatialDropout1D(self.dropout_spatial)(x)
if self.rnn_units=="LSTM":
layer_cell = LSTM
elif self.rnn_units=="GRU":
layer_cell = GRU
elif self.rnn_units=="CuDNNLSTM":
layer_cell = CuDNNLSTM
elif self.rnn_units=="CuDNNGRU":
layer_cell = CuDNNGRU
else:
layer_cell = GRU
# CNN
convs = []
for kernel_size in self.filters:
conv = Conv1D(self.filters_num,
kernel_size=kernel_size,
strides=1,
padding='SAME',
kernel_regularizer=regularizers.l2(self.l2),
bias_regularizer=regularizers.l2(self.l2),
)(embedding_output_spatial)
convs.append(conv)
x = Concatenate(axis=1)(convs)
# Bi-LSTM, 论文中使用的是LSTM
x = Bidirectional(layer_cell(units=self.rnn_units,
return_sequences=True,
activation='relu',
kernel_regularizer=regularizers.l2(self.l2),
recurrent_regularizer=regularizers.l2(self.l2)
))(x)
x = Dropout(self.dropout)(x)
x = Flatten()(x)
# 最后就是softmax
dense_layer = Dense(self.label, activation=self.activate_classify)(x)
output = [dense_layer]
self.model = Model(self.word_embedding.input, output)
self.model.summary(120)
| 5,492
|
https://github.com/won21kr/RemsStudio/blob/master/src/me/anno/studio/Build.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
RemsStudio
|
won21kr
|
Kotlin
|
Code
| 10
| 22
|
package me.anno.studio
object Build {
val isDebug = true
}
| 15,766
|
https://github.com/stones/webdriver-cucumberjs-setup/blob/master/components/reddit-homepage/check-title.feature
|
Github Open Source
|
Open Source
|
Unlicense
| 2,017
|
webdriver-cucumberjs-setup
|
stones
|
Gherkin
|
Code
| 55
| 101
|
Feature: Reddit Home Page Title
As a developer
I want to make sure I can be distracted
Background:
Given I open the url "https://www.reddit.com"
Scenario: Is not Google
Then I expect that the title is not "Google"
@components
Scenario: Is correct
Then I expect that the title is "reddit: the front page of the internet"
| 8,735
|
https://github.com/tolchanov/GyrocopterApp/blob/master/app/src/main/java/com/test/hyrocoptertestapp/data/LogDataManager.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
GyrocopterApp
|
tolchanov
|
Kotlin
|
Code
| 201
| 813
|
package com.test.hyrocoptertestapp.data
import android.os.Environment
import com.test.hyrocoptertestapp.model.InputModel
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
interface ILogDataManager {
fun initLogging()
fun getFileList() : MutableList<String>
fun log(data: String)
fun log(data: InputModel)
fun endLog()
fun saveLog() : Boolean
}
class LogDataManager(private val headers: Array<String>) : ILogDataManager {
companion object{
val TEMP_DIR = "${Environment.getExternalStorageDirectory().path}/Gyrocopter/Temp"
val LOG_DIR = "${Environment.getExternalStorageDirectory().path}/Gyrocopter/Logs"
}
private var tempLogFile: File? = null
private var tempOS: FileOutputStream? = null
override fun initLogging() {
Timber.d("Initializing logging...")
createTempLogFile()
Timber.d("Logging initialized!")
}
private fun createTempLogFile() {
val dir = File(TEMP_DIR)
if(!dir.exists()) dir.mkdirs()
tempLogFile = File(TEMP_DIR, "temp_feed.csv")
if(tempLogFile?.exists()==true){
tempLogFile?.delete()
}
tempOS = tempLogFile?.outputStream()
val sb = StringBuilder()
headers.forEachIndexed { ind, str ->
sb.append(str)
if(ind < headers.size -1) {
sb.append(", ")
}
}
Timber.e(sb.toString())
tempOS?.write("${sb.toString()}\n".toByteArray())
}
override fun log(data: InputModel){
tempOS?.write("$data\n".toByteArray())
}
override fun log(data: String){
tempOS?.write("$data\n".toByteArray())
}
override fun endLog(){
Timber.d("Stopping logging...")
tempOS?.flush()
tempOS?.close()
Timber.d("Logging stopped!")
}
override fun saveLog(): Boolean {
return try {
val dir = File(LOG_DIR)
if(!dir.exists()) dir.mkdirs()
if(tempLogFile != null){
tempLogFile!!.copyTo(File(LOG_DIR, "LOG_${SimpleDateFormat("yyyy_MM_dd_hh_mm_ss", Locale.getDefault()).format(Calendar.getInstance(Locale.getDefault()).time)}.txt"))
true
} else {
false
}
} catch (e: Exception){
Timber.e(e)
false
}
}
override fun getFileList() : MutableList<String>{
val dir = File(LOG_DIR)
if(!dir.exists()) return mutableListOf()
return dir.listFiles().filter { it.extension in arrayOf("csv", "txt") }.map{ it.name }.toMutableList()
}
}
| 18,323
|
https://github.com/foxycoder/gatsby-starter-netlify-cms/blob/master/src/components/Footer.sass
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
gatsby-starter-netlify-cms
|
foxycoder
|
Sass
|
Code
| 67
| 247
|
.footer,
.footer strong
color: #fff
a:link,
a:hover,
a:visited
color: #fff
font-weight: bolder
a:hover
color: #fff
text-decoration: underline
.footer
.social-icons
display: flex
margin: 1rem 0
align-items: center
.icon-container
flex: 1
margin: 0.5rem
text-align: center
.syndicates
display: flex
align-items: center
text-align: center
align-content: space-between
.syndicate
flex: 1
display: flex
align-content: space-around
align-self: center
figure
display: flex
flex: 1
align-items: center
max-width: 50px
text-align: center
margin: auto
img
max-width: 50px
| 15,497
|
https://github.com/opensource-emr/hospital-management-emr/blob/master/Code/Components/DanpheEMR.ServerModel/AdmissionModels/DischargeSummaryModel.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
hospital-management-emr
|
opensource-emr
|
C#
|
Code
| 361
| 775
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DanpheEMR.ServerModel
{
public class DischargeSummaryModel
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DischargeSummaryId { get; set; }
//[Key, ForeignKey("Visit")]
[Key]
public int PatientVisitId { get; set; }
public int DischargeTypeId { get; set; }
public int ConsultantId { get; set; }
public int DoctorInchargeId { get; set; }
public string OperativeProcedure { get; set; }
public string OperativeFindings { get; set; }
public int? AnaesthetistsId { get; set; }
public string Diagnosis { get; set; }
public string CaseSummary { get; set; }
public string Condition { get; set; }
public string Treatment { get; set; }
public string HistologyReport { get; set; }
public string SpeicialNotes { get; set; }
public string Medications { get; set; }
public string Allergies { get; set; }
public string Activities { get; set; }
public string Diet { get; set; }
public int? RestDays { get; set; }
public int? FollowUp { get; set; }
public string Others { get; set; }
//Ashim: 15Dec2017 : ResidenceDr is not mandatory
public int? ResidenceDrId { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
//public virtual VisitModel Visit { get; set; }
public bool? IsSubmitted { get; set; }
public bool? IsDischargeCancel { get; set; }
public string LabTests { get; set; }
public int? DischargeConditionId { get; set; }
public int? DeliveryTypeId { get; set; }
public int? BabyBirthConditionId { get; set; }
public int? DeathTypeId { get; set; }
public string DeathPeriod { get; set; }
[NotMapped]
public virtual List<DischargeSummaryMedication> DischargeSummaryMedications { get; set; }
[NotMapped]
public virtual List<BabyBirthDetailsModel> BabyBirthDetails { get; set; }
public int? NotesId { get; set; }
public string ChiefComplaint { get; set; }
public string PendingReports { get; set; }
public string HospitalCourse { get; set; }
public string PresentingIllness { get; set; }
public string ProcedureNts { get; set; }
public string SelectedImagingItems { get; set; }
public string DiagnosisFreeText { get; set; }
public string ProvisionalDiagnosis { get; set; }
}
}
| 36,499
|
https://github.com/hoangpq/graphql-app/blob/master/orm/db.go
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
graphql-app
|
hoangpq
|
Go
|
Code
| 161
| 621
|
package orm
import (
"fmt"
_ "github.com/lib/pq"
"go-grapgql-practice/configs"
"go-grapgql-practice/models"
"github.com/jinzhu/gorm"
)
func GetConnection() (*gorm.DB) {
config, _ := configs.GetDatabaseConfig()
connString := fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=disable",
config.User, config.Password, config.Host, config.Port, config.Dbname,
)
db, err := gorm.Open("postgres", connString)
db.LogMode(true)
if err != nil {
panic("Failed to connect database")
}
return db
}
func GetProducts() []models.Product {
db := GetConnection()
defer db.Close()
var products []models.Product
db.Debug().Select([]string{"id", "name", "list_price"}).Find(&products)
return products
}
func GetUomById(uomId int) interface{} {
db := GetConnection()
defer db.Close()
var uom models.ProductUOM
db.Debug().Where("id = ?", uomId).Select([]string{"id", "name"}).First(&uom)
return uom
}
func GetProductById(productId int) interface{} {
db := GetConnection()
defer db.Close()
var product models.Product
db.Debug().Where("id = ?", productId).Select([]string{"id", "name", "list_price"}).First(&product)
return product
}
func GetUOMByProductID(productId int) interface{} {
db := GetConnection()
defer db.Close()
uom := models.ProductUOM{}
db.Debug().
Table("product_template tmpl").
Select("uom.id, uom.name").
Joins("left join product_uom uom on tmpl.uom_id = uom.id").
Where("tmpl.id = ?", productId).
Find(&uom)
return uom
}
func GetProductCount() (int) {
db := GetConnection()
defer db.Close()
var count int
db.Debug().
Model(&models.Product{}).
Count(&count)
return count
}
| 15,543
|
https://github.com/CatOrmerod/coding-cat-portfolio/blob/master/controllers/profileRoutes.js
|
Github Open Source
|
Open Source
|
MIT
| null |
coding-cat-portfolio
|
CatOrmerod
|
JavaScript
|
Code
| 131
| 373
|
const router = require("express").Router();
const { Project, Admin, Contact } = require("../models");
const withAuth = require("../utils/auth");
router.get("/", withAuth, async (req, res) => {
try {
// Get all blog posts and JOIN with user and comment data
const projectData = await Project.findAll({
where: {
user_id: req.session.user_id,
},
});
// Serialize data so the template can read it
const projects = projectData.map((project) => project.get({ plain: true }));
// Pass serialized data and session flag into template
console.log("logged in status", req.session.logged_in);
res.render("profile", {
projects,
logged_in: req.session.logged_in,
});
} catch (err) {
res.status(500).json(err);
}
});
router.get("/update/:id", withAuth, async (req, res) => {
try {
const projectData = await Project.findByPk(req.params.id, {});
const project = projectData.get({ plain: true });
console.log(project);
res.render("update", {
...project,
logged_in: req.session.logged_in,
});
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
| 10,543
|
https://github.com/devFoysal/glil/blob/master/resources/sass/home.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
glil
|
devFoysal
|
SCSS
|
Code
| 2,642
| 9,382
|
.container {
max-width: 1400px;
@media screen and (min-width: 1200px) and (max-width: 1400px) {
max-width: 1300px;
}
}
.detail-appointment {
display: flex;
justify-content: space-between;
@media screen and (max-width: 576px) {
display: block;
}
}
.book-appointment {
border: 1px solid #2c302e;
box-sizing: border-box;
border-radius: 30px;
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 16px;
line-height: 28px;
text-align: center;
color: #2c302e;
width: 228px;
padding: 15px 0;
&:hover {
background-color: #232075;
color: #fff !important;
}
@media screen and (max-width: 576px) {
width: auto;
padding: 10px 20px;
font-size: 14px;
}
}
.form-control {
height: 60px;
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 28px;
background: #ffffff;
border: 0.5px solid #d8d8d8;
border-radius: 6px 10px 10px 6px;
option {
margin: 40px;
background: #fff;
color: #f7941e;
//text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
&:hover {
background-color: #f7941e;
}
}
&:focus {
outline: 0 !important;
background-color: #fff;
border-color: #f7941e;
border-left: 5px solid #f7941e;
box-shadow: none !important;
&::placeholder {
color: #f7941e !important;
}
}
}
.yellow-btn {
width: 160px;
height: 60px;
background: #f7941e;
border-radius: 30px;
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 28px;
text-align: center;
color: #ffffff;
text-transform: capitalize;
@media screen and (max-width: 576px) {
width: auto;
height: auto;
}
}
// /* width */
// ::-webkit-scrollbar {
// width: 12px;
// }
// /* Track */
// ::-webkit-scrollbar-track {
// box-shadow: inset 0 0 5px grey;
// border-radius: 0px;
// }
// /* Handle */
// ::-webkit-scrollbar-thumb {
// background: #f7941e;
// border-radius: 8px;
// }
// /* Handle on hover */
// ::-webkit-scrollbar-thumb:hover {
// background: #d37503;
// }
// ========================================
// ========== COMMON Dessign END =========
//=========================================
#header {
display: block;
@media screen and (max-width: 769px) {
display: none;
}
.socials {
li {
a {
color: #fff;
text-decoration: none;
transition: ease-in-out 0.3s;
}
&:hover {
a {
color: #f7941e;
transform: scale(1.1);
}
}
}
}
}
.logo {
position: absolute;
background: #ffffff;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
border-radius: 0px 0px 40px 40px;
width: 247px;
height: 205px;
z-index: 6;
left: 180px;
img {
position: relative;
padding: 10px;
width: 90%;
}
@media screen and (min-width: 1200px) and (max-width: 1600px) {
left: 40px;
width: 200px;
height: 180px;
}
}
.top-header {
background: #232075;
li {
font-size: 16px;
font-family: Open Sans;
color: #ffffff;
display: inline-block;
padding: 10px 20px;
}
.phone {
background: #f7941e !important;
span {
margin-right: 10px;
}
}
}
.main-header {
z-index: 5;
background: #ffffff;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
position: relative;
li {
display: inline-block;
//padding: 10px 0px;
margin: 30px 35px;
border-bottom: 3px solid transparent;
&:hover {
border-bottom: 3px solid #f7941e;
&:last-child {
border-bottom: 0;
cursor: pointer;
}
.main-link {
color: #f7941e;
}
}
.main-link {
padding: 50px 0;
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 18px;
line-height: 25px;
text-align: center;
color: #2c302e;
text-decoration: none;
}
@media screen and (min-width: 1200px) and (max-width: 1600px) {
margin: 20px 13px;
}
}
// .line {
// margin-left: 25px;
// margin-right: 35px;
// }
.img-btn {
border: 1px solid rgba(196, 196, 196, 0.5);
box-sizing: border-box;
border-radius: 30px;
width: 120px;
height: 50px;
margin: 0 10px;
background-color: transparent;
&:focus {
outline: none;
}
&:hover {
border-color: #f7941e;
}
}
.dropdown2 {
@media screen and (min-width: 1200px) and (max-width: 1600px) {
top: 102px;
right: 60px;
}
}
.dropdown {
display: none;
position: absolute;
background: #ffffff;
border: 0.5px solid rgba(196, 196, 196, 0.5);
border-bottom: 5px solid #f7941e;
height: 82px;
align-items: center;
box-sizing: border-box;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
top: 120px;
transition: ease-in-out 1s;
@media screen and (min-width: 1200px) and (max-width: 1600px) {
top: 102px;
}
.dropdown-item {
border-right: 0.5px solid rgba(0, 0, 0, 0.25);
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 18px;
line-height: 25px;
&:last-child {
border-right: 0;
}
&:hover {
color: #f7941e;
}
}
}
.dropdowns {
display: none;
position: absolute;
background-color: #fff;
padding: 10px 0;
border-bottom: 5px solid #f7941e;
top: 107px;
@media screen and (min-width: 1200px) and (max-width: 1600px) {
top: 103px;
}
.dropdown-item {
&:active {
background-color: transparent;
}
&:hover {
background-color: transparent;
}
}
.fa-times {
&:hover {
color: #f7941e;
}
}
}
.more-options {
right: 10%;
}
.d {
&:hover {
.dropdown {
display: flex;
transition: ease-in-out 1s;
.dropdown-item {
background-color: transparent;
}
}
}
}
}
// ==============================
//============== Mobile Header ================
//==============================
#mobile-header {
display: none;
@media screen and (max-width: 768px) {
display: block;
}
.navbar-brand {
img {
width: 45%;
}
}
.navbar-bg {
background: #ffffff;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
z-index: 2;
}
.nav-link {
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 18px;
line-height: 25px;
color: #2c302e;
&:hover {
color: #f7941e;
}
}
.dropdown {
z-index: 500;
}
.dropdown-menu {
background: transparent;
.dropdown-item {
font-family: Open Sans !important;
font-style: normal;
font-weight: 600;
font-size: 18px;
line-height: 25px;
color: #2c302e;
&:hover {
color: #f7941e;
}
}
}
.img-btn {
border: 1px solid rgba(196, 196, 196, 0.5);
box-sizing: border-box;
border-radius: 30px;
width: 120px;
height: 50px;
margin-right: 15px;
margin-top: 10px;
background-color: transparent;
&:hover {
border-color: #f7941e;
}
}
.yellow-bg {
@media screen and (max-width: 576px) {
background-color: #f7941e;
}
}
}
#carouselExampleControls {
.carousel-inner {
z-index: 0 !important;
}
.carousel-control-prev-icon,
.carousel-control-next-icon {
height: 100px;
width: 100px;
outline: black;
background-size: 100%, 100%;
background-image: none;
}
.carousel-control-next-icon:after {
font-size: 35px;
color: #000;
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f054";
}
.carousel-control-prev-icon:after {
font-size: 35px;
color: #000;
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f053";
}
}
#banner {
height: 70vh;
//background-image: url("../assets/img/home/banner.png");
background-repeat: no-repeat;
background-size: cover;
border-bottom: 5px solid #232075;
@media screen and (min-width: 1500px) and (max-width: 1700px) {
background-position-x: 60%;
}
.banner-inner {
//background-image: url("../assets/img/home/banner2.png");
background-repeat: no-repeat;
background-size: contain;
height: 100%;
background-position-x: -20%;
@media screen and (min-width: 1500px) and (max-width: 1700px) {
background-position-x: -90%;
}
@media screen and (max-width: 576px) {
background-size: cover;
text-align: center;
}
.container {
height: 100%;
.row {
height: 100%;
.banner-2 {
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
}
}
}
h5 {
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 24px;
line-height: 36px;
text-transform: capitalize;
color: #232075;
}
h1 {
font-family: Open Sans;
font-style: normal;
font-weight: 700;
font-size: 50px;
line-height: 50px;
text-transform: capitalize;
color: #232075;
@media screen and (min-width: 1200px) and (max-width: 1400px) {
font-size: 45px;
}
}
}
// ==============================
//=============== SLIDER SECTION ===============
//==============================
#silder-section {
padding: 50px 0 80px 0;
background: rgba(247, 148, 30, 0.05);
.headline {
border-bottom: 2px solid #f7941e;
padding-bottom: 15px;
a {
font-family: Open Sans;
font-style: normal;
font-weight: 400;
font-size: 18px;
line-height: 28px;
color: #2c302e;
text-decoration: none;
}
span {
color: #f7941e;
font-weight: bold;
margin-right: 10px;
}
}
.col {
&:focus {
outline: none;
}
}
.card {
background: #ffffff;
border: 0.5px solid rgba(44, 48, 46, 0.1);
border-radius: 17px;
overflow: hidden;
transition: all 2s;
.img-box {
overflow: hidden;
transition: all 2s;
img {
filter: grayscale(100%);
}
}
h5 {
font-family: Open Sans;
font-style: normal;
font-weight: bold;
font-size: 36px;
line-height: 36px;
text-align: center;
text-transform: capitalize;
color: #232075;
padding: 20px 0;
@media screen and (min-width: 1200px) and (max-width: 1400px) {
font-size: 30px;
}
@media screen and (max-width: 768px) {
font-size: 25px;
}
}
&:hover {
cursor: pointer;
img {
transition: ease-out 0.5s;
transform: scale(1.1);
filter: grayscale(0);
}
}
}
.owl-dots {
text-align: center;
bottom: 5px;
width: 100%;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
position: absolute;
bottom: -45px;
.active {
background: #232075 !important;
border-radius: 5px;
width: 58px;
height: 7px;
}
}
.owl-dot {
width: 16px;
height: 7px;
display: inline-block;
background: #c4c4c4;
border-radius: 5px;
margin-left: 5px;
margin-right: 5px;
}
.owl-carousel .owl-nav button.owl-prev {
background: #ffffff;
width: 55px;
height: 55px;
border-radius: 10px;
position: absolute;
top: 45%;
left: -50px;
i {
font-size: 25px;
}
@media screen and (min-width: 1200px) and (max-width: 1400px) {
left: -12px;
}
}
.owl-carousel .owl-nav button.owl-next {
background: #ffffff;
width: 55px;
height: 55px;
border-radius: 10px;
position: absolute;
top: 45%;
right: -50px;
i {
font-size: 25px;
}
@media screen and (min-width: 1200px) and (max-width: 1400px) {
right: -12px;
}
}
}
// ==============================
//=============== Insurance plan SECTION ===============
//==============================
#insurance-plan {
padding: 50px 10px;
h1 {
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 48px;
line-height: 65px;
color: #2c302e;
span {
font-weight: bold;
}
@media screen and (min-width: 1200px) and (max-width: 1400px) {
font-size: 40px;
}
@media screen and (max-width: 576px) {
font-size: 36px;
}
}
h3 {
font-family: Montserrat;
font-style: normal;
font-weight: bold;
font-size: 36px;
line-height: 24px;
color: #4e4e4e;
padding: 30px 0 20px 0;
text-transform: capitalize;
line-height: 35px;
@media screen and (max-width: 576px) {
font-size: 25px;
}
}
.details-div {
margin-top: 70px;
display: flex;
align-items: center;
justify-content: space-between;
.details {
font-family: Open Sans;
font-style: normal;
font-weight: bold;
font-size: 18px;
line-height: 28px;
color: #2c302e;
text-decoration: none;
}
.book-appointment {
border: 1px solid #2c302e;
box-sizing: border-box;
border-radius: 30px;
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 16px;
line-height: 28px;
text-align: center;
color: #2c302e;
width: 228px;
padding: 15px 0;
&:hover {
background-color: #232075;
color: #fff;
}
@media screen and (max-width: 576px) {
width: 173px;
padding: 10px 0;
font-size: 14px;
}
}
}
.card {
border: none;
background: #fcfcfc !important;
.card-body {
hr {
margin-bottom: 4rem;
}
@media screen and (max-width: 576px) {
padding: 0;
hr {
margin-bottom: 5rem;
}
}
}
.card-footer {
background: #fcfcfc !important;
@media screen and (max-width: 576px) {
padding: 0;
}
}
}
p {
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 28px;
color: #2c302e;
@media screen and (max-width: 576px) {
font-size: 16px;
}
}
.blue-bg {
background: #232075;
border-radius: 10px 0 0 10px;
.nav {
align-items: center;
.nav-link {
font-family: Open Sans;
font-style: normal;
font-weight: normal;
text-align: center;
font-size: 18px;
line-height: 28px;
display: flex;
align-items: left;
color: #ffffff;
margin: 10px 0;
&:first-child {
margin-top: 60px;
}
}
.active {
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 20px;
line-height: 36px;
display: flex;
align-items: center;
text-transform: capitalize;
color: #ffffff;
span {
background: #f7941e;
width: 5px;
height: 25px;
margin-left: 20px;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
border-radius: 20px;
}
}
@media screen and (max-width: 576px) {
flex-direction: row !important;
.nav-link {
margin: 20px 0;
&:first-child {
margin-top: 20px;
}
}
.active {
font-size: 18px;
span {
background: #f7941e;
width: 5px;
height: 20px;
}
}
}
}
}
.ash-bg {
background: #fcfcfc;
}
.pic-bg {
background: #fcfcfc;
padding-right: 0;
img {
border-radius: 10px;
}
}
.carousel-control-next {
position: absolute;
background: rgba(196, 196, 196, 0.25);
border-radius: 10px;
width: 50px;
height: 50px;
top: 86%;
left: 83%;
@media screen and (max-width: 576px) {
width: 40px;
height: 40px;
top: 88%;
}
}
.carousel-control-prev {
position: absolute;
background: rgba(196, 196, 196, 0.5);
border-radius: 10px;
width: 50px;
height: 50px;
top: 86%;
left: 70%;
@media screen and (max-width: 576px) {
width: 40px;
height: 40px;
left: 67%;
top: 88%;
}
}
.carousel-control-next-icon,
.carousel-control-prev-icon {
width: 13px;
height: 26px;
}
.carousel-control-next-icon {
background-image: url("../../public/assets/img/home/rightarrow.png");
}
.carousel-control-prev-icon {
background-image: url("../../public/assets/img/home/leftarrow.png");
}
}
// ==============================
//=============== APP SECTION ===============
//==============================
#app-section {
background: rgba(247, 148, 30, 0.05);
padding: 70px 0;
.app-card {
overflow: hidden;
display: flex;
justify-content: space-between;
background: #ffffff;
box-shadow: 0px 10px 25px rgba(99, 65, 65, 0.1);
border-radius: 10px;
padding: 10px 20px 0 30px;
align-items: center;
.image {
img {
transition: ease-in-out 0.5s;
}
}
&:hover {
.image {
img {
transform: scale(1.1);
}
}
}
@media screen and (max-width: 768px) {
display: block;
text-align: center;
margin-bottom: 30px;
padding-top: 40px;
img {
width: 60%;
margin-top: 30px;
}
h2 {
font-size: 30px;
margin-bottom: 20px;
}
}
}
h2 {
font-family: Open Sans;
font-style: normal;
font-weight: bold;
font-size: 36px;
line-height: 48px;
text-transform: capitalize;
color: #232075;
margin-bottom: 40px;
@media screen and (min-width: 1200px) and (max-width: 1400px) {
font-size: 30px;
}
}
}
// ==============================
//=============== FOOTER SECTION ===============
//==============================
#footer-top {
position: relative;
background: #2c302e;
border-radius: 150px 150px 0px 0px;
height: 80px;
.social-icons {
//background-image: url("../assets/img/home/socialbg.png");
background-repeat: no-repeat;
background-size: cover;
height: 47px;
align-items: center;
display: flex;
justify-content: center;
li {
list-style: none;
a {
display: inline-block;
color: #f7941e;
font-size: 18px;
padding: 0 15px;
text-decoration: none;
transition: ease-in-out 0.3s;
&:hover {
transform: scale(1.1);
margin-bottom: 10px;
}
}
}
@media screen and (max-width: 576px) {
height: 55px;
}
@media screen and (max-width: 768px) {
height: 53px;
}
}
.text-box {
position: absolute;
right: 15%;
.text {
background: #f7941e;
font-family: Open Sans;
font-style: normal;
font-weight: 600;
font-size: 14px;
line-height: 19px;
color: #ffffff;
padding: 10px 20px;
}
@media screen and (max-width: 768px) {
display: none;
}
}
}
#footer {
background: #2c302e;
h5 {
font-family: Open Sans;
font-style: normal;
font-weight: bold;
font-size: 24px;
line-height: 40px;
color: #f4f4f9;
}
p {
font-family: Open Sans;
font-style: normal;
font-weight: bold;
font-size: 16px;
line-height: 28px;
color: #efefef;
}
.logo-section {
padding-right: 50px;
.sponsors {
img {
margin-right: 10px;
}
}
.form-control {
background: #eaeaea;
border-radius: 10px 0 0px 10px;
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 24px;
color: #4e4e4e;
height: 50px;
}
.btn-send {
background: #f7941e;
border-radius: 0px 10px 10px 0px;
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 24px;
color: #ffffff;
}
@media screen and (max-width: 576px) {
padding-right: 0;
text-align: center;
.input-group {
width: 70%;
transform: translate(20%, 10px);
}
}
@media screen and (min-width: 577px) and (max-width: 768px) {
padding-right: 0;
text-align: center;
.input-group {
width: 50%;
transform: translate(50%, 10px);
}
}
}
.quick-links {
display: flex;
justify-content: space-between;
li {
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 40px;
color: #f4f4f9;
a {
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 40px;
text-decoration: none;
color: #f4f4f9;
}
&:hover {
color: #f7941e;
a {
color: #f7941e;
}
}
}
@media screen and (max-width: 576px) {
display: block;
}
}
.right-side {
padding-left: 40px;
.icon-text {
display: flex;
margin-bottom: 20px;
i {
width: 30px;
height: 30px;
color: #850312;
background-color: #eeeeee;
border-radius: 50%;
text-align: center;
padding-top: 5px;
}
p {
margin-bottom: 0;
margin-left: 10px;
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 28px;
color: #ffffff;
opacity: 0.9;
}
}
.img-btn {
border: 1px solid rgba(196, 196, 196, 0.5);
box-sizing: border-box;
border-radius: 30px;
width: 120px;
height: 50px;
margin-right: 20px;
background-color: #fff;
&:hover {
border-color: #f7941e;
}
}
@media screen and (max-width: 768px) {
padding-left: 15px;
}
}
.border-bottoms {
border-bottom: 3px solid #3d3d3d;
}
.copyright {
font-family: Open Sans;
padding-top: 15px;
padding-bottom: 15px;
margin-bottom: 0;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 28px;
color: #ffffff;
opacity: 0.25;
}
}
// =========================================
// Social Sidebar
//===========================================
#social-sidebar {
right: 0;
// margin-top: -135px;
position: fixed;
top: 35%;
z-index: 10000;
@media screen and (max-width: 576px) {
display: none;
}
}
#social-sidebar ul {
list-style: none;
padding: 0;
margin: 0;
}
#social-sidebar .bangla {
// height: 190px;
border-radius: 10px 0px 0px 0px;
border-top: transparent !important;
&:hover {
background-color: #222;
}
}
.fa-calendar-alt {
font-size: 25px;
position: absolute;
top: 7px;
right: 10px;
}
#social-sidebar .a2a_dd {
border-radius: 0px 0px 0px 10px;
}
#social-sidebar .transform2 {
height: 80px;
}
#social-sidebar .entypo-self {
height: 45px;
img {
position: relative;
bottom: -10px;
}
}
#social-sidebar .entypo-self,
#social-sidebar .transform {
font-size: 14px;
margin-bottom: 0px;
position: relative;
}
#social-sidebar .entypo-self,
#social-sidebar .lag_transform,
#social-sidebar .transform2,
#social-sidebar .transform {
line-height: 30px;
text-align: center;
width: 40px;
background: #f7941e;
// border-radius: 10px 0px 0px 10px;
// border-radius: 5px;
display: block;
font-family: Montserrat;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 20px;
text-align: center;
color: #fcf7f4;
&:hover {
background-color: #222;
}
}
#social-sidebar .transform span {
transform: rotate(90deg);
color: #fff;
font-weight: 400;
}
#social-sidebar .transform2 span {
transform: rotate(90deg);
color: #fff;
font-weight: 400;
}
#social-sidebar .transform span,
#social-sidebar .transform:hover span {
right: -55px;
z-index: 0;
opacity: 1;
}
#social-sidebar .transform2 span,
#social-sidebar .transform2:hover span {
right: -5px;
z-index: 5;
opacity: 1;
position: absolute;
top: 40px;
}
#social-sidebar a span {
border-radius: 3px;
line-height: 24px;
right: -522%;
margin-top: -16px;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
filter: alpha(opacity=0);
opacity: 0;
padding: 4px 8px;
position: absolute;
-webkit-transition: opacity 0.3s, right 0.4s;
-moz-transition: opacity 0.3s, right 0.4s;
-ms-transition: opacity 0.3s, right 0.4s;
-o-transition: opacity 0.3s, right 0.4s;
transition: opacity 0.3s, right 0.4s;
top: 50%;
white-space: nowrap;
z-index: -1;
}
#social-sidebar a span:before {
content: "";
display: block;
height: 8px;
right: -4px;
margin-top: -4px;
position: absolute;
top: 50%;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
width: 8px;
z-index: -2;
}
#social-sidebar .lag_transform {
font-size: 18px;
margin-bottom: 7px;
position: relative;
height: 70px;
}
| 29,578
|
https://github.com/TheShellLand/python/blob/master/v3/Libraries/socket/socket netcat.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python
|
TheShellLand
|
Python
|
Code
| 27
| 93
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 31337))
s.send('python says hello nc')
# 20
s.recv(30)
'nc says hello python\n'
s.close()
| 15,882
|
https://github.com/uwgraphics/hierarchicaldd/blob/master/external_libraries/Physbam/Public_Library/PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Shaders/RENDERING_HOMOGENEOUS_VOLUME_SHADER.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
hierarchicaldd
|
uwgraphics
|
C++
|
Code
| 202
| 1,563
|
//#####################################################################
// Copyright 2004, Andrew Selle.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#ifndef __RENDERING_HOMOGENEOUS_VOLUME_SHADER__
#define __RENDERING_HOMOGENEOUS_VOLUME_SHADER__
#include <PhysBAM_Geometry/Basic_Geometry_Intersections/RAY_BOX_INTERSECTION.h>
#include <PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering/RENDERING_RAY_DEBUG.h>
#include <PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Objects/RENDERING_VOXELS.h>
#include <PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Shaders/VOLUMETRIC_SHADER.h>
namespace PhysBAM{
template<class T>
class RENDERING_HOMOGENEOUS_VOLUME_SHADER:public VOLUMETRIC_SHADER<T>
{
public:
using VOLUMETRIC_SHADER<T>::world;using VOLUMETRIC_SHADER<T>::supports_photon_mapping;
T absorption,scattering,extinction;
T volumetric_step;
RENDERING_HOMOGENEOUS_VOLUME_SHADER(const T absorption_input,const T scattering_input,const T volumetric_step_input,RENDER_WORLD<T>& world_input)
:VOLUMETRIC_SHADER<T>(world_input),absorption(absorption_input),scattering(scattering_input),volumetric_step(volumetric_step_input)
{
extinction=absorption+scattering;
supports_photon_mapping=false;
}
T Phase(const VECTOR<T,3>& incoming, const VECTOR<T,3>& outgoing)
{return VOLUMETRIC_SHADER<T>::Isotropic_Phase_Function(incoming,outgoing);}
VECTOR<T,3> Attenuate_Color(const RENDERING_RAY<T>& ray,const RENDERING_OBJECT<T>& object,const VECTOR<T,3>& color,const int tid=1) PHYSBAM_OVERRIDE
{T start_t,end_t;
if(!object.Get_Intersection_Range(ray.ray,start_t,end_t))return color;
T current_t=end_t;T old_t;
bool last_segment=false;
const ARRAY<RENDERING_LIGHT<T> *>& lights=world.Lights();
VECTOR<T,3> attenuated_color=color;
int step_count=0;
while(!last_segment){
step_count++;
T current_volumetric_step=volumetric_step;
if(ray.debug_ray) ray.debug_ray->Add_Comment(STRING_UTILITIES::string_sprintf("Volumetric_Step %f, Current_T %f\n",current_volumetric_step,current_t));
if(current_t-current_volumetric_step<start_t){last_segment=true;current_volumetric_step=current_t-start_t;}
VECTOR<T,3> midpoint=ray.ray.Point(current_t-T(.5)*current_volumetric_step);
// absorption and outscattering
T exponential_attenuation=exp(-current_volumetric_step*extinction);
VECTOR<T,3> attenuation(exponential_attenuation,exponential_attenuation,exponential_attenuation);
attenuated_color*=attenuation;
// Compute inscattering (only direct lighting i.e. signle bounce)
for(int light_index=1;light_index<=lights.m;light_index++){
VECTOR<T,3> accumulated_radiance_samples(0,0,0);
ARRAY<RAY<VECTOR<T,3> > > sample_array;
lights(light_index)->Sample_Points(midpoint,VECTOR<T,3>(1,0,0),sample_array);
for(int sample=1;sample<=sample_array.m;sample++){
RENDERING_RAY<T> ray_to_light(sample_array(sample),1,&object);
VECTOR<T,3> attenuated_light_radiance=world.Incident_Light(ray_to_light,*lights(light_index),ray_to_light,ray,tid);
accumulated_radiance_samples+=attenuated_light_radiance*Phase(-ray_to_light.ray.direction,-ray.ray.direction);}
accumulated_radiance_samples/=(T)sample_array.m;
attenuated_color+=current_volumetric_step*accumulated_radiance_samples*scattering;}
// step next
old_t=current_t;current_t-=current_volumetric_step;}
return attenuated_color;}
VECTOR<T,3> Attenuate_Light(const RENDERING_RAY<T>& ray,const RENDERING_OBJECT<T>& object,const RENDERING_LIGHT<T>& light,const VECTOR<T,3>& light_color,const int tid=1) PHYSBAM_OVERRIDE
{const RENDERING_VOXELS<T>* voxel_object=(const RENDERING_VOXELS<T>*)&object;
T start_t,end_t;if(!INTERSECTION::Get_Intersection_Range(ray.ray,voxel_object->box,start_t,end_t))return light_color;
T attenuation_length=end_t-start_t;return std::exp(-attenuation_length*extinction)*light_color;}
bool Scatter_Photon_Ray(const RENDERING_OBJECT<T>& object,RENDERING_RAY<T>& ray,VECTOR<T,3>& photon_power,const typename PHOTON_MAP<T>::PHOTON_MAP_TYPE type,const T fixed_step_size,const int tid=1) PHYSBAM_OVERRIDE
{return false;}
//#####################################################################
};
}
#endif
| 13,635
|
https://github.com/ixaxaar/handyR/blob/master/dtw.r
|
Github Open Source
|
Open Source
|
MIT
| null |
handyR
|
ixaxaar
|
R
|
Code
| 305
| 986
|
require(dtw)
require(RColorBrewer)
# Data
a = c(rep(0, 1000), 10*sin(seq(1, 10*pi, length.out=500)) + 2*rnorm(500), rep(0, 1500)) +
arima.sim(n=3000, model=list(1,0,0))
# Pattern
b = 100*cos(seq(0, 2*pi, length.out=100))
# Number of sliding windows
winnum = 100
overlap = 10
# calculate window size
winsize = 0
winsize = ifelse (length(a) / winnum < length(b), length(b), length(a) / winnum)
print(paste("Window size ", winsize + overlap))
n = seq(winnum)
distances = rep(0, winnum)
n1s = rep(0, winnum)
n2s = rep(0, winnum)
last = 1
# Perform dtw fitting for each sliding window
for (ctr in n) {
n1 = last
n2 = last + winsize + overlap
last = last + (length(a) / winnum)
c = a[n1:n2]
d = dtw(x=b, y=c,
keep=TRUE,
open.end=TRUE,
open.begin=TRUE,
step=asymmetric,
window.type = "sakoechiba",
window.size=winsize+overlap)
# Store dtw distances for each window
distances[ctr] = d$distance
n1s[ctr] = n1
n2s[ctr] = n2
}
distances=data.frame(dist=distances, n1=n1s, n2=n2s)
distances.sub = subset(distances, dist>0)
distances.sorted = distances.sub[with(distances.sub, order(dist, decreasing=FALSE)),]
distances.mean = mean(distances.sorted$dist)
distances.min = subset(distances.sorted, dist < distances.mean)
matches = as.numeric(rownames(distances.min))
a.max = max(a)
a.min = min(a)
matches.unique = rep(TRUE, length(matches))
# Filter out overlapping solutions and keep ones with lowest distance
for (match in matches[matches.unique]) {
d = distances[match,]
d.int = sapply(matches, function(x) {
d2 = distances[x,]
n = length(intersect( seq(d$n2, d$n1), seq(d2$n2, d2$n1) ))
ifelse(n > (winsize+overlap)/2 && d$dist < d2$dist, FALSE, TRUE)
})
matches.unique = matches.unique & d.int
}
matches.unique = matches[matches.unique]
print(paste("Found ", length(matches.unique), " matches"))
ctr = 1
colors = rainbow(length(matches.unique))
par(mfrow=c(2,1), mai = c(0.5, 0.5, 0.5, 0.5))
# Plot the given signal
plot.ts(a,
ylim=c(a.min, a.max + 10))
for (match in matches.unique) {
d = distances[match,]
# Highlight the matched parts of the signal
lines(y=a[d$n1 : d$n2],
x=d$n1 : d$n2, col=colors[ctr])
# Indicate a bar depciting the range of match
points(y=rep(a.max + 5, d$n2-d$n1+1),
x=d$n1 : d$n2, col=colors[ctr], pch="-")
ctr = ctr + 1
}
plot.ts(distances$dist)
| 42,486
|
https://github.com/Schnitzel/ripple/blob/master/packages/components/Organisms/SiteFooter/stories.js
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,019
|
ripple
|
Schnitzel
|
JavaScript
|
Code
| 406
| 1,208
|
import { storiesOf } from '@storybook/vue'
import RplSiteFooter from './index.vue'
import {
text,
object
} from '@storybook/addon-knobs/vue'
storiesOf('Organisms/SiteFooter', module)
.add('Site footer', () => ({
components: { RplSiteFooter },
template: `
<rpl-site-footer
:nav="nav"
:links="links"
:copyright="copyright"
:acknowledgement="acknowledgement"
:logos="logos"
/>
`,
data () {
return {
nav: object('Nav', [
{
text: 'Your Services',
url: '#',
children: [
{
text: 'Grants awards and assistance',
url: '#'
},
{
text: 'Law and safety',
url: '#'
},
{
text: 'Business and Industry',
url: '#'
},
{
text: 'Jobs and the Workplace',
url: '#'
},
{
text: 'Transport and Traffic',
url: '#'
},
{
text: 'Education',
url: '#'
},
{
text: 'Housing and Property',
url: '#'
},
{
text: 'Health',
url: '#'
},
{
text: 'Community',
url: '#'
},
{
text: 'Art, Culture and Sport',
url: '#'
},
{
text: 'Environment and Water',
url: '#'
}
]
},
{
text: 'About VIC Government',
url: '#',
children: [
{
text: 'Grants awards and assistance',
url: '#'
},
{
text: 'Law and safety',
url: '#'
},
{
text: 'Business and Industry',
url: '#'
},
{
text: 'Jobs and the Workplace',
url: '#'
},
{
text: 'Transport and Traffic',
url: '#'
},
{
text: 'Education',
url: '#'
},
{
text: 'Housing and Property',
url: '#'
},
{
text: 'Health',
url: '#'
},
{
text: 'Community',
url: '#'
},
{
text: 'Art, Culture and Sport',
url: '#'
},
{
text: 'Environment and Water',
url: '#'
}
]
},
{
text: 'News',
url: '#'
},
{
text: 'Events',
url: '#'
},
{
text: 'Connect with us',
url: '#',
children: [
{
text: 'Education',
url: '#'
},
{
text: 'Housing and Property',
url: '#'
},
{
text: 'Health',
url: '#'
}
]
}
]),
links: object('Links', [
{
text: 'Privacy',
url: '#'
},
{
text: 'Disclaimer',
url: '#'
},
{
text: 'Terms of use',
url: '#'
},
{
text: 'Sitemap',
url: '#'
},
{
text: 'Accessibility Statement',
url: '#'
},
{
text: 'Help',
url: '#'
}
]),
copyright: text('Copyright', '© Copyright State Government of Victoria'),
acknowledgement: text('Acknowledgement', 'The Victorian Government acknowledges Aboriginal and Torres Strait Islander people as the Traditional Custodians of the land and acknowledges and pays respect to their Elders, past and present.'),
logos: object('Logos', [
{
src: 'https://placehold.it/112x52',
alt: 'Max native size',
url: '#'
},
{
src: 'https://placehold.it/32x32',
alt: 'Smaller than max size',
url: '#'
},
{
src: 'https://placehold.it/80x200',
alt: 'Portrait',
url: '#'
},
{
src: 'https://placehold.it/200x80',
alt: 'Landscape',
url: '#'
}
])
}
}
}))
| 15,456
|
https://github.com/danielsz/gerbil/blob/master/src/std/db/_sqlite.scm
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
gerbil
|
danielsz
|
Scheme
|
Code
| 602
| 2,728
|
;;; -*- Scheme -*-
;;; (C) vyzo at hackzen.org
;;; SQLite FFI
;; compile: -ld-options "-lsqlite3"
(declare
(block)
(standard-bindings)
(extended-bindings)
(not safe))
(namespace ("std/db/_sqlite#"))
(##namespace ("" define-macro define let let* if or and
quote quasiquote unquote unquote-splicing
c-lambda c-define-type c-declare c-initialize
))
(c-declare #<<END-C
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
#ifndef ___HAVE_FFI_U8VECTOR
#define ___HAVE_FFI_U8VECTOR
#define U8_DATA(obj) ___CAST (___U8*, ___BODY_AS (obj, ___tSUBTYPED))
#define U8_LEN(obj) ___HD_BYTES (___HEADER (obj))
#endif
END-C
)
(c-initialize #<<END-C
if (sqlite3_initialize () != SQLITE_OK) {
fprintf (stderr, "Warning: error initializing sqlite3 library\n");
}
END-C
)
(define-macro (define-c-lambda id args ret #!optional (name #f))
(let ((name (or name (##symbol->string id))))
`(define ,id
(c-lambda ,args ,ret ,name))))
(define-macro (define-const symbol)
(let* ((str (##symbol->string symbol))
(ref (##string-append "___return (" str ");")))
`(define ,symbol
((c-lambda () int ,ref)))))
(define-const SQLITE_OPEN_READONLY)
(define-const SQLITE_OPEN_READWRITE)
(define-const SQLITE_OPEN_CREATE)
(define-const SQLITE_OPEN_URI)
(define-const SQLITE_OPEN_MEMORY)
(define-const SQLITE_OPEN_NOMUTEX)
(define-const SQLITE_OPEN_FULLMUTEX)
(define-const SQLITE_OPEN_SHAREDCACHE)
(define-const SQLITE_OPEN_PRIVATECACHE)
(define-const SQLITE_OK)
(define-const SQLITE_ROW)
(define-const SQLITE_DONE)
(define-const SQLITE_INTEGER)
(define-const SQLITE_FLOAT)
(define-const SQLITE_BLOB)
(define-const SQLITE_NULL)
(define-const SQLITE_TEXT)
(c-declare #<<END-C
static int ffi_sqlite3_open (sqlite3**, const char *path, int flags);
static int ffi_sqlite3_prepare (sqlite3_stmt**, sqlite3* db, const char *sql);
static int ffi_sqlite3_bind_blob (sqlite3_stmt* stmt, int col, ___SCMOBJ data);
static int ffi_sqlite3_bind_text (sqlite3_stmt* stmt, int col, const char *str);
static void ffi_sqlite3_column_blob (sqlite3_stmt* stmt, int col, ___SCMOBJ bytes);
static ___SCMOBJ ffi_free (void *ptr);
END-C
)
(c-define-type sqlite3 "sqlite3")
(c-define-type sqlite3*
(pointer sqlite3 (sqlite3*)))
(c-define-type sqlite3**
(pointer sqlite3* (sqlite3**) "ffi_free"))
(c-define-type sqlite3_stmt "sqlite3_stmt")
(c-define-type sqlite3_stmt*
(pointer sqlite3_stmt (sqlite3_stmt*)))
(c-define-type sqlite3_stmt**
(pointer sqlite3_stmt* (sqlite3_stmt**) "ffi_free"))
(define-c-lambda make_sqlite3_ptr_ptr () sqlite3**
"___return ((sqlite3**)malloc (sizeof (sqlite3*)));")
(define-c-lambda sqlite3_ptr (sqlite3**) sqlite3*
"___return (*___arg1);")
(define-c-lambda make_sqlite3_stmt_ptr_ptr () sqlite3_stmt**
"___return ((sqlite3_stmt**)malloc (sizeof (sqlite3_stmt*)));")
(define-c-lambda sqlite3_stmt_ptr (sqlite3_stmt**) sqlite3_stmt*
"___return (*___arg1);")
(define-c-lambda sqlite3_errstr (int) UTF-8-string
"___return ((char*)sqlite3_errstr (___arg1));")
(define-c-lambda sqlite3_open (sqlite3** char-string int) int
"ffi_sqlite3_open")
(define-c-lambda sqlite3_close (sqlite3*) int
"sqlite3_close_v2")
(define-c-lambda sqlite3_prepare (sqlite3_stmt** sqlite3* UTF-8-string) int
"ffi_sqlite3_prepare")
(define-c-lambda sqlite3_stmt_readonly (sqlite3_stmt*) bool
"sqlite3_stmt_readonly")
(define-c-lambda sqlite3_stmt_busy (sqlite3_stmt*) bool
"sqlite3_stmt_busy")
(define-c-lambda sqlite3_bind_blob (sqlite3_stmt* int scheme-object) int
"ffi_sqlite3_bind_blob")
(define-c-lambda sqlite3_bind_int (sqlite3_stmt* int int) int
"sqlite3_bind_int")
(define-c-lambda sqlite3_bind_int64 (sqlite3_stmt* int int64) int
"sqlite3_bind_int64")
(define-c-lambda sqlite3_bind_double (sqlite3_stmt* int double) int
"sqlite3_bind_double")
(define-c-lambda sqlite3_bind_null (sqlite3_stmt* int) int
"sqlite3_bind_null")
(define-c-lambda sqlite3_bind_text (sqlite3_stmt* int UTF-8-string) int
"ffi_sqlite3_bind_text")
(define-c-lambda sqlite3_bind_zeroblob (sqlite3_stmt* int int) int
"sqlite3_bind_zeroblob")
(define-c-lambda sqlite3_bind_parameter_count (sqlite3_stmt*) int
"sqlite3_bind_parameter_count")
(define-c-lambda sqlite3_clear_bindings (sqlite3_stmt*) int
"sqlite3_clear_bindings")
(define-c-lambda sqlite3_column_count (sqlite3_stmt*) int
"sqlite3_column_count")
(define-c-lambda sqlite3_column_name (sqlite3_stmt* int) UTF-8-string
"___return ((char*)sqlite3_column_name (___arg1, ___arg2));")
(define-c-lambda sqlite3_column_decltype (sqlite3_stmt* int) UTF-8-string
"___return ((char*)sqlite3_column_decltype (___arg1, ___arg2));")
(define-c-lambda sqlite3_step (sqlite3_stmt*) int
"sqlite3_step")
(define-c-lambda sqlite3_data_count (sqlite3_stmt*) int
"sqlite3_data_count")
(define-c-lambda sqlite3_column_type (sqlite3_stmt* int) int
"sqlite3_column_type")
(define-c-lambda sqlite3_column_bytes (sqlite3_stmt* int) int
"sqlite3_column_bytes")
(define-c-lambda sqlite3_column_blob (sqlite3_stmt* int scheme-object) void
"ffi_sqlite3_column_blob")
(define-c-lambda sqlite3_column_text (sqlite3_stmt* int) UTF-8-string
"___return ((char*)sqlite3_column_text (___arg1, ___arg2));")
(define-c-lambda sqlite3_column_int (sqlite3_stmt* int) int
"sqlite3_column_int")
(define-c-lambda sqlite3_column_int64 (sqlite3_stmt* int) int64
"sqlite3_column_int64")
(define-c-lambda sqlite3_column_double (sqlite3_stmt* int) double
"sqlite3_column_double")
(define-c-lambda sqlite3_finalize (sqlite3_stmt*) int
"sqlite3_finalize")
(define-c-lambda sqlite3_reset (sqlite3_stmt*) int
"sqlite3_reset")
(c-declare #<<END-C
static int ffi_sqlite3_open (sqlite3** db, const char *path, int flags)
{
int r = sqlite3_open_v2 (path, db, flags, NULL);
if (r != SQLITE_OK) {
sqlite3_close_v2 (*db);
}
return r;
}
static int ffi_sqlite3_prepare (sqlite3_stmt** stmt, sqlite3* db, const char *sql)
{
int r = sqlite3_prepare_v2 (db, sql, strlen (sql), stmt, NULL);
if (r != SQLITE_OK) {
sqlite3_finalize (*stmt);
}
return r;
}
static int ffi_sqlite3_bind_blob (sqlite3_stmt* stmt, int col, ___SCMOBJ data)
{
return sqlite3_bind_blob (stmt, col, U8_DATA (data), U8_LEN (data), SQLITE_TRANSIENT);
}
static int ffi_sqlite3_bind_text (sqlite3_stmt* stmt, int col, const char *str)
{
return sqlite3_bind_text (stmt, col, str, strlen (str), SQLITE_TRANSIENT);
}
static void ffi_sqlite3_column_blob (sqlite3_stmt* stmt, int col, ___SCMOBJ bytes)
{
const void *blob = sqlite3_column_blob (stmt, col);
memcpy (U8_DATA (bytes), blob, U8_LEN (bytes));
}
#ifndef ___HAVE_FFI_FREE
#define ___HAVE_FFI_FREE
___SCMOBJ ffi_free (void *ptr)
{
free (ptr);
return ___FIX (___NO_ERR);
}
#endif
END-C
)
| 1,006
|
https://github.com/Allaeddineattia/Valravn/blob/master/src/DataBase/Imp/Repos/ImageRepo.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
Valravn
|
Allaeddineattia
|
C++
|
Code
| 359
| 1,711
|
//
// Created by alro on 29/11/2020.
//
#include <Shared/DependencyInjector.h>
#include "DataBase/Contracts/Repos/ImageRepo.h"
#include "DataBase/Contracts/Repos/Tools.h"
class ImageRepo::Impl{
private:
shared_ptr<DataBase > data_base = nullptr;
shared_ptr<IRepository<Multimedia>> multimedia_repo = nullptr;
string table_name = "IMAGE";
string get_create_table_sql() {
return "CREATE TABLE " + table_name + "("\
"ID INT PRIMARY KEY NOT NULL,"\
"MULTIMEDIA_ID INT UNIQUE,"\
"RESOLUTION TEXT NOT NULL,"\
"FOREIGN KEY(MULTIMEDIA_ID) REFERENCES " + multimedia_repo->getTableName() + "(ID)"\
");";
}
[[nodiscard]] static string_map get_string_map(const Image& image) {
string_map map;
map.insert(string_pair("ID", to_string(image.getId())));
map.insert(string_pair("MULTIMEDIA_ID", to_string(image.getMultimedia().getId())));
map.insert(string_pair("RESOLUTION" , DataBase::to_sql_string(image.getResolution())));
return map;
}
[[nodiscard]] static string_map get_update_string_map(const Image& old_element, const Image& new_element) {
string_map map;
if(new_element.getResolution() != old_element.getResolution())
map.insert(string_pair("RESOLUTION", DataBase::to_sql_string(new_element.getResolution())));
return map;
}
[[nodiscard]] unique_ptr<Image> get_entity_from_map(const string_map &map) {
int id = stoi(map.find("ID")->second);
string resolution = map.find("RESOLUTION")->second;
auto multimedia = multimedia_repo->getById(stoi(map.find("MULTIMEDIA_ID")->second)).value();
return make_unique<Image>(id, resolution, move(multimedia));
}
void create_element(const Image& element) const {
data_base->begin_transaction();
try {
multimedia_repo->save(element.getMultimedia());
string_map map = get_string_map(element);
data_base->insert_into_table(table_name, map);
}catch (const std::exception& ex){
data_base->abort_transaction();
throw ;
}
data_base->end_transaction();
}
void update_element(const Image& old_element, const Image& new_element) const {
string_map map = get_update_string_map(old_element, new_element);
if(!map.empty()){
string_pair id ("ID",to_string(old_element.getId()));
data_base->update_into_table(table_name, id, map);
}
multimedia_repo->save(new_element.getMultimedia());
}
public:
template<class Dependency>
explicit Impl(shared_ptr<Dependency> dependency_injector){
data_base = dependency_injector->get_data_base(dependency_injector);
multimedia_repo = dependency_injector->get_multimedia_repo(dependency_injector);
data_base->add_table_creation_sql(get_create_table_sql());
}
[[nodiscard]] const string & get_table_name() {
return table_name;
};
optional<unique_ptr<Image>> get_by_id(unsigned int id) {
auto image_map = data_base->get_by_id(table_name, to_string(id));
if(!image_map.empty())
return get_entity_from_map(image_map);
return std::nullopt;
};
vector<unique_ptr<Image>> get_all() {
vector<string_map> vector_res = data_base->get_all(table_name);
vector<unique_ptr<Image>> images;
for(auto &image_map: vector_res) {
auto multimedia = multimedia_repo->getById(stoi(image_map.find("MULTIMEDIA_ID")->second));
if(multimedia) images.push_back(get_entity_from_map(image_map));
}
return images;
};
[[nodiscard]] void save(const Image& element) {
auto exist = get_by_id(element.getId());
if(exist.has_value()){
auto img = move(exist.value());
if(img){
return update_element(*img, element);
}
}
create_element(element);
};
void delete_by_id(unsigned int id) {
string_pair feature_selection("ID", to_string(id));
auto image = get_by_id(id);
if(!image.has_value()){
throw "No Element found with id ";
}
data_base->begin_transaction();
try{
data_base->delete_by_feature(table_name, feature_selection);
multimedia_repo->deleteById(image.value()->getMultimedia().getId());
}catch (const std::exception& ex){
data_base->abort_transaction();
throw ;
}
data_base->end_transaction();
}
};
const string &ImageRepo::getTableName() const {
return mImpl->get_table_name();
}
optional<unique_ptr<Image>> ImageRepo::getById(unsigned int id) {
return mImpl->get_by_id(id);
}
vector<unique_ptr<Image>> ImageRepo::getAll() {
return mImpl->get_all();
}
void ImageRepo::save(const Image &element) {
mImpl->save(element);
}
void ImageRepo::deleteById(unsigned int id) {
return mImpl->delete_by_id(id);
}
template<class Dependency>
ImageRepo::ImageRepo(shared_ptr<Dependency> dependency_injector) {
mImpl = make_unique<Impl>(dependency_injector);
}
ImageRepo::~ImageRepo() = default;
namespace DO_NOT_EXECUTE{
void conf_template_image_repo(){
auto di = std::make_shared<DependencyInjector>();
ImageRepo a(di);
}
}
| 12,172
|
https://github.com/2387744807/RunCodeOnline/blob/master/CQPdemo/user/curlpost.h
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
RunCodeOnline
|
2387744807
|
C
|
Code
| 80
| 291
|
#pragma once
#define CURL_STATICLIB
#include "../libcurl/curl/curl.h"
#include <string>
#include <map>
class Http {
public:
Http(const std::string& url, const std::map<std::string, std::string>& headers = {}) noexcept;
void setUrl(const std::string& url) noexcept;
void setHeaders(const std::map<std::string, std::string>& headers)noexcept;
std::string static UTF8ToGBK(const std::string& strUTF8);
std::string static GBKToUTF8(const std::string& strGBK);
std::string static escape(const std::string& POSTFIELDS);
std::string Get() const;
std::string Post(const std::map<std::string, std::string>& postdata) const;
std::string Post(const std::string& postdata) const;
private:
std::string url;
std::map<std::string, std::string> headers;
size_t static write_data(void* buffer, size_t size, size_t nmemb, void* userp);
};
| 11,782
|
https://github.com/mlanett/screw/blob/master/lib/screw/queue.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
screw
|
mlanett
|
Ruby
|
Code
| 209
| 464
|
require "thread"
module Screw
class Queue
Unlimited = 0
Forever = (2 ** (0.size * 8 - 2) - 1) # Ruby uses an extra bit as a Fixnum flag.
NoWait = 0
class Timeout < ::Exception
end
# @param max is the maximum size of the queue. Optional, defaults to 0 (Unlimited).
def initialize(max = Unlimited)
raise max.inspect unless (Fixnum === max && max >= 0)
@max = max
@queue = []
@mutex = Mutex.new
@nempty = ConditionVariable.new
@nfull = ConditionVariable.new
end
def push(it)
@mutex.synchronize do
while @max > 0 && @queue.size >= @max do
@nfull.wait(@mutex)
end
# Push. But also if anyone else is waiting to pop, they can do it now.
@queue << it
@nempty.signal
self
end
end
# @param wait is timeout in seconds; Optional, defaults to Forever.
# @raises Timeout in the event of a timeout
def pop(wait = Forever)
raise wait.inspect unless (Fixnum === wait && wait >= 0)
@mutex.synchronize do
while @queue.size == 0
# Have we run out of time?
raise Timeout if wait <= 0
# Wait. Subtract wait time from timeout.
now = Time.now.to_i
@nempty.wait(@mutex, wait)
wait -= (Time.now.to_i - now)
end
# Pop
it = @queue.shift
@nfull.signal
it
end # synchronize
end # pop
end # Queue
end
| 3,455
|
https://github.com/wso2/andes/blob/master/modules/andes-core/management/eclipse-plugin/src/main/java/org/wso2/andes/management/ui/model/ManagedAttributeModel.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
andes
|
wso2
|
Java
|
Code
| 299
| 855
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.andes.management.ui.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ManagedAttributeModel
{
HashMap<String, AttributeData> _attributeMap = new HashMap<String, AttributeData>();
public void setAttributeValue(String name, Object value)
{
if (value == null)
return;
AttributeData data = null;
String dataType = value.getClass().getName();
if (_attributeMap.containsKey(name))
{
data = _attributeMap.get(name);
data.setValue(value);
}
else
{
data = new AttributeData();
data.setName(name);
data.setValue(value);
_attributeMap.put(name, data);
}
data.setDataType(dataType);
}
public void setAttributeDescription(String name, String value)
{
if (_attributeMap.containsKey(name))
{
_attributeMap.get(name).setDescription(value);
}
else
{
AttributeData data = new AttributeData();
data.setName(name);
data.setDescription(value);
_attributeMap.put(name, data);
}
}
public void setAttributeReadable(String name, boolean readable)
{
if (_attributeMap.containsKey(name))
{
_attributeMap.get(name).setReadable(readable);
}
else
{
AttributeData data = new AttributeData();
data.setName(name);
data.setReadable(readable);
_attributeMap.put(name, data);
}
}
public void setAttributeWritable(String name, boolean writable)
{
if (_attributeMap.containsKey(name))
{
_attributeMap.get(name).setWritable(writable);
}
else
{
AttributeData data = new AttributeData();
data.setName(name);
data.setWritable(writable);
_attributeMap.put(name, data);
}
}
public List<String> getAttributeNames()
{
return new ArrayList<String>(_attributeMap.keySet());
}
public AttributeData[] getAttributes()
{
return _attributeMap.values().toArray(new AttributeData[0]);
}
public AttributeData getAttribute(String name)
{
return _attributeMap.get(name);
}
public int getCount()
{
return _attributeMap.size();
}
}
| 8,351
|
https://github.com/aflame143/rit-iste422-project/blob/master/build.gradle
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
rit-iste422-project
|
aflame143
|
Gradle
|
Code
| 73
| 201
|
/*
* This file was generated by the Gradle 'init' task.
*
* This is a general purpose Gradle build.
* Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds/
*/
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testImplementation('junit:junit:4.12')
}
sourceSets {
main {
java {
srcDirs = ['src/java']
}
}
test {
java {
srcDirs = ['test/java']
}
}
}
task run(type: JavaExec) {
main = 'RunEdgeConvert'
classpath = sourceSets.main.runtimeClasspath
}
| 27,005
|
https://github.com/Vapor-Solutions/elsieworks-final/blob/master/resources/views/livewire/admin/skills/create.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
elsieworks-final
|
Vapor-Solutions
|
PHP
|
Code
| 9
| 33
|
<div>
<x-slot name="header">
Create a new Skill
</x-slot>
</div>
| 34,181
|
https://github.com/ccmbioinfo/crg/blob/master/crg.merge.annotate.sv.sh
|
Github Open Source
|
Open Source
|
MIT
| null |
crg
|
ccmbioinfo
|
Shell
|
Code
| 148
| 666
|
#!/bin/bash
# usage: crg.merge.annotate.sv.sh <family>
# run from within family/bcbio-sv/
FAMILY=$1
#run from bcbio-sv folder
dir=`pwd`;
logfile="${dir}/${FAMILY}_sv_jobids.log";
if [ ! -f $logfile ]; then
touch $logfile;
fi;
#run metasv on each sample
for f in $FAMILY_*/$FAMILY/final/$FAMILY*
do
cd $f
SAMPLE="$(echo $f | cut -d'/' -f1)"
metasv_jobs+=($(qsub ~/crg/metasv.pbs -v SAMPLE=$SAMPLE,FAMILY=$FAMILY))
cd ../../../..
done
metasv_string=$( IFS=$':'; echo "${metasv_jobs[*]}" )
#run snpeff on each sample
for f in $FAMILY_*/$FAMILY/final/$FAMILY*
do
SAMPLE="$(echo $f | cut -d'/' -f1)"
snpeff_jobs+=($(qsub ~/crg/crg.snpeff.sh -F $f/$SAMPLE/variants.vcf.gz -W depend=afterany:"${metasv_string}"))
done
snpeff_string=$( IFS=$':'; echo "${snpeff_jobs[*]}" )
#run svscore on each sample
for f in $FAMILY_*/$FAMILY/final/$FAMILY*
do
SAMPLE="$(echo $f | cut -d'/' -f1)"
svscore_jobs+=($(qsub ~/crg/crg.svscore.sh -F $f/$SAMPLE/variants.vcf.gz.snpeff.vcf -W depend=afterany:"${snpeff_string}"))
done
svscore_string=$( IFS=$':'; echo "${svscore_jobs[*]}" )
echo "metasv=${metasv_string}" >> ${logfile}
echo "snpeff=${snpeff_string}" >> ${logfile}
echo "svscore=${svscore_string}" >> ${logfile}
echo "Merging SVs with metaSV, annotating with snpeff, scoring with svscore, and creating report..."
jobid=$(qsub ~/crg/crg.intersect_sv_vcfs.sh -F $FAMILY -W depend=afterany:"${svscore_string}")
echo "intersect=$jobid">> ${logfile}
| 35,593
|
https://github.com/gunwook/development_blog_server/blob/master/src/components/Auth/interface.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
development_blog_server
|
gunwook
|
TypeScript
|
Code
| 38
| 100
|
import { IUserModel, SignUp } from '../User/model';
/**
* @export
* @interaface IAuthService
*/
export interface IAuthService {
/**
* @param {SignUp} SignUp
* @returns {Promise<IUserModel>}
* @memberof AuthService
*/
createUser(signUp: SignUp): Promise < IUserModel > ;
}
| 42,380
|
https://github.com/max-ieremenko/AdventOfCode2019/blob/master/Day04/Task2.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
AdventOfCode2019
|
max-ieremenko
|
C#
|
Code
| 107
| 296
|
namespace Day04
{
internal static class Task2
{
public static int Solve(int min, int max)
{
var current = Numbers.Split(min, 6);
var limit = Numbers.Split(max, 6);
Numbers.Normalize(current);
var result = 0;
while (Numbers.LessOrEqual(current, limit))
{
if (MeetsCriteria(current))
{
result++;
}
Numbers.FindNext(current);
}
return result;
}
internal static bool MeetsCriteria(int[] value)
{
const int GroupSize = 2;
var groupSign = value[0];
var groupLength = 1;
for (var i = 1; i < value.Length; i++)
{
if (groupSign == value[i])
{
groupLength++;
}
else if (groupLength == GroupSize)
{
return true;
}
else
{
groupSign = value[i];
groupLength = 1;
}
}
return groupLength == GroupSize;
}
}
}
| 16,710
|
https://github.com/stealthsoftwareinc/sst/blob/master/doc/manual/cl_sst_parse_opt.adoc
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
sst
|
stealthsoftwareinc
|
AsciiDoc
|
Code
| 490
| 1,237
|
//
// Copyright (C) 2012-2023 Stealth Software Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice (including
// the next paragraph) shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// SPDX-License-Identifier: MIT
//
[#cl-sst-parse-opt]
= The `sst::parse_opt` function
.{cpp}
[source,cpp,subs="{sst_subs_source}"]
----
#include <link:{repo_browser_url}/src/c-cpp/include/sst/catalog/parse_opt.hpp[sst/catalog/parse_opt.hpp,window=_blank]>
namespace sst {
template<class StringList, class String>
auto parse_opt(StringList & args,
String const & opt,
opt_arg style = opt_arg::required,
bool * has_arg = nullptr) ->
typename std::enable_if<!std::is_pointer<String>::value,
bool>::type;
template<class StringList, class CharT>
bool parse_opt(StringList & args,
CharT const * opt,
opt_arg style = opt_arg::required,
bool * has_arg = nullptr);
template<class StringList, class String1, class String2>
bool parse_opt(StringList & args,
std::initializer_list<String1> opts,
String2 * parsed_opt = nullptr,
opt_arg style = opt_arg::required,
bool * has_arg = nullptr);
template<class StringList, class String>
bool parse_opt(StringList & args,
std::initializer_list<String> opts,
opt_arg style = opt_arg::required,
bool * has_arg = nullptr);
}
----
.{empty}
[example]
====
The following program demonstrates how `sst::parse_opt` could be used to
parse the command-line arguments similarly to the `git init` command of
Git 2.31.0 (see
link:https://github.com/git/git/blob/v2.31.0/Documentation/git-init.txt[,window=_blank]):
.link:{repo_browser_url}/doc/manual/cl_sst_parse_opt_git_init_example.cpp[`cl_sst_parse_opt_git_init_example.cpp`,window=_blank]
[source,cpp]
----
include::cl_sst_parse_opt_git_init_example.cpp[]
----
.Invocation examples
[listing]
----
$ g++ cl_sst_parse_opt_git_init_example.cpp -lsst
$ ./a.out
ok
$ ./a.out --quiet --initial-branch foo
ok
$ ./a.out --quiet --initial-branch=foo
ok
# "--initial-branch foo" and "--initial-branch=foo" are equivalent
# because --initial-branch uses sst::opt_arg::required.
$ ./a.out --quiet --initial-branch
./a.out: option requires an argument: --initial-branch
$ ./a.out -q -b foo
ok
$ ./a.out -qbfoo
ok
# "-q -b foo", "-q -bfoo", and "-qbfoo" are equivalent because -q uses
# sst::opt_arg::forbidden and -b uses sst::opt_arg::required.
$ ./a.out -qb
./a.out: option requires an argument: -b
$ ./a.out -qbfoo --bar=baz
./a.out: unknown option: --bar
$ ./a.out -qbfoo -- --bar=baz
ok
# "--" is conventionally the options terminator (no further arguments
# are options, even if they begin with "-" or "--").
$ ./a.out --shared=all .
ok
$ ./a.out --shared all .
./a.out: directory given twice
# "--shared all" and "--shared=all" are not equivalent because --shared
# uses sst::opt_arg::permitted, not sst::opt_arg::required.
----
====
//
| 14,763
|
https://github.com/AnRADI/ProjectVue1/blob/master/webpack.mix.js
|
Github Open Source
|
Open Source
|
MIT
| null |
ProjectVue1
|
AnRADI
|
JavaScript
|
Code
| 120
| 457
|
const mix = require('laravel-mix');
const del = require('del');
const glob = require('glob');
let project_name = require("path").basename(__dirname);
let production = mix.inProduction();
// ------------- Don't generate license file --------------
mix.options({
terser: {
extractComments: false,
}
});
// ------------- Js glob --------------
let jsFiles = glob.sync('resources/js/**/*.js', {"ignore": 'resources/js/includes/**'});
let length = jsFiles.length;
for(let i = 0; i < length; i++) {
mix.js(jsFiles[i], jsFiles[i].replace('resources', 'public'));
}
// ------------- Scss glob --------------
let scssFiles = glob.sync('resources/sass/**/*.scss', {"ignore": 'resources/sass/includes/**'});
length = scssFiles.length;
for(let i = 0; i < length; i++) {
mix.sass(scssFiles[i], scssFiles[i].replace('resources/sass', 'public/css').replace('.scss', '.css')).options({
processCssUrls: false
});
}
// ------------- Other --------------
mix.webpackConfig(require('./webpack.config'))
.sourceMaps(!production, 'source-map')
.disableNotifications()
.browserSync({
proxy: project_name,
host: project_name,
notify: false,
open: 'external'
});
if (production) {
mix.version();
del(['public/js', 'public/css']);
//mix.version(['public/images', 'public/Admin/**/*.{js,css,png,jpg,gif,svg}']);
}
| 43,490
|
https://github.com/assintates/jikan/blob/master/src/Model/AnimeEpisode.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
jikan
|
assintates
|
PHP
|
Code
| 26
| 71
|
<?php
namespace Jikan\Model;
/**
* Class AnimeEpisode
*
* @package Jikan\Model
*/
class AnimeEpisode extends Model
{
public $episode = [];
public $episode_last_page = 1;
}
| 37,371
|
https://github.com/rahulkumaran/ui-components/blob/master/stories/NumberedSteps.stories.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
ui-components
|
rahulkumaran
|
TypeScript
|
Code
| 275
| 713
|
import { storiesOf } from '@storybook/react';
import React from 'react';
import { Column } from '../src/grid/column';
import { Row } from '../src/grid/row';
import { NumberedStep, NumberedSteps } from '../src/numbered-steps';
const stories = storiesOf('NumberedSteps', module);
stories.add('Numbered Steps with short content', () => (
<Row>
<Column width={4}>
<NumberedSteps>
<NumberedStep header="Use these settings">
<p>Configure your application with the settings below.</p>
</NumberedStep>
<NumberedStep header="Send your first email">
<p>Test your integration by sending email through your application.</p>
</NumberedStep>
</NumberedSteps>
</Column>
</Row>
));
stories.add('Numbered Steps with longer content', () => (
<Row>
<Column width={4}>
<NumberedSteps>
<NumberedStep header="Use these settings">
<p>Configure your application with the settings below.</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean rutrum neque nec felis pellentesque,
mollis varius libero consectetur. Nulla elementum pellentesque accumsan. Fusce sit amet quam quis
elit lobortis egestas sed eu turpis. Nullam luctus pellentesque enim placerat pretium. Vivamus
viverra nunc a tortor convallis egestas. Vestibulum mattis, nunc quis dapibus rhoncus, dui magna feugiat
tortor, ut rutrum orci dui dictum leo. Fusce convallis diam sit amet luctus maximus. Pellentesque vehicula
faucibus nunc, at cursus mi congue quis. Pellentesque tempus, est eget vestibulum ultricies, elit odio
blandit diam, in venenatis risus leo luctus orci.
</p>
</NumberedStep>
<NumberedStep header="Send your first email">
<div>
<p>Test your integration by sending email through your application.</p>
<p>
Vivamus quis volutpat nibh. Maecenas nibh eros, fermentum posuere convallis sed, consectetur et massa.
Donec feugiat a nisl quis porttitor. Ut egestas, libero non cursus posuere, quam nulla feugiat magna,
eget rutrum justo odio a nisi. Donec tincidunt urna in vulputate ultricies. Fusce id dolor vehicula,
tincidunt neque vel, iaculis nulla. Duis sed arcu leo.
</p>
</div>
</NumberedStep>
</NumberedSteps>
</Column>
</Row>
));
| 26,508
|
https://github.com/isqip/isqip-17/blob/master/Codezilla/Project/public/js/activate.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
isqip-17
|
isqip
|
JavaScript
|
Code
| 5
| 26
|
var page = window.location.pathname;
document.getElementById(page).classList.add('active');
| 21,664
|
https://github.com/idiotic/idiotic-legacy/blob/master/idiotic/distrib/udp.py
|
Github Open Source
|
Open Source
|
MIT
| null |
idiotic-legacy
|
idiotic
|
Python
|
Code
| 481
| 1,730
|
from . import base
import logging
import socket
import struct
import queue
PACKET_HEAD = b"ID10T"
ID_EVENT = 1
ID_DISCOVERY = 2
EVENT = 1
DISCOVERY = 2
RESPONSE = 3
FORMAT = {
EVENT: "{}s",
DISCOVERY: "H{}s",
RESPONSE: "H{}s",
}
HEADER_FORMAT = "!5sBI"
HEADER_LEN = struct.calcsize(HEADER_FORMAT)
LOG = logging.getLogger("idiotic.distrib.udp")
class UDPItem(base.RemoteItem):
pass
class UDPModule(base.RemoteModule):
pass
class UDPNeighbor(base.Neighbor):
def __init__(self, name, host, port):
self.name = name
self.host = host
self.port = port
self.modules = []
self.items = []
class UDPTransportMethod(base.TransportMethod):
NEIGHBOR_CLASS = UDPNeighbor
MODULE_CLASS = UDPModule
ITEM_CLASS = UDPItem
NAME = "udp"
def __init__(self, hostname, config):
self.hostname = hostname
config = config or {}
self.listen_port = config.get("port", 28300)
self.listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.listener.settimeout(5)
self.listener.bind(('', self.listen_port))
self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sender.bind(('', 0))
self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.incoming = queue.Queue()
self.neighbor_dict = {}
for connection in config.get("connect", []):
if 'name' in connection and 'host' in connection:
self.neighbor_dict[connection['name']] = UDPNeighbor(
connection['name'],
connection['host'],
connection.get('port',
self.listen_port))
self.running = False
def _encode_packet(self, kind, *data):
strlens = [len(s) for s in data if isinstance(s, str) or isinstance(s, bytes)]
msg_len = struct.calcsize('!' + FORMAT[kind].format(*strlens))
return struct.pack(HEADER_FORMAT + FORMAT[kind].format(*strlens),
PACKET_HEAD, kind, msg_len,
*[s.encode('UTF-8') if type(s) is str else s for s in data])
def _decode_packet(self, data):
head, kind, data_len = struct.unpack_from(HEADER_FORMAT, data)
if head != PACKET_HEAD:
raise ValueError("Invalid packet header '{}'".format(head))
if kind == EVENT:
tup = struct.unpack_from('!' + FORMAT[EVENT].format(data_len), data, HEADER_LEN)
elif kind == DISCOVERY or kind == RESPONSE:
port, host = struct.unpack_from('!' + FORMAT[DISCOVERY].format(
data_len - struct.calcsize(FORMAT[DISCOVERY][:1])), data, HEADER_LEN)
tup = port, host.decode('UTF-8')
return kind, tup
def _send_discovery(self, target='<broadcast>', port=None, response=False):
if port is None:
port = self.listen_port
LOG.info("Sending discovery message to ({}, {})".format(target, port))
try:
self.sender.sendto(self._encode_packet(RESPONSE if response else DISCOVERY,
self.listen_port, self.hostname),
(target, port))
except OSError:
LOG.warn("Unable to send UDP packet")
def connect(self):
for neighbor in self.neighbor_dict.values():
self._send_discovery(neighbor.host, neighbor.port)
self._send_discovery()
def run(self):
LOG.info("Starting UDP Distribution client.")
self.running = True
while self.running:
try:
data, addr = self.listener.recvfrom(2048)
LOG.debug("Received '{}' from {}".format(data, addr))
try:
kind, tup = self._decode_packet(data)
except ValueError:
LOG.error("Received invalid packet from {}: {}".format(addr, data))
if kind == DISCOVERY or kind == RESPONSE:
LOG.debug("Received discovery packet")
port, host = tup
if host == self.hostname and port == self.listen_port:
# Skip our own packets because... well... we're already
# connected to us...
continue
if host in self.neighbor_dict:
LOG.debug("Updating existing neighbor {}".format(host))
self.neighbor_dict[host].name = host
self.neighbor_dict[host].host = addr[0]
self.neighbor_dict[host].port = port
else:
LOG.info("Found new neighbor {} at {}".format(host, addr))
self.neighbor_dict[host] = UDPNeighbor(host, addr[0], port)
if kind != RESPONSE:
self._send_discovery(addr[0], port, response=True)
elif kind == ID_EVENT:
LOG.debug("Received event packet")
event, = tup
self.__do_callback(event)
else:
LOG.debug("Bad message kind: {}".format(kind))
except socket.timeout:
continue
def stop(self):
self.running = False
def disconnect(self):
pass
def __do_callback(self, event):
for cb in list(self.callbacks):
cb(event)
def send(self, event, targets=True):
LOG.debug("Sending event {} to: {}".format(event, targets))
if targets is True:
targets = [('<broadcast>', self.listen_port)]
else:
targets = [(self.neighbor_dict[n].host, self.neighbor_dict[n].port) for n in targets
if n in self.neighbor_dict]
for target in targets:
self.sender.sendto(self._encode_packet(EVENT, event),
target)
def neighbors(self):
return list(self.neighbor_dict.values())
METHOD = UDPTransportMethod
| 26,377
|
https://github.com/luserx0/UVA_solved/blob/master/UVA/11462_Age_Sort/age_sort.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
UVA_solved
|
luserx0
|
C++
|
Code
| 68
| 227
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define pb push_back
int main(){
long n;
scanf("%ld", &n);
while( n!= 0 ){
vector<int> ppl;
for( int i=0; i<n; ++i ){
int a;
scanf("%d", &a);
ppl.pb( a );
}
sort(ppl.begin(), ppl.end());
for( int j=0; j < n; ++j ){
if( j == n-1 )
printf("%d\n", ppl[j]);
else
printf("%d ", ppl[j]);
}
scanf("%ld", &n);
}
return 0;
}
| 27,171
|
https://github.com/backstage/backstage/blob/master/plugins/playlist/src/components/PlaylistCard/PlaylistCard.tsx
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-dco-1.1, Apache-2.0
| 2,023
|
backstage
|
backstage
|
TSX
|
Code
| 335
| 1,070
|
/*
* Copyright 2022 The Backstage 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.
*/
import {
ItemCardHeader,
LinkButton,
MarkdownContent,
} from '@backstage/core-components';
import { useRouteRef } from '@backstage/core-plugin-api';
import { EntityRefLinks } from '@backstage/plugin-catalog-react';
import { Playlist } from '@backstage/plugin-playlist-common';
import { BackstageTheme } from '@backstage/theme';
import {
Box,
Card,
CardActions,
CardContent,
CardMedia,
Chip,
makeStyles,
Tooltip,
Typography,
} from '@material-ui/core';
import LockIcon from '@material-ui/icons/Lock';
import React from 'react';
import { playlistRouteRef } from '../../routes';
const useStyles = makeStyles((theme: BackstageTheme) => ({
cardHeader: {
position: 'relative',
},
title: {
backgroundImage: theme.getPageTheme({ themeId: 'home' }).backgroundImage,
},
box: {
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
'-webkit-line-clamp': 10,
'-webkit-box-orient': 'vertical',
paddingBottom: '0.8em',
},
label: {
color: theme.palette.text.secondary,
textTransform: 'uppercase',
fontSize: '0.65rem',
fontWeight: 'bold',
letterSpacing: 0.5,
lineHeight: 1,
paddingBottom: '0.2rem',
},
chip: {
marginRight: 'auto',
},
privateIcon: {
position: 'absolute',
top: theme.spacing(0.5),
right: theme.spacing(0.5),
padding: '0.25rem',
},
}));
export type PlaylistCardProps = {
playlist: Playlist;
};
export const PlaylistCard = ({ playlist }: PlaylistCardProps) => {
const classes = useStyles();
const playlistRoute = useRouteRef(playlistRouteRef);
return (
<Card>
<CardMedia className={classes.cardHeader}>
{!playlist.public && (
<Tooltip className={classes.privateIcon} title="Private">
<LockIcon />
</Tooltip>
)}
<ItemCardHeader title={playlist.name} classes={{ root: classes.title }}>
<Chip
size="small"
variant="outlined"
label={`${playlist.entities} entities`}
/>
<Chip
size="small"
variant="outlined"
label={`${playlist.followers} followers`}
/>
</ItemCardHeader>
</CardMedia>
<CardContent style={{ display: 'grid' }}>
<Box className={classes.box}>
<Typography variant="body2" className={classes.label}>
Description
</Typography>
<MarkdownContent content={playlist.description ?? ''} />
</Box>
<Box className={classes.box}>
<Typography variant="body2" className={classes.label}>
Owner
</Typography>
<EntityRefLinks entityRefs={[playlist.owner]} defaultKind="group" />
</Box>
</CardContent>
<CardActions>
<LinkButton
color="primary"
aria-label={`Choose ${playlist.name}`}
to={playlistRoute({ playlistId: playlist.id })}
>
Choose
</LinkButton>
</CardActions>
</Card>
);
};
| 47,531
|
https://github.com/byverdu/crypto-dashboard/blob/master/packages/client/src/redux/actions/fetchApi.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
crypto-dashboard
|
byverdu
|
JavaScript
|
Code
| 56
| 187
|
import { createAction } from 'redux-actions';
import {
FETCH_API_DATA_REQUEST,
FETCH_API_DATA_SUCCESS,
FETCH_API_DATA_FAILED
} from '../constants';
const fetchApiDataRequest = createAction(
FETCH_API_DATA_REQUEST
);
const fetchApiDataSuccess = createAction(
FETCH_API_DATA_SUCCESS,
( status, data ) => ({ status, data })
);
const fetchApiDataFailed = createAction(
FETCH_API_DATA_FAILED,
( status, message ) => ({ status, message })
);
export {
fetchApiDataRequest,
fetchApiDataSuccess,
fetchApiDataFailed
};
| 25,514
|
https://github.com/sundusk/Bee/blob/master/Bee/Bee/Classes/four/Main/XW_Model/XW_IconsModel.h
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Bee
|
sundusk
|
Objective-C
|
Code
| 40
| 135
|
//
// XW_IconsModel.h
// Bee
//
// Created by 9264 on 16/9/8.
// Copyright © 2016年 ys. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface XW_IconsModel : NSObject
@property(nonatomic,copy) NSString *img;
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *customURL;
+ (instancetype)newsWithDict:(NSDictionary *)dict;
@end
| 18,199
|
https://github.com/qpham01/udacity/blob/master/dlfnd/deep-learning-local/tv-script-generation/tflib.py
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
udacity
|
qpham01
|
Python
|
Code
| 231
| 645
|
""" A library of classes for working with TensorFlow """
from collections import Counter
class TfTextRnn:
""" A base class for working with RNN for text processing in TensorFlow """
def __init__(self):
# Text data members
self.words = None
self.raw_features = None
self.raw_labels = None
self.features = None
self.feature_size = 0
self.embeddings = None
self.vocab_to_int = None
self.int_to_vocab = None
self.int_words = None
self.sorted_vocab = None
self.vocab_size = 0
self.embedding_size = 0
self.int_features = None
self.punctuation = None
# Train, validation, test
self.train_x = None
self.train_y = None
self.valid_x = None
self.valid_y = None
self.test_x = None
self.test_y = None
# TensorFlow graph data members
self.graph = None
self.inputs = None
self.labels = None
self.keep_prob = None
self.embedding = None
self.embed = None
self.lstm = None
self.drop = None
self.cell = None
self.initial_state = None
self.softmax_w = None
self.softmax_b = None
self.outputs = None
self.predictions = None
self.final_state = None
self.loss = None
self.cost = None
self.optimizer = None
self.accuracy = None
self.correct_pred = None
# Hyper parameters
self.lstm_size = 0
self.lstm_layers = 0
self.batch_size = 0
self.embed_size = 0
self.learning_rate = 0
self.epochs = 0
def _create_vocabulary(self):
"""
Create the vocabulary from the text corpus used for training.
Parameters:
"""
word_counts = Counter(self.words)
self.sorted_vocab = sorted(word_counts, key=word_counts.get, reverse=True)
self.int_to_vocab = {idx: word for idx, word in enumerate(self.sorted_vocab)}
self.vocab_to_int = {word: idx for idx, word in enumerate(self.sorted_vocab, 1)}
self.vocab_size = len(self.vocab_to_int)
| 5,043
|
https://github.com/clem16/pm-rtmgr-gen-db/blob/master/lib/Rtmgr/Gen/get_difference_between_server_and_database.pm
|
Github Open Source
|
Open Source
|
ClArtistic
| 2,020
|
pm-rtmgr-gen-db
|
clem16
|
Perl
|
Code
| 220
| 585
|
package Rtmgr::Gen::get_difference_between_server_and_database;
use 5.006;
use strict;
use warnings;
use DBI;
use Exporter qw(import);
our @EXPORT = qw(get_difference_between_server_and_database);
sub get_difference_between_server_and_database {
# $_[0]; # Reference to download list hash. Dereference with @{ $_[0] }
# $_[1]; # Scalar of name of database file.
# Open SQLite database.
my $driver = "SQLite";
my $database = "$_[1].db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = ""; # Not implemented no need for database security on local filesystem at this time.
my $password = ""; # Not implemented.
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr;
my $stmt = qq(SELECT ID from SEEDBOX;);
my $sth = $dbh->prepare( $stmt );
my $rv = $sth->execute() or die $DBI::errstr;
my @disk_array;
# Go through every item in database in while loop.
while(my @row = $sth->fetchrow_array()){
push(@disk_array, $row[0])
}
if( $rv < 0 ) {
print $DBI::errstr;
}
# Check if there is a difference between the two arrays.
my %diff1;
my %diff2;
@diff1{ @disk_array } = @disk_array;
delete @diff1{ @{ $_[0] } };
# %diff1 contains elements from '@disk_array' that are not in '@{ $_[0] }'
@diff2{ @{ $_[0] } } = @{ $_[0] };
delete @diff2{ @disk_array };
# %diff2 contains elements from '@{ $_[0] }' that are not in '@disk_array'
my @k = (keys %diff1, keys %diff2);
return(\@k);
$dbh->disconnect();
}
| 19,780
|
https://github.com/ncodeitbharath/gradle/blob/master/src/main/java/com/dotmarketing/struts/PortalRequestProcessor.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
gradle
|
ncodeitbharath
|
Java
|
Code
| 124
| 495
|
/*
* Created on Feb 17, 2005
*
*/
package com.dotmarketing.struts;
import com.dotmarketing.filters.Constants;
import com.dotmarketing.util.Config;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionMapping;
/**
* @author will
*
*/
public class PortalRequestProcessor extends com.liferay.portal.struts.PortalRequestProcessor {
protected String processPath(HttpServletRequest req, HttpServletResponse res) throws IOException {
String path = null;
if (req.getRequestURI().startsWith(Config.getStringProperty("CMS_STRUTS_PATH"))) {
path = super.callParentProcessPath(req, res);
} else {
path = super.processPath(req, res);
}
return path;
}
protected boolean processRoles(HttpServletRequest req, HttpServletResponse res, ActionMapping mapping) throws IOException,
ServletException {
if (req.getRequestURI().startsWith(Config.getStringProperty("CMS_STRUTS_PATH"))) {
return super.callParentProcessRoles(req, res, mapping);
} else {
return super.processRoles(req, res, mapping);
}
}
protected void doForward(String uri, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
if (req.getRequestURI().startsWith(Config.getStringProperty("CMS_STRUTS_PATH"))) {
req.setAttribute(Constants.CMS_FILTER_URI_OVERRIDE, uri);
req.getRequestDispatcher("/servlets/VelocityServlet").forward(req, res);
} else {
super.doForward(uri, req, res);
}
}
}
| 39,475
|
https://github.com/tabulon-ext/zeesh/blob/master/plugins/osx/func/screencap
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
zeesh
|
tabulon-ext
|
Shell
|
Code
| 165
| 384
|
#!/bin/sh
# Integrates Mac OS X's screenshot utility with DropBox for easy sharing.
# - Starts the interactive take-screenshot function, saves it to your public
# Dropbox (if you didn't cancel it) where it will be uploaded automatically.
# Copies the public URL to your clipboard and opens your browser to it.
## Config
dropbox_id="112358132134" ## this is fibonacci's dropbox id
dropbox_public_folder="$HOME/dropbox/Public/screenshots"
upload_delay_in_second=1.5
## Derivative Variables
filename=$(date '+%F__%H-%M-%S.png')
save_to="$dropbox_public_folder/$filename"
url="http://dl.dropbox.com/u/$dropbox_id/screenshots/$filename"
## start interactive screen capture
screencapture -i "$save_to"
## if the screenshot actually saved to a file (user didn't cancel by pressing escape)
if [[ -e "$save_to" ]]; then
## echo some output in case you run this in a shell
echo "Saved screenshot to:" "$save_to"
## copy url to the clipboard
echo "$url" | pbcopy
## wait for Dropbox to upload your screenshot, then open in your browser
sleep $upload_delay_in_second
## The `-g` flag means it won't bring your browser to the foreground, which
## feels less like getting interrupted.
open -g "$url"
fi
| 19,447
|
https://github.com/Zero-Rock/netease-cloud-music-react/blob/master/src/store/cube.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
netease-cloud-music-react
|
Zero-Rock
|
TypeScript
|
Code
| 30
| 86
|
/**
* Created by 含光<mobius_pan@yeah.net> on 2020/4/14 10:12 下午.
*/
import init from "cube-state";
const { createStore, createFlatStore, storeMap, use } = init();
export { createStore, createFlatStore, storeMap, use };
| 32,130
|
https://github.com/watawuwu/blackhole/blob/master/src/server.rs
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| null |
blackhole
|
watawuwu
|
Rust
|
Code
| 25
| 110
|
use crate::middleware::AccessLogMiddleware;
use anyhow::*;
use std::net::ToSocketAddrs;
pub async fn serve(addr: impl ToSocketAddrs) -> Result<()> {
let mut app = tide::new();
app.with(AccessLogMiddleware::new());
app.listen(addr.to_socket_addrs()?.collect::<Vec<_>>())
.await?;
Ok(())
}
| 13,318
|
https://github.com/ric2b/Vivaldi-browser/blob/master/chromium/chrome/browser/resources/settings/chromeos/device_page/display_layout.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
Vivaldi-browser
|
ric2b
|
JavaScript
|
Code
| 1,261
| 3,712
|
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* 'display-layout' presents a visual representation of the layout of one or
* more displays and allows them to be arranged.
*/
import 'chrome://resources/polymer/v3_0/paper-styles/shadow.js';
import '../../settings_shared.css.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {IronResizableBehavior} from 'chrome://resources/polymer/v3_0/iron-resizable-behavior/iron-resizable-behavior.js';
import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {DevicePageBrowserProxy, DevicePageBrowserProxyImpl} from './device_page_browser_proxy.js';
import {DragBehavior, DragBehaviorInterface, DragPosition} from './drag_behavior.js';
import {LayoutBehavior, LayoutBehaviorInterface} from './layout_behavior.js';
/**
* Container for DisplayUnitInfo. Mostly here to make the DisplaySelectEvent
* typedef more readable.
* @typedef {{item: !chrome.system.display.DisplayUnitInfo}}
*/
let InfoItem;
/**
* Required member fields for events which select displays.
* @typedef {{model: !InfoItem, target: !HTMLDivElement}}
*/
let DisplaySelectEvent;
/** @type {number} */ const MIN_VISUAL_SCALE = .01;
/**
* @constructor
* @extends {PolymerElement}
* @implements {DragBehaviorInterface}
* @implements {LayoutBehaviorInterface}
*/
const DisplayLayoutElementBase = mixinBehaviors(
[IronResizableBehavior, DragBehavior, LayoutBehavior], PolymerElement);
/** @polymer */
class DisplayLayoutElement extends DisplayLayoutElementBase {
static get is() {
return 'display-layout';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Array of displays.
* @type {!Array<!chrome.system.display.DisplayUnitInfo>}
*/
displays: Array,
/** @type {!chrome.system.display.DisplayUnitInfo|undefined} */
selectedDisplay: Object,
/**
* The ratio of the display area div (in px) to DisplayUnitInfo.bounds.
* @type {number}
*/
visualScale: {
type: Number,
value: 1,
},
/**
* Ids for mirroring destination displays.
* @type {!Array<string>|undefined}
* @private
*/
mirroringDestinationIds_: Array,
};
}
/** @override */
constructor() {
super();
/** @private {!{left: number, top: number}} */
this.visualOffset_ = {left: 0, top: 0};
/**
* Stores the previous coordinates of a display once dragging starts. Used
* to calculate the delta during each step of the drag. Null when there is
* no drag in progress.
* @private {?{x: number, y: number}}
*/
this.lastDragCoordinates_ = null;
/** @private {!DevicePageBrowserProxy} */
this.browserProxy_ = DevicePageBrowserProxyImpl.getInstance();
/** @private {boolean} */
this.allowDisplayAlignmentApi_ =
loadTimeData.getBoolean('allowDisplayAlignmentApi');
/** @private {string} */
this.invalidDisplayId_ = loadTimeData.getString('invalidDisplayId');
/** @private {boolean} */
this.hasDragStarted_ = false;
}
/** @override */
disconnectedCallback() {
super.disconnectedCallback();
this.initializeDrag(false);
}
/**
* Called explicitly when |this.displays| and their associated |this.layouts|
* have been fetched from chrome.
* @param {!Array<!chrome.system.display.DisplayUnitInfo>} displays
* @param {!Array<!chrome.system.display.DisplayLayout>} layouts
* @param {!Array<string>} mirroringDestinationIds
*/
updateDisplays(displays, layouts, mirroringDestinationIds) {
this.displays = displays;
this.layouts = layouts;
this.mirroringDestinationIds_ = mirroringDestinationIds;
this.initializeDisplayLayout(displays, layouts);
const self = this;
const retry = 100; // ms
function tryCalcVisualScale() {
if (!self.calculateVisualScale_()) {
setTimeout(tryCalcVisualScale, retry);
}
}
tryCalcVisualScale();
// Enable keyboard dragging before initialization.
this.keyboardDragEnabled = true;
this.initializeDrag(
!this.mirroring, this.$.displayArea,
(id, amount) => this.onDrag_(id, amount));
}
/**
* Calculates the visual offset and scale for the display area
* (i.e. the ratio of the display area div size to the area required to
* contain the DisplayUnitInfo bounding boxes).
* @return {boolean} Whether the calculation was successful.
* @private
*/
calculateVisualScale_() {
const displayAreaDiv = this.$.displayArea;
if (!displayAreaDiv || !displayAreaDiv.offsetWidth || !this.displays ||
!this.displays.length) {
return false;
}
let display = this.displays[0];
let bounds = this.getCalculatedDisplayBounds(display.id);
const boundsBoundingBox = {
left: bounds.left,
right: bounds.left + bounds.width,
top: bounds.top,
bottom: bounds.top + bounds.height,
};
let maxWidth = bounds.width;
let maxHeight = bounds.height;
for (let i = 1; i < this.displays.length; ++i) {
display = this.displays[i];
bounds = this.getCalculatedDisplayBounds(display.id);
boundsBoundingBox.left = Math.min(boundsBoundingBox.left, bounds.left);
boundsBoundingBox.right =
Math.max(boundsBoundingBox.right, bounds.left + bounds.width);
boundsBoundingBox.top = Math.min(boundsBoundingBox.top, bounds.top);
boundsBoundingBox.bottom =
Math.max(boundsBoundingBox.bottom, bounds.top + bounds.height);
maxWidth = Math.max(maxWidth, bounds.width);
maxHeight = Math.max(maxHeight, bounds.height);
}
// Create a margin around the bounding box equal to the size of the
// largest displays.
const boundsWidth = boundsBoundingBox.right - boundsBoundingBox.left;
const boundsHeight = boundsBoundingBox.bottom - boundsBoundingBox.top;
// Calculate the scale.
const horizontalScale =
displayAreaDiv.offsetWidth / (boundsWidth + maxWidth * 2);
const verticalScale =
displayAreaDiv.offsetHeight / (boundsHeight + maxHeight * 2);
const scale = Math.min(horizontalScale, verticalScale);
// Calculate the offset.
this.visualOffset_.left =
((displayAreaDiv.offsetWidth - (boundsWidth * scale)) / 2) -
boundsBoundingBox.left * scale;
this.visualOffset_.top =
((displayAreaDiv.offsetHeight - (boundsHeight * scale)) / 2) -
boundsBoundingBox.top * scale;
// Update the scale which will trigger calls to getDivStyle_.
this.visualScale = Math.max(MIN_VISUAL_SCALE, scale);
return true;
}
/**
* @param {string} id
* @param {!chrome.system.display.Bounds} displayBounds
* @param {number} visualScale
* @param {number=} opt_offset
* @return {string} The style string for the div.
* @private
*/
getDivStyle_(id, displayBounds, visualScale, opt_offset) {
// This matches the size of the box-shadow or border in CSS.
/** @type {number} */ const BORDER = 1;
/** @type {number} */ const MARGIN = 4;
/** @type {number} */ const OFFSET = opt_offset || 0;
/** @type {number} */ const PADDING = 3;
const bounds = this.getCalculatedDisplayBounds(id, true /* notest */);
if (!bounds) {
return '';
}
const height = Math.round(bounds.height * this.visualScale) - BORDER * 2 -
MARGIN * 2 - PADDING * 2;
const width = Math.round(bounds.width * this.visualScale) - BORDER * 2 -
MARGIN * 2 - PADDING * 2;
const left = OFFSET +
Math.round(this.visualOffset_.left + (bounds.left * this.visualScale));
const top = OFFSET +
Math.round(this.visualOffset_.top + (bounds.top * this.visualScale));
return 'height: ' + height + 'px; width: ' + width + 'px;' +
' left: ' + left + 'px; top: ' + top + 'px';
}
/**
* @param {number} mirroringDestinationIndex
* @param {number} mirroringDestinationDisplayNum
* @param {!Array<!chrome.system.display.DisplayUnitInfo>} displays
* @param {number} visualScale
* @return {string} The style string for the mirror div.
* @private
*/
getMirrorDivStyle_(
mirroringDestinationIndex, mirroringDestinationDisplayNum, displays,
visualScale) {
// All destination displays have the same bounds as the mirroring source
// display, but we add a little offset to each destination display's bounds
// so that they can be distinguished from each other in the layout.
return this.getDivStyle_(
displays[0].id, displays[0].bounds, visualScale,
(mirroringDestinationDisplayNum - mirroringDestinationIndex) * -4);
}
/**
* @param {!chrome.system.display.DisplayUnitInfo} display
* @param {!chrome.system.display.DisplayUnitInfo} selectedDisplay
* @return {boolean}
* @private
*/
isSelected_(display, selectedDisplay) {
return display.id === selectedDisplay.id;
}
focusSelectedDisplay_() {
if (!this.selectedDisplay) {
return;
}
const children = Array.from(this.$.displayArea.children);
const selected =
children.find(display => display.id === '_' + this.selectedDisplay.id);
if (selected) {
selected.focus();
}
}
/**
* @param {!DisplaySelectEvent} e
* @private
*/
onSelectDisplayTap_(e) {
const selectDisplayEvent = new CustomEvent(
'select-display', {composed: true, detail: e.model.item.id});
this.dispatchEvent(selectDisplayEvent);
// Force active in case the selected display was clicked.
// TODO(dpapad): Ask @stevenjb, why are we setting 'active' on a div?
e.target.active = true;
}
/**
* @param {!DisplaySelectEvent} e
* @private
*/
onFocus_(e) {
const selectDisplayEvent = new CustomEvent(
'select-display', {composed: true, detail: e.model.item.id});
this.dispatchEvent(selectDisplayEvent);
this.focusSelectedDisplay_();
}
/**
* @param {string} id
* @param {?DragPosition} amount
*/
onDrag_(id, amount) {
id = id.substr(1); // Skip prefix
let newBounds;
if (!amount) {
this.finishUpdateDisplayBounds(id);
newBounds = this.getCalculatedDisplayBounds(id);
this.lastDragCoordinates_ = null;
// When the drag stops, remove the highlight around the display.
this.browserProxy_.highlightDisplay(this.invalidDisplayId_);
} else {
this.browserProxy_.highlightDisplay(id);
// Make sure the dragged display is also selected.
if (id !== this.selectedDisplay.id) {
const selectDisplayEvent =
new CustomEvent('select-display', {composed: true, detail: id});
this.dispatchEvent(selectDisplayEvent);
}
const calculatedBounds = this.getCalculatedDisplayBounds(id);
newBounds =
/** @type {chrome.system.display.Bounds} */ (
Object.assign({}, calculatedBounds));
newBounds.left += Math.round(amount.x / this.visualScale);
newBounds.top += Math.round(amount.y / this.visualScale);
if (this.displays.length >= 2) {
newBounds = this.updateDisplayBounds(id, newBounds);
}
if (this.allowDisplayAlignmentApi_) {
if (!this.lastDragCoordinates_) {
this.hasDragStarted_ = true;
this.lastDragCoordinates_ = {
x: calculatedBounds.left,
y: calculatedBounds.top,
};
}
const deltaX = newBounds.left - this.lastDragCoordinates_.x;
const deltaY = newBounds.top - this.lastDragCoordinates_.y;
this.lastDragCoordinates_.x = newBounds.left;
this.lastDragCoordinates_.y = newBounds.top;
// Only call dragDisplayDelta() when there is a change in position.
if (deltaX !== 0 || deltaY !== 0) {
this.browserProxy_.dragDisplayDelta(
id, Math.round(deltaX), Math.round(deltaY));
}
}
}
const left =
this.visualOffset_.left + Math.round(newBounds.left * this.visualScale);
const top =
this.visualOffset_.top + Math.round(newBounds.top * this.visualScale);
const div = this.shadowRoot.querySelector('#_' + id);
div.style.left = '' + left + 'px';
div.style.top = '' + top + 'px';
this.focusSelectedDisplay_();
}
}
customElements.define(DisplayLayoutElement.is, DisplayLayoutElement);
| 5,324
|
https://github.com/thinhx2/Semyon/blob/master/io.asm
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Semyon
|
thinhx2
|
Assembly
|
Code
| 128
| 395
|
.module io
.title "IOs and sequence gen."
;Def file includes
.include "define.def"
.include "macro.def"
.area CODE
get_led_color:
;Puts in r3 the value of the next LED to display.
mov r3, #0
lcall inc_lfsr
jnc get_led_color_2
inc r3
inc r3
get_led_color_2:
lcall inc_lfsr
jnc get_led_color_ret
inc r3
get_led_color_ret:
ret
inc_lfsr:
;Now with Galois LFSR of 16 bits with polynomial x^16 + x^15 + x^13 + x^4 + 1 (mask 0xa011)
clr c
mov a, r0
rlc a
mov r0, a
mov a, r1
rlc a
mov r1, a
jnc inc_lfsr_ret
xrl 0x00, #P_LFSRMASK_L ;using absolute addresses of r0 and r1
xrl 0x01, #P_LFSRMASK_H
inc_lfsr_ret:
ret
display_led:
mov dptr, #D_LEDLOC
mov a, r3
anl a, #0x03
movc a, @a+dptr
mov V_PWM_LED, a
xrl P3, a
lcall delay_display
lcall pwm_led
ret
| 41,916
|
https://github.com/vinaykarora/Google-API/blob/master/Samples/YouTube Analytics API/v1beta1/ReportsSample.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
Google-API
|
vinaykarora
|
C#
|
Code
| 957
| 2,001
|
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Youtubeanalytics v1beta1 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Retrieves your YouTube Analytics data.
// API Documentation Link http://developers.google.com/youtube/analytics/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Youtubeanalytics/v1beta1/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Youtubeanalytics.v1beta1/
// Install Command: PM> Install-Package Google.Apis.Youtubeanalytics.v1beta1
//
//------------------------------------------------------------------------------
using Google.Apis.Youtubeanalytics.v1beta1;
using Google.Apis.Youtubeanalytics.v1beta1.Data;
using System;
namespace GoogleSamplecSharpSample.Youtubeanalyticsv1beta1.Methods
{
public static class ReportsSample
{
public class ReportsQueryOptionalParms
{
/// The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag will be ignored. Responds with an error if the specified currency is not recognized.
public string Currency { get; set; }
/// A comma-separated list of YouTube Analytics dimensions, such as views or ageGroup,gender. See the Available Reports document for a list of the reports that you can retrieve and the dimensions used for those reports. Also see the Dimensions document for definitions of those dimensions.
public string Dimensions { get; set; }
/// A list of filters that should be applied when retrieving YouTube Analytics data. The Available Reports document identifies the dimensions that can be used to filter each report, and the Dimensions document defines those dimensions. If a request uses multiple filters, join them together with a semicolon (;), and the returned result table will satisfy both filters. For example, a filters parameter value of video==dMH0bHeiRNg;country==IT restricts the result set to include data for the given video in Italy.
public string Filters { get; set; }
/// If set to true historical data (i.e. channel data from before the linking of the channel to the content owner) will be retrieved.
public bool? Include-historical-channel-data { get; set; }
/// The maximum number of rows to include in the response.
public int? Max-results { get; set; }
/// A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The '-' prefix causes descending sort order.
public string Sort { get; set; }
/// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive).
public int? Start-index { get; set; }
}
/// <summary>
/// Retrieve your YouTube Analytics reports.
/// Documentation https://developers.google.com/youtubeanalytics/v1beta1/reference/reports/query
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Youtubeanalytics service.</param>
/// <param name="ids">Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data.- To request data for a YouTube user, set the ids parameter value to channel==CHANNEL_ID, where CHANNEL_ID specifies the unique YouTube channel ID.- To request data for a YouTube CMS content owner, set the ids parameter value to contentOwner==OWNER_NAME, where OWNER_NAME is the CMS name of the content owner.</param>
/// <param name="start-date">The start date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format.</param>
/// <param name="end-date">The end date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format.</param>
/// <param name="metrics">A comma-separated list of YouTube Analytics metrics, such as views or likes,dislikes. See the Available Reports document for a list of the reports that you can retrieve and the metrics available in each report, and see the Metrics document for definitions of those metrics.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>ResultTableResponse</returns>
public static ResultTable Query(YoutubeanalyticsService service, string ids, string start-date, string end-date, string metrics, ReportsQueryOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (ids == null)
throw new ArgumentNullException(ids);
if (start-date == null)
throw new ArgumentNullException(start-date);
if (end-date == null)
throw new ArgumentNullException(end-date);
if (metrics == null)
throw new ArgumentNullException(metrics);
// Building the initial request.
var request = service.Reports.Query(ids, start-date, end-date, metrics);
// Applying optional parameters to the request.
request = (ReportsResource.QueryRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Reports.Query failed.", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
}
| 9,258
|
https://github.com/idorenyinudoh/modules/blob/master/scripts/content.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
modules
|
idorenyinudoh
|
TypeScript
|
Code
| 127
| 364
|
import { Octokit } from '@octokit/rest'
import got from 'got'
const rand = (min, max) => min + Math.round((Math.random() * (max - min)))
export default function () {
const { nuxt } = this
nuxt.hook('content:file:beforeInsert', async (module) => {
if (process.env.GITHUB_TOKEN) {
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN })
module.downloads = 0
try {
const body = await got(`https://api.npmjs.org/downloads/point/last-month/${module.npm}`).json() as any
module.downloads = body.downloads
} catch (err) {
console.error(`Could not fetch NPM stats for ${module.npm}`, err.message)
}
try {
const [owner, repo] = module.repo.split('#')[0].split('/')
const { data } = await octokit.repos.get({ owner, repo })
module.stars = data.stargazers_count || 0
} catch (err) {
console.error(`Could not fetch GitHub stars for ${module.repo}`, err.message)
}
} else {
module.downloads = rand(0, 500)
module.stars = rand(0, 2000)
}
})
}
| 45,427
|
https://github.com/Noxalus/Bomberman-AI/blob/master/Bomberman/Assets/Scripts/Player/PlayerMovement.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Bomberman-AI
|
Noxalus
|
C#
|
Code
| 235
| 946
|
using UnityEngine;
using UnityEngine.InputSystem;
using static UnityEngine.InputSystem.InputAction;
public class PlayerMovement : MonoBehaviour
{
[Header("Inner references")]
[SerializeField] private Player _player = null;
[SerializeField] private Rigidbody2D _rigidbody = null;
[SerializeField] private Animator _animator = null;
[SerializeField] private PlayerInput _input = null;
[Header("Assets")]
[SerializeField] private GameSettings _gameSettings = null;
private Vector2 _movement = Vector2.zero;
private float _speed = 0f;
public float Speed => _speed;
private void OnEnable()
{
if (_input)
{
_input.actions.Enable();
}
}
private void OnDisable()
{
if (_input)
{
_input.actions.Disable();
}
}
private void Awake()
{
if (_input)
{
_input.actions.FindAction("Bomb").performed += OnBombKeyPerformed;
_input.actions.FindAction("Move").performed += OnInputMovePerformed;
_input.actions.FindAction("Move").canceled += OnInputMoveCanceled;
}
_player.OnSpawn.AddListener(OnPlayerSpawn);
_player.OnDeath.AddListener(OnPlayerKill);
}
private void OnDestroy()
{
if (_input)
{
_input.actions.FindAction("Bomb").performed -= OnBombKeyPerformed;
}
_player.OnSpawn.RemoveListener(OnPlayerSpawn);
_player.OnDeath.RemoveListener(OnPlayerKill);
}
private void OnPlayerSpawn(Player player)
{
if (_input)
{
_input.actions.Enable();
}
}
private void OnPlayerKill(Player player)
{
if (_input)
{
_input.actions.Disable();
}
}
#region Used for ML agents
public void PlantBomb()
{
_player.AddBomb();
}
public void Move(Vector2 movement)
{
_movement = movement;
}
#endregion
private void OnBombKeyPerformed(CallbackContext context)
{
_player.AddBomb();
}
private void OnInputMovePerformed(CallbackContext context)
{
_movement = context.ReadValue<Vector2>();
}
private void OnInputMoveCanceled(CallbackContext context)
{
_movement = Vector2.zero;
}
private void Update()
{
_animator.SetFloat("Horizontal", _movement.x);
_animator.SetFloat("Vertical", _movement.y);
bool isMoving = _movement.sqrMagnitude > 0 && !_player.IsDead;
if (isMoving)
{
_animator.SetFloat("PreviousHorizontal", _movement.x);
_animator.SetFloat("PreviousVertical", _movement.y);
}
_animator.SetBool("IsMoving", isMoving);
}
private void FixedUpdate()
{
if (_player.IsDead)
{
return;
}
_speed = _gameSettings.PlayerBaseSpeed + (_player.SpeedBonus * _gameSettings.SpeedBonusIncrement);
_rigidbody.MovePosition(_rigidbody.position + _movement * _speed * Time.fixedDeltaTime);
}
}
| 18,827
|
https://github.com/josecostamartins/pythonreges/blob/master/prova1/exec2.py
|
Github Open Source
|
Open Source
|
MIT
| null |
pythonreges
|
josecostamartins
|
Python
|
Code
| 21
| 68
|
def verifica_numero(numero):
if numero > 0:
return "P"
else:
return "N"
valor = int(raw_input("Informe o valor: ") or 0)
print verifica_numero(valor)
| 27,708
|
https://github.com/mworion/MountWizzard4/blob/master/tests/unit_tests/gui/mainWmixin1/test_tabManageModel.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
MountWizzard4
|
mworion
|
Python
|
Code
| 1,917
| 9,056
|
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 for python
#
# written in python3, (c) 2019-2023 by mworion
# Licence APL2.0
#
###########################################################
# standard libraries
import unittest.mock as mock
import pytest
import glob
import json
import shutil
import os
# external packages
import PyQt5
from PyQt5.QtWidgets import QWidget
from skyfield.api import Star, Angle
from mountcontrol.modelStar import ModelStar
# local import
from tests.unit_tests.unitTestAddOns.baseTestApp import App
from gui.mainWmixin.tabManageModel import ManageModel
from gui.widgets.main_ui import Ui_MainWindow
from gui.utilities.toolsQtWidget import MWidget
@pytest.fixture(autouse=True, scope='module')
def module(qapp):
files = glob.glob('tests/workDir/model/*.model')
for f in files:
os.remove(f)
shutil.copy('tests/testData/test.model', 'tests/workDir/model/test.model')
shutil.copy('tests/testData/test1.model', 'tests/workDir/model/test1.model')
shutil.copy('tests/testData/test-opt.model', 'tests/workDir/model/test-opt.model')
yield
@pytest.fixture(autouse=True, scope='function')
def function(module):
class Mixin(MWidget, ManageModel):
def __init__(self):
super().__init__()
self.app = App()
self.msg = self.app.msg
self.widget1 = QWidget()
self.widget2 = QWidget()
self.widget3 = QWidget()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
ManageModel.__init__(self)
window = Mixin()
yield window
def test_initConfig_1(function):
function.app.config['mainW'] = {}
with mock.patch.object(function,
'showModelPosition'):
with mock.patch.object(function,
'showErrorAscending'):
with mock.patch.object(function,
'showErrorDistribution'):
function.initConfig()
assert function.ui.targetRMS.value() == 10
def test_storeConfig_1(function):
suc = function.storeConfig()
assert suc
def test_colorChangeManageModel(function):
with mock.patch.object(function,
'showModelPosition'):
with mock.patch.object(function,
'showErrorAscending'):
with mock.patch.object(function,
'showErrorDistribution'):
suc = function.colorChangeManageModel()
assert suc
def test_setNameList(function):
value = ['Test1', 'test2', 'test3', 'test4']
function.app.mount.model.nameList = value
function.setNameList(function.app.mount.model)
assert 4 == function.ui.nameList.count()
function.app.mount.model.nameList = []
def test_findKeysFromSourceInDest_1(function):
val1, val2 = function.findKeysFromSourceInDest({}, {})
assert val1 == []
assert val2 == []
def test_findKeysFromSourceInDest_2(function):
source = {1: {'ha': 1, 'dec': 2}, 2: {'ha': 4, 'dec': 3}}
dest = {1: {'ha': 2, 'dec': 1}, 2: {'ha': 3, 'dec': 4}}
val1, val2 = function.findKeysFromSourceInDest(source, dest)
assert val1 == []
assert 1 in val2
assert 2 in val2
def test_findKeysFromSourceInDest_3(function):
source = {1: {'ha': 1, 'dec': 2}, 2: {'ha': 3, 'dec': 4}}
dest = {1: {'ha': 2, 'dec': 1}, 2: {'ha': 3, 'dec': 4}}
val1, val2 = function.findKeysFromSourceInDest(source, dest)
assert 2 in val1
assert 1 in val2
def test_compareModel_1(function):
val1, val2 = function.compareModel({}, {})
assert val1 == []
assert val2 == []
def test_compareModel_2(function):
source = [{'errorIndex': 1, 'ha': 10, 'dec': 20}, {'errorIndex': 2, 'ha': 30, 'dec': 40}]
dest = {'1': {'ha': 30, 'dec': 40}}
val1, val2 = function.compareModel(source, dest)
assert val1 == []
assert val2 == [1, 2]
def test_findFittingModel_1(function):
function.app.mount.model.starList = list()
name, pointsIn, pointsOut = function.findFittingModel()
assert name == ''
assert pointsIn == []
assert pointsOut == []
def test_findFittingModel_2(function):
function.app.mwGlob['modelDir'] = 'tests/testData'
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
with mock.patch.object(function,
'compareModel',
return_value=([], [])):
name, pointsIn, pointsOut = function.findFittingModel()
assert name == ''
assert pointsIn == []
assert pointsOut == []
function.app.mwGlob['modelDir'] = 'tests/workDir/model'
def test_findFittingModel_3(function):
function.app.mwGlob['modelDir'] = 'tests/testData'
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
with mock.patch.object(json,
'load',
return_value={},
side_effect=Exception):
with mock.patch.object(function,
'compareModel',
return_value=([], [])):
name, pointsIn, pointsOut = function.findFittingModel()
assert name == ''
assert pointsIn == []
assert pointsOut == []
function.app.mwGlob['modelDir'] = 'tests/workDir/model'
def test_findFittingModel_4(function):
function.app.mwGlob['modelDir'] = 'tests/testData'
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
with mock.patch.object(json,
'load',
return_value={}):
with mock.patch.object(function,
'compareModel',
return_value=([1, 2, 3], [4])):
name, pointsIn, pointsOut = function.findFittingModel()
assert pointsIn == [1, 2, 3]
assert pointsOut == [4]
function.app.mwGlob['modelDir'] = 'tests/workDir/model'
def test_showModelPosition_1(function):
function.app.mount.model.starList = list()
suc = function.showModelPosition()
assert not suc
def test_showModelPosition_2(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
suc = function.showModelPosition()
assert suc
def test_showErrorAscending_1(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
suc = function.showErrorAscending()
assert suc
def test_showErrorAscending_2(function):
function.app.mount.model.starList = list()
suc = function.showErrorAscending()
assert not suc
def test_showErrorAscending_3(function):
temp = function.app.mount.obsSite.location
function.app.mount.obsSite.location = None
function.app.mount.model.starList = list()
suc = function.showErrorAscending()
assert not suc
function.app.mount.obsSite.location = temp
def test_showErrorAscending_4(function):
function.app.mount.model.starList = list()
suc = function.showErrorAscending()
assert not suc
def test_showErrorDistribution_1(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
suc = function.showErrorDistribution()
assert suc
def test_showErrorDistribution_2(function):
function.app.mount.model.starList = list()
suc = function.showErrorDistribution()
assert not suc
def test_showErrorDistribution_3(function):
temp = function.app.mount.obsSite.location
function.app.mount.obsSite.location = None
function.app.mount.model.starList = list()
suc = function.showErrorDistribution()
assert not suc
function.app.mount.obsSite.location = temp
def test_showErrorDistribution_4(function):
function.app.mount.model.starList = list()
suc = function.showErrorDistribution()
assert not suc
def test_clearRefreshName(function):
function.app.mount.signals.namesDone.connect(function.clearRefreshName)
suc = function.clearRefreshName()
assert suc
def test_refreshName_1(function):
with mock.patch.object(function.app.mount,
'getNames',
return_value=True):
suc = function.refreshName()
assert suc
suc = function.clearRefreshName()
assert suc
def test_refreshName_2(function):
suc = function.refreshName()
assert suc
suc = function.refreshName()
assert suc
def test_loadName_1(function):
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=None):
suc = function.loadName()
assert not suc
def test_loadName_2(function):
class Test:
@staticmethod
def text():
return 'test'
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=Test):
with mock.patch.object(function.app.mount.model,
'loadName',
return_value=True):
suc = function.loadName()
assert suc
def test_loadName_3(function):
class Test:
@staticmethod
def text():
return 'test'
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=Test):
with mock.patch.object(function.app.mount.model,
'loadName',
return_value=False):
suc = function.loadName()
assert not suc
def test_saveName_1(function):
with mock.patch.object(PyQt5.QtWidgets.QInputDialog,
'getText',
return_value=('', True)):
suc = function.saveName()
assert not suc
def test_saveName_2(function):
with mock.patch.object(PyQt5.QtWidgets.QInputDialog,
'getText',
return_value=(None, True)):
suc = function.saveName()
assert not suc
def test_saveName_3(function):
with mock.patch.object(PyQt5.QtWidgets.QInputDialog,
'getText',
return_value=('test', False)):
suc = function.saveName()
assert not suc
def test_saveName_4(function):
with mock.patch.object(PyQt5.QtWidgets.QInputDialog,
'getText',
return_value=('test', True)):
with mock.patch.object(function.app.mount.model,
'storeName',
return_value=False):
suc = function.saveName()
assert not suc
def test_saveName_5(function):
with mock.patch.object(PyQt5.QtWidgets.QInputDialog,
'getText',
return_value=('test', True)):
with mock.patch.object(function.app.mount.model,
'storeName',
return_value=True):
suc = function.saveName()
assert suc
def test_deleteName_1(function):
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=None):
suc = function.deleteName()
assert not suc
def test_deleteName_2(function):
class Test:
@staticmethod
def text():
return 'test'
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=Test):
with mock.patch.object(function,
'messageDialog',
return_value=False):
suc = function.deleteName()
assert not suc
def test_deleteName_3(function):
class Test:
@staticmethod
def text():
return 'test'
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=Test):
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'deleteName',
return_value=True):
suc = function.deleteName()
assert suc
def test_deleteName_4(function):
class Test:
@staticmethod
def text():
return 'test'
with mock.patch.object(function.ui.nameList,
'currentItem',
return_value=Test):
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'deleteName',
return_value=False):
suc = function.deleteName()
assert not suc
def writeRFD(a, b):
return {}
@mock.patch('gui.mainWmixin.tabManageModel.writeRetrofitData', writeRFD)
def test_writeBuildModelOptimized_1(function):
with mock.patch.object(json,
'load',
return_value=[{'errorIndex': 1}, {'errorIndex': 3}]):
with mock.patch.object(json,
'dump'):
suc = function.writeBuildModelOptimized('test', [1])
assert suc
@mock.patch('gui.mainWmixin.tabManageModel.writeRetrofitData', writeRFD)
def test_writeBuildModelOptimized_2(function):
with mock.patch.object(json,
'load',
return_value=[{'errorIndex': 1}, {'errorIndex': 3}],
side_effect=Exception):
suc = function.writeBuildModelOptimized('test', [1])
assert not suc
def test_clearRefreshModel_1(function):
function.app.mount.signals.alignDone.connect(function.clearRefreshModel)
suc = function.clearRefreshModel()
assert suc
def test_clearRefreshModel_2(function):
function.app.mount.signals.alignDone.connect(function.clearRefreshModel)
function.ui.autoUpdateActualAnalyse.setChecked(True)
with mock.patch.object(function,
'findFittingModel',
return_value=('test', [], [])):
with mock.patch.object(function,
'writeBuildModelOptimized'):
with mock.patch.object(function,
'showActualModelAnalyse'):
suc = function.clearRefreshModel()
assert suc
def test_refreshModel(function):
function.app.mount.signals.alignDone.connect(function.clearRefreshModel)
with mock.patch.object(function.app.mount,
'getAlign'):
suc = function.clearRefreshModel()
assert suc
def test_clearModel_1(function):
with mock.patch.object(function,
'messageDialog',
return_value=False):
suc = function.clearModel()
assert not suc
def test_clearModel_2(function):
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'clearAlign',
return_value=False):
suc = function.clearModel()
assert not suc
def test_clearModel_3(function):
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'clearAlign',
return_value=True):
suc = function.clearModel()
assert suc
def test_deleteWorstPoint_1(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
function.app.mount.model.numberStars = 0
suc = function.deleteWorstPoint()
assert not suc
def test_deleteWorstPoint_2(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
function.app.mount.model.numberStars = 3
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=True):
with mock.patch.object(function,
'refreshModel'):
suc = function.deleteWorstPoint()
assert suc
def test_deleteWorstPoint_3(function):
star = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0, errorAngle=0,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star, star, star]
function.app.mount.model.numberStars = 3
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=False):
with mock.patch.object(function,
'refreshModel'):
suc = function.deleteWorstPoint()
assert not suc
def test_runTargetRMS_1(function):
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
function.app.mount.signals.alignDone.connect(function.runTargetRMS)
function.app.mount.model.errorRMS = 0.1
suc = function.runTargetRMS()
assert suc
def test_runTargetRMS_2(function):
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
star1 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=5, errorAngle=90,
number=1, obsSite=function.app.mount.obsSite)
star2 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=4, errorAngle=90,
number=2, obsSite=function.app.mount.obsSite)
star3 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=3, errorAngle=90,
number=3, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star1, star2, star3]
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = 3
function.runningTargetRMS = True
function.app.mount.signals.alignDone.connect(function.runTargetRMS)
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=False):
with mock.patch.object(function.app.mount,
'getAlign'):
suc = function.runTargetRMS()
assert suc
def test_runTargetRMS_3(function):
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
star1 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=5, errorAngle=90,
number=1, obsSite=function.app.mount.obsSite)
star2 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=4, errorAngle=90,
number=2, obsSite=function.app.mount.obsSite)
star3 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=3, errorAngle=90,
number=3, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star1, star2, star3]
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = 3
function.runningTargetRMS = True
function.app.mount.signals.alignDone.connect(function.runTargetRMS)
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=True):
with mock.patch.object(function.app.mount,
'getAlign'):
suc = function.runTargetRMS()
assert suc
def test_runTargetRMS_4(function):
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = None
function.runningTargetRMS = False
function.app.mount.signals.alignDone.connect(function.runTargetRMS)
suc = function.runTargetRMS()
assert suc
def test_runSingleRMS_1(function):
function.ui.targetRMS.setValue(1)
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
star1 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=0.1, errorAngle=90,
number=1, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star1]
function.app.mount.signals.alignDone.connect(function.runSingleRMS)
function.app.mount.model.errorRMS = 0.1
suc = function.runSingleRMS()
assert suc
def test_runSingleRMS_2(function):
function.ui.targetRMS.setValue(1)
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
star1 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=5, errorAngle=90,
number=1, obsSite=function.app.mount.obsSite)
star2 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=4, errorAngle=90,
number=2, obsSite=function.app.mount.obsSite)
star3 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=3, errorAngle=90,
number=3, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star1, star2, star3]
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = 3
function.runningTargetRMS = True
function.app.mount.signals.alignDone.connect(function.runSingleRMS)
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=False):
with mock.patch.object(function.app.mount,
'getAlign'):
suc = function.runSingleRMS()
assert suc
def test_runSingleRMS_3(function):
function.ui.targetRMS.setValue(1)
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
star1 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=5, errorAngle=90,
number=1, obsSite=function.app.mount.obsSite)
star2 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=4, errorAngle=90,
number=2, obsSite=function.app.mount.obsSite)
star3 = ModelStar(Star(ra_hours=0, dec_degrees=0), errorRMS=3, errorAngle=90,
number=3, obsSite=function.app.mount.obsSite)
function.app.mount.model.starList = [star1, star2, star3]
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = 3
function.runningTargetRMS = True
function.app.mount.signals.alignDone.connect(function.runSingleRMS)
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=True):
with mock.patch.object(function.app.mount,
'getAlign'):
suc = function.runSingleRMS()
assert suc
def test_runSingleRMS_4(function):
function.ui.targetRMS.setValue(1)
function.runningOptimize = True
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
function.app.mount.model.errorRMS = 100
function.app.mount.model.numberStars = None
function.runningTargetRMS = False
function.app.mount.signals.alignDone.connect(function.runSingleRMS)
with mock.patch.object(function,
'finishOptimize'):
suc = function.runSingleRMS()
assert suc
def test_runOptimize_1(function):
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
with mock.patch.object(function,
'runTargetRMS'):
suc = function.runOptimize()
assert suc
def test_runOptimize_2(function):
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
with mock.patch.object(function,
'runSingleRMS'):
suc = function.runOptimize()
assert suc
def test_finishOptimize_1(function):
function.ui.optimizeOverall.setChecked(False)
function.ui.optimizeSingle.setChecked(True)
function.app.mount.signals.alignDone.connect(function.runSingleRMS)
suc = function.finishOptimize()
assert suc
def test_finishOptimize_2(function):
function.ui.optimizeOverall.setChecked(True)
function.ui.optimizeSingle.setChecked(False)
function.app.mount.signals.alignDone.connect(function.runTargetRMS)
suc = function.finishOptimize()
assert suc
def test_cancelOptimize_1(function):
suc = function.cancelOptimize()
assert suc
assert not function.runningOptimize
def test_showOriginalModelAnalyse_1(function):
function.fittedModelPath = ''
suc = function.showOriginalModelAnalyse()
assert not suc
def test_showOriginalModelAnalyse_2(function):
function.fittedModelPath = 'test'
suc = function.showOriginalModelAnalyse()
assert not suc
def test_showOriginalModelAnalyse_3(function):
function.fittedModelPath = 'tests/testData/test.model'
suc = function.showOriginalModelAnalyse()
assert suc
def test_showActualModelAnalyse_1(function):
function.fittedModelPath = ''
suc = function.showActualModelAnalyse()
assert not suc
def test_showActualModelAnalyse_2(function):
function.fittedModelPath = 'test'
suc = function.showActualModelAnalyse()
assert not suc
def test_showActualModelAnalyse_3(function):
function.fittedModelPath = 'tests/testData/test.model'
suc = function.showActualModelAnalyse()
assert suc
def test_pointClicked_1(function):
class Event:
@staticmethod
def button():
return 1
@staticmethod
def double():
return True
suc = function.pointClicked(None, None, Event())
assert not suc
def test_pointClicked_2(function):
class Event:
@staticmethod
def button():
return 2
@staticmethod
def double():
return False
suc = function.pointClicked(None, None, Event())
assert not suc
def test_pointClicked_3(function):
class Event:
@staticmethod
def button():
return 1
@staticmethod
def double():
return False
class Points:
@staticmethod
def data():
return []
points = [Points()]
suc = function.pointClicked(None, points, Event())
assert not suc
def test_pointClicked_4(function):
class Event:
@staticmethod
def button():
return 1
@staticmethod
def double():
return False
class Points:
@staticmethod
def data():
return [1, 1]
points = [Points()]
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
function.app.mount.model.starList.append(a)
with mock.patch.object(function,
'messageDialog',
return_value=False):
suc = function.pointClicked(None, points, Event())
assert not suc
def test_pointClicked_5(function):
class Event:
@staticmethod
def button():
return 1
@staticmethod
def double():
return False
class Points:
@staticmethod
def data():
return [1, 1]
points = [Points()]
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
function.app.mount.model.starList.append(a)
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=False):
suc = function.pointClicked(None, points, Event())
assert not suc
def test_pointClicked_6(function):
class Event:
@staticmethod
def button():
return 1
@staticmethod
def double():
return False
class Points:
@staticmethod
def data():
return [1, 1]
points = [Points()]
function.app.mount.model.starList = list()
a = ModelStar(obsSite=function.app.mount.obsSite)
a.alt = 0
a.az = 0
a.coord = Star(ra_hours=0, dec_degrees=0)
a.errorAngle = Angle(degrees=0)
a.errorRMS = 1
function.app.mount.model.starList.append(a)
function.app.mount.model.starList.append(a)
with mock.patch.object(function,
'messageDialog',
return_value=True):
with mock.patch.object(function.app.mount.model,
'deletePoint',
return_value=True):
with mock.patch.object(function,
'refreshModel'):
suc = function.pointClicked(None, points, Event())
assert suc
| 24,557
|
https://github.com/Veil-Project/veil/blob/master/src/pow.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
veil
|
Veil-Project
|
C++
|
Code
| 2,107
| 7,091
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2019-2020 Veil developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pow.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>
#include <tinyformat.h>
#include <boost/thread.hpp>
// ProgPow
#include <crypto/ethash/lib/ethash/endianness.hpp>
// RandomX
#include <crypto/randomx/randomx.h>
#include <miner.h>
#include <validation.h>
#include <chainparams.h>
// TODO, build an class object that holds this data
// Used by CPU miner for randomx
CCriticalSection cs_randomx_mining;
static uint256 mining_key_block;
static randomx_cache *myMiningCache;
static randomx_dataset *myMiningDataset;
std::vector<randomx_vm*> vecRandomXVM;
std::vector<std::thread> vecRandomXThreads;
bool fKeyBlockedChanged = false;
// Used by Validator
CCriticalSection cs_randomx_validator;
static uint256 validation_key_block;
static randomx_cache *myCacheValidating;
static randomx_vm *myMachineValidating;
static bool fLightCacheInited = false;
bool IsRandomXLightInit()
{
LOCK(cs_randomx_validator);
return fLightCacheInited;
}
void InitRandomXLightCache(const int32_t& height) {
LOCK(cs_randomx_validator);
if (fLightCacheInited)
return;
validation_key_block = GetKeyBlock(height);
global_randomx_flags = (int)randomx_get_flags();
myCacheValidating = randomx_alloc_cache((randomx_flags)global_randomx_flags);
randomx_init_cache(myCacheValidating, &validation_key_block, sizeof uint256());
LogPrintf("%s: Spinning up a new vm at new block height: %d\n", __func__, height);
myMachineValidating = randomx_create_vm_timed((randomx_flags)global_randomx_flags, myCacheValidating, NULL, true);
fLightCacheInited = true;
}
void KeyBlockChanged(const uint256& new_block) {
LOCK(cs_randomx_validator);
validation_key_block = new_block;
DeallocateRandomXLightCache();
myCacheValidating = randomx_alloc_cache((randomx_flags)global_randomx_flags);
randomx_init_cache(myCacheValidating, &validation_key_block, sizeof uint256());
LogPrintf("%s: Spinning up a new vm at new block: %s\n", __func__, new_block.GetHex());
myMachineValidating = randomx_create_vm_timed((randomx_flags)global_randomx_flags, myCacheValidating, NULL, true);
fLightCacheInited = true;
}
uint256 GetCurrentKeyBlock() {
return validation_key_block;
}
randomx_vm* GetMyMachineValidating() {
return myMachineValidating;
}
randomx_flags GetRandomXFlags() {
return (randomx_flags)global_randomx_flags;
}
bool CheckIfMiningKeyShouldChange(const uint256& check_block)
{
LOCK(cs_randomx_validator);
return check_block != mining_key_block;
}
void CheckIfValidationKeyShouldChangeAndUpdate(const uint256& check_block)
{
LOCK(cs_randomx_validator);
if (check_block != validation_key_block)
KeyBlockChanged(check_block);
}
void DeallocateRandomXLightCache() {
LOCK(cs_randomx_validator);
if (!fLightCacheInited) {
LogPrintf("%s: Return because light cache isn't inited\n", __func__);
return;
}
if (myMachineValidating) {
LogPrintf("%s: Releasing the vm\n",__func__);
randomx_destroy_vm(myMachineValidating);
myMachineValidating = nullptr;
}
if (myCacheValidating) {
LogPrintf("%s: Releasing the validating cache\n",__func__);
randomx_release_cache(myCacheValidating);
myCacheValidating = nullptr;
}
fLightCacheInited = false;
}
arith_uint256 GetPowLimit(int nPoWType)
{
const Consensus::Params& params = Params().GetConsensus();
// Select the correct pow limit
if (nPoWType & CBlockHeader::PROGPOW_BLOCK) {
return UintToArith256(params.powLimitProgPow);
} else if (nPoWType & CBlock::RANDOMX_BLOCK) {
return UintToArith256(params.powLimitRandomX);
} else if (nPoWType & CBlock::SHA256D_BLOCK) {
return UintToArith256(params.powLimitSha256);
} else {
return UintToArith256(params.powLimit);
}
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock,
const Consensus::Params& params, bool fProofOfStake, int nPoWType)
{
assert(pindexLast != nullptr);
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
if (nPoWType & CBlock::RANDOMX_BLOCK) {
nProofOfWorkLimit = UintToArith256(params.powLimitRandomX).GetCompact();
}
if (!fProofOfStake && !nPoWType && (pindexLast->GetBlockTime() >= Params().PowUpdateTimestamp())) {
// If it's the old algo, don't even waste time calculating the difficulty.
return UintToArith256(params.powLimit).GetCompact();
}
if (params.fPowNoRetargeting) // regtest only
return nProofOfWorkLimit;
if (pindexLast->GetBlockTime() < Params().PowUpdateTimestamp()) {
// Use old algo
return DGW_old(pindexLast, params, fProofOfStake);
}
// Retarget every block with DarkGravityWave
return DarkGravityWave(pindexLast, params, fProofOfStake, nPoWType);
}
unsigned int DGW_old(const CBlockIndex* pindexLast, const Consensus::Params& params, bool fProofOfStake) {
/* current difficulty formula, veil - DarkGravity v3, written by Evan Duffield - evan@dash.org */
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
const CBlockIndex *pindex = pindexLast;
const CBlockIndex* pindexLastMatchingProof = nullptr;
arith_uint256 bnPastTargetAvg = 0;
unsigned int nCountBlocks = 0;
while (nCountBlocks < params.nDgwPastBlocks_old) {
// Ran out of blocks, return pow limit
if (!pindex)
return bnPowLimit.GetCompact();
// Only consider PoW or PoS blocks but not both
if (pindex->IsProofOfStake() != fProofOfStake) {
pindex = pindex->pprev;
continue;
} else if (!pindexLastMatchingProof) {
pindexLastMatchingProof = pindex;
}
arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);
bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) / (nCountBlocks + 1);
if (++nCountBlocks != params.nDgwPastBlocks_old)
pindex = pindex->pprev;
}
arith_uint256 bnNew(bnPastTargetAvg);
//Should only happen on the first PoS block
if (pindexLastMatchingProof)
pindexLastMatchingProof = pindexLast;
int64_t nActualTimespan = pindexLastMatchingProof->GetBlockTime() - pindex->GetBlockTime();
int64_t nTargetTimespan = params.nDgwPastBlocks_old * params.nPowTargetSpacing;
if (nActualTimespan < nTargetTimespan/3)
nActualTimespan = nTargetTimespan/3;
if (nActualTimespan > nTargetTimespan*3)
nActualTimespan = nTargetTimespan*3;
// Retarget
bnNew *= nActualTimespan;
bnNew /= nTargetTimespan;
if (bnNew > bnPowLimit) {
bnNew = bnPowLimit;
}
return bnNew.GetCompact();
}
unsigned int DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params, bool fProofOfStake, int nPoWType) {
/* current difficulty formula, veil - DarkGravity v3, written by Evan Duffield - evan@dash.org */
arith_uint256 bnPowLimit = GetPowLimit(nPoWType);
const CBlockIndex *pindex = pindexLast;
const CBlockIndex *pStart = pindexLast;
const CBlockIndex* pindexLastMatchingProof = nullptr;
const CBlockIndex* pindexOneBack = nullptr;
arith_uint256 bnPastTargetAvg = 0;
unsigned int nCountBlocks = 0;
int64_t nPastBlocks = Params().GetDwgPastBlocks(pindexLast, nPoWType, fProofOfStake);
bool fNewPoW = true;
while (nCountBlocks < nPastBlocks) {
// Ran out of blocks, return pow limit
if (!pindex)
return bnPowLimit.GetCompact();
fNewPoW = false;
// If we're looking for new algo blocks
if (nPoWType & (CBlockHeader::PROGPOW_BLOCK | CBlockHeader::RANDOMX_BLOCK | CBlockHeader::SHA256D_BLOCK)) {
// Check if we've walked to before the switchover
fNewPoW = true;
if (pindex->GetBlockTime() < Params().PowUpdateTimestamp()) {
// We don't have enough of the blocks, get out and use what we have
break;
}
}
// Only consider PoW or PoS blocks but not both
if (pindex->IsProofOfStake() != fProofOfStake) {
pindex = pindex->pprev;
continue;
} else if ((nPoWType & CBlockHeader::PROGPOW_BLOCK) && !pindex->IsProgProofOfWork()) {
pindex = pindex->pprev;
continue;
} else if ((nPoWType & CBlockHeader::RANDOMX_BLOCK) && !pindex->IsRandomXProofOfWork()) {
pindex = pindex->pprev;
continue;
} else if ((nPoWType & CBlockHeader::SHA256D_BLOCK) && !pindex->IsSha256DProofOfWork()) {
pindex = pindex->pprev;
continue;
} else if (pindex->IsX16RTProofOfWork() && !fProofOfStake && nPoWType != 0) {
pindex = pindex->pprev;
continue;
} else if (!pindexLastMatchingProof) {
// save the tip block for the proof
pindexLastMatchingProof = pindex;
} else if (!pindexOneBack) {
// save the second one back in case the tip is the mined one
pindexOneBack = pindex;
}
arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);
bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) / (nCountBlocks + 1);
if (++nCountBlocks < nPastBlocks)
pindex = pindex->pprev;
}
arith_uint256 bnNew(bnPastTargetAvg);
//Should only happen on the first PoS block
if (pindexLastMatchingProof && !pindex->IsProgProofOfWork() &&
!pindex->IsRandomXProofOfWork() && !pindex->IsSha256DProofOfWork()) {
pindexLastMatchingProof = pindexLast;
}
if (!pindexLastMatchingProof) {
// If the algo isn't mined yet, set to min difficulty and be done
return bnPowLimit.GetCompact();
}
int64_t nPowSpacing = Params().GetTargetSpacing(pindexLast, nPoWType, fProofOfStake);
int64_t nActualTimespan;
int64_t nTargetTimespan;
if (fProofOfStake) {
// Proof of Stake will judge the whole chain spacing, and adjust in case there isn't
// enough mining to maintain optimum spacing
nActualTimespan = pStart->GetBlockTime() - pindex->GetBlockTime();
nTargetTimespan =(pStart->nHeight - pindex->nHeight) * nPowSpacing;
} else {
nActualTimespan = pindexLastMatchingProof->GetBlockTime() - pindex->GetBlockTime();
nTargetTimespan = nCountBlocks * nPowSpacing;
}
// If we are calculating the diff for RandomX, Sha256, or ProgPow
// We want to take into account the latest block tip time into the calculation
int64_t nTipToLastMatchingProof = pindexLast->GetBlockTime() - pindexLastMatchingProof->GetBlockTime();
int64_t nOverdueTime = nTipToLastMatchingProof - nPowSpacing;
if (!nTipToLastMatchingProof) {
// Tip is our algo, so look one more back to see where we're at
if (pindexOneBack) {
nOverdueTime = pindexLastMatchingProof->GetBlockTime() - pindexOneBack->GetBlockTime() - nPowSpacing;
}
}
if (fProofOfStake) {
// The concept of Overdue is variable; as it's anywhere from 60 to 120s, based on how many blocks
// over the timespan.
// pStart->nHeight - pindex->nHeight = number of blocks in measured sequence.
// number of blocks in sequence - nCountBlocks = number of non-PoS blocks in measured sequence
// number of blocks in sequence >> 1 = number of Non-PoS blocks there is supposed to be
// spacing = 60 + 60 * (actual / supposed)
// e.g. 60 + 60 * 30/30 = 120. 60 + 60 * 15/30 = 90. 60 + 60 * 0/30 = 60.
int64_t nBlocksMeasured = (pStart->nHeight - pindex->nHeight) + 1;
int64_t nBlocksPoW = nBlocksMeasured - nCountBlocks;
int64_t nBlocksIntended = nBlocksMeasured >> 1; // 50%
int64_t nPosSpacing = nPowSpacing + (nPowSpacing * nBlocksPoW / nBlocksIntended);
nOverdueTime = nTipToLastMatchingProof - nPosSpacing;
if (!nTipToLastMatchingProof && pindexOneBack) {
// Tip is our algo, so look one more back to see where we're at
nOverdueTime = pindexLastMatchingProof->GetBlockTime() - pindexOneBack->GetBlockTime() - nPosSpacing;
}
LogPrint(BCLog::BLOCKCREATION,
"%s: Blocks Measured=%d, PoS Blocks=%d, ActualPoWBlocks=%d, ExpectedPoWBlocks=%d, nPosSpacing=%d Overdue=%d (%s)\n",
__func__, nBlocksMeasured, nCountBlocks, nBlocksPoW, nBlocksIntended,
nPosSpacing, nOverdueTime, GetMiningType(nPoWType, fProofOfStake).c_str());
} else {
// In the case of fProofOfStake, the actual timespan already runs to the tip, so
// we're not going to add in the time from last of the proof to tip.
if (fNewPoW && nOverdueTime > 0) {
// We're overdue and may need to adjust more.
nActualTimespan += nOverdueTime;
}
}
LogPrint(BCLog::BLOCKCREATION, "%s: nActualTimespan=%d, nTargetTimespan=%d Overdue=%d (%s)\n", __func__,
nActualTimespan, nTargetTimespan, nOverdueTime, GetMiningType(nPoWType, fProofOfStake).c_str());
// ***
// Make sure we don't overadjust
if ((nActualTimespan < nTargetTimespan) && (nOverdueTime > 0)) {
// if we're ahead and adjusting, we might already be where we need
// to be. Don't make it more difficult if we're already overdue.
LogPrint(BCLog::BLOCKCREATION, "%s: %s is ahead but now overdue, don't adjust anymore.\n",
__func__, GetMiningType(nPoWType, fProofOfStake).c_str());
return bnNew.GetCompact();
}
if ((nActualTimespan > nTargetTimespan) && (nOverdueTime <= 0)) {
// if we're behind, and we're not overdue, we might be where we need to be
LogPrint(BCLog::BLOCKCREATION, "%s: %s is behind but moving don't adjust anymore.\n",
__func__, GetMiningType(nPoWType, fProofOfStake).c_str());
return bnNew.GetCompact();
}
// ***
LogPrint(BCLog::BLOCKCREATION, "%s: Adjusting %s: old target: %s\n",
__func__, GetMiningType(nPoWType, fProofOfStake).c_str(), bnNew.GetHex());
arith_uint256 bnOld(bnNew); // Save the old target
// Retarget
bnNew *= nActualTimespan;
bnNew /= nTargetTimespan;
if (bnNew > bnPowLimit) {
bnNew = bnPowLimit;
}
if ((nActualTimespan > nTargetTimespan) && (bnOld > bnNew)) {
// If we should be reducing the difficulty, and the target has gone down, we've overflowed.
LogPrint(BCLog::BLOCKCREATION, "%s: Multiplier %.4f for %s overflowed. Setting Min Difficulty.\n",
__func__, (double) ((double)nActualTimespan / (double)nTargetTimespan),
GetMiningType(nPoWType, fProofOfStake).c_str());
bnNew = bnPowLimit;
}
LogPrint(BCLog::BLOCKCREATION, "%s: Adjusting %s: new target: %s\n",
__func__, GetMiningType(nPoWType, fProofOfStake).c_str(), bnNew.GetHex());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params, int algo)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
arith_uint256 bnPowLimit = GetPowLimit(algo);
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > bnPowLimit) {
return false;
}
// Check proof of work matches claimed amount
return UintToArith256(hash) < bnTarget;
}
#define KEY_CHANGE 2048
#define SWITCH_KEY 64
uint256 GetKeyBlock(const uint32_t& nHeight)
{
static uint256 current_key_block = uint256();
uint32_t checkMultiplier = 0;
// We don't want to go negative
if (nHeight >= SWITCH_KEY)
checkMultiplier = (nHeight - SWITCH_KEY) / KEY_CHANGE;
int checkHeight = checkMultiplier * KEY_CHANGE;
if (chainActive.Height() >= checkHeight) {
current_key_block = chainActive[checkHeight]->GetBlockHash();
} else {
LogPrintf("%s: Not synched for KeyBlock(%d) @ %d, Synched Height: %d\n", __func__,
checkHeight, nHeight, chainActive.Height());
}
if (current_key_block == uint256())
current_key_block = chainActive.Genesis()->GetBlockHash();
return current_key_block;
}
bool CheckRandomXProofOfWork(const CBlockHeader& block, unsigned int nBits, const Consensus::Params& params)
{
LOCK(cs_randomx_validator);
InitRandomXLightCache(block.nHeight);
// This will check if the key block needs to change and will take down the cache and vm, and spin up the new ones
CheckIfValidationKeyShouldChangeAndUpdate(GetKeyBlock(block.nHeight));
// Create the eth_boundary from the nBits
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimitRandomX)) {
return false;
}
uint256 hash_blob = block.GetRandomXHeaderHash();
char hash[RANDOMX_HASH_SIZE];
randomx_calculate_hash(GetMyMachineValidating(), &hash_blob, sizeof uint256(), hash);
uint256 nHash = RandomXHashToUint256(hash);
// Check proof of work matches claimed amount
return UintToArith256(nHash) < bnTarget;
}
uint256 RandomXHashToUint256(const char* p_char)
{
int i;
std::vector<unsigned char> vec;
for (i = 0; i < RANDOMX_HASH_SIZE; i++) {
vec.push_back(p_char[i]);
}
std::string hexStr = HexStr(vec.begin(), vec.end());
return uint256S(hexStr);
}
void StartRandomXMining(void* pPowThreadGroup, const int nThreads, std::shared_ptr<CReserveScript> pCoinbaseScript)
{
bool fInitialized = false;
auto threadGroup = (boost::thread_group *) pPowThreadGroup;
while (true) {
boost::this_thread::interruption_point();
if (!fInitialized) {
boost::this_thread::interruption_point();
auto full_flags = RANDOMX_FLAG_FULL_MEM | randomx_get_flags();
LogPrint(BCLog::BLOCKCREATION, "%s: RandomX flags set to %s\n", __func__, full_flags);
myMiningCache = randomx_alloc_cache(full_flags);
/// Create the RandomX Dataset
myMiningDataset = randomx_alloc_dataset(full_flags);
mining_key_block = GetKeyBlock(chainActive.Height());
randomx_init_cache(myMiningCache, &mining_key_block, sizeof(mining_key_block));
auto nTime1 = GetTimeMillis();
LogPrintf("%s: Starting dataset creation\n", __func__);
CreateRandomXInitDataSet(nThreads, myMiningDataset, myMiningCache);
boost::this_thread::interruption_point();
auto nTime2 = GetTimeMillis();
LogPrintf("%s: Finished dataset creation %.2fms\n", __func__, nTime2 - nTime1);
boost::this_thread::interruption_point();
/// Create the RandomX Virtual Machines
for (int i = 0; i < nThreads; ++i) {
randomx_vm *vm = randomx_create_vm(full_flags, nullptr, myMiningDataset);
if (vm == nullptr) {
LogPrintf("%s: Cannot create VM\n", __func__);
return;
}
vecRandomXVM.push_back(vm);
}
boost::this_thread::interruption_point();
auto nTime3 = GetTimeMillis();
LogPrintf("%s: Finished vm creation %.2fms\n", __func__, nTime3 - nTime2);
boost::this_thread::interruption_point();
uint32_t startNonce = 0;
for (int i = 0; i < nThreads; i++) {
threadGroup->create_thread(boost::bind(&ThreadRandomXBitcoinMiner, pCoinbaseScript, i, startNonce));
startNonce += 100000;
}
boost::this_thread::interruption_point();
fInitialized = true;
}
if (fKeyBlockedChanged) {
boost::this_thread::interruption_point();
threadGroup->interrupt_all();
threadGroup->join_all();
DeallocateVMVector();
DeallocateDataSet();
fInitialized = false;
fKeyBlockedChanged = false;
}
}
}
void CreateRandomXInitDataSet(int nThreads, randomx_dataset* dataset, randomx_cache* cache)
{
uint32_t datasetItemCount = randomx_dataset_item_count();
if (nThreads > 1) {
uint32_t datasetItemCount = randomx_dataset_item_count();
auto perThread = datasetItemCount / nThreads;
auto remainder = datasetItemCount % nThreads;
uint32_t startItem = 0;
for (int i = 0; i < nThreads; ++i) {
auto count = perThread + (i == nThreads - 1 ? remainder : 0);
vecRandomXThreads.push_back(std::thread(&randomx_init_dataset, dataset, cache, startItem, count));
startItem += count;
}
for (unsigned i = 0; i < vecRandomXThreads.size(); ++i) {
vecRandomXThreads[i].join();
}
} else {
randomx_init_dataset(dataset, cache, 0, datasetItemCount);
}
randomx_release_cache(cache);
cache = nullptr;
vecRandomXThreads.clear();
}
void DeallocateVMVector()
{
if (vecRandomXVM.size()) {
for (unsigned i = 0; i < vecRandomXVM.size(); ++i)
randomx_destroy_vm(vecRandomXVM[i]);
}
vecRandomXVM.clear();
}
void DeallocateDataSet()
{
if (myMiningDataset == nullptr)
return;
randomx_release_dataset(myMiningDataset);
myMiningDataset = nullptr;
}
void DeallocateCache()
{
LOCK(cs_randomx_validator);
if (myMiningCache == nullptr)
return;
randomx_release_cache(myMiningCache);
myMiningCache = nullptr;
}
| 14,219
|
https://github.com/adehtiarov/intellij-community/blob/master/platform/core-impl/src/com/intellij/psi/stubs/StubTree.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
intellij-community
|
adehtiarov
|
Java
|
Code
| 196
| 561
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* @author max
*/
package com.intellij.psi.stubs;
import com.intellij.psi.impl.source.StubbedSpine;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class StubTree extends ObjectStubTree<StubElement<?>> {
private final StubSpine mySpine = new StubSpine(this);
public StubTree(@NotNull final PsiFileStub root) {
this(root, true);
}
public StubTree(@NotNull final PsiFileStub root, final boolean withBackReference) {
super((ObjectStubBase)root, withBackReference);
}
@Override
protected List<StubElement<?>> enumerateStubs(@NotNull Stub root) {
return ((StubBase)root).myStubList.finalizeLoadingStage().toPlainList();
}
@NotNull
@Override
final List<StubElement<?>> getPlainListFromAllRoots() {
PsiFileStub[] roots = ((PsiFileStubImpl<?>)getRoot()).getStubRoots();
if (roots.length == 1) return super.getPlainListFromAllRoots();
return ContainerUtil.concat(roots, stub -> ((PsiFileStubImpl)stub).myStubList.toPlainList());
}
@NotNull
@Override
public PsiFileStub getRoot() {
return (PsiFileStub)myRoot;
}
@NotNull
public StubbedSpine getSpine() {
return mySpine;
}
}
| 18,963
|
https://github.com/jsoftgem/fluid-web/blob/master/src/js/modules/fluid-progress.js
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
fluid-web
|
jsoftgem
|
JavaScript
|
Code
| 738
| 2,602
|
/**
* Created by Jerico on 6/19/2015.
*/
angular.module("fluidProgress", [])
.directive("fluidProgress", ["$templateCache", "fluidProgressService", "FluidProgress", "$timeout", "$q", function (tc, fps, FluidProgress, timeout, q) {
return {
restrict: "AE",
scope: false,
template: tc.get("templates/fluid/fluidProgress.html"),
replace: true,
transclude: true,
link: function (scope, element, attr) {
scope.runnerStack = [];
scope.asynchronous = false;
scope.max = 0;
scope.min = 0;
scope.count = 0;
if (attr.asynchronous) {
scope.asynchronous = attr.asynchronous === "true";
}
if (attr.id) {
var id = element.attr("id");
element.attr("id", id + "_progress");
scope.progress = FluidProgress({id: id});
} else {
throw "Id attribute is required.";
}
scope.$on(element.attr("id"), function () {
console.debug("fluid-progress-'have triggered': ", element.attr("id"));
var progress = scope.progress;
angular.forEach(progress.runners, function (runner, $index) {
progress.inProgress = true;
if (runner.triggered) {
runner.triggered = false;
var progressBar = element.find(".progress-bar");
if (progressBar) {
if (runner.max) {
if (scope.max === 0) {
progress.max = 0;
}
progress.max += runner.max;
scope.max += runner.max;
}
if (runner.min) {
if (scope.min === 0) {
progress.min = scope.min;
}
progress.min += runner.min;
scope.min += runner.min;
}
if (scope.count === 0) {
progress.count = scope.count;
}
}
if (scope.runner && !scope.asynchronous) {
scope.runnerStack.push(runner);
} else if (scope.asynchronous) {
var defer = q.defer();
timeout(function () {
loadRunner(scope, element, runner, progress);
defer.resolve(runner);
}, runner.sleep);
} else {
scope.runner = runner;
console.debug("fluid-progress-'have triggered': - currentRunner ", runner);
}
}
});
});
scope.startLoader = function () {
element.removeClass("fluid-progress");
element.addClass("fluid-progress-loading");
}
scope.endLoader = function () {
element.addClass("fluid-progress");
element.removeClass("fluid-progress-loading");
}
scope.$watch(function (scope) {
return scope.runner;
}, function (newRunner, oldRunner) {
console.debug("fluid-progress.runner.new", newRunner);
function checkRunner() {
if (newRunner.done || newRunner.cancelled) {
if (scope.runnerStack) {
scope.runner = scope.runnerStack.shift();
}
} else {
if (!newRunner.inProgress) {
newRunner.inProgress = true;
loadRunner(scope, element, newRunner, scope.progress);
}
timeout(checkRunner, newRunner.sleep);
}
}
if (newRunner) {
checkRunner();
}
});
scope.$on("$destroy", function () {
if (scope.progress) {
scope.progress.completeFuncs = [];
scope.progress.cancelledFuncs = [];
fps.clearProgress(scope.progress.id);
}
});
}
}
}])
.factory("FluidProgress", ["fluidProgressService", "$timeout", function (fps, t) {
var fluidProgress = function (param) {
console.debug("fluidProgress-FluidProgress.param", param);
var progress = {};
if (param.id) {
if (fps.getFluidProgress(param.id) !== undefined) {
progress = fps.getFluidProgress(param.id);
} else {
progress.completeFuncs = [];
progress.cancelledFuncs = [];
progress.max = 0;
progress.min = 0;
progress.count = 0;
progress.id = param.id;
progress.run = function (name, loadFn, options) {
var exists = false;
console.debug("progress-run.name", name);
if (progress.runners) {
console.debug("progress-run.runners", progress.runners);
for (var i = 0; i < progress.runners.length; i++) {
var runner = progress.runners[i];
if (runner.name === name) {
exists = true;
runner.done = false;
runner.cancelled = false;
runner.inProgress = false;
runner.triggered = true;
if(loadFn){
runner.load = loadFn;
}
if (options) {
runner.max = options.max ? options.max : runner.max;
runner.min = options.min ? options.min : runner.min;
runner.sleep = options.sleep ? options.sleep : runner.sleep;
}
console.debug("progress-run.saved-triggered.runner", runner);
console.debug("progress-run.saved-triggered.name", name);
}
}
}
if (!exists) {
var runner = {};
if (options) {
runner.max = options.max;
runner.min = options.min;
runner.sleep = options.sleep;
}
runner.name = name;
runner.load = loadFn;
runner.message = "Loading please wait...";
if (progress.runners === undefined) {
progress.runners = [];
}
runner.triggered = true;
progress.runners.push(runner);
}
progress.element = angular.element(progress.$());
console.debug("progress.element", progress.element);
var scope = progress.element.scope();
if (scope) {
progress.element.scope().$broadcast(progress.element.attr("id"));
console.debug("progress.triggered", progress.element.attr("id"));
}
}
progress.$ = function () {
return $("#" + progress.id + "_progress");
}
progress.onComplete = function (name, completeFunc) {
if (this.completeFuncs[name] == null) {
this.completeFuncs[name] = [];
}
this.completeFuncs[name].push(completeFunc);
console.debug("progress.completeFunc-name", name);
console.debug("progress.completeFunc", completeFunc);
console.debug("progress.completeFuncs", this.completeFuncs);
}
progress.onCancelled = function (name, cancelledFunc) {
if (this.cancelledFuncs[name] == null) {
this.cancelledFuncs[name] = [];
}
this.cancelledFuncs[name].push(cancelledFunc);
console.debug("progress.cancelledFuncs", this.cancelledFuncs);
}
progress.cancel = function (name, reason) {
if (this.cancelledFuncs) {
var cancelFuncs = this.cancelledFuncs[name];
if (cancelFuncs) {
angular.forEach(cancelFuncs, function (func, $index) {
t(function () {
if (func) {
func(reason);
}
});
});
}
}
}
progress.complete = function (name, resolver) {
if (this.completeFuncs) {
var completeFuncs = this.completeFuncs[name];
console.debug("fluid-progress.complete.name", name);
console.debug("fluid-progress.complete.completeFuncs", completeFuncs);
if (completeFuncs) {
console.debug("fluid-progress.complete.length", completeFuncs.length);
angular.forEach(completeFuncs, function (func, $index) {
console.debug("fluid-progress.complete.$index", $index)
t(function () {
if (func) {
func(resolver);
}
});
});
}
}
}
progress.clear = function () {
progress.completeFuncs = [];
progress.cancelledFuncs = [];
progress.runners = [];
}
fps.addFluidProgress(progress);
}
} else {
throw "param id is required";
}
console.debug("fluid-progress.progress", progress);
return progress;
}
return fluidProgress;
}])
.service("fluidProgressService", ["$timeout", function (t) {
this.addFluidProgress = function (progress) {
var id = progress.id + "_progress";
if (this.progressObjects == null) {
this.progressObjects = [];
}
this.progressObjects[id] = progress;
console.debug("fluid-progress-fluidProgressService-addFluidProgress.progressObjects", this.progressObjects);
console.debug("fluid-progress-fluidProgressService-addFluidProgress.id", id);
}
this.getFluidProgress = function (id) {
if (this.progressObjects) {
console.debug("fluid-progress-fluidProgressService-getFluidProgress.id", id);
console.debug("fluid-progress-fluidProgressService-getFluidProgress.progressObjects", this.progressObjects);
var key = id + "_progress";
var progressObject = this.progressObjects[key];
console.debug("fluid-progress-fluidProgressService-getFluidProgress.progressObject", progressObject);
return progressObject;
}
}
this.clearProgress = function (id) {
this.progressObjects[id + "_progress"] = undefined;
}
return this;
}]);
| 3,231
|
https://github.com/rossant/galry/blob/master/galry/processors/navigation_processor.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,016
|
galry
|
rossant
|
Python
|
Code
| 1,074
| 3,884
|
import inspect
import time
import numpy as np
from processor import EventProcessor
from galry import Manager, TextVisual, get_color
__all__ = ['NavigationEventProcessor']
# Maximum viewbox allowed when constraining navigation.
MAX_VIEWBOX = (-1., -1., 1., 1.)
class NavigationEventProcessor(EventProcessor):
"""Handle navigation-related events."""
def initialize(self, constrain_navigation=False,
normalization_viewbox=None, momentum=False):
# zoom box
self.navigation_rectangle = None
self.constrain_navigation = constrain_navigation
self.normalization_viewbox = normalization_viewbox
self.reset()
self.set_navigation_constraints()
self.activate_navigation_constrain()
# register events processors
self.register('Pan', self.process_pan_event)
self.register('Rotation', self.process_rotation_event)
self.register('Zoom', self.process_zoom_event)
self.register('ZoomBox', self.process_zoombox_event)
self.register('Reset', self.process_reset_event)
self.register('ResetZoom', self.process_resetzoom_event)
self.register('SetPosition', self.process_setposition_event)
self.register('SetViewbox', self.process_setviewbox_event)
# Momentum
if momentum:
self.register('Animate', self.process_animate_event)
self.pan_list = []
self.pan_list_maxsize = 10
self.pan_vec = np.zeros(2)
self.is_panning = False
self.momentum = False
self.register('Grid', self.process_grid_event)
self.grid_visible = getattr(self.parent, 'show_grid', False)
self.activate_grid()
def activate_grid(self):
self.set_data(visual='grid_lines', visible=self.grid_visible)
self.set_data(visual='grid_text', visible=self.grid_visible)
processor = self.get_processor('grid')
# print processor
if processor:
processor.activate(self.grid_visible)
if self.grid_visible:
processor.update_axes(None)
def process_grid_event(self, parameter):
self.grid_visible = not(self.grid_visible)
self.activate_grid()
def transform_view(self):
"""Change uniform variables to implement interactive navigation."""
translation = self.get_translation()
scale = self.get_scaling()
# update all non static visuals
for visual in self.paint_manager.get_visuals():
if not visual.get('is_static', False):
self.set_data(visual=visual['name'],
scale=scale, translation=translation)
# Event processing methods
# ------------------------
def process_none(self):
"""Process the None event, i.e. where there is no event. Useful
to trigger an action at the end of a long-lasting event."""
# when zoombox event finished: set_relative_viewbox
if (self.navigation_rectangle is not None):
self.set_relative_viewbox(*self.navigation_rectangle)
self.paint_manager.hide_navigation_rectangle()
self.navigation_rectangle = None
# Trigger panning momentum
if self.is_panning:
self.is_panning = False
if len(self.pan_list) >= self.pan_list_maxsize:
self.momentum = True
self.parent.block_refresh = False
# self.set_cursor(None)
self.transform_view()
def add_pan(self, parameter):
# Momentum.
self.pan_list.append(parameter)
if len(self.pan_list) > self.pan_list_maxsize:
del self.pan_list[0]
self.pan_vec = np.array(self.pan_list).mean(axis=0)
def process_pan_event(self, parameter):
# Momentum.
self.is_panning = True
self.momentum = False
self.parent.block_refresh = False
self.add_pan(parameter)
self.pan(parameter)
self.set_cursor('ClosedHandCursor')
self.transform_view()
def process_animate_event(self, parameter):
# Momentum.
if self.is_panning:
self.add_pan((0., 0.))
if self.momentum:
self.pan(self.pan_vec)
self.pan_vec *= .975
# End momentum.
if (np.abs(self.pan_vec) < .0001).all():
self.momentum = False
self.parent.block_refresh = True
self.pan_list = []
self.pan_vec = np.zeros(2)
self.transform_view()
def process_rotation_event(self, parameter):
self.rotate(parameter)
self.set_cursor('ClosedHandCursor')
self.transform_view()
def process_zoom_event(self, parameter):
self.zoom(parameter)
self.parent.block_refresh = False
# Block momentum when zooming.
self.momentum = False
self.set_cursor('MagnifyingGlassCursor')
self.transform_view()
def process_zoombox_event(self, parameter):
self.zoombox(parameter)
self.parent.block_refresh = False
self.set_cursor('MagnifyingGlassCursor')
self.transform_view()
def process_reset_event(self, parameter):
self.reset()
self.parent.block_refresh = False
self.set_cursor(None)
self.transform_view()
def process_resetzoom_event(self, parameter):
self.reset_zoom()
self.parent.block_refresh = False
self.set_cursor(None)
self.transform_view()
def process_setposition_event(self, parameter):
self.set_position(*parameter)
self.parent.block_refresh = False
self.transform_view()
def process_setviewbox_event(self, parameter):
self.set_viewbox(*parameter)
self.parent.block_refresh = False
self.transform_view()
# Navigation methods
# ------------------
def set_navigation_constraints(self, constraints=None, maxzoom=1e6):
"""Set the navigation constraints.
Arguments:
* constraints=None: the coordinates of the bounding box as
(xmin, ymin, xmax, ymax), by default (+-1).
"""
if not constraints:
constraints = MAX_VIEWBOX
# view constraints
self.xmin, self.ymin, self.xmax, self.ymax = constraints
# minimum zoom allowed
self.sxmin = 1./min(self.xmax, -self.xmin)
self.symin = 1./min(self.ymax, -self.ymin)
# maximum zoom allowed
self.sxmax = self.symax = maxzoom
def reset(self):
"""Reset the navigation."""
self.tx, self.ty, self.tz = 0., 0., 0.
self.sx, self.sy = 1., 1.
self.sxl, self.syl = 1., 1.
self.rx, self.ry = 0., 0.
self.navigation_rectangle = None
def pan(self, parameter):
"""Pan along the x,y coordinates.
Arguments:
* parameter: (dx, dy)
"""
self.tx += parameter[0] / self.sx
self.ty += parameter[1] / self.sy
def rotate(self, parameter):
self.rx += parameter[0]
self.ry += parameter[1]
def zoom(self, parameter):
"""Zoom along the x,y coordinates.
Arguments:
* parameter: (dx, px, dy, py)
"""
dx, px, dy, py = parameter
if self.parent.constrain_ratio:
if (dx >= 0) and (dy >= 0):
dx, dy = (max(dx, dy),) * 2
elif (dx <= 0) and (dy <= 0):
dx, dy = (min(dx, dy),) * 2
else:
dx = dy = 0
self.sx *= np.exp(dx)
self.sy *= np.exp(dy)
# constrain scaling
if self.constrain_navigation:
self.sx = np.clip(self.sx, self.sxmin, self.sxmax)
self.sy = np.clip(self.sy, self.symin, self.symax)
self.tx += -px * (1./self.sxl - 1./self.sx)
self.ty += -py * (1./self.syl - 1./self.sy)
self.sxl = self.sx
self.syl = self.sy
def zoombox(self, parameter):
"""Indicate to draw a zoom box.
Arguments:
* parameter: the box coordinates (xmin, ymin, xmax, ymax)
"""
self.navigation_rectangle = parameter
self.paint_manager.show_navigation_rectangle(parameter)
def reset_zoom(self):
"""Reset the zoom."""
self.sx, self.sy = 1, 1
self.sxl, self.syl = 1, 1
self.navigation_rectangle = None
def get_viewbox(self, scale=1.):
"""Return the coordinates of the current view box.
Returns:
* (xmin, ymin, xmax, ymax): the current view box in data coordinate
system.
"""
x0, y0 = self.get_data_coordinates(-scale, -scale)
x1, y1 = self.get_data_coordinates(scale, scale)
return (x0, y0, x1, y1)
def get_data_coordinates(self, x, y):
"""Convert window relative coordinates into data coordinates.
Arguments:
* x, y: coordinates in [-1, 1] of a point in the window.
Returns:
* x', y': coordinates of this point in the data coordinate system.
"""
return x/self.sx - self.tx, y/self.sy - self.ty
def get_window_coordinates(self, x, y):
"""Inverse of get_data_coordinates.
"""
return (x + self.tx) * self.sx, (y + self.ty) * self.sy
def constrain_viewbox(self, x0, y0, x1, y1):
"""Constrain the viewbox ratio."""
if (x1-x0) > (y1-y0):
d = ((x1-x0)-(y1-y0))/2
y0 -= d
y1 += d
else:
d = ((y1-y0)-(x1-x0))/2
x0 -= d
x1 += d
return x0, y0, x1, y1
def set_viewbox(self, x0, y0, x1, y1):
"""Set the view box in the data coordinate system.
Arguments:
* x0, y0, x1, y1: viewbox coordinates in the data coordinate system.
"""
# force the zoombox to keep its original ratio
if self.parent.constrain_ratio:
x0, y0, x1, y1 = self.constrain_viewbox(x0, y0, x1, y1)
if (x1-x0) and (y1-y0):
self.tx = -(x1+x0)/2
self.ty = -(y1+y0)/2
self.sx = 2./abs(x1-x0)
self.sy = 2./abs(y1-y0)
self.sxl, self.syl = self.sx, self.sy
def set_relative_viewbox(self, x0, y0, x1, y1):
"""Set the view box in the window coordinate system.
Arguments:
* x0, y0, x1, y1: viewbox coordinates in the window coordinate system.
These coordinates are all in [-1, 1].
"""
# prevent too small zoombox
if (np.abs(x1 - x0) < .07) & (np.abs(y1 - y0) < .07):
return
# force the zoombox to keep its original ratio
if self.parent.constrain_ratio:
x0, y0, x1, y1 = self.constrain_viewbox(x0, y0, x1, y1)
if (x1-x0) and (y1-y0):
self.tx += -(x1+x0)/(2*self.sx)
self.ty += -(y1+y0)/(2*self.sy)
self.sx *= 2./abs(x1-x0)
self.sy *= 2./abs(y1-y0)
self.sxl, self.syl = self.sx, self.sy
def set_position(self, x, y):
"""Set the current position.
Arguments:
* x, y: coordinates in the data coordinate system.
"""
self.tx = -x
self.ty = -y
def activate_navigation_constrain(self):
"""Constrain the navigation to a bounding box."""
if self.constrain_navigation:
# constrain scaling
self.sx = np.clip(self.sx, self.sxmin, self.sxmax)
self.sy = np.clip(self.sy, self.symin, self.symax)
# constrain translation
self.tx = np.clip(self.tx, 1./self.sx - self.xmax,
-1./self.sx - self.xmin)
self.ty = np.clip(self.ty, 1./self.sy + self.ymin,
-1./self.sy + self.ymax)
else:
# constrain maximum zoom anyway
self.sx = min(self.sx, self.sxmax)
self.sy = min(self.sy, self.symax)
def get_translation(self):
"""Return the translation vector.
Returns:
* tx, ty: translation coordinates.
"""
self.activate_navigation_constrain()
return self.tx, self.ty
def get_rotation(self):
return self.rx, self.ry
def get_scaling(self):
"""Return the scaling vector.
Returns:
* sx, sy: scaling coordinates.
"""
if self.constrain_navigation:
self.activate_navigation_constrain()
return self.sx, self.sy
| 7,711
|
https://github.com/Chapmania/Juniper/blob/master/src/Juniper.Root/NETFX/DateTimeExt.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Juniper
|
Chapmania
|
C#
|
Code
| 271
| 641
|
namespace System
{
public static class DateTimeExt
{
/// <summary>
/// The minimum time, according to Unix.
/// </summary>
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Converts time representations.
/// </summary>
/// <param name="timeStamp">
/// The number of seconds since the Unix Epoch (Midnight, January 1st, 1970)
/// </param>
/// <returns>A structured date representation.</returns>
public static DateTime UnixTimestampToDateTime(this double timeStamp)
{
return epoch.AddSeconds(timeStamp).ToLocalTime();
}
/// <summary>
/// Converts time representations.
/// </summary>
/// <param name="timeStamp">
/// The number of seconds since the Unix Epoch (Midnight, January 1st, 1970)
/// </param>
/// <returns>A structured date representation.</returns>
public static DateTime UnixTimestampToDateTime(this long timeStamp)
{
return UnixTimestampToDateTime((double)timeStamp);
}
/// <summary>
/// Converts time representations.
/// </summary>
/// <param name="time">A structured date represntation.</param>
/// <returns>
/// The number of days since the Celestial Julian Day Calculation Epoch (Day 2451545 on the
/// Julian Calendar).
/// </returns>
public static float ToJulianDays(this DateTime time)
{
const float JDEpoch = 2451545f;
// Julian Day
var jdDate = new DateTime(time.Year, time.Month, time.Day, 12, 0, 0);
if (time.Hour < 12)
{
jdDate = jdDate.AddDays(-1);
}
var delta = time - jdDate;
var Y = jdDate.Year;
var M = jdDate.Month;
var D = jdDate.Day;
// use integer division explicitly
var JD = (1461 * (Y + 4800 + ((M - 14) / 12)) / 4)
+ (367 * (M - 2 - (12 * ((M - 14) / 12))) / 12)
- (3 * ((Y + 4900 + ((M - 14) / 12)) / 100) / 4)
+ D - 32075;
return JD + (float)delta.TotalDays - JDEpoch;
}
}
}
| 37,946
|
https://github.com/AdamFedor/Udemy-GA/blob/master/Advanced Dev Bootcamp/D3/Tooltip/app.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Udemy-GA
|
AdamFedor
|
JavaScript
|
Code
| 232
| 993
|
var width = 500;
var height = 500;
var padding = 30;
var yScale = d3.scaleLinear()
.domain(d3.extent(birthData2011, d => d.lifeExpectancy))
.range([height - padding, padding]);
var xScale = d3.scaleLinear()
.domain(d3.extent(birthData2011, d => d.births / d.population))
.range([padding, width - padding]);
var xAxis = d3.axisBottom(xScale)
.tickSize(-height + 2 * padding)
.tickSizeOuter(0);
var yAxis = d3.axisLeft(yScale)
.tickSize(-width + 2 * padding)
.tickSizeOuter(0);
var colorScale = d3.scaleLinear()
.domain(d3.extent(birthData2011, d => d.population / d.area))
.range(['lightgreen', 'black']);
var radiusScale = d3.scaleLinear()
.domain(d3.extent(birthData2011, d => d.births))
.range([2, 40]);
var tooltip = d3.select('body')
.append('div')
.classed('tooltip', true)
d3.select("svg")
.append("g")
.attr("transform", "translate(0," + (height - padding) + ")")
.call(xAxis);
d3.select("svg")
.append("g")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
d3.select("svg")
.attr("width", width)
.attr("height", height)
.selectAll("circle")
.data(birthData2011)
.enter()
.append("circle")
.attr("cx", d => xScale(d.births / d.population))
.attr("cy", d => yScale(d.lifeExpectancy))
.attr("fill", d => colorScale(d.population / d.area))
.attr("r", d => radiusScale(d.births))
.on('mousemove', function (d) {
tooltip
.style('opacity', 1)
.style('left', d3.event.x - (tooltip.node().offsetWidth / 2) + 'px')
.style('top', d3.event.y + 25 + 'px')
.html(`
<p>Region: ${d.region}</p>
<p>Births: ${d.births.toLocaleString()}</p>
<p>Population: ${d.population.toLocaleString()}</p>
<p>Area: ${d.area.toLocaleString()}</p>
<p>Life Expectancy: ${d.lifeExpectancy}</p>
`);
})
.on('mouseout', function () {
tooltip .style('opacity', 0)
})
d3.select("svg")
.append("text")
.attr("x", width / 2)
.attr("y", height - padding)
.attr("dy", "1.5em")
.style("text-anchor", "middle")
.text("Births per Capita");
d3.select("svg")
.append("text")
.attr("x", width / 2)
.attr("y", padding)
.style("text-anchor", "middle")
.style("font-size", "1.5em")
.text("Data on Births by Country in 2011");
d3.select("svg")
.append("text")
.attr("transform", "rotate(-90)")
.attr("x", - height / 2)
.attr("y", padding)
.attr("dy", "-1.1em")
.style("text-anchor", "middle")
.text("Life Expectancy");
| 41,381
|
https://github.com/factorysh/streamcast/blob/master/vorbis/stream.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
streamcast
|
factorysh
|
Go
|
Code
| 251
| 794
|
package vorbis
import (
"errors"
"fmt"
"sync"
"github.com/factorysh/streamcast/ogg"
)
type WriterFlusher interface {
Flush()
Write([]byte)
}
type Streams struct {
streams map[uint32]*Stream
current uint32
lock sync.RWMutex
Pipe ogg.PageWriter
}
func NewStreams() *Streams {
return &Streams{
streams: make(map[uint32]*Stream),
}
}
func (s *Streams) CurrentStream() *Stream {
s.lock.RLock()
defer s.lock.RUnlock()
return s.streams[s.current]
}
func (s *Streams) WritePage(page *ogg.Page) error {
header := page.Header()
s.lock.Lock()
defer s.lock.Unlock()
stream, ok := s.streams[header.Serial]
if !ok { // new Stream
if header.HeaderType != ogg.BOS {
return fmt.Errorf("Bad type, it must be begining, not %v", header.HeaderType)
}
if header.Granule != 0 {
return fmt.Errorf("Screwed vorbis page, it must begin with granule 0, not %v", header.Granule)
}
stream = &Stream{
headers: []*ogg.Page{page},
Pipe: s.Pipe,
}
s.streams[header.Serial] = stream
s.current = header.Serial
return nil
}
if header.HeaderType == ogg.EOS {
s.lock.Unlock()
defer func() {
s.lock.Lock()
delete(s.streams, header.Serial)
s.lock.Unlock()
}()
}
return stream.WritePage(page)
}
type Stream struct {
headers []*ogg.Page
Pipe ogg.PageWriter
}
func NewStream() *Stream {
return &Stream{
headers: make([]*ogg.Page, 0),
}
}
func (s *Stream) WritePage(page *ogg.Page) error {
if s.Pipe != nil {
s.Pipe.WritePage(page)
}
if len(s.headers) == 1 { // Vorbis starts with 2 pages of headers
if page.Header().Granule != 0 {
return errors.New("Vorbis starts with 2 pages of headers")
}
s.headers = append(s.headers, page)
return nil
}
return nil
}
func (s *Stream) WriteBegining(w WriterFlusher) bool {
// FIXME are all needed headers already here?
if len(s.headers) < 2 {
return false
}
for _, h := range s.headers {
w.Write(h.Raw)
}
w.Flush()
return true
}
| 27,187
|
https://github.com/nonothing/Dyna-Blaster-cocos2dx/blob/master/Classes/Scene/StartingScene.cpp
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
Dyna-Blaster-cocos2dx
|
nonothing
|
C++
|
Code
| 348
| 1,927
|
#include "Scene/StartingScene.h"
#include "editor-support/cocostudio/CocoStudio.h"
#include "Model/GameSounds.h"
#include "utils/Utils.h"
#define ANIM_TAG 444
USING_NS_CC;
StartingScene* StartingScene::create(LoadLevelScene* loadScene)
{
StartingScene* scene = new StartingScene();
if (scene && scene->init(loadScene))
{
return (StartingScene*)scene->autorelease();
}
CC_SAFE_DELETE(scene);
return scene;
}
Scene* StartingScene::createScene(LoadLevelScene* loadScene)
{
auto scene = Scene::create();
auto layer = StartingScene::create(loadScene);
scene->addChild(layer);
return scene;
}
bool StartingScene::init(LoadLevelScene* loadScene)
{
if ( !Layer::init() )
{
return false;
}
_loadScene = loadScene;
_rootNode = CSLoader::createNode("nodes/StartingScene.csb");
_action = CSLoader::createTimeline("nodes/StartingScene.csb");
_rootNode->runAction(_action);
transparentNodes();
_action->gotoFrameAndPlay(0, false);
_action->setFrameEventCallFunc(CC_CALLBACK_1(StartingScene::onFrameEvent, this));
_keyboardListener = EventListenerKeyboard::create();
_keyboardListener->onKeyPressed = CC_CALLBACK_2(StartingScene::onKeyPressed, this);
getEventDispatcher()->addEventListenerWithSceneGraphPriority(_keyboardListener, this);
addChild(_rootNode);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("plists/startingscene.plist", "atlas/startingscene.png");
AnimationCache::getInstance()->addAnimationsWithFile("animation/staringscene.plist");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("plists/players.plist", "atlas/players.png");
AnimationCache::getInstance()->addAnimationsWithFile("animation/players.plist");
_humanSprite = static_cast<Sprite*>(_rootNode->getChildByName("human_3_7"));
humanRun(LEFT);
_doctorSprite = static_cast<Sprite*>(_rootNode->getChildByName("doctor_3_6"));
doctorRun(RIGHT);
_draculaSprite = static_cast<Sprite*>(_rootNode->getChildByName("dracon_2_8"));
draculaFly("dracula_move_1");
CSVReader::getInst()->parse("gamedata/starting_scene.csv");
_map = CSVReader::getInst()->getNormalMap();
GameSounds::Instance().playMusic(ES_INTRO, false);
return true;
}
void StartingScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
if (keyCode == EventKeyboard::KeyCode::KEY_SPACE)
{
end();
}
}
void StartingScene::transparentNodes()
{
for (auto node : _rootNode->getChildren())
{
if (node->getTag() != 1)
{
node->setOpacity(0);
}
}
}
void StartingScene::showElementByTag(int tag)
{
for (auto node : _rootNode->getChildren())
{
if (node->getTag() == tag)
{
node->setOpacity(inverseOpacity(node->getOpacity()));
}
}
}
void StartingScene::onFrameEvent(cocostudio::timeline::Frame *frame)
{
auto* evnt = dynamic_cast<cocostudio::timeline::EventFrame*>(frame);
if (!evnt)
return;
auto it = _map.find(myUtils::to_string(evnt->getFrameIndex()));
if (it != _map.end())
{
showElementByTag(atoi(it->second.c_str()));
}
if (evnt->getEvent() == "dracula_move_2") draculaFly(evnt->getEvent());
if (evnt->getEvent() == "dracula_move_3")
{
draculaFly(evnt->getEvent());
stopPanic();
}
if (evnt->getEvent() == "human_right") humanRun(RIGHT);
if (evnt->getEvent() == "show_base") showBase();
if (evnt->getEvent() == "doctor_left") doctorRun(LEFT);
if (evnt->getEvent() == "stop_doctor") runPanicAnim(_doctorSprite, "doctor");
if (evnt->getEvent() == "stop_human") runPanicAnim(_humanSprite, "human");
if (evnt->getEvent() == "End") end();
}
int StartingScene::inverseOpacity(int var)
{
return var == 0 ? 255 : 0;
}
void StartingScene::humanRun(Direction dir)
{
runAnimation(_humanSprite, "player_white_move_" + sDirName[dir]);
_humanSprite->setFlippedX(dir == RIGHT);
}
void StartingScene::showBase()
{
auto sprite = static_cast<Sprite*>(_rootNode->getChildByName("base_0_9"));
sprite->runAction(FadeIn::create(0.5));
}
void StartingScene::doctorRun(Direction dir)
{
runAnimation(_doctorSprite, "doctor_move_" + sDirName[dir]);
_doctorSprite->setFlippedX(dir == LEFT);
}
void StartingScene::draculaFly(const std::string& key)
{
runAnimation(_draculaSprite, key);
}
void StartingScene::runPanicAnim(cocos2d::Sprite* sprite, const std::string& animKey)
{
runAnimation(sprite, animKey + "_panic");
}
void StartingScene::end()
{
auto action = Sequence::create(FadeOut::create(0.5),
CallFunc::create(CC_CALLBACK_0(StartingScene::stopMusic, this)),
CallFunc::create(CC_CALLBACK_0(LoadLevelScene::loadAfterStartingScene, _loadScene)), nullptr);
_rootNode->runAction(action);
}
void StartingScene::runAnimation(cocos2d::Sprite* sprite, const std::string& animKey)
{
auto animation = AnimationCache::getInstance()->getAnimation(animKey);
if (animation)
{
sprite->stopActionByTag(ANIM_TAG);
auto action = RepeatForever::create(Animate::create(animation));
action->setTag(ANIM_TAG);
sprite->runAction(action);
}
}
void StartingScene::stopPanic()
{
_doctorSprite->stopActionByTag(ANIM_TAG);
_doctorSprite->setSpriteFrame("doctor_0.png");
_humanSprite->stopActionByTag(ANIM_TAG);
_humanSprite->setSpriteFrame("human_0.png");
}
void StartingScene::stopMusic()
{
GameSounds::Instance().stopAll();
}
| 18,029
|
https://github.com/shreyansh26/RevOpiD-IJCNLP-17-/blob/master/Doc2Vec Model/train_doc2vecmodel.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
RevOpiD-IJCNLP-17-
|
shreyansh26
|
Python
|
Code
| 194
| 719
|
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk import word_tokenize, pos_tag, sent_tokenize, RegexpTokenizer
import string, re
from autocorrect import spell
from nltk.tokenize import TweetTokenizer
from nltk.stem.lancaster import LancasterStemmer
from nltk.corpus import state_union
import nltk
import gensim
from gensim.test.test_doc2vec import ConcatenatedDoc2Vec
import pandas as pd
from sklearn.cluster import KMeans
import os
import pickle
from random import shuffle
with open('db.pickle', 'rb') as handle:
db = pickle.load(handle)
with open('docLabel.pickle', 'rb') as handle:
docLabel = pickle.load(handle)
class LabeledLineSentence(object):
def __init__(self, doc_list, labels_list):
self.labels_list = labels_list
self.doc_list = doc_list
def __iter__(self):
for idx, doc in enumerate(self.doc_list):
yield gensim.models.doc2vec.LabeledSentence(doc, [self.labels_list[idx]])
data = db
#iterator returned over all documents
it = LabeledLineSentence(data, docLabel)
model1 = gensim.models.Doc2Vec(dm=0, size=300, min_count=10, alpha=0.025, min_alpha=0.001, dbow_words=1) # DBOW
model2 = gensim.models.Doc2Vec(dm=1, size=300, min_count=10, alpha=0.025, min_alpha=0.001, dm_concat=1) # DBOW
## Only DBOW
model.build_vocab(it)
total_epoch = 100
#training of model
model.train(it, total_examples=len(data), epochs=total_epoch)
#saving the created model
model.save('complete_doc2vec_dbow.model')
print("model_dbow saved")
## Only DMC
model2.build_vocab(it)
total_epoch = 100
#training of model
model2.train(it, total_examples=len(data), epochs=total_epoch)
#saving the created model
model2.save('complete_doc2vec_dmc.model')
print("model_dmc saved")
'''
## DBOW + DMC
model3 = ConcatenatedDoc2Vec([model1, model2])
total_epoch = 100
#training of model
model3.train(it, total_examples=len(data), epochs=total_epoch)
#saving the created model
model3.save('complete_doc2vec_dbow+dmc.model')
print("model_dbow+dmc saved")
'''
| 22,656
|
https://github.com/scibian/fmgui/blob/master/src/com/intel/stl/ui/wizards/impl/preferences/PreferencesWizardController.java
|
Github Open Source
|
Open Source
|
Intel
| null |
fmgui
|
scibian
|
Java
|
Code
| 950
| 3,490
|
/**
* Copyright (c) 2015, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.stl.ui.wizards.impl.preferences;
import javax.swing.JComponent;
import com.intel.stl.api.IMessage;
import com.intel.stl.api.configuration.ConfigurationException;
import com.intel.stl.api.performance.PMConfigBean;
import com.intel.stl.ui.common.STLConstants;
import com.intel.stl.ui.common.Util;
import com.intel.stl.ui.wizards.impl.IMultinetWizardListener;
import com.intel.stl.ui.wizards.impl.IMultinetWizardTask;
import com.intel.stl.ui.wizards.impl.IWizardListener;
import com.intel.stl.ui.wizards.impl.InteractionType;
import com.intel.stl.ui.wizards.impl.WizardValidationException;
import com.intel.stl.ui.wizards.model.IModelChangeListener;
import com.intel.stl.ui.wizards.model.IWizardModel;
import com.intel.stl.ui.wizards.model.MultinetWizardModel;
import com.intel.stl.ui.wizards.model.preferences.PreferencesModel;
import com.intel.stl.ui.wizards.view.preferences.PreferencesWizardView;
/**
* Controller for the User Preferences Wizard
*/
public class PreferencesWizardController
implements IMultinetWizardTask, IModelChangeListener<IWizardModel> {
private final PreferencesWizardView view;
private PreferencesModel preferencesModel;
@SuppressWarnings("unused")
private IWizardListener wizardController;
private IMultinetWizardListener multinetWizardController;
private boolean done;
private PreferencesInputValidator validator;
private boolean firstPass = true;
private boolean connectable;
public PreferencesWizardController(PreferencesWizardView view) {
this.view = view;
}
public PreferencesWizardController(PreferencesWizardView view,
PreferencesModel preferencesModel) {
this(view);
view.setDirty(false);
this.preferencesModel = preferencesModel;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#getName()
*/
@Override
public String getName() {
return STLConstants.K3005_PREFERENCES.getValue();
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#getView()
*/
@Override
public JComponent getView() {
return view;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#init()
*/
@Override
public void init() {
// Singleton logging validator
validator = PreferencesInputValidator.getInstance();
if (firstPass || multinetWizardController.isNewWizard()) {
view.resetPanel();
}
firstPass = false;
view.setDirty(false);
done = false;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#setDone(boolean)
*/
@Override
public void setDone(boolean done) {
this.done = done;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#isDone()
*/
@Override
public boolean isDone() {
return done;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#onApply()
*/
@Override
public boolean validateUserEntry() throws WizardValidationException {
boolean success = false;
// Only try to get the PMConfig if the host is reachable
int sweepInterval = 0;
if (connectable) {
try {
// The call to getPMConfig() may fail silently since the user
// may be setting up subnets that are known to be disconnected
PMConfigBean pmConfig = null;
pmConfig = multinetWizardController.getPMConfig();
if (pmConfig != null) {
sweepInterval = pmConfig.getSweepInterval();
}
} catch (ConfigurationException e) {
} catch (Exception e) {
Util.showError(view, e);
return false;
}
} else {
PreferencesValidatorError error =
PreferencesValidatorError.UNABLE_TO_VALIDATE;
throw new WizardValidationException(error.getLabel());
}
// Since it is possible to be unable to connect to the host,
// update the model whether it is valid or not
updateModel();
int errorCode = validator.validate(preferencesModel, sweepInterval);
if (errorCode == PreferencesValidatorError.OK.getId()) {
success = true;
} else {
view.logMessage(PreferencesValidatorError.getValue(errorCode));
IMessage message = PreferencesValidatorError.getMessage(errorCode);
if (message != null) {
throw new WizardValidationException(message,
PreferencesValidatorError.getData(errorCode));
} else {
throw new WizardValidationException();
}
}
return (success && connectable);
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#onPrevious()
*/
@Override
public void onPrevious() {
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#onReset()
*/
@Override
public void onReset() {
view.resetPanel();
view.setDirty(false);
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#cleanup()
*/
@Override
public void cleanup() {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.impl.IWizardTask#selectStep(java.lang.String)
*/
@Override
public void selectStep(String taskName) {
multinetWizardController.selectStep(taskName);
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#isDirty()
*/
@Override
public boolean isDirty() {
return view.isDirty();
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#setDirty(boolean)
*/
@Override
public void setDirty(boolean dirty) {
view.setDirty(dirty);
multinetWizardController.setDirty(dirty);
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.impl.IWizardTask#doInteractiveAction(com.intel
* .stl.ui.wizards.impl.InteractionType, java.lang.Object[])
*/
@Override
public void doInteractiveAction(InteractionType action, Object... data) {
switch (action) {
case CHANGE_WIZARDS:
if (data == null) {
return;
}
String taskName = (String) data[0];
if (taskName != null) {
onReset();
view.closeStatusPanel();
selectStep(taskName);
}
break;
case SAVE_LOGGING:
// NOP
break;
default:
break;
}
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#updateModel()
*/
@Override
public void updateModel() {
// Update the local preferences model
preferencesModel.setRefreshRate(view.getRefreshRate());
preferencesModel.setRefreshRateUnits(view.getRefreshRateUnits());
preferencesModel
.setTimingWindowInSeconds(view.getTimeWindowInSeconds());
preferencesModel.setNumWorstNodes(view.getNumWorstNodes());
preferencesModel.setMailRecipients(view.getEmailList());
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.impl.IWizardTask#promoteModel(com.intel.stl.
* ui.wizards.model.MultinetWizardModel)
*/
@Override
public void promoteModel(MultinetWizardModel topModel) {
// Promote the preferences model to the top model
topModel.setPreferencesModel(preferencesModel);
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.model.IModelChangeListener#onModelChange(com
* .intel.stl.ui.wizards.model.IWizardModel)
*/
@Override
public void onModelChange(IWizardModel m) {
MultinetWizardModel model = (MultinetWizardModel) m;
view.updateView(model);
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.impl.IWizardTask#setWizardController(com.intel
* .stl.ui.wizards.impl.IMultinetWizardListener)
*/
@Override
public void setWizardController(IMultinetWizardListener controller) {
multinetWizardController = controller;
}
/*
* (non-Javadoc)
*
* @see
* com.intel.stl.ui.wizards.impl.IWizardTask#setWizardController(com.intel
* .stl.ui.wizards.impl.IWizardListener)
*/
@Override
public void setWizardController(IWizardListener controller) {
this.wizardController = controller;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#clear()
*/
@Override
public void clear() {
view.clearPanel();
preferencesModel.clear();
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#setConnectable(boolean)
*/
@Override
public void setConnectable(boolean connectable) {
this.connectable = connectable;
}
/*
* (non-Javadoc)
*
* @see com.intel.stl.ui.wizards.impl.IWizardTask#isEditValid()
*/
@Override
public boolean isEditValid() {
return view.isEditValid();
}
public void onEmailTest(String recipients) {
multinetWizardController.onEmailTest(recipients);
}
}
| 17,514
|
https://github.com/chiang/teamcode/blob/master/src/main/java/io/teamcode/common/vcs/svn/callback/SvnLogMessageCallback.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
teamcode
|
chiang
|
Java
|
Code
| 251
| 1,107
|
package io.teamcode.common.vcs.svn.callback;
import io.teamcode.common.vcs.svn.ChangedFile;
import io.teamcode.common.vcs.svn.ChangedFileAction;
import io.teamcode.common.vcs.svn.Commit;
import io.teamcode.service.project.integration.ProjectIntegrationServiceManager;
import org.apache.subversion.javahl.callback.LogMessageCallback;
import org.apache.subversion.javahl.types.ChangePath;
import org.apache.subversion.javahl.types.ChangePath.Action;
import org.apache.subversion.javahl.types.LogDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;
public class SvnLogMessageCallback implements LogMessageCallback {
private static final Logger logger = LoggerFactory.getLogger(SvnLogMessageCallback.class);
private List<Commit> repositoryHistories = new ArrayList<>();
private Set<String> revisionProps;
public SvnLogMessageCallback() {
}
public SvnLogMessageCallback(Set<String> revisionProps) {
this.revisionProps = revisionProps;
}
public void singleMessage(Set<ChangePath> changedPaths, long revision, Map<String, byte[]> revprops, boolean hasChildren) {
Commit history = new Commit();
if (changedPaths != null) {
for (ChangePath cp: changedPaths) {
history.addChangedFile(new ChangedFile(ChangedFileAction.valueOf(cp.getAction().toString().toUpperCase()), cp.getPath(), cp.getNodeKind().toString()));
if (cp.getAction().equals(Action.add)) {
history.plusAddtions();
}
else if (cp.getAction().equals(Action.delete)) {
history.plusDeletions();
}
else if (cp.getAction().equals(Action.replace)) {
history.plusReplacements();
}
else if (cp.getAction().equals(Action.modify)) {
history.plusModifications();
}
if (StringUtils.hasText(cp.getCopySrcPath())) {
history.setCopiedFromPath(cp.getCopySrcPath());
history.setCopiedFromRevision(cp.getCopySrcRevision());
}
}
}
String author;
try {
author = new String(revprops.get("svn:author"), "UTF8");
} catch (UnsupportedEncodingException e) {
author = new String(revprops.get("svn:author"));
}
String message;
try {
message = new String(revprops.get("svn:log"), "UTF8");
} catch (UnsupportedEncodingException e) {
message = new String(revprops.get("svn:log"));
}
long timeMillis;
try {
LogDate date = new LogDate(new String(revprops.get("svn:date")));
timeMillis = date.getDate().getTime();
} catch (ParseException ex) {
timeMillis = 0L;
}
if (this.revisionProps != null) {
byte[] propValue;
for (String revisionProp : revisionProps) {
logger.trace("'{}' 속성 값을 추출합니다...", revisionProp);
propValue = revprops.get(revisionProp);
if (propValue != null) {
try {
history.addRevisionProp(revisionProp, new String(propValue, "UTF-8"));
} catch (UnsupportedEncodingException e) {
history.addRevisionProp(revisionProp, new String(propValue));
}
}
}
}
if (revision != -1L) {
history.setRevision(revision);
history.setMessage(message);
history.setAuthor(author);
history.setCreatedAt(new Date(timeMillis));
this.repositoryHistories.add(history);
}
}
public List<Commit> getRepositoryHistories() {
return this.repositoryHistories;
}
}
| 3,175
|
https://github.com/hermixy/LT/blob/master/PROJECTS/IupSample/InterServer/InterServer/myJsonServerPacket.c
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
LT
|
hermixy
|
C
|
Code
| 374
| 1,371
|
#include "stdio.h"
#include "stdlib.h"
#include "myJsonServerPacket.h"
#include "myDialog.h"
static void SaveToParseStruct(JsonParseStruct * pParseStruct, const char * left, int size)
{
int oldsize;
char * pTmp;
if(pParseStruct->content == NULL)
{
pParseStruct->content = malloc(size + 1);
BCOPY(left, pParseStruct->content, size);
pParseStruct->content[size] = '\0';
}
else
{
oldsize = strlen(pParseStruct->content);
pTmp = pParseStruct->content;
pParseStruct->content = malloc(size + oldsize + 1);
BCOPY(pTmp, pParseStruct->content, oldsize);
free(pTmp);
BCOPY(left, pParseStruct->content + oldsize, size);
pParseStruct->content[size + oldsize] = '\0';
}
}
static char * CombineParseStruct(JsonParseStruct * pParseStruct, const char * packet)
{
int oldsize, size;
char * pRequestData;
if(pParseStruct->content == NULL)
{
pRequestData = STR_NEW(packet);
}
else
{
oldsize = strlen(pParseStruct->content);
size = strlen(packet);
pRequestData = (char *)malloc(oldsize + size + 1);
strcpy(pRequestData, pParseStruct->content);
strcat(pRequestData, packet);
free(pParseStruct->content);
pParseStruct->content = NULL;
}
return pRequestData;
}
/*
reutrn 0 or LT_ERR_PACKET
*/
int myJsonServerParseFunc(const char * recvBuff, int recvSize, LT_Server * pServer, LT_ClientNode * pClientNode)
{
JsonParseStruct * pParseStruct;
char * pRecv;
char * pPacket;
char * pRequestData;
int i;
int size;
pParseStruct = (JsonParseStruct * )LT_Server_GetParseStruct(pClientNode);
pRecv = (char *)recvBuff;
pPacket = (char *)recvBuff;
for(i = 0; i < recvSize; i++)
{
if(pRecv[i] == '\0')
{
pRequestData = CombineParseStruct(pParseStruct, (const char * )pPacket);
LT_Server_Append(pServer, pClientNode, 0, pRequestData);
if(i < recvSize - 1)
{
pPacket = pRecv + i + 1;
}
else
{
pPacket = NULL;
}
}
}
//left some bytes
if(pPacket != NULL)
{
size = recvSize - (pPacket - pRecv);
SaveToParseStruct(pParseStruct, pPacket, size);
}
return 0;
}
void * myJsonServerParseStructAllocFunc()
{
JsonParseStruct * pParseStruct;
pParseStruct = (JsonParseStruct *)malloc(sizeof(JsonParseStruct));
BZERO(pParseStruct, sizeof(JsonParseStruct));
return pParseStruct;
}
void myJsonServerParseStructFreeFunc(void * data)
{
JsonParseStruct * pParseStruct;
pParseStruct = (JsonParseStruct *)data;
if(pParseStruct->content)
free(pParseStruct->content);
free(pParseStruct);
}
int myJsonServerSerialFunc(LT_RequestInfo * pInfo, char ** buf, int * buflen)
{
if(pInfo->replyData == NULL)
return -1;
*buflen = strlen((const char *)pInfo->replyData) + 1;
*buf = malloc(*buflen);
BCOPY(pInfo->replyData, *buf, *buflen);
return 0;
}
void myJsonServerRequestDataFreeFunc(void * data)
{
free(data);
}
void myJsonServerReplyDataFreeFunc(void * data)
{
free(data);
}
void myJsonServerProcessFunc(LT_RequestInfo * pInfo)
{
int len;
void * pReplyData;
if(pInfo->ltEvent == LT_SERVER_EVENT_CONNECT)
{
printf("one client connect %d\n",pInfo->clientID);
myMatrixAppend(pInfo->clientID, inet_ntoa(pInfo->remote.sin_addr), pInfo->remote.sin_port);
return;
}
else if(pInfo->ltEvent == LT_SERVER_EVENT_DISCONNECT)
{
printf("one client disconnect %d\n",pInfo->clientID);
myMatrixDelete(pInfo->clientID);
return;
}
len = strlen((const char *)pInfo->requestData) + 1;
pReplyData = malloc(len);
BCOPY(pInfo->requestData, pReplyData, len);
LT_Server_Send(pInfo->pServer, 0, 0, pReplyData);
pInfo->dontReply = 1;
}
| 28,877
|
https://github.com/greyluxtech/greylux-properties-webapp/blob/master/resources/views/layouts/mainlayout.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
greylux-properties-webapp
|
greyluxtech
|
Blade
|
Code
| 32
| 153
|
<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.partials.head')
</head>
<body>
<div id="app">
{{-- @include('layouts.partials.header') --}}
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
@yield('content')
</div>
@include('layouts.partials.footer')
{{-- @include('layouts.partials.form') --}}
@include('layouts.partials.footer-script')
</div>
</body>
</html>
| 38,640
|
https://github.com/alexfordc/Au/blob/master/Libraries/_TreeList/Au/AuScrollableControl.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Au
|
alexfordc
|
C#
|
Code
| 899
| 2,950
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Drawing;
//using System.Linq;
using Au.Types;
namespace Au.Controls
{
/// <summary>
/// Allows to set/get scroll info and receive scroll notifications.
/// This class exists because .NET ScrollableControl does not work when AutoScroll is false.
/// </summary>
public class AuScrollableControl : Control
{
public class ScrollInfo
{
public bool IsVertical { get; private set; }
public ScrollEventType EventType { get; private set; }
public int Min { get; private set; }
public int Max { get; private set; }
public int Page { get; private set; }
public int Pos { get; private set; }
//public int TrackPos { get; private set; }
internal void Set(bool vert, ScrollEventType et, ref Api.SCROLLINFO k)
{
IsVertical = vert;
EventType = et;
Min = k.nMin;
Max = k.nMax;
Page = k.nPage;
Pos = k.nPos;
//TrackPos = k.nTrackPos;
}
}
ScrollInfo _e;
Api.SCROLLINFO _h, _v;
public AuScrollableControl()
{
_h.cbSize = _v.cbSize = Api.SizeOf(_h);
_h.nMax = _v.nMax = 100;
_e = new ScrollInfo();
}
void _GetScrollInfo(bool vertical, out Api.SCROLLINFO k)
{
if(IsHandleCreated) {
k = default; unsafe { k.cbSize = sizeof(Api.SCROLLINFO); }
k.fMask = Api.SIF_TRACKPOS | Api.SIF_POS | Api.SIF_PAGE | Api.SIF_RANGE;
Api.GetScrollInfo((AWnd)this, vertical, ref k);
} else if(vertical) k = _v;
else k = _h;
}
public ScrollInfo GetScrollInfo(bool vertical)
{
_GetScrollInfo(vertical, out var k);
var r = new ScrollInfo();
r.Set(vertical, ScrollEventType.ThumbPosition, ref k);
return r;
}
public int GetScrollPos(bool vertical)
{
Api.SCROLLINFO k = default; unsafe { k.cbSize = sizeof(Api.SCROLLINFO); }
k.fMask = Api.SIF_POS;
Api.GetScrollInfo((AWnd)this, vertical, ref k);
return k.nPos;
}
public void SetScrollPos(bool vertical, int pos, bool notify)
{
_GetScrollInfo(vertical, out var k);
pos = AMath.MinMax(pos, k.nMin, k.nMax);
if(pos == k.nPos) return;
k.nPos = pos;
ref var x = ref (vertical ? ref _v : ref _h);
x.fMask |= Api.SIF_POS;
x.nPos = pos;
if(IsHandleCreated) _SetScrollInfo();
if(notify) OnScroll(GetScrollInfo(vertical));
}
public void SetScrollInfo(bool vertical, int max, int page, int? pos = null, bool notify = false)
{
ref var x = ref (vertical ? ref _v : ref _h);
x.fMask |= Api.SIF_PAGE | Api.SIF_RANGE;
x.nMax = max; x.nPage = page;
if(pos.HasValue) {
x.fMask |= Api.SIF_POS;
x.nPos = pos.GetValueOrDefault();
} else if(0 != (x.fMask & Api.SIF_POS)) { //can be when was no handle
if(x.nPos > max) x.nPos = max;
}
if(IsHandleCreated) _SetScrollInfo();
if(notify) OnScroll(GetScrollInfo(vertical));
}
void _SetScrollInfo()
{
if(_v.fMask != 0) {
Api.SetScrollInfo((AWnd)this, true, _v, true);
_v.fMask = 0;
}
if(_h.fMask != 0) {
Api.SetScrollInfo((AWnd)this, false, _h, true);
_h.fMask = 0;
}
}
protected override void WndProc(ref Message m)
{
switch(m.Msg) {
case Api.WM_HSCROLL:
case Api.WM_VSCROLL:
_OnScroll(m.Msg == Api.WM_VSCROLL, (ScrollEventType)AMath.LoUshort(m.WParam));
break;
case Api.WM_CREATE:
_SetScrollInfo();
break;
}
base.WndProc(ref m);
}
void _OnScroll(bool vert, ScrollEventType code)
{
if(code == ScrollEventType.EndScroll) return;
Api.SCROLLINFO k = default; unsafe { k.cbSize = sizeof(Api.SCROLLINFO); }
k.fMask = Api.SIF_TRACKPOS | Api.SIF_POS | Api.SIF_PAGE | Api.SIF_RANGE;
Api.GetScrollInfo((AWnd)this, vert, ref k);
//AOutput.Write(k.nPos, k.nTrackPos, k.nPage, k.nMax);
int i = k.nPos;
switch(code) {
case ScrollEventType.ThumbTrack: i = k.nTrackPos; break;
case ScrollEventType.SmallDecrement: i--; break;
case ScrollEventType.SmallIncrement: i++; break;
case ScrollEventType.LargeDecrement: i -= k.nPage; break;
case ScrollEventType.LargeIncrement: i += k.nPage; break;
case ScrollEventType.First: i = k.nMin; break;
case ScrollEventType.Last: i = k.nMax; break;
}
int max = k.nMax - k.nPage + 1;
if(i > max) i = max;
if(i < k.nMin) i = k.nMin;
k.nPos = i;
k.fMask = Api.SIF_POS;
Api.SetScrollInfo((AWnd)this, vert, k, true);
//if(vert) _v = k; else _h = k;
_e.Set(vert, code, ref k);
OnScroll(_e);
}
public event EventHandler<ScrollInfo> Scroll;
protected virtual void OnScroll(ScrollInfo e)
{
Scroll?.Invoke(this, e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
//_search?.EndSearch();
int lines = e.Delta / 120 * SystemInformation.MouseWheelScrollLines;
var k = GetScrollInfo(true);
int newValue = k.Pos - lines;
newValue = Math.Min(k.Max - k.Page + 1, newValue);
newValue = Math.Min(k.Max, newValue);
var pos = Math.Max(0, newValue);
SetScrollPos(true, pos, true);
base.OnMouseWheel(e);
}
protected Size CalcClientAreaSizeWithScrollbars(int contentWidth, int contentHeight)
{
//calc current client size + scrollbars
var z = this.ClientSize;
if(IsHandleCreated) {
var w = (AWnd)this;
Api.SCROLLBARINFO sbi = default; unsafe { sbi.cbSize = sizeof(Api.SCROLLBARINFO); }
Api.GetScrollBarInfo(w, AccOBJID.VSCROLL, ref sbi); z.Width += sbi.rcScrollBar.Width;
Api.GetScrollBarInfo(w, AccOBJID.HSCROLL, ref sbi); z.Height += sbi.rcScrollBar.Height;
}
//subtract scrollbars if will be added
bool needV = false, needH = false;
for(int i = 0; i < 2; i++) {
if(!needV && contentHeight > z.Height) {
int k = SystemInformation.VerticalScrollBarWidth;
if(needV = k <= z.Width && z.Height > 0) z.Width -= k;
}
if(!needH && contentWidth >= z.Width) {
int k = SystemInformation.HorizontalScrollBarHeight;
if(needH = k < z.Height && (z.Width > 0 || needV)) z.Height -= k;
}
}
return z;
}
protected void SetListScrollbars(int count, int itemHeight, int itemWidth, bool resetPos)
{
if(_inSetScroll) return; _inSetScroll = true;
try {
if(count <= 0 || itemHeight <= 0) {
this.SetScrollInfo(true, 0, 0, 0);
this.SetScrollInfo(false, 0, 0, 0);
} else {
//var p1 = APerf.Create();
var z = CalcClientAreaSizeWithScrollbars(itemWidth, count * itemHeight);
int? pos = resetPos ? (int?)0 : null;
this.SetScrollInfo(true, count - 1, z.Height / itemHeight, pos);
this.SetScrollInfo(false, itemWidth, z.Width, pos);
//p1.Next();
if(resetPos) {
//workaround for Windows or .NET bug: sometimes then mouse behaves incorrectly: on scrollbar generates client messages (eg WM_MOUSEMOVE instead of WM_NCMOUSEMOVE). This workaround makes this func almost 2 times slower, but I don't know a better way.
((AWnd)this).SetWindowPos(Native.SWP.FRAMECHANGED | Native.SWP.NOMOVE | Native.SWP.NOSIZE | Native.SWP.NOACTIVATE | Native.SWP.NOZORDER | Native.SWP.NOSENDCHANGING);
Invalidate();
}
//p1.NW('S');
ADebug.PrintIf(z != ClientSize && Visible, $"calc={z} now={ClientSize}");
}
}
finally { _inSetScroll = false; }
}
bool _inSetScroll;
}
}
| 22,773
|
https://github.com/Zenika/immutadot/blob/master/packages/immutadot/src/nav/finalNav.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
immutadot
|
Zenika
|
JavaScript
|
Code
| 34
| 98
|
class FinalNav {
constructor(value) {
this.value = value
}
get() {
return this.value
}
update(updater) {
return updater(this.value)
}
get final() {
return true
}
}
export function finalNav(value) {
return new FinalNav(value)
}
| 41,168
|
https://github.com/aparnachaudhary/javaee-service-registry/blob/master/examples/tweet-store/src/main/java/io/github/aparnachaudhary/tweetstore/TweetResource.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
javaee-service-registry
|
aparnachaudhary
|
Java
|
Code
| 39
| 175
|
package io.github.aparnachaudhary.tweetstore;
import io.github.aparnachaudhary.tweet.Tweet;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
* REST Endpoint for feed producer
*
* @author Aparna Chaudhary
*/
@Path("/tweets")
public interface TweetResource {
@Path("{id}")
@GET
@Produces({"application/json"})
Tweet get(@PathParam("id") String id);
@POST
@Consumes(MediaType.APPLICATION_JSON)
String store(Tweet tweet);
}
| 19,686
|
https://github.com/tombish/newton-dynamics/blob/master/newton-4.00/doc/html/structnd_shape_info_1_1dg_cone_data.js
|
Github Open Source
|
Open Source
|
Zlib
| null |
newton-dynamics
|
tombish
|
JavaScript
|
Code
| 15
| 126
|
var structnd_shape_info_1_1dg_cone_data =
[
[ "m_height", "structnd_shape_info_1_1dg_cone_data.html#a54e717c7377dbf537a1e1991cb9705af", null ],
[ "m_r", "structnd_shape_info_1_1dg_cone_data.html#a4ac1c573887e3ef2c581ec80c1a7defe", null ]
];
| 24,393
|
https://github.com/AntonIT99/Flans-Mod-NPC-Vehicles/blob/master/src/main/java/com/wolffsmod/entity/manus/ww2/EntityWW2_AAGun_Flak88_2A.java
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
Flans-Mod-NPC-Vehicles
|
AntonIT99
|
Java
|
Code
| 38
| 176
|
package com.wolffsmod.entity.manus.ww2;
import com.wolffsmod.entity.EntityFlanAAGunNPC;
import net.minecraft.world.World;
public class EntityWW2_AAGun_Flak88_2A extends EntityFlanAAGunNPC
{
public EntityWW2_AAGun_Flak88_2A(World w)
{
super(w);
}
@Override
public void setupConfig()
{
setDriver("3 30 -16 -360 360 0 90");
setNumBarrels(1);
addBarrel("0 72 28 0");
setRecoil(5F);
}
}
| 36,859
|
https://github.com/rkhomyk/FFT.Oanda/blob/master/src/FFT.Oanda/Transactions/FixedPriceOrderReason.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
FFT.Oanda
|
rkhomyk
|
C#
|
Code
| 111
| 257
|
// Copyright (c) True Goodwill. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace FFT.Oanda.Transactions
{
using System.Text.Json.Serialization;
/// <summary>
/// The reason that the Fixed Price Order was created.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum FixedPriceOrderReason
{
/// <summary>
/// The Fixed Price Order was created as part of a platform account
/// migration
/// </summary>
PLATFORM_ACCOUNT_MIGRATION,
/// <summary>
/// The Fixed Price Order was created to close a Trade as part of division
/// account migration
/// </summary>
TRADE_CLOSE_DIVISION_ACCOUNT_MIGRATION,
/// <summary>
/// The Fixed Price Order was created to close a Trade administratively
/// </summary>
TRADE_CLOSE_ADMINISTRATIVE_ACTION,
}
}
| 3,827
|
https://github.com/yangrong688/hive/blob/master/itests/hive-jmh/src/main/java/org/apache/hive/benchmark/vectorization/mapjoin/load/LongKeyBase.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
hive
|
yangrong688
|
Java
|
Code
| 315
| 1,108
|
/*
* 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.apache.hive.benchmark.vectorization.mapjoin.load;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.MapJoinTestConfig;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.MapJoinTestDescription;
import org.apache.hadoop.hive.ql.plan.VectorMapJoinDesc;
import org.apache.hadoop.hive.serde2.ByteStream;
import org.apache.hadoop.hive.serde2.binarysortable.fast.BinarySortableSerializeWrite;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.io.BytesWritable;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class LongKeyBase extends AbstractHTLoadBench {
public void doSetup(VectorMapJoinDesc.VectorMapJoinVariation vectorMapJoinVariation,
MapJoinTestConfig.MapJoinTestImplementation mapJoinImplementation, int rows) throws Exception {
long seed = 2543;
int rowCount = rows;
HiveConf hiveConf = new HiveConf();
int[] bigTableKeyColumnNums = new int[] { 0 };
String[] bigTableColumnNames = new String[] { "number1" };
TypeInfo[] bigTableTypeInfos = new TypeInfo[] { TypeInfoFactory.longTypeInfo };
int[] smallTableRetainKeyColumnNums = new int[] {};
TypeInfo[] smallTableValueTypeInfos =
new TypeInfo[] { TypeInfoFactory.dateTypeInfo, TypeInfoFactory.stringTypeInfo };
MapJoinTestDescription.SmallTableGenerationParameters smallTableGenerationParameters =
new MapJoinTestDescription.SmallTableGenerationParameters();
smallTableGenerationParameters
.setValueOption(MapJoinTestDescription.SmallTableGenerationParameters.ValueOption.ONLY_ONE);
setupMapJoinHT(hiveConf, seed, rowCount, vectorMapJoinVariation, mapJoinImplementation, bigTableColumnNames,
bigTableTypeInfos, bigTableKeyColumnNums, smallTableValueTypeInfos, smallTableRetainKeyColumnNums,
smallTableGenerationParameters);
this.customKeyValueReader = generateLongKVPairs(rowCount, seed);
}
private static CustomKeyValueReader generateLongKVPairs(int rows, long seed) throws IOException {
LOG.info("Data GEN for: " + rows);
Random random = new Random(seed);
BytesWritable[] keys = new BytesWritable[rows];
BytesWritable[] values = new BytesWritable[rows];
BinarySortableSerializeWrite bsw = new BinarySortableSerializeWrite(1);
long startTime = System.currentTimeMillis();
ByteStream.Output outp;
BytesWritable key;
BytesWritable value;
for (int i = 0; i < rows; i++) {
outp = new ByteStream.Output();
bsw.set(outp);
long k = random.nextInt(rows);
bsw.writeLong(k);
key = new BytesWritable(outp.getData(), outp.getLength());
outp = new ByteStream.Output();
bsw.reset();
bsw.writeLong(random.nextInt(rows * 2));
value = new BytesWritable(outp.getData(), outp.getLength());
keys[i] = key;
values[i] = value;
}
LOG.info("Data GEN done after {} sec",
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime));
return new CustomKeyValueReader(keys, values);
}
}
| 24,458
|
https://github.com/SyedThaseemuddin/MPLAB-Harmony-Reference-Apps/blob/master/apps/sam_e54_cult/same54_sdcard_usb_audio_player/firmware/src/config/same54_cult/gfx/legato/image/raw/legato_imagedecoder_raw_write.c
|
Github Open Source
|
Open Source
|
0BSD
| 2,022
|
MPLAB-Harmony-Reference-Apps
|
SyedThaseemuddin
|
C
|
Code
| 325
| 1,022
|
// DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
// DOM-IGNORE-END
#include "gfx/legato/image/raw/legato_imagedecoder_raw.h"
#if LE_ENABLE_RAW_DECODER == 1
#include "gfx/legato/renderer/legato_renderer.h"
void _leRawImageDecoder_InjectStage(leRawDecodeState* state,
leRawDecodeStage* stage);
static struct FrameBufferWriteStage
{
leRawDecodeStage base;
} frameBufferWriteStage;
//#include <stdio.h>
#if LE_ALPHA_BLENDING_ENABLED == 1
static leResult stage_FrameBufferWrite(leRawDecodeStage* stage)
{
// write color
leRenderer_BlendPixel(stage->state->targetX,
stage->state->targetY,
stage->state->writeColor,
stage->state->globalAlpha);
/*printf("%i, %i, %u\n", stage->state->targetX,
stage->state->targetY,
stage->state->writeColor);*/
return LE_SUCCESS;
}
#else
static leResult stage_FrameBufferWrite(leRawDecodeStage* stage)
{
// write color
leRenderer_PutPixel(stage->state->targetX,
stage->state->targetY,
stage->state->writeColor);
return LE_SUCCESS;
}
#endif
leResult _leRawImageDecoder_FrameBufferWriteStage(leRawDecodeState* state)
{
memset(&frameBufferWriteStage, 0, sizeof(frameBufferWriteStage));
frameBufferWriteStage.base.state = state;
frameBufferWriteStage.base.exec = stage_FrameBufferWrite;
_leRawImageDecoder_InjectStage(state, (void*) &frameBufferWriteStage);
return LE_SUCCESS;
}
static struct ImageWriteStage
{
leRawDecodeStage base;
} imageWriteStage;
static leResult stage_ImageWrite(leRawDecodeStage* stage)
{
// write color
lePixelBufferSet_Unsafe(&stage->state->target->buffer,
stage->state->targetX,
stage->state->targetY,
stage->state->writeColor);
return LE_SUCCESS;
}
leResult _leRawImageDecoder_ImageWriteStage(leRawDecodeState* state)
{
memset(&imageWriteStage, 0, sizeof(imageWriteStage));
imageWriteStage.base.state = state;
imageWriteStage.base.exec = stage_ImageWrite;
_leRawImageDecoder_InjectStage(state, (void*)&imageWriteStage);
return LE_SUCCESS;
}
#endif /* LE_ENABLE_RAW_DECODER */
| 49,299
|
https://github.com/FuzzicalLogic/PoE-Bot/blob/master/Checks/RequireRoleAttribute.cs
|
Github Open Source
|
Open Source
|
0BSD
| 2,021
|
PoE-Bot
|
FuzzicalLogic
|
C#
|
Code
| 264
| 867
|
namespace PoE.Bot.Checks
{
using Discord;
using PoE.Bot.Contexts;
using PoE.Bot.Helpers;
using Qmmands;
using System;
using System.Linq;
using System.Threading.Tasks;
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class RequireAdminAttribute : CheckBaseAttribute
{
public override async Task<CheckResult> CheckAsync(ICommandContext ctx, IServiceProvider provider)
{
var context = ctx as GuildContext;
var botOwner = (await context.Client.GetApplicationInfoAsync().ConfigureAwait(false)).Owner.Id;
var user = context.User;
if (botOwner == user.Id || user.Id == context.Guild.OwnerId || user.GuildPermissions.Administrator || user.GuildPermissions.ManageGuild)
return CheckResult.Successful;
return new CheckResult(EmoteHelper.Cross + " I am sorry, God. We must learn not to abuse your creations. *Requires `Admin`*");
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class RequireModeratorAttribute : CheckBaseAttribute
{
public override async Task<CheckResult> CheckAsync(ICommandContext ctx, IServiceProvider provider)
{
var context = ctx as GuildContext;
var botOwner = (await context.Client.GetApplicationInfoAsync().ConfigureAwait(false)).Owner.Id;
var user = context.User;
if (botOwner == user.Id || user.Id == context.Guild.OwnerId || user.GuildPermissions.Administrator || user.GuildPermissions.ManageGuild || user.GuildPermissions.ManageChannels
|| user.GuildPermissions.ManageRoles || user.GuildPermissions.BanMembers || user.GuildPermissions.KickMembers)
{
return CheckResult.Successful;
}
return new CheckResult(EmoteHelper.Cross + " I am sorry, God. We must learn not to abuse your creations. *Requires `Moderator`*");
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class RequireRoleAttribute : CheckBaseAttribute
{
private readonly string[] _roleNames;
public RequireRoleAttribute(params string[] roleNames) => _roleNames = roleNames;
public override async Task<CheckResult> CheckAsync(ICommandContext ctx, IServiceProvider provider)
{
var context = ctx as GuildContext;
var botOwner = (await context.Client.GetApplicationInfoAsync().ConfigureAwait(false)).Owner.Id;
var user = context.User;
if (botOwner == user.Id || context.User.Id == context.Guild.OwnerId || user.GuildPermissions.Administrator || user.GuildPermissions.ManageGuild)
return CheckResult.Successful;
if ((context.User as IGuildUser)?.RoleIds.Intersect(context.Guild.Roles.Where(x => _roleNames.Contains(x.Name)).Select(x => x.Id)).Any() is true)
return CheckResult.Successful;
return new CheckResult(EmoteHelper.Cross + " I am sorry, God. We must learn not to abuse your creations. *Requires `" + string.Join(", ", _roleNames) + "` Role *");
}
}
}
| 45,024
|
https://github.com/amyami187/nngeometry/blob/master/nngeometry/object/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
nngeometry
|
amyami187
|
Python
|
Code
| 26
| 105
|
from .pspace import (PMatDense, PMatBlockDiag, PMatDiag,
PMatLowRank, PMatImplicit,
PMatKFAC, PMatEKFAC, PMatQuasiDiag)
from .vector import (PVector, FVector)
from .fspace import (FMatDense,)
from .map import (PushForwardDense, PushForwardImplicit,
PullBackDense)
| 2,323
|
https://github.com/namofun/uik/blob/master/sample/SatelliteSite.SampleModule/Controllers/MainController.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
uik
|
namofun
|
C#
|
Code
| 78
| 313
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SatelliteSite.SampleModule.Services;
namespace SatelliteSite.SampleModule.Controllers
{
[Area("Sample")]
[Route("[area]/[controller]/[action]")]
[SupportStatusCodePage]
public class MainController : ViewControllerBase
{
private ForecastService Service { get; }
public MainController(ForecastService service)
{
Service = service;
}
[HttpGet]
public IActionResult Home()
{
return View(Service.Forecast());
}
[HttpGet]
public IActionResult CardSample1()
{
return View();
}
[HttpGet]
public IActionResult Markdown()
{
return View();
}
[Authorize]
[HttpGet]
[HttpPost]
public IActionResult Claims(string roleName)
{
return Json(User.IsInRole(roleName));
}
[HttpGet]
public IActionResult ThrowErrors()
{
throw new System.Exception("hello?\ndhewufghe\ndheuwfhe");
}
}
}
| 6,160
|
https://github.com/asifkottakal1/jms/blob/master/application/models/Mdl_salesrtninvce.php
|
Github Open Source
|
Open Source
|
MIT
| null |
jms
|
asifkottakal1
|
PHP
|
Code
| 177
| 834
|
<?php
class Mdl_salesrtninvce extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function salesrtninvce_reg($data,$items,$quantities,$prices,$amounts)
{
if($this->db->insert('salesrtnin',$data))
{
$id=$this->db->insert_id();
foreach ($items as $key => $item) {
if($key<sizeof($items))
{
$quantity=$quantities[$key];
$price=$prices[$key];
$amount=$amounts[$key];
$this->db->insert('salesrtndetails',array('salesrtnid'=>$id,'salesrtnitem'=>$item,'quantity'=>$quantity,'price'=>$price,'amount'=>$amount));
}
}
return true;
}
else
{
return false;
}
}
public function get_areauid($stag)
{
$res=$this->db->query("select areauid from area where areauid like '$stag%'");
if($row=$res->result_array())
{
return $row;
}
else
{
return false;
}
}
public function verify_areauid($areauid){
$res=$this->db->query("select areauid from area where areauid='$areauid'");
if($row=$res->result_array())
{
return true;
}
else
{
return false;
}
}
public function get_sabha($areauid)
{
$res=$this->db->query("select * from sabha where areauid = '$areauid'");
if($row=$res->result_array())
{
return $row;
}
else
{
return false;
}
}
public function get_salesrtnuid($stag)
{
$res=$this->db->query("select salesrtnuid from salesrtn where salesrtnuid like '$stag%'");
if($row=$res->result_array())
{
return $row;
}
else
{
return false;
}
}
public function verify_salesrtnuid($salesrtnuid){
$res=$this->db->query("select salesrtnuid from salesrtn where salesrtnuid='$salesrtnuid'");
if($row=$res->result_array())
{
return true;
}
else
{
return false;
}
}
public function get_salesrtn($salesrtnuid)
{
$res=$this->db->query("select * from salesrtn where salesrtnuid = '$salesrtnuid'");
if($row=$res->result_array())
{
return $row;
}
else
{
return false;
}
}
}
| 14,096
|
https://github.com/lzuk/AwsWatchman/blob/master/Watchman.AwsResources/Services/RdsCluster/RdsClusterSource.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
AwsWatchman
|
lzuk
|
C#
|
Code
| 86
| 298
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.RDS;
using Amazon.RDS.Model;
namespace Watchman.AwsResources.Services.RdsCluster
{
public class RdsClusterSource : ResourceSourceBase<DBCluster>
{
private readonly IAmazonRDS _client;
public RdsClusterSource(IAmazonRDS client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
protected override async Task<IEnumerable<DBCluster>> FetchResources()
{
var results = new List<IEnumerable<DBCluster>>();
string marker = null;
do
{
var response = await _client.DescribeDBClustersAsync(new DescribeDBClustersRequest
{
Marker = marker
});
results.Add(response.DBClusters);
marker = response.Marker;
}
while (!string.IsNullOrEmpty(marker));
return results.SelectMany(x => x).ToList();
}
protected override string GetResourceName(DBCluster resource) => resource.DBClusterIdentifier;
}
}
| 9,586
|
https://github.com/NightHouseStudio/KelleEstellaDiscord/blob/master/comandos/setprefix.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
KelleEstellaDiscord
|
NightHouseStudio
|
JavaScript
|
Code
| 162
| 663
|
const prefixModel = require("../models/prefix");
const { MessageEmbed } = require("discord.js");
exports.run = async (bot,message,args) => {
if(!message.member.hasPermission("ADMINISTRATOR")) {
return;
} else {
const data = await prefixModel.findOne({
GuildID: message.guild.id
})
if (!args[0]) return message.lineReply("**❌ | Você precisa dizer qual o prefixo que quer utilizar!**");
if (args[0].length > 5) return message.lineReply("**❌ | O prefixo precisa ser menor que 5 caracteres.**")
if (data) {
await prefixModel.findOneAndRemove({
GuildID: message.guild.id
})
linkP = "https://cdn.discordapp.com/avatars/?";
linkC = linkP.replace('?', `${message.author.id}/${message.author.avatar}.png?size=2048`);
const embed = new MessageEmbed()
.setAuthor(`${message.author.username}`, linkC)
.setColor('#6e33cc')
.addField('Prefixo alterado!', `Por: ${message.author} \nNovo prefixo: \`${args[0]}\``)
.setFooter('Kelle Estella | 2021', bot.user.avatarURL())
message.lineReply(embed)
let newData = new prefixModel({
Prefix: args[0],
GuildID: message.guild.id
})
newData.save();
} else if (!data) {
linkP = "https://cdn.discordapp.com/avatars/?";
linkC = linkP.replace('?', `${message.author.id}/${message.author.avatar}.png?size=2048`);
const embed = new MessageEmbed()
.setAuthor(`${message.author.username}`, linkC)
.setColor('#6e33cc')
.addField('Prefixo alterado!', `Por: ${message.author} \nNovo prefixo: \`${args[0]}\``)
.setFooter('Kelle Estella | 2021', bot.user.avatarURL())
message.lineReply(embed)
let newData = new prefixModel({
Prefix: args[0],
GuildID: message.guild.id
})
newData.save();
}
};
}
exports.help = {
name: ["setprefix", "mudarprefixo"],
aliases: []
};
| 25,569
|
https://github.com/ElMassimo/capybara_test_helpers/blob/master/docs/.vitepress/components/SampleComponent.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
capybara_test_helpers
|
ElMassimo
|
Vue
|
Code
| 18
| 60
|
<script>
export default {
name: 'SampleComponent',
created () {
},
}
</script>
<template>
<div>Sample Component</div>
</template>
<style>
</style>
| 34,808
|
https://github.com/moorle/aries/blob/master/d2-admin/src/views/aries/system/index.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
aries
|
moorle
|
Vue
|
Code
| 233
| 1,104
|
<template>
<d2-container>
<el-row>
<el-col :span="8">
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>文章</span>
<el-button size="medium" icon="el-icon-notebook-2" style="float: right; padding: 3px 0"
type="text" @click="$router.push('/post')"></el-button>
</div>
<div class="text item"><h2 style="color: #2f74ff" class="card-num">{{ indexData.article_count }}</h2></div>
</el-card>
</el-col>
<el-col :span="8">
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>评论</span>
<el-button size="medium" icon="el-icon-s-comment" style="float: right; padding: 3px 0"
type="text" @click="$router.push('/comment')"></el-button>
</div>
<div class="text item"><h2 style="color: #4dc820" class="card-num">{{ indexData.comment_count }}</h2></div>
</el-card>
</el-col>
<el-col :span="8">
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>访问量</span>
<el-button size="medium" icon="el-icon-view" style="float: right; padding: 3px 0" type="text"></el-button>
</div>
<div class="text item"><h2 style="color: slategrey" class="card-num">0</h2></div>
</el-card>
</el-col>
<el-col :span="24">
<el-tabs class="box-card" type="border-card">
<el-tab-pane label="最近文章">
<el-timeline>
<p class="no-tip" v-if="indexData.latest_articles.length === 0">暂无文章</p>
<el-timeline-item :key="item.ID" v-for="item in indexData.latest_articles"
:timestamp="formatDate(item.CreatedAt)" placement="top">
{{ item.title }}
</el-timeline-item>
</el-timeline>
</el-tab-pane>
<el-tab-pane label="最近评论">
<el-timeline>
<p class="no-tip" v-if="indexData.latest_comments.length === 0">暂无评论</p>
<el-timeline-item :key="item.ID" v-for="item in indexData.latest_comments"
:timestamp="formatDate(item.CreatedAt)" placement="top">
{{ item.content }}
</el-timeline-item>
</el-timeline>
</el-tab-pane>
</el-tabs>
</el-col>
</el-row>
</d2-container>
</template>
<script>
import { getAdminIndexData } from '@api/aries/sys'
import { dateFormat } from '@/plugin/time/date'
export default {
name: 'index',
data () {
return {
indexData: {
article_count: 0,
comment_count: 0,
latest_articles: [],
latest_comments: []
},
fmt: 'yyyy-MM-dd',
currentDate: new Date()
}
},
created () {
this.fetchAdminIndexData()
},
methods: {
fetchAdminIndexData () {
getAdminIndexData()
.then(res => {
this.indexData = res.data
})
.catch(() => {
})
},
formatDate (time) {
return dateFormat(this.fmt, new Date(time))
}
}
}
</script>
<style scoped lang="scss">
.box-card {
margin: 10px;
}
.card-num {
margin: 5px;
}
.no-tip {
color: #99aabb;
}
</style>
| 27,127
|
https://github.com/arunsurya77/iris_readout/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
iris_readout
|
arunsurya77
|
Ignore List
|
Code
| 37
| 157
|
*~
*.o
*.lo
*.a
*.la
/build*/
# autotools stuff
/m4/lt*.m4
/m4/libtool.m4
/aclocal.m4
/ltmain.sh
/install-sh
/config.guess
/config.h.in
/config.sub
/autom4te.cache/
/compile
/configure
/depcomp
/missing
/test-driver
# automake
/ar-lib
Makefile.in
# cscope and other tags
/cscope.*
/GPATH
/GRTAGS
/GSYMS
/GTAGS
| 36,639
|
https://github.com/SHIVJITH/Odoo_Machine_Test/blob/master/addons/base_automation/tests/test_automation.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Odoo_Machine_Test
|
SHIVJITH
|
Python
|
Code
| 289
| 1,114
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import TransactionCase
from odoo.exceptions import UserError
import odoo.tests
@odoo.tests.tagged('post_install', '-at_install')
class TestAutomation(TransactionCase):
def test_01_on_create(self):
""" Simple on_create with admin user """
self.env["base.automation"].create({
"name": "Force Archived Contacts",
"trigger": "on_create_or_write",
"model_id": self.env.ref("base.model_res_partner").id,
"type": "ir.actions.server",
"trigger_field_ids": [(6, 0, [self.env.ref("base.field_res_partner__name").id])],
"fields_lines": [(0, 0, {
"col1": self.env.ref("base.field_res_partner__active").id,
"evaluation_type": "equation",
"value": "False",
})],
})
# verify the partner can be created and the action still runs
bilbo = self.env["res.partner"].create({"name": "Bilbo Baggins"})
self.assertFalse(bilbo.active)
# verify the partner can be updated and the action still runs
bilbo.active = True
bilbo.name = "Bilbo"
self.assertFalse(bilbo.active)
def test_02_on_create_restricted(self):
""" on_create action with low portal user """
action = self.env["base.automation"].create({
"name": "Force Archived Filters",
"trigger": "on_create_or_write",
"model_id": self.env.ref("base.model_ir_filters").id,
"type": "ir.actions.server",
"trigger_field_ids": [(6, 0, [self.env.ref("base.field_ir_filters__name").id])],
"fields_lines": [(0, 0, {
"col1": self.env.ref("base.field_ir_filters__active").id,
"evaluation_type": "equation",
"value": "False",
})],
})
# action cached was cached with admin, force CacheMiss
action.env.clear()
self_portal = self.env["ir.filters"].with_user(self.env.ref("base.user_demo").id)
# verify the portal user can create ir.filters but can not read base.automation
self.assertTrue(self_portal.env["ir.filters"].check_access_rights("create", raise_exception=False))
self.assertFalse(self_portal.env["base.automation"].check_access_rights("read", raise_exception=False))
# verify the filter can be created and the action still runs
filters = self_portal.create({
"name": "Where is Bilbo?",
"domain": "[('name', 'ilike', 'bilbo')]",
"model_id": "res.partner",
})
self.assertFalse(filters.active)
# verify the filter can be updated and the action still runs
filters.active = True
filters.name = "Where is Bilbo Baggins?"
self.assertFalse(filters.active)
def test_03_on_change_restricted(self):
""" on_create action with low portal user """
action = self.env["base.automation"].create({
"name": "Force Archived Filters",
"trigger": "on_change",
"model_id": self.env.ref("base.model_ir_filters").id,
"type": "ir.actions.server",
"on_change_field_ids": [(6, 0, [self.env.ref("base.field_ir_filters__name").id])],
"state": "code",
"code": """action = {'value': {'active': False}}""",
})
# action cached was cached with admin, force CacheMiss
action.env.clear()
self_portal = self.env["ir.filters"].with_user(self.env.ref("base.user_demo").id)
# simulate a onchange call on name
onchange = self_portal.onchange({}, [], {"name": "1", "active": ""})
self.assertEqual(onchange["value"]["active"], False)
| 4,882
|
https://github.com/0x802/federalist/blob/master/api/controllers/user-action.js
|
Github Open Source
|
Open Source
|
CC0-1.0, LicenseRef-scancode-public-domain, CC-BY-3.0
| 2,021
|
federalist
|
0x802
|
JavaScript
|
Code
| 51
| 173
|
const { showActions } = require('../authorizers/site');
const { UserAction } = require('../models');
const userActionSerializer = require('../serializers/user-action');
const { toInt } = require('../utils');
module.exports = {
find(req, res) {
const id = toInt(req.params.site_id);
showActions(req.user, { id })
.then(siteId => UserAction.findAllBySite(siteId))
.then(userActions => userActions || [])
.then(userActionSerializer.serialize)
.then(serialized => res.json(serialized))
.catch(res.error);
},
};
| 24,504
|
https://github.com/RichardTMiles/carbonphp/blob/master/tests/feature/FullRestTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
carbonphp
|
RichardTMiles
|
PHP
|
Code
| 595
| 2,688
|
<?php
namespace Tests\Feature;
use CarbonPHP\Rest;
use CarbonPHP\Tables\Location_References;
use CarbonPHP\Tables\Locations;
use CarbonPHP\Tables\Photos;
use CarbonPHP\Tables\Users;
class FullRestTest extends CarbonRestTest
{
public function testGenerateCorrectDistinctCountAndThreeArgumentBooleanConditionsUsingIntAndStringSql(): void
{
$_GET = [
Rest::SELECT => [
[Rest::COUNT, Photos::PHOTO_ID, 'countCustomNamed'],
[Rest::DISTINCT, Photos::PHOTO_PATH, 'distCustomNamed']
],
Rest::JOIN => [
Rest::INNER => [
Locations::TABLE_NAME => [
[
Locations::ENTITY_ID,
Rest::EQUAL,
Location_References::LOCATION_REFERENCE
]
],
]
],
Rest::WHERE => [
[Photos::PHOTO_ID, Rest::NOT_EQUAL, 1],
[Photos::PHOTO_ID => Location_References::ENTITY_REFERENCE],
],
Rest::GROUP_BY => [
Photos::PHOTO_ID
],
Rest::PAGINATION => [
Rest::LIMIT => 1000,
]
];
$_SERVER['REQUEST_METHOD'] = 'GET';
ob_start(null, 0, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE);
self::assertTrue(Rest::ExternalRestfulRequestsAPI(Photos::TABLE_NAME, null, Users::CLASS_NAMESPACE));
$out = trim(ob_get_clean());
$json_array = json_decode(trim($out), true);
self::assertArrayHasKey('sql', $json_array);
self::assertArrayHasKey('rest', $json_array);
self::assertEquals(
"SELECT DISTINCT(carbon_photos.photo_path) AS :injection1, COUNT(carbon_photos.photo_id) AS :injection0 FROM CarbonPHP.carbon_photos INNER JOIN CarbonPHP.carbon_locations ON ((carbon_locations.entity_id = UNHEX(:injection2))) WHERE ((carbon_photos.photo_id <> UNHEX(:injection3)) AND (carbon_photos.photo_id = UNHEX(:injection4))) GROUP BY carbon_photos.photo_id LIMIT 1000",
$GLOBALS['json']['sql'][0][1] ?? $GLOBALS['json']);
}
public function testRootLevelJoinConditionBooleanSwitch(): void
{
$_GET = [
Rest::SELECT => [
Users::USER_USERNAME,
Locations::STATE,
],
Rest::JOIN => [
Rest::INNER => [
Location_References::TABLE_NAME => [
Users::USER_ID => Location_References::ENTITY_REFERENCE,
Users::USER_EMAIL => 'example@example.com', // this very much does not matter
[
Users::USER_ID => Location_References::ENTITY_REFERENCE,
[
Users::USER_EMAIL => 'example@example.com'
]
],
Users::USER_ABOUT_ME => Location_References::ENTITY_REFERENCE
],
Locations::TABLE_NAME => [
[
Locations::ENTITY_ID => Location_References::LOCATION_REFERENCE,
Locations::LONGITUDE => Users::USER_ABOUT_ME // this doesnt matter we are testing structure
]
]
]
],
Rest::WHERE => [
[Users::USER_USERNAME, Rest::LIKE, '%rock%']
],
Rest::PAGINATION => [
Rest::LIMIT => 10,
Rest::ORDER => [
Users::USER_USERNAME => Rest::ASC
] // todo - I think Users::USER_USERNAME . Users::ASC worked, or didnt throw an error..
]
];
$_SERVER['REQUEST_METHOD'] = 'GET';
ob_start(null, 0, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE);
self::assertTrue(Rest::ExternalRestfulRequestsAPI(Users::TABLE_NAME, null, Users::CLASS_NAMESPACE));
$out = trim(ob_get_clean());
$json_array = json_decode(trim($out), true);
self::assertArrayHasKey('sql', $json_array);
self::assertArrayHasKey('rest', $json_array);
self::assertEquals(
"SELECT carbon_users.user_username, carbon_locations.state FROM CarbonPHP.carbon_users INNER JOIN CarbonPHP.carbon_location_references ON (carbon_users.user_id = carbon_location_references.entity_reference AND carbon_users.user_email = :injection0 AND (carbon_users.user_id = carbon_location_references.entity_reference OR (carbon_users.user_email = :injection0)) AND carbon_users.user_about_me = carbon_location_references.entity_reference) INNER JOIN CarbonPHP.carbon_locations ON ((carbon_locations.entity_id = carbon_location_references.location_reference OR carbon_locations.longitude = carbon_users.user_about_me)) WHERE ((carbon_users.user_username LIKE :injection1)) ORDER BY carbon_users.user_username ASC LIMIT 10",
$GLOBALS['json']['sql'][0][1] ?? $GLOBALS['json']);
}
public function testMultipleJoinConditionsOnSingleTableNoLimit(): void
{
$_GET = [
Rest::SELECT => [
Users::USER_USERNAME,
Locations::STATE,
],
Rest::JOIN => [
Rest::INNER => [
Location_References::TABLE_NAME => [
[Users::USER_ID =>
Location_References::ENTITY_REFERENCE]
],
Locations::TABLE_NAME => [
[Locations::ENTITY_ID =>
Location_References::LOCATION_REFERENCE]
]
]
],
Rest::WHERE => [
[Users::USER_USERNAME, Rest::LIKE, '%admin%']
],
Rest::PAGINATION => [
Rest::LIMIT => null,
Rest::ORDER => [
Users::USER_USERNAME => Rest::ASC
] // todo - I think Users::USER_USERNAME . Users::ASC worked, or didnt throw an error..
]
];
$_SERVER['REQUEST_METHOD'] = 'GET';
ob_start(null, 0, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE);
self::assertTrue(Rest::ExternalRestfulRequestsAPI(Users::TABLE_NAME, null, Users::CLASS_NAMESPACE));
$out = trim(ob_get_clean());
$json_array = json_decode(trim($out), true);
self::assertArrayHasKey('sql', $json_array);
self::assertArrayHasKey('rest', $json_array);
self::assertEquals(
"SELECT carbon_users.user_username, carbon_locations.state FROM CarbonPHP.carbon_users INNER JOIN CarbonPHP.carbon_location_references ON ((carbon_users.user_id = carbon_location_references.entity_reference)) INNER JOIN CarbonPHP.carbon_locations ON ((carbon_locations.entity_id = carbon_location_references.location_reference)) WHERE ((carbon_users.user_username LIKE :injection0)) ORDER BY carbon_users.user_username ASC",
$GLOBALS['json']['sql'][0][1] ?? $GLOBALS['json']);
}
public function testBooleanJoinToNestedAggregateHavingAndGroupBy(): void
{
$_GET = [
Rest::SELECT => [
Users::USER_USERNAME,
Users::USER_ABOUT_ME,
[Rest::COUNT, Location_References::ENTITY_REFERENCE],
[Rest::DISTINCT, Location_References::ENTITY_REFERENCE],
],
Rest::JOIN => [
Rest::INNER => [
Location_References::TABLE_NAME => [
[Users::USER_ID =>
Location_References::ENTITY_REFERENCE]
],
Locations::TABLE_NAME => [
[Locations::ENTITY_ID =>
Location_References::LOCATION_REFERENCE]
]
]
],
Rest::WHERE => [
[Users::USER_USERNAME, Rest::LIKE, '%rock%'],
],
Rest::GROUP_BY => [
Users::USER_USERNAME
],
Rest::HAVING => [
Users::USER_ABOUT_ME => [
Rest::NOT_EQUAL,
[Rest::COUNT, Location_References::ENTITY_REFERENCE]
]
],
Rest::PAGINATION => [
Rest::LIMIT => null,
Rest::ORDER => [
Users::USER_USERNAME => Rest::ASC
]
]
];
$_SERVER['REQUEST_METHOD'] = 'GET';
ob_start(null, 0, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE);
self::assertTrue(Rest::ExternalRestfulRequestsAPI(Users::TABLE_NAME, null, Users::CLASS_NAMESPACE));
$out = trim(ob_get_clean());
$json_array = json_decode(trim($out), true);
self::assertArrayHasKey('sql', $json_array);
self::assertArrayHasKey('rest', $json_array);
self::assertEquals(
"SELECT DISTINCT HEX(carbon_location_references.entity_reference) AS entity_reference, carbon_users.user_username, carbon_users.user_about_me, COUNT(carbon_location_references.entity_reference) FROM CarbonPHP.carbon_users INNER JOIN CarbonPHP.carbon_location_references ON ((carbon_users.user_id = carbon_location_references.entity_reference)) INNER JOIN CarbonPHP.carbon_locations ON ((carbon_locations.entity_id = carbon_location_references.location_reference)) WHERE ((carbon_users.user_username LIKE :injection0)) GROUP BY carbon_users.user_username HAVING (carbon_users.user_about_me <> COUNT(carbon_location_references.entity_reference)) ORDER BY carbon_users.user_username ASC",
$GLOBALS['json']['sql'][0][1] ?? $GLOBALS['json']);
}
}
| 17,327
|
https://github.com/hiep1998vnhn11/laravel-vite-vue3-antdv-less-starter/blob/master/resources/js/api/admin/account.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
laravel-vite-vue3-antdv-less-starter
|
hiep1998vnhn11
|
TypeScript
|
Code
| 153
| 431
|
import { defHttp } from '/@/utils/http/axios'
import {
ListAccount,
AccountCreateParams,
GetListAccountParams,
ToggleAccessParams,
DeleteAccountParams,
UpdateAccountParams,
SchoolParams,
UnsuspendAccountParams,
ActionAccountParams,
ApprovalEmailParams,
} from './model/accountModel'
import { BasicResponseMessage } from '../model/baseModel'
const indexApi = '/accounts'
export const getListAccount = (params: GetListAccountParams) =>
defHttp.get<ListAccount>({ url: indexApi, params })
export const createAccount = (params: AccountCreateParams) =>
defHttp.post<BasicResponseMessage>({ url: indexApi, params })
export const toggleAccessAccount = (params: ToggleAccessParams) =>
defHttp.put({ url: indexApi + '/toggle-access', params })
export const deleteListAccount = (params: DeleteAccountParams) =>
defHttp.delete({
url: indexApi + '/delete',
params,
})
export const updateAccount = (params: UpdateAccountParams) =>
defHttp.put({ url: indexApi + '/update', params })
export const actionAccount = (params: ActionAccountParams) =>
defHttp.put({ url: indexApi + '/action', params })
export const getCountStudent = (params: SchoolParams) =>
defHttp.get({ url: indexApi + '/get-count-status', params })
export const unsuspendAccount = (params: UnsuspendAccountParams) =>
defHttp.put({ url: indexApi + '/unsuspend', params })
export const approvalEmail = (params: ApprovalEmailParams) =>
defHttp.post({ url: indexApi + '/approvalEmail', params })
| 25,862
|
https://github.com/SinsofSloth/RF5-global-metadata/blob/master/System/Linq/Expressions/ExpressionType.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
RF5-global-metadata
|
SinsofSloth
|
C#
|
Code
| 525
| 984
|
public enum ExpressionType // TypeDefIndex: 2265
{
// Fields
public int value__; // 0x0
public const ExpressionType Add = 0;
public const ExpressionType AddChecked = 1;
public const ExpressionType And = 2;
public const ExpressionType AndAlso = 3;
public const ExpressionType ArrayLength = 4;
public const ExpressionType ArrayIndex = 5;
public const ExpressionType Call = 6;
public const ExpressionType Coalesce = 7;
public const ExpressionType Conditional = 8;
public const ExpressionType Constant = 9;
public const ExpressionType Convert = 10;
public const ExpressionType ConvertChecked = 11;
public const ExpressionType Divide = 12;
public const ExpressionType Equal = 13;
public const ExpressionType ExclusiveOr = 14;
public const ExpressionType GreaterThan = 15;
public const ExpressionType GreaterThanOrEqual = 16;
public const ExpressionType Invoke = 17;
public const ExpressionType Lambda = 18;
public const ExpressionType LeftShift = 19;
public const ExpressionType LessThan = 20;
public const ExpressionType LessThanOrEqual = 21;
public const ExpressionType ListInit = 22;
public const ExpressionType MemberAccess = 23;
public const ExpressionType MemberInit = 24;
public const ExpressionType Modulo = 25;
public const ExpressionType Multiply = 26;
public const ExpressionType MultiplyChecked = 27;
public const ExpressionType Negate = 28;
public const ExpressionType UnaryPlus = 29;
public const ExpressionType NegateChecked = 30;
public const ExpressionType New = 31;
public const ExpressionType NewArrayInit = 32;
public const ExpressionType NewArrayBounds = 33;
public const ExpressionType Not = 34;
public const ExpressionType NotEqual = 35;
public const ExpressionType Or = 36;
public const ExpressionType OrElse = 37;
public const ExpressionType Parameter = 38;
public const ExpressionType Power = 39;
public const ExpressionType Quote = 40;
public const ExpressionType RightShift = 41;
public const ExpressionType Subtract = 42;
public const ExpressionType SubtractChecked = 43;
public const ExpressionType TypeAs = 44;
public const ExpressionType TypeIs = 45;
public const ExpressionType Assign = 46;
public const ExpressionType Block = 47;
public const ExpressionType DebugInfo = 48;
public const ExpressionType Decrement = 49;
public const ExpressionType Dynamic = 50;
public const ExpressionType Default = 51;
public const ExpressionType Extension = 52;
public const ExpressionType Goto = 53;
public const ExpressionType Increment = 54;
public const ExpressionType Index = 55;
public const ExpressionType Label = 56;
public const ExpressionType RuntimeVariables = 57;
public const ExpressionType Loop = 58;
public const ExpressionType Switch = 59;
public const ExpressionType Throw = 60;
public const ExpressionType Try = 61;
public const ExpressionType Unbox = 62;
public const ExpressionType AddAssign = 63;
public const ExpressionType AndAssign = 64;
public const ExpressionType DivideAssign = 65;
public const ExpressionType ExclusiveOrAssign = 66;
public const ExpressionType LeftShiftAssign = 67;
public const ExpressionType ModuloAssign = 68;
public const ExpressionType MultiplyAssign = 69;
public const ExpressionType OrAssign = 70;
public const ExpressionType PowerAssign = 71;
public const ExpressionType RightShiftAssign = 72;
public const ExpressionType SubtractAssign = 73;
public const ExpressionType AddAssignChecked = 74;
public const ExpressionType MultiplyAssignChecked = 75;
public const ExpressionType SubtractAssignChecked = 76;
public const ExpressionType PreIncrementAssign = 77;
public const ExpressionType PreDecrementAssign = 78;
public const ExpressionType PostIncrementAssign = 79;
public const ExpressionType PostDecrementAssign = 80;
public const ExpressionType TypeEqual = 81;
public const ExpressionType OnesComplement = 82;
public const ExpressionType IsTrue = 83;
public const ExpressionType IsFalse = 84;
}
| 9,812
|
https://github.com/affinitydev/auth/blob/master/src/Affinity/SimpleAuth/Helper/Extension/ContextContainerTrait.php
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,013
|
auth
|
affinitydev
|
PHP
|
Code
| 91
| 251
|
<?php
/**
* This file is part of the Affinity Development
* open source toolset.
*
* @author Brendan Bates <brendanbates89@gmail.com>
* @package Affinity.SimpleAuth
* @license http://opensource.org/licenses/bsd-license.php BSD
*/
namespace Affinity\SimpleAuth\Helper\Extension;
use Affinity\SimpleAuth\AuthContext;
/**
*
* Class Description.
*
* @package Affinity.SimpleAuth
*
*/
trait ContextContainerTrait
{
/**
* The Authentication Context for the current user.
*
* @var AuthContext $authContext
*/
private $authContext;
/**
*
* @return AuthContext The authentication context object.
*/
public function getContext()
{
return $this->authContext;
}
public function setContext(AuthContext $context)
{
$this->authContext = $context;
}
}
| 51,002
|
https://github.com/zhao-qc/zstack/blob/master/test/src/test/java/org/zstack/test/utils/TestSshCheckToolFailure.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
zstack
|
zhao-qc
|
Java
|
Code
| 53
| 269
|
package org.zstack.test.utils;
import org.junit.Test;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshException;
import org.zstack.utils.ssh.SshResult;
public class TestSshCheckToolFailure {
@Test(expected = SshException.class)
public void test() {
SshResult res = new Ssh().setHostname("localhost").setUsername("root").setPassword("password")
.checkTool("ls", "this_tool_is_not_existing", "cp", "mv", "not_existing_too").run();
res.raiseExceptionIfFailed();
}
@Test(expected = SshException.class)
public void test1() {
SshResult res = new Ssh().setHostname("localhost").setUsername("root").setPassword("password")
.checkTool("ls", "cp", "mv", "this_tool_is_not_existing", "rm").run();
res.raiseExceptionIfFailed();
}
}
| 23,963
|
https://github.com/jhh67/chapel/blob/master/test/users/franzf/v2/chpl/fft_128.chpl
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,022
|
chapel
|
jhh67
|
Chapel
|
Code
| 1,842
| 6,340
|
/***************************************************************
This code was generated by Spiral 5.0 beta, www.spiral.net --
Copyright (c) 2005, Carnegie Mellon University
All rights reserved.
The code is distributed under a BSD style license
(see http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, reference to Spiral, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Carnegie Mellon University nor the name of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*AS IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************/
use omega;
var buf2: [0..127] complex;
var dat2: [0..127] complex;
proc init_fft128() {
for i1315 in 0..3 {
for i1318 in 0..3 {
for i1324 in 0..1 {
for i1326 in 0..1 {
dat2(((i1315*32) + (i1318*8) + (i1324*4) + (i1326*2))) = omega(128, ((i1318 + ((i1324 + (i1326*2))*4))*i1315));
dat2(((i1315*32) + (i1318*8) + (i1324*4) + (i1326*2) + 1)) = omega(128, ((i1318 + ((i1324 + (i1326*2))*4) + 16)*i1315));
}
}
}
}
}
proc fft128(Y: [] complex, X: [] complex) {
for i1316 in 0..31 {
var s2609, s2610, s2611, s2612, s2613, t4511, t4512,
t4513:complex;
var a2715:int;
s2609 = X(i1316);
s2610 = X((64 + i1316));
t4511 = (s2609 + s2610);
t4512 = (s2609 - s2610);
s2611 = X((32 + i1316));
s2612 = X((96 + i1316));
t4513 = (s2611 + s2612);
a2715 = (4*i1316);
buf2(a2715) = (t4511 + t4513);
buf2((2 + a2715)) = (t4511 - t4513);
s2613 = (1.0i*(s2611 - s2612));
buf2((1 + a2715)) = (t4512 + s2613);
buf2((3 + a2715)) = (t4512 - s2613);
}
for i1315 in 0..3 {
var s2840, s2841, s2842, s2843, s2844, s2845, s2846,
s2847, s2848, s2849, s2850, s2851, s2852, s2853, s2854,
s2855, s2856, s2857, s2858, s2859, s2860, s2861, s2862,
s2863, s2864, s2865, s2866, s2867, s2868, s2869, s2870,
s2871, s2872, s2873, s2874, s2875, s2876, s2877, s2878,
s2879, s2880, s2881, s2882, s2883, s2884, s2885, s2886,
s2887, s2888, s2889, s2890, s2891, s2892, s2893, s2894,
s2895, s2896, s2897, s2898, s2899, s2900, s2901, s2902,
s2903, s2904, s2905, s2906, s2907, s2908, s2909, s2910,
s2911, s2912, s2913, s2914, s2915, s2916, s2917, s2918,
s2919, s2920, t4834, t4835, t4836, t4837, t4838, t4839,
t4840, t4841, t4842, t4843, t4844, t4845, t4846, t4847,
t4848, t4849, t4850, t4851, t4852, t4853, t4854, t4855,
t4856, t4857, t4858, t4859, t4860, t4861, t4862, t4863,
t4864, t4865, t4866, t4867, t4868, t4869, t4870, t4871,
t4872, t4873, t4874, t4875, t4876, t4877, t4878, t4879,
t4880, t4881, t4882, t4883, t4884, t4885, t4886, t4887,
t4888, t4889, t4890, t4891, t4892, t4893, t4894, t4895,
t4896, t4897, t4898, t4899, t4900, t4901, t4902, t4903,
t4904, t4905, t4906, t4907, t4908, t4909, t4910, t4911,
t4912:complex;
var a2968, a2969, a2970, a2971, a2972, a2973, a2974,
a2975, a2976, a2977, a2978, a2979, a2980, a2981, a2982,
a2983, a2984, a2985, a2986, a2987, a2988, a2989, a2990,
a2991, a2992, a2993, a2994, a2995, a2996, a2997, a2998,
a2999:int;
a2968 = (64 + i1315);
a2969 = (32*i1315);
s2840 = (dat2(a2969)*buf2(i1315));
s2841 = (dat2((1 + a2969))*buf2(a2968));
t4834 = (s2840 + s2841);
t4835 = (s2840 - s2841);
a2970 = (32 + i1315);
a2971 = (96 + i1315);
s2842 = (dat2((2 + a2969))*buf2(a2970));
s2843 = (dat2((3 + a2969))*buf2(a2971));
t4836 = (s2842 + s2843);
t4837 = (t4834 + t4836);
t4838 = (t4834 - t4836);
s2844 = (1.0i*(s2842 - s2843));
t4839 = (t4835 + s2844);
t4840 = (t4835 - s2844);
a2972 = (16 + i1315);
a2973 = (80 + i1315);
s2845 = (dat2((4 + a2969))*buf2(a2972));
s2846 = (dat2((5 + a2969))*buf2(a2973));
t4841 = (s2845 + s2846);
t4842 = (s2845 - s2846);
a2974 = (48 + i1315);
a2975 = (112 + i1315);
s2847 = (dat2((6 + a2969))*buf2(a2974));
s2848 = (dat2((7 + a2969))*buf2(a2975));
t4843 = (s2847 + s2848);
t4844 = (t4841 + t4843);
s2849 = (1.0i*(s2847 - s2848));
t4845 = (t4837 + t4844);
t4846 = (t4837 - t4844);
s2850 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4842 + s2849));
t4847 = (t4839 + s2850);
t4848 = (t4839 - s2850);
s2851 = (1.0i*(t4841 - t4843));
t4849 = (t4838 + s2851);
t4850 = (t4838 - s2851);
s2852 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4842 - s2849));
t4851 = (t4840 + s2852);
t4852 = (t4840 - s2852);
a2976 = (4 + i1315);
a2977 = (68 + i1315);
s2853 = (dat2((8 + a2969))*buf2(a2976));
s2854 = (dat2((9 + a2969))*buf2(a2977));
t4853 = (s2853 + s2854);
t4854 = (s2853 - s2854);
a2978 = (36 + i1315);
a2979 = (100 + i1315);
s2855 = (dat2((10 + a2969))*buf2(a2978));
s2856 = (dat2((11 + a2969))*buf2(a2979));
t4855 = (s2855 + s2856);
t4856 = (t4853 + t4855);
t4857 = (t4853 - t4855);
s2857 = (1.0i*(s2855 - s2856));
t4858 = (t4854 + s2857);
t4859 = (t4854 - s2857);
a2980 = (20 + i1315);
a2981 = (84 + i1315);
s2858 = (dat2((12 + a2969))*buf2(a2980));
s2859 = (dat2((13 + a2969))*buf2(a2981));
t4860 = (s2858 + s2859);
t4861 = (s2858 - s2859);
a2982 = (52 + i1315);
a2983 = (116 + i1315);
s2860 = (dat2((14 + a2969))*buf2(a2982));
s2861 = (dat2((15 + a2969))*buf2(a2983));
t4862 = (s2860 + s2861);
t4863 = (t4860 + t4862);
s2862 = (1.0i*(s2860 - s2861));
t4864 = (t4856 + t4863);
s2863 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4861 + s2862));
s2864 = (1.0i*(t4860 - t4862));
s2865 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4861 - s2862));
a2984 = (8 + i1315);
a2985 = (72 + i1315);
s2866 = (dat2((16 + a2969))*buf2(a2984));
s2867 = (dat2((17 + a2969))*buf2(a2985));
t4865 = (s2866 + s2867);
t4866 = (s2866 - s2867);
a2986 = (40 + i1315);
a2987 = (104 + i1315);
s2868 = (dat2((18 + a2969))*buf2(a2986));
s2869 = (dat2((19 + a2969))*buf2(a2987));
t4867 = (s2868 + s2869);
t4868 = (t4865 + t4867);
t4869 = (t4865 - t4867);
s2870 = (1.0i*(s2868 - s2869));
t4870 = (t4866 + s2870);
t4871 = (t4866 - s2870);
a2988 = (24 + i1315);
a2989 = (88 + i1315);
s2871 = (dat2((20 + a2969))*buf2(a2988));
s2872 = (dat2((21 + a2969))*buf2(a2989));
t4872 = (s2871 + s2872);
t4873 = (s2871 - s2872);
a2990 = (56 + i1315);
a2991 = (120 + i1315);
s2873 = (dat2((22 + a2969))*buf2(a2990));
s2874 = (dat2((23 + a2969))*buf2(a2991));
t4874 = (s2873 + s2874);
t4875 = (t4872 + t4874);
s2875 = (1.0i*(s2873 - s2874));
t4876 = (t4868 + t4875);
s2876 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4873 + s2875));
s2877 = (1.0i*(t4872 - t4874));
s2878 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4873 - s2875));
a2992 = (12 + i1315);
a2993 = (76 + i1315);
s2879 = (dat2((24 + a2969))*buf2(a2992));
s2880 = (dat2((25 + a2969))*buf2(a2993));
t4877 = (s2879 + s2880);
t4878 = (s2879 - s2880);
a2994 = (44 + i1315);
a2995 = (108 + i1315);
s2881 = (dat2((26 + a2969))*buf2(a2994));
s2882 = (dat2((27 + a2969))*buf2(a2995));
t4879 = (s2881 + s2882);
t4880 = (t4877 + t4879);
t4881 = (t4877 - t4879);
s2883 = (1.0i*(s2881 - s2882));
t4882 = (t4878 + s2883);
t4883 = (t4878 - s2883);
a2996 = (28 + i1315);
a2997 = (92 + i1315);
s2884 = (dat2((28 + a2969))*buf2(a2996));
s2885 = (dat2((29 + a2969))*buf2(a2997));
t4884 = (s2884 + s2885);
t4885 = (s2884 - s2885);
a2998 = (60 + i1315);
a2999 = (124 + i1315);
s2886 = (dat2((30 + a2969))*buf2(a2998));
s2887 = (dat2((31 + a2969))*buf2(a2999));
t4886 = (s2886 + s2887);
t4887 = (t4884 + t4886);
s2888 = (1.0i*(s2886 - s2887));
t4888 = (t4880 + t4887);
s2889 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4885 + s2888));
s2890 = (1.0i*(t4884 - t4886));
s2891 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4885 - s2888));
t4889 = (t4845 + t4876);
t4890 = (t4845 - t4876);
t4891 = (t4864 + t4888);
Y(i1315) = (t4889 + t4891);
Y(a2968) = (t4889 - t4891);
s2892 = (1.0i*(t4864 - t4888));
Y(a2970) = (t4890 + s2892);
Y(a2971) = (t4890 - s2892);
s2893 = ((0.92387953251128674 + 1.0i * 0.38268343236508978)*(t4870 + s2876));
t4892 = (t4847 + s2893);
t4893 = (t4847 - s2893);
s2894 = ((0.98078528040323043 + 1.0i * 0.19509032201612825)*(t4858 + s2863));
s2895 = ((0.83146961230254524 + 1.0i * 0.55557023301960218)*(t4882 + s2889));
t4894 = (s2894 + s2895);
Y(a2976) = (t4892 + t4894);
Y(a2977) = (t4892 - t4894);
s2896 = (1.0i*(s2894 - s2895));
Y(a2978) = (t4893 + s2896);
Y(a2979) = (t4893 - s2896);
s2897 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4869 + s2877));
t4895 = (t4849 + s2897);
t4896 = (t4849 - s2897);
s2898 = ((0.92387953251128674 + 1.0i * 0.38268343236508978)*(t4857 + s2864));
s2899 = ((0.38268343236508978 + 1.0i * 0.92387953251128674)*(t4881 + s2890));
t4897 = (s2898 + s2899);
Y(a2984) = (t4895 + t4897);
Y(a2985) = (t4895 - t4897);
s2900 = (1.0i*(s2898 - s2899));
Y(a2986) = (t4896 + s2900);
Y(a2987) = (t4896 - s2900);
s2901 = ((0.38268343236508978 + 1.0i * 0.92387953251128674)*(t4871 + s2878));
t4898 = (t4851 + s2901);
t4899 = (t4851 - s2901);
s2902 = ((0.83146961230254524 + 1.0i * 0.55557023301960218)*(t4859 + s2865));
s2903 = ((-0.19509032201612825 + 1.0i * 0.98078528040323043)*(t4883 + s2891));
t4900 = (s2902 + s2903);
Y(a2992) = (t4898 + t4900);
Y(a2993) = (t4898 - t4900);
s2904 = (1.0i*(s2902 - s2903));
Y(a2994) = (t4899 + s2904);
Y(a2995) = (t4899 - s2904);
s2905 = (1.0i*(t4868 - t4875));
t4901 = (t4846 + s2905);
t4902 = (t4846 - s2905);
s2906 = ((0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4856 - t4863));
s2907 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4880 - t4887));
t4903 = (s2906 + s2907);
Y(a2972) = (t4901 + t4903);
Y(a2973) = (t4901 - t4903);
s2908 = (1.0i*(s2906 - s2907));
Y(a2974) = (t4902 + s2908);
Y(a2975) = (t4902 - s2908);
s2909 = ((-0.38268343236508978 + 1.0i * 0.92387953251128674)*(t4870 - s2876));
t4904 = (t4848 + s2909);
t4905 = (t4848 - s2909);
s2910 = ((0.55557023301960218 + 1.0i * 0.83146961230254524)*(t4858 - s2863));
s2911 = ((-0.98078528040323043 + 1.0i * 0.19509032201612825)*(t4882 - s2889));
t4906 = (s2910 + s2911);
Y(a2980) = (t4904 + t4906);
Y(a2981) = (t4904 - t4906);
s2912 = (1.0i*(s2910 - s2911));
Y(a2982) = (t4905 + s2912);
Y(a2983) = (t4905 - s2912);
s2913 = ((-0.70710678118654757 + 1.0i * 0.70710678118654757)*(t4869 - s2877));
t4907 = (t4850 + s2913);
t4908 = (t4850 - s2913);
s2914 = ((0.38268343236508978 + 1.0i * 0.92387953251128674)*(t4857 - s2864));
s2915 = ((-0.92387953251128674 - 1.0i * 0.38268343236508978)*(t4881 - s2890));
t4909 = (s2914 + s2915);
Y(a2988) = (t4907 + t4909);
Y(a2989) = (t4907 - t4909);
s2916 = (1.0i*(s2914 - s2915));
Y(a2990) = (t4908 + s2916);
Y(a2991) = (t4908 - s2916);
s2917 = ((-0.92387953251128674 + 1.0i * 0.38268343236508978)*(t4871 - s2878));
t4910 = (t4852 + s2917);
t4911 = (t4852 - s2917);
s2918 = ((0.19509032201612825 + 1.0i * 0.98078528040323043)*(t4859 - s2865));
s2919 = ((-0.55557023301960218 - 1.0i * 0.83146961230254524)*(t4883 - s2891));
t4912 = (s2918 + s2919);
Y(a2996) = (t4910 + t4912);
Y(a2997) = (t4910 - t4912);
s2920 = (1.0i*(s2918 - s2919));
Y(a2998) = (t4911 + s2920);
Y(a2999) = (t4911 - s2920);
}
}
| 25,838
|
https://github.com/varrcan/workcalendar/blob/master/europe/czechrepublic/czechrepublic.go
|
Github Open Source
|
Open Source
|
MIT
| null |
workcalendar
|
varrcan
|
Go
|
Code
| 175
| 549
|
package czechrepublic
import (
"fmt"
"time"
core "github.com/varrcan/workcalendar"
)
var (
holidays = core.Holidays{
"1/1": core.Event("Restoration Day of the Independent Czech State"),
"5/8": core.Event("Liberation Day"),
"7/5": core.Event("Saints Cyril and Methodius Day"),
"7/6": core.Event("Jan Hus Day"),
"9/28": core.Event("St. Wenceslas Day (Czech Statehood Day)"),
"10/28": core.Event("Independent Czechoslovak State Day"),
"11/17": core.Event("Struggle for Freedom and Democracy Day"),
"12/26": core.Event("St. Stephen's Day (The Second Christmas Day)"),
}
calendar = core.NewCalendar(
holidays,
core.WithNewYearDay(),
core.WithLabourDay(),
core.WithEasterMonday(),
//TODO: check whether good friday is ok
core.WithGoodFriday(),
core.WithChristmas(),
core.WithChristmasEve(),
)
)
//IsWorkingDay is inteded to check whether a day is working or not
func IsWorkingDay(date time.Time) bool {
return calendar.IsWorkingDay(date)
}
//IsHoliday is inteded to check whether a day is holiday or not
func IsHoliday(date time.Time) bool {
return calendar.IsHoliday(date)
}
//GetHoliday is inteded to check whether a day is holiday or not
func GetHoliday(date time.Time) (*core.CalEvent, error) {
if !IsHoliday(date) {
return nil, fmt.Errorf("There is no holiday for %s", date)
}
holiday := calendar.GetHoliday(date)
if holiday == nil {
return nil, fmt.Errorf("There is no holiday for %s", date)
}
return calendar.GetHoliday(date), nil
}
| 50,690
|
https://github.com/alexzhangs/xsh-lib-core/blob/master/functions/date/minute.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
xsh-lib-core
|
alexzhangs
|
Shell
|
Code
| 56
| 132
|
#? Description:
#? Get the Minute part from a given timestamp.
#? If no timestamp given, then generate one.
#?
#? Usage:
#? @minute [-M] [TIMESTAMP]
#?
#? Options:
#? [-M] Get the minute (00..59).
#?
#? This is the default option.
#?
#? [TIMESTAMP] Timestamp.
#?
function minute () {
xsh /date/get "%M" "$@"
}
| 50,453
|
https://github.com/inovexia/commerce/blob/master/framework/saleor/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
commerce
|
inovexia
|
TSX
|
Code
| 37
| 89
|
import { getCommerceProvider, useCommerce as useCoreCommerce } from '@commerce'
import { saleorProvider, SaleorProvider } from './provider'
export { saleorProvider }
export type { SaleorProvider }
export const CommerceProvider = getCommerceProvider(saleorProvider)
export const useCommerce = () => useCoreCommerce<SaleorProvider>()
| 38,353
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.